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
|
---|---|---|---|---|---|---|
190,923 |
<p>I have a nav menu with a depth of 2.</p>
<pre><code>wp_nav_menu( array( 'theme_location' => 'primary_navigation',
'depth' => 2
) );
</code></pre>
<p>When I am active on a page in the nav menu that has no children, that <code>li</code> menu item has <code>active</code> appended. However, when the menu item has children, <code>has-children</code> is appended, but no 'active' or even a related class name.</p>
<pre><code><ul id="menu-main-top-navigation">
<li class="parent1"></li>
<li class="has-dropdown not-click">
<ul class="dropdown">
<li class="child1"></li>
<li class="child2"></li>
</ul>
</li>
<li class="parent3"></li>
<li class="parent4"></li>
<li class="active parent5"></li>
<li class="parent6"></li>
</ul>
</code></pre>
<p>In this case I am the page relating to menu item 'parent5'. This is fine. When I navigate to what is meant to be 'parent2', the class name is replaced completely with 'has-dropdown' so there is no differing class name or 'active'.</p>
<p>How can I fix this. Even to remove the JQuery in this case.</p>
|
[
{
"answer_id": 190926,
"author": "Hemant Aggarwal",
"author_id": 63853,
"author_profile": "https://wordpress.stackexchange.com/users/63853",
"pm_score": 1,
"selected": false,
"text": "<p>Can you add the complete output code for the navigation menu. The code you pasted seems to be a stripped version. Moreover, WordPress adds 'current_page_item' class to the list item if it is currently being viewed.</p>\n\n<p>For more info, check this <a href=\"https://codex.wordpress.org/Function_Reference/wp_nav_menu#Backward_Compatibility_with_wp_page_menu.28.29\" rel=\"nofollow\">WordPress documentation</a> on classes added to Navigation menu items.</p>\n"
},
{
"answer_id": 190934,
"author": "myol",
"author_id": 51823,
"author_profile": "https://wordpress.stackexchange.com/users/51823",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks to mstoic for pointing out that this is not default WP functionality. This ended up being an unhelpful feature (for me) used in a WordPress stack.</p>\n\n<p>I found the offending line and commented it out.</p>\n\n<pre><code> $output .= \"\\n<ul class=\\\"dropdown\\\">\\n\";\n }\n\n function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0) {\n $item_html = '';\n parent::start_el($item_html, $item, $depth, $args);\n\n if ($item->is_dropdown && ($depth === 0)) {\n //$item_html = str_replace('<li', '<li class=\"has-dropdown not-click\"', $item_html);\n ...\n</code></pre>\n"
}
] |
2015/06/09
|
[
"https://wordpress.stackexchange.com/questions/190923",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/51823/"
] |
I have a nav menu with a depth of 2.
```
wp_nav_menu( array( 'theme_location' => 'primary_navigation',
'depth' => 2
) );
```
When I am active on a page in the nav menu that has no children, that `li` menu item has `active` appended. However, when the menu item has children, `has-children` is appended, but no 'active' or even a related class name.
```
<ul id="menu-main-top-navigation">
<li class="parent1"></li>
<li class="has-dropdown not-click">
<ul class="dropdown">
<li class="child1"></li>
<li class="child2"></li>
</ul>
</li>
<li class="parent3"></li>
<li class="parent4"></li>
<li class="active parent5"></li>
<li class="parent6"></li>
</ul>
```
In this case I am the page relating to menu item 'parent5'. This is fine. When I navigate to what is meant to be 'parent2', the class name is replaced completely with 'has-dropdown' so there is no differing class name or 'active'.
How can I fix this. Even to remove the JQuery in this case.
|
Can you add the complete output code for the navigation menu. The code you pasted seems to be a stripped version. Moreover, WordPress adds 'current\_page\_item' class to the list item if it is currently being viewed.
For more info, check this [WordPress documentation](https://codex.wordpress.org/Function_Reference/wp_nav_menu#Backward_Compatibility_with_wp_page_menu.28.29) on classes added to Navigation menu items.
|
190,940 |
<p>I am currently working on a theme for a client and now just got into a problem: When I want to set an image (also existing/already uploaded images don't work) the editor just not accept it and don't set it as the post thumbnail for the post.</p>
<p>Any help would be appreciated.</p>
<p>EDIT:
Here is an screenshot for the case that somebody didn't know, what I am talking about:</p>
<p><img src="https://i.stack.imgur.com/k0DvD.png" alt="enter image description here"></p>
<p>It's like this <strong>before</strong> and <strong>after</strong> the "change". So what's going on there?</p>
<p>Normal file upload is working.</p>
|
[
{
"answer_id": 190941,
"author": "TalwinderSingh",
"author_id": 74421,
"author_profile": "https://wordpress.stackexchange.com/users/74421",
"pm_score": -1,
"selected": false,
"text": "<p>You need to add support for thumbnails in your theme. So, put this in your theme files:</p>\n\n<p><code>function custom_theme_setup() {\n add_theme_support( $feature, $arguments );\n}\nadd_action( 'after_setup_theme', 'custom_theme_setup' );</code></p>\n\n<p>This enables the thumbnail/feature image support for all post types in your current theme including normal posts and pages.</p>\n"
},
{
"answer_id": 191173,
"author": "Dominik Schmidt",
"author_id": 71075,
"author_profile": "https://wordpress.stackexchange.com/users/71075",
"pm_score": 1,
"selected": true,
"text": "<p>I figured out it was because of an script that was delivered with the <strong>Options Framework</strong>. There was a little piece of code in my <code>functions.php</code> which caused wrong javascript to be loaded.</p>\n\n<p>When you are having the same problem, be sure to search for something like <code>wp_enqueue_media();</code> or something of the following script, comment out and try to upload a thumbnail.</p>\n\n<pre><code>if( function_exists( 'wp_enqueue_media' ) ){\n wp_enqueue_media();\n} else {\n wp_enqueue_style('thickbox');\n wp_enqueue_script('media-upload');\n wp_enqueue_script('thickbox');\n}\n</code></pre>\n\n<p>Thanks for all answers, though.</p>\n"
}
] |
2015/06/09
|
[
"https://wordpress.stackexchange.com/questions/190940",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/71075/"
] |
I am currently working on a theme for a client and now just got into a problem: When I want to set an image (also existing/already uploaded images don't work) the editor just not accept it and don't set it as the post thumbnail for the post.
Any help would be appreciated.
EDIT:
Here is an screenshot for the case that somebody didn't know, what I am talking about:

It's like this **before** and **after** the "change". So what's going on there?
Normal file upload is working.
|
I figured out it was because of an script that was delivered with the **Options Framework**. There was a little piece of code in my `functions.php` which caused wrong javascript to be loaded.
When you are having the same problem, be sure to search for something like `wp_enqueue_media();` or something of the following script, comment out and try to upload a thumbnail.
```
if( function_exists( 'wp_enqueue_media' ) ){
wp_enqueue_media();
} else {
wp_enqueue_style('thickbox');
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
}
```
Thanks for all answers, though.
|
190,951 |
<p>I'm quite new to WP theme development so I'm sorry if the answer for this question may seem obvious. </p>
<p>I'm developing a custom WordPress theme from scratch, and I'm stuck working on the menus. My header menu has some submenus that I'd like to style, but when I call the menu with the wp_nav_menu() function, the HTML output doesn't recognize them as submenus. </p>
<p>I mean, even if I built correctly the menus in the admin panel, the output I get is:</p>
<pre><code><ul>
<li>Item #1</li>
<li>Item #2</li>
<li>Item #3</li>
<li>Item #4</li>
<li>Item #5</li>
<li>Item #6</li>
</ul>
</code></pre>
<p>Item #4 and Item #5 are nested into a submenu under Item #3, for example, and I want them to be nested inside another ul, how they should be.
I'm sure it's a theme related problem, because everything works well by switching to a default theme. </p>
<p>This is how I use the wp_nav_menu() function:</p>
<pre><code>wp_nav_menu( array( 'theme_location' => 'header-menu',
'container_class' => 'navigator' ) )
</code></pre>
<p>Maybe I have to add something in functions.php, but I really don't know what. </p>
<p>Thank you all. </p>
|
[
{
"answer_id": 190941,
"author": "TalwinderSingh",
"author_id": 74421,
"author_profile": "https://wordpress.stackexchange.com/users/74421",
"pm_score": -1,
"selected": false,
"text": "<p>You need to add support for thumbnails in your theme. So, put this in your theme files:</p>\n\n<p><code>function custom_theme_setup() {\n add_theme_support( $feature, $arguments );\n}\nadd_action( 'after_setup_theme', 'custom_theme_setup' );</code></p>\n\n<p>This enables the thumbnail/feature image support for all post types in your current theme including normal posts and pages.</p>\n"
},
{
"answer_id": 191173,
"author": "Dominik Schmidt",
"author_id": 71075,
"author_profile": "https://wordpress.stackexchange.com/users/71075",
"pm_score": 1,
"selected": true,
"text": "<p>I figured out it was because of an script that was delivered with the <strong>Options Framework</strong>. There was a little piece of code in my <code>functions.php</code> which caused wrong javascript to be loaded.</p>\n\n<p>When you are having the same problem, be sure to search for something like <code>wp_enqueue_media();</code> or something of the following script, comment out and try to upload a thumbnail.</p>\n\n<pre><code>if( function_exists( 'wp_enqueue_media' ) ){\n wp_enqueue_media();\n} else {\n wp_enqueue_style('thickbox');\n wp_enqueue_script('media-upload');\n wp_enqueue_script('thickbox');\n}\n</code></pre>\n\n<p>Thanks for all answers, though.</p>\n"
}
] |
2015/06/09
|
[
"https://wordpress.stackexchange.com/questions/190951",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74422/"
] |
I'm quite new to WP theme development so I'm sorry if the answer for this question may seem obvious.
I'm developing a custom WordPress theme from scratch, and I'm stuck working on the menus. My header menu has some submenus that I'd like to style, but when I call the menu with the wp\_nav\_menu() function, the HTML output doesn't recognize them as submenus.
I mean, even if I built correctly the menus in the admin panel, the output I get is:
```
<ul>
<li>Item #1</li>
<li>Item #2</li>
<li>Item #3</li>
<li>Item #4</li>
<li>Item #5</li>
<li>Item #6</li>
</ul>
```
Item #4 and Item #5 are nested into a submenu under Item #3, for example, and I want them to be nested inside another ul, how they should be.
I'm sure it's a theme related problem, because everything works well by switching to a default theme.
This is how I use the wp\_nav\_menu() function:
```
wp_nav_menu( array( 'theme_location' => 'header-menu',
'container_class' => 'navigator' ) )
```
Maybe I have to add something in functions.php, but I really don't know what.
Thank you all.
|
I figured out it was because of an script that was delivered with the **Options Framework**. There was a little piece of code in my `functions.php` which caused wrong javascript to be loaded.
When you are having the same problem, be sure to search for something like `wp_enqueue_media();` or something of the following script, comment out and try to upload a thumbnail.
```
if( function_exists( 'wp_enqueue_media' ) ){
wp_enqueue_media();
} else {
wp_enqueue_style('thickbox');
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
}
```
Thanks for all answers, though.
|
190,967 |
<p>I use a random wp_query to load 3 posts from over 600 posts in total with this query.</p>
<pre><code> <?php
$args = array(
'post_type' => 'post',
'cat' => 1,
'orderby' => 'rand',
'posts_per_page' => 3
);
$all_posts = new WP_Query( $args );
while ( $all_posts->have_posts() ) : $all_posts->the_post();
get_template_part( 'content' );
endwhile;
?>
<?php wp_reset_postdata(); ?>
</code></pre>
<p>Works great, but it seems for a lot of people a lot of the same images popup in the random display over and over again. So it seems the random isn't really random. At least it doesn't feel this way. Is there a way to force Wordpress to skip random displayed images and load new ones? Or is it out of my hands in this case? I can't really find an answer online.</p>
<p>Thanks in advance! </p>
|
[
{
"answer_id": 190968,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 0,
"selected": false,
"text": "<p>You aren't really talking about forcing WordPress to be more random; you are talking about forcing the database server to be more random. WordPress just pushed <code>ORDER BY RAND()</code> through to the server. And yes, generated \"random\" isn't truly random, it is pseudo-random but for all intents and purposes it should be close enough. The only thins I can think of that might help would be to push <code>'ignore_sticky_posts' => true</code> through your argument array.</p>\n\n<pre><code>$args = array(\n 'post_type' => 'post',\n 'cat' => 1,\n 'orderby' => 'rand',\n 'posts_per_page' => 3,\n 'ignore_sticky_posts' => true\n);\n</code></pre>\n\n<p><code>'ignore_sticky_posts'</code>, somewhat inexplicably from my perspective, defaults to <code>false</code> meaning that sticky posts always get shuffled to the top unless an argument is explicitly passed to the query. That is backwards to me, but so it is. At any rate, if you have a lot of sticky posts that could explain why you are seeing the same few things over and over.</p>\n"
},
{
"answer_id": 191009,
"author": "ScottG",
"author_id": 62518,
"author_profile": "https://wordpress.stackexchange.com/users/62518",
"pm_score": 1,
"selected": false,
"text": "<p>I wanted to point out that sometimes in the case of random it's not the code at all, if you're using a host that does auto cache or are using a cache plugin, it's possible the page or the query itself is getting cached and therefor the same results will show.</p>\n\n<p>Fixes for this issue would be to have the host or the plugin turn off caching completely on the page that has the query.</p>\n"
}
] |
2015/06/09
|
[
"https://wordpress.stackexchange.com/questions/190967",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/9442/"
] |
I use a random wp\_query to load 3 posts from over 600 posts in total with this query.
```
<?php
$args = array(
'post_type' => 'post',
'cat' => 1,
'orderby' => 'rand',
'posts_per_page' => 3
);
$all_posts = new WP_Query( $args );
while ( $all_posts->have_posts() ) : $all_posts->the_post();
get_template_part( 'content' );
endwhile;
?>
<?php wp_reset_postdata(); ?>
```
Works great, but it seems for a lot of people a lot of the same images popup in the random display over and over again. So it seems the random isn't really random. At least it doesn't feel this way. Is there a way to force Wordpress to skip random displayed images and load new ones? Or is it out of my hands in this case? I can't really find an answer online.
Thanks in advance!
|
I wanted to point out that sometimes in the case of random it's not the code at all, if you're using a host that does auto cache or are using a cache plugin, it's possible the page or the query itself is getting cached and therefor the same results will show.
Fixes for this issue would be to have the host or the plugin turn off caching completely on the page that has the query.
|
190,973 |
<p>I am trying to set up a <code>wp-cli.yml</code> file but every time I run the command, the file is ignored.</p>
<p>Where should the file be located?
And how should I call the command to use it?</p>
<p>I tried having a file in the project's root directory, as well as a folder above. I have also tried using the following file names:</p>
<p><code>wp-cli.local.yml</code>,
<code>wp-cli.yml</code></p>
<p>The I tried running something like:</p>
<pre><code>wp local core download
</code></pre>
<p>But I keep getting the following error:</p>
<blockquote>
<p>Error: This does not seem to be a WordPress install.
Pass --path=<code>path/to/wordpress</code> or run <code>wp core download</code>.</p>
</blockquote>
<p><strong>PS:</strong> I am not sure wp-cli questions are off topic because I see tons of questions about wp-cli with answers, and I also see that there's a wp-cli tag. If this questions is off topic, please let me know before down voting it, and I will remove it.</p>
|
[
{
"answer_id": 190975,
"author": "Welcher",
"author_id": 27210,
"author_profile": "https://wordpress.stackexchange.com/users/27210",
"pm_score": 2,
"selected": false,
"text": "<p>According to the <a href=\"https://make.wordpress.org/cli/handbook/config/\" rel=\"nofollow noreferrer\">docs</a> wp-cli.yml should be in the working directory where you are calling <code>wp</code> commands. Inside the file you should have the path to the WordPress install relative to the file's location.</p>\n\n<p>Using <a href=\"https://github.com/Varying-Vagrant-Vagrants/VVV\" rel=\"nofollow noreferrer\">VVV</a> as an example, the file structure would have a <code>site-name</code> folder where I would call the 'WP_CLI' commands. Inside that directory is an <code>htdocs</code> folder where the WordPress files are located and the <code>wp-cli.yml</code> file that contains this:</p>\n\n<pre><code>path: htdocs\n</code></pre>\n\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 229533,
"author": "Ian Dunn",
"author_id": 3898,
"author_profile": "https://wordpress.stackexchange.com/users/3898",
"pm_score": 3,
"selected": false,
"text": "<p><strong>TL;DR</strong>:</p>\n<ol>\n<li>Run <code>wp --version --debug</code></li>\n<li>Check that <code>wp-cli.yml</code> was found</li>\n<li>Check that the <code>ABSPATH</code> set by WP-CLI matches the directory where WP is installed</li>\n<li>Look at <code>find_wp_root()</code> for hints about why it's finding the wrong folder</li>\n</ol>\n<hr />\n<p>The docs say:</p>\n<blockquote>\n<p>inside the current working directory <strong>(or upwards)</strong></p>\n</blockquote>\n<p>...so you should be able to use it in parent directories, not just in the directory where you call <code>wp</code> from. i.e., you should be able to have it several levels above the folder where Core is installed, and then call it from anywhere below the directory where <code>wp-cli.yml</code> is installed [<a href=\"https://github.com/wp-cli/wp-cli/blob/5090616a38b920f1d1b71cf8046757749503424b/php/WP_CLI/Runner.php#L91\" rel=\"nofollow noreferrer\">1</a>].</p>\n<h1>Was <code>wp-cli.yml</code> included?</h1>\n<p>You can find out by running <code>wp --version --debug</code></p>\n<ul>\n<li>Found: <code>Debug: Using project config: /var/www/example.localhost/wp-cli.yml (0.012s)</code></li>\n<li>NOT Found: <code>Debug: No project config found (0.014s)</code></li>\n</ul>\n<h1>Is WP-CLI's <code>ABSPATH</code> set correctly?</h1>\n<p><em>Note: This is the <code>ABSPATH</code> that WP-CLI defines internally, <strong>not</strong> the one from your <code>wp-config.php</code></em></p>\n<p>WP-CLI's internal <code>ABSPATH</code> is what it uses to find WordPress [<a href=\"https://github.com/wp-cli/wp-cli/blob/5090616a38b920f1d1b71cf8046757749503424b/php/WP_CLI/Runner.php#L565\" rel=\"nofollow noreferrer\">2</a>, <a href=\"https://github.com/wp-cli/wp-cli/blob/5090616a38b920f1d1b71cf8046757749503424b/php/WP_CLI/Runner.php#L553\" rel=\"nofollow noreferrer\">3</a>], so if it's wrong then you'll get the <code>This does not seem to be a WordPress install</code> error.</p>\n<p>To find out if it's wrong, you can run <code>wp --version --debug</code> from a few different directories, and look at the <code>ABSPATH</code> output. Does it match the actual path to the folder where Core is installed?</p>\n<p>Assuming the path to WP is <code>/var/www/example.localhost/web/wordpress/</code>, then:</p>\n<ul>\n<li>Correct: <code>Debug: ABSPATH defined: ABSPATH defined: /var/www/example.localhost/web/wordpress/ (0.013s)</code></li>\n<li>Incorrect: <code>Debug: ABSPATH defined: /var/www/example.localhost/web/content/plugins/akismet/wordpress/ (0.019s)</code></li>\n</ul>\n<p>Keep in mind that any arguments passed via parameters (e.g., <code>wp --path=foo</code>) will override the values in <code>wp-cli.yml</code>.</p>\n<h1>Why is <code>ABSPATH</code> wrong?</h1>\n<p>There are probably lots of different causes for it being wrong, because it depends on how your folder structure is setup, the <code>path</code> defined in <code>wp-cli.yml</code>, etc.</p>\n<p><code>ABSPATH</code> is set to the value of <code>find_wp_root()</code>[[4], [5], [6]], so that's where you need to start troubleshooting.</p>\n<p>You can read through <code>find_wp_root()</code> and mentally step through the code, looking for clues. If you have WP-CLI <a href=\"http://wp-cli.org/docs/pull-requests/\" rel=\"nofollow noreferrer\">installed via composer</a>, then you can also edit <code>Runner.php</code> to add debugging output to <code>find_wp_root()</code>, use Xdebug, etc.</p>\n<p>In my case, I had a Bash alias setup for <code>wp</code> that was passing <code>--path</code> to the command, which was overriding the <code>path</code> set in <code>wp-cli.yml</code>, but I'd forgotten about it.</p>\n<p>[4]: <a href=\"https://github.com/wp-cli/wp-cli/blob/5090616a38b920f1d1b71cf8046757749503424b/php/WP_CLI/Runner.php#L199\" rel=\"nofollow noreferrer\">https://github.com/wp-cli/wp-cli/blob/5090616a38b920f1d1b71cf8046757749503424b/php/WP_CLI/Runner.php#L199</a>)\n[5]: <a href=\"https://github.com/wp-cli/wp-cli/blob/5090616a38b920f1d1b71cf8046757749503424b/php/WP_CLI/Runner.php#L753\" rel=\"nofollow noreferrer\">https://github.com/wp-cli/wp-cli/blob/5090616a38b920f1d1b71cf8046757749503424b/php/WP_CLI/Runner.php#L753</a>)\n[6]: <a href=\"https://github.com/wp-cli/wp-cli/blob/5090616a38b920f1d1b71cf8046757749503424b/php/WP_CLI/Runner.php#L160\" rel=\"nofollow noreferrer\">https://github.com/wp-cli/wp-cli/blob/5090616a38b920f1d1b71cf8046757749503424b/php/WP_CLI/Runner.php#L160</a></p>\n"
},
{
"answer_id": 258581,
"author": "Abdalla Mohamed Aly Ibrahim",
"author_id": 110496,
"author_profile": "https://wordpress.stackexchange.com/users/110496",
"pm_score": 0,
"selected": false,
"text": "<p>with me it works with me this way </p>\n\n<pre><code>path: E:\\xampp\\htdocs\\wordpress\n</code></pre>\n\n<p>it should be added to wp-cli.yml which located at the same directory where the wp cli is installed<br>\ni use it in windows so i used full path not relative</p>\n"
}
] |
2015/06/09
|
[
"https://wordpress.stackexchange.com/questions/190973",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/30984/"
] |
I am trying to set up a `wp-cli.yml` file but every time I run the command, the file is ignored.
Where should the file be located?
And how should I call the command to use it?
I tried having a file in the project's root directory, as well as a folder above. I have also tried using the following file names:
`wp-cli.local.yml`,
`wp-cli.yml`
The I tried running something like:
```
wp local core download
```
But I keep getting the following error:
>
> Error: This does not seem to be a WordPress install.
> Pass --path=`path/to/wordpress` or run `wp core download`.
>
>
>
**PS:** I am not sure wp-cli questions are off topic because I see tons of questions about wp-cli with answers, and I also see that there's a wp-cli tag. If this questions is off topic, please let me know before down voting it, and I will remove it.
|
**TL;DR**:
1. Run `wp --version --debug`
2. Check that `wp-cli.yml` was found
3. Check that the `ABSPATH` set by WP-CLI matches the directory where WP is installed
4. Look at `find_wp_root()` for hints about why it's finding the wrong folder
---
The docs say:
>
> inside the current working directory **(or upwards)**
>
>
>
...so you should be able to use it in parent directories, not just in the directory where you call `wp` from. i.e., you should be able to have it several levels above the folder where Core is installed, and then call it from anywhere below the directory where `wp-cli.yml` is installed [[1](https://github.com/wp-cli/wp-cli/blob/5090616a38b920f1d1b71cf8046757749503424b/php/WP_CLI/Runner.php#L91)].
Was `wp-cli.yml` included?
==========================
You can find out by running `wp --version --debug`
* Found: `Debug: Using project config: /var/www/example.localhost/wp-cli.yml (0.012s)`
* NOT Found: `Debug: No project config found (0.014s)`
Is WP-CLI's `ABSPATH` set correctly?
====================================
*Note: This is the `ABSPATH` that WP-CLI defines internally, **not** the one from your `wp-config.php`*
WP-CLI's internal `ABSPATH` is what it uses to find WordPress [[2](https://github.com/wp-cli/wp-cli/blob/5090616a38b920f1d1b71cf8046757749503424b/php/WP_CLI/Runner.php#L565), [3](https://github.com/wp-cli/wp-cli/blob/5090616a38b920f1d1b71cf8046757749503424b/php/WP_CLI/Runner.php#L553)], so if it's wrong then you'll get the `This does not seem to be a WordPress install` error.
To find out if it's wrong, you can run `wp --version --debug` from a few different directories, and look at the `ABSPATH` output. Does it match the actual path to the folder where Core is installed?
Assuming the path to WP is `/var/www/example.localhost/web/wordpress/`, then:
* Correct: `Debug: ABSPATH defined: ABSPATH defined: /var/www/example.localhost/web/wordpress/ (0.013s)`
* Incorrect: `Debug: ABSPATH defined: /var/www/example.localhost/web/content/plugins/akismet/wordpress/ (0.019s)`
Keep in mind that any arguments passed via parameters (e.g., `wp --path=foo`) will override the values in `wp-cli.yml`.
Why is `ABSPATH` wrong?
=======================
There are probably lots of different causes for it being wrong, because it depends on how your folder structure is setup, the `path` defined in `wp-cli.yml`, etc.
`ABSPATH` is set to the value of `find_wp_root()`[[4], [5], [6]], so that's where you need to start troubleshooting.
You can read through `find_wp_root()` and mentally step through the code, looking for clues. If you have WP-CLI [installed via composer](http://wp-cli.org/docs/pull-requests/), then you can also edit `Runner.php` to add debugging output to `find_wp_root()`, use Xdebug, etc.
In my case, I had a Bash alias setup for `wp` that was passing `--path` to the command, which was overriding the `path` set in `wp-cli.yml`, but I'd forgotten about it.
[4]: <https://github.com/wp-cli/wp-cli/blob/5090616a38b920f1d1b71cf8046757749503424b/php/WP_CLI/Runner.php#L199>)
[5]: <https://github.com/wp-cli/wp-cli/blob/5090616a38b920f1d1b71cf8046757749503424b/php/WP_CLI/Runner.php#L753>)
[6]: <https://github.com/wp-cli/wp-cli/blob/5090616a38b920f1d1b71cf8046757749503424b/php/WP_CLI/Runner.php#L160>
|
190,993 |
<p>My ajax call for json data works ok like this
functions.php:</p>
<pre><code>add_action( 'wp_ajax_nopriv_load-filter', 'prefix_load_cat_posts' );
add_action( 'wp_ajax_load-filter', 'prefix_load_cat_posts' );
function prefix_load_cat_posts () {
//get data here
}
</code></pre>
<p>javascript:</p>
<pre><code>var ajaxurl = 'http://'+window.location.host+'/wp-admin/admin-ajax.php';
jQuery.ajax({
type: 'POST',
url: ajaxurl,
etc.
</code></pre>
<p>I have 2 questions.</p>
<p>1) Why use admin-ajax.php instead of encoding your json in a separate file like <code>themes/example/json.php</code> and encode your data there?</p>
<p>2) How does admin-ajax.php work? I don't understand much from that file. Does it load all the functions so you are ready to use them?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 191029,
"author": "sohan",
"author_id": 69017,
"author_profile": "https://wordpress.stackexchange.com/users/69017",
"pm_score": 3,
"selected": false,
"text": "<p><code>admin-ajax.php</code> is part of the WordPress <a href=\"http://codex.wordpress.org/AJAX_in_Plugins\" rel=\"noreferrer\">AJAX API</a>, and yes, it does handle requests from both backend and front.\nhere what i figure-out for your question that is: </p>\n\n<blockquote>\n <p>2) How does admin-ajax.php work?</p>\n</blockquote>\n\n<p>for the <a href=\"https://stackoverflow.com/questions/19906502/wordpress-admin-ajax-php-is-dying-0-without-processing-function\">logic</a> you can visit here.</p>\n\n<p>This assumes you already know how to enqueue JavaScript, etc.</p>\n\n<p><strong>JavaScript Piece:</strong></p>\n\n<pre><code>jQuery(document).ready(function($) {\n\n // We'll pass this variable to the PHP function example_ajax_request\n var fruit = 'Banana';\n\n // This does the ajax request\n $.ajax({\n url: ajaxurl,\n data: {\n 'action':'example_ajax_request',\n 'fruit' : fruit\n },\n success:function(data) {\n // This outputs the result of the ajax request\n console.log(data);\n },\n error: function(errorThrown){\n console.log(errorThrown);\n }\n }); \n\n});\n</code></pre>\n\n<p><strong>PHP Piece:</strong></p>\n\n<pre><code>function example_ajax_request() {\n\n // The $_REQUEST contains all the data sent via ajax \n if ( isset($_REQUEST) ) {\n\n $fruit = $_REQUEST['fruit'];\n\n // Let's take the data that was sent and do something with it\n if ( $fruit == 'Banana' ) {\n $fruit = 'Apple';\n }\n\n // Now we'll return it to the javascript function\n // Anything outputted will be returned in the response\n echo $fruit;\n\n // If you're debugging, it might be useful to see what was sent in the $_REQUEST\n // print_r($_REQUEST);\n\n }\n\n // Always die in functions echoing ajax content\n die();\n}\n\nadd_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );\n\n// If you wanted to also use the function for non-logged in users (in a theme for example)\n add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' );\n</code></pre>\n\n<blockquote>\n <p>1) Why use admin-ajax.php instead of encoding your json in a separate\n file like themes/example/json.php and encode your data there?</p>\n</blockquote>\n\n<p>may be this helpful.<a href=\"https://wordpress.stackexchange.com/questions/59289/admin-ajax-php-vs-custom-page-template-for-ajax-requests\">admin-ajax.php vs Custom Page Template for Ajax Requests</a></p>\n"
},
{
"answer_id": 191073,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 5,
"selected": true,
"text": "<blockquote>\n <p>1) Why use <code>admin-ajax.php</code> instead of encoding your json in a separate\n file like <code>themes/example/json.php</code> and encode your data there?</p>\n</blockquote>\n\n<p>Using <code>admin-ajax.php</code> means that the WordPress Core is loaded and available. WIthout that, you would need to hand load the files you need, which is a complicated process and prone to failure if you don't know the Core very, very well. And, how good are you with Javascript security? </p>\n\n<blockquote>\n <p>2) How does <code>admin-ajax.php</code> work? I don't understand much from that\n file. Does it load all the functions so you are ready to use them?</p>\n</blockquote>\n\n<ol>\n<li>It loads the WordPress Core, meaning you can use things like <code>$wpdb</code>\nand <code>$WP_Query</code>. That is through about line 25.</li>\n<li>It sends a few headers-- lines 37 - 41.<br>\n<ol>\n<li>A content type header </li>\n<li>A header to tell browsers not to cache the results </li>\n<li>The interesting headers are those sent by <a href=\"https://codex.wordpress.org/Function_Reference/send_nosniff_header\"><code>send_nosniff_headers()</code></a></li>\n<li>and <a href=\"https://codex.wordpress.org/Function_Reference/nocache_headers\"><code>nocache_headers()</code></a>.</li>\n</ol></li>\n<li>The <code>admin_init</code> hook fires.</li>\n<li>Core actions are defined and registered dynamically-- lines 46 - 73.\nThese won't be registered unless they are needed-- that is, unless\nthey are requested via <code>$_GET</code> or <code>$_POST</code>.</li>\n<li>The \"heartbeat\" API hook fires-- line 75</li>\n<li>The \"logged in\" status of the requesting user is checked and the\nappropriate administrative or \"no priviledge\" hook is fired.</li>\n</ol>\n\n<p>Items #1 and #6 are the primary reasons to use the AJAX API, in my opinion. You have the WordPress Core, which you almost certainly need, and you have the same login security system as with the rest of WordPress. </p>\n"
}
] |
2015/06/09
|
[
"https://wordpress.stackexchange.com/questions/190993",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58117/"
] |
My ajax call for json data works ok like this
functions.php:
```
add_action( 'wp_ajax_nopriv_load-filter', 'prefix_load_cat_posts' );
add_action( 'wp_ajax_load-filter', 'prefix_load_cat_posts' );
function prefix_load_cat_posts () {
//get data here
}
```
javascript:
```
var ajaxurl = 'http://'+window.location.host+'/wp-admin/admin-ajax.php';
jQuery.ajax({
type: 'POST',
url: ajaxurl,
etc.
```
I have 2 questions.
1) Why use admin-ajax.php instead of encoding your json in a separate file like `themes/example/json.php` and encode your data there?
2) How does admin-ajax.php work? I don't understand much from that file. Does it load all the functions so you are ready to use them?
Thanks!
|
>
> 1) Why use `admin-ajax.php` instead of encoding your json in a separate
> file like `themes/example/json.php` and encode your data there?
>
>
>
Using `admin-ajax.php` means that the WordPress Core is loaded and available. WIthout that, you would need to hand load the files you need, which is a complicated process and prone to failure if you don't know the Core very, very well. And, how good are you with Javascript security?
>
> 2) How does `admin-ajax.php` work? I don't understand much from that
> file. Does it load all the functions so you are ready to use them?
>
>
>
1. It loads the WordPress Core, meaning you can use things like `$wpdb`
and `$WP_Query`. That is through about line 25.
2. It sends a few headers-- lines 37 - 41.
1. A content type header
2. A header to tell browsers not to cache the results
3. The interesting headers are those sent by [`send_nosniff_headers()`](https://codex.wordpress.org/Function_Reference/send_nosniff_header)
4. and [`nocache_headers()`](https://codex.wordpress.org/Function_Reference/nocache_headers).
3. The `admin_init` hook fires.
4. Core actions are defined and registered dynamically-- lines 46 - 73.
These won't be registered unless they are needed-- that is, unless
they are requested via `$_GET` or `$_POST`.
5. The "heartbeat" API hook fires-- line 75
6. The "logged in" status of the requesting user is checked and the
appropriate administrative or "no priviledge" hook is fired.
Items #1 and #6 are the primary reasons to use the AJAX API, in my opinion. You have the WordPress Core, which you almost certainly need, and you have the same login security system as with the rest of WordPress.
|
190,999 |
<p>I'd like to auto-generate images, or rather image sizes, in old posts where the size is currently missing.</p>
<p>Specifically I'm hoping to generate sizes on the fly when a specific (old) image size is missing, but the original image is still in tact.</p>
<p><strong>Background:</strong> A while back I cleaned house with images on a site in hopes of normalizing my image sizes. Totally forgetting about the various older auto-generated images that were soft-cropped. So now there are a couple hundred old images that aren't displaying.</p>
<p><strong>Details:</strong> I did regenerate all the sizes when the house cleaning took place.</p>
|
[
{
"answer_id": 191000,
"author": "Welcher",
"author_id": 27210,
"author_profile": "https://wordpress.stackexchange.com/users/27210",
"pm_score": 1,
"selected": false,
"text": "<p>If you have access to install, or if it is available on your server I would recommend using <a href=\"http://wp-cli.org/\" rel=\"nofollow\">WP-CLI</a>. It has a command to regenerate the media:</p>\n\n<pre><code>wp media regenerate\n</code></pre>\n\n<p>If not, you can try a plugin such as <a href=\"https://wordpress.org/plugins/regenerate-thumbnails/\" rel=\"nofollow\">Regenerate Thumbnails</a></p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 232966,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 0,
"selected": false,
"text": "<p>If the images are all referred to by URLs embedded in post content, then you could just upload the missing files from an old backup.</p>\n"
}
] |
2015/06/10
|
[
"https://wordpress.stackexchange.com/questions/190999",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/28821/"
] |
I'd like to auto-generate images, or rather image sizes, in old posts where the size is currently missing.
Specifically I'm hoping to generate sizes on the fly when a specific (old) image size is missing, but the original image is still in tact.
**Background:** A while back I cleaned house with images on a site in hopes of normalizing my image sizes. Totally forgetting about the various older auto-generated images that were soft-cropped. So now there are a couple hundred old images that aren't displaying.
**Details:** I did regenerate all the sizes when the house cleaning took place.
|
If you have access to install, or if it is available on your server I would recommend using [WP-CLI](http://wp-cli.org/). It has a command to regenerate the media:
```
wp media regenerate
```
If not, you can try a plugin such as [Regenerate Thumbnails](https://wordpress.org/plugins/regenerate-thumbnails/)
Good luck!
|
191,002 |
<p>I am attempting to create a file using <code>fopen()</code> on <code>save_post</code>. I am having trouble finding the right condtionals to prevent the the file from being created from an auto save. I only want to create the file when I click publish the post. Currently the file is created when I click "add new" and when I fill in the title.</p>
<p>I have tried several combinations using <code>wp_is_post_revision()</code> and <code>wp_is_post_autosave()</code> any help would be appreciated. </p>
|
[
{
"answer_id": 191008,
"author": "josh",
"author_id": 24323,
"author_profile": "https://wordpress.stackexchange.com/users/24323",
"pm_score": 2,
"selected": false,
"text": "<p>If you are using the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/save_post\" rel=\"nofollow\">save_post</a> action hook; then you can prevent the code from executing during an autosave with the following conditional:</p>\n\n<pre><code>function do_not_autosave( $post ) {\n\n // Check to see if we are autosaving\n if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)\n return;\n\n // Rest of the code here\n}\nadd_action( 'save_post', 'do_not_autosave');\n</code></pre>\n"
},
{
"answer_id": 398538,
"author": "Α. Papadakis",
"author_id": 159305,
"author_profile": "https://wordpress.stackexchange.com/users/159305",
"pm_score": 1,
"selected": false,
"text": "<p>Although it's an old answer, you should check the post status, when you create a post (before starting editing), it has post status <strong>auto-draft</strong>.</p>\n<p>So the code should be:</p>\n<pre><code>function my_theme_name_save_post_callback($post_id, $post) { \n if ( !wp_is_post_autosave( $post ) && $post->post_status !== 'auto-draft' && \n !wp_is_post_revision( $post_id ) ) {\n\n /* your code here */\n\n }\n}\nadd_action('save_post', 'my_theme_name_save_post_callback', 10, 3);\n</code></pre>\n<p>Replace "my_theme_name" prefix with your theme name (slug), as a best practice.\n<a href=\"https://developer.wordpress.org/plugins/plugin-basics/best-practices/#prefix-everything\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/plugins/plugin-basics/best-practices/#prefix-everything</a></p>\n"
}
] |
2015/06/10
|
[
"https://wordpress.stackexchange.com/questions/191002",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/35351/"
] |
I am attempting to create a file using `fopen()` on `save_post`. I am having trouble finding the right condtionals to prevent the the file from being created from an auto save. I only want to create the file when I click publish the post. Currently the file is created when I click "add new" and when I fill in the title.
I have tried several combinations using `wp_is_post_revision()` and `wp_is_post_autosave()` any help would be appreciated.
|
If you are using the [save\_post](https://codex.wordpress.org/Plugin_API/Action_Reference/save_post) action hook; then you can prevent the code from executing during an autosave with the following conditional:
```
function do_not_autosave( $post ) {
// Check to see if we are autosaving
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return;
// Rest of the code here
}
add_action( 'save_post', 'do_not_autosave');
```
|
191,003 |
<p>I use a plugin that creates a custom post type with a slug that I am wanting to change. I don't want to overwrite the plugin files, so I'm wondering how I can change the slug using a separate function? Thanks.</p>
<pre><code>// Register post type
add_action( 'init', 'ctc_register_post_type_item' );
function ctc_register_post_type_item() {
// Arguments
$args = array(
'labels' => array(
'name' => _x( 'items', 'post type general name', 'church-theme-content' ),
'singular_name' => _x( 'item', 'post type singular name', 'church-theme-content' ),
'add_new' => _x( 'Add New', 'item', 'church-theme-content' ),
'add_new_item' => __( 'Add Item', 'church-theme-content' ),
'edit_item' => __( 'Edit Item', 'church-theme-content' ),
'new_item' => __( 'New Item', 'church-theme-content' ),
'all_items' => __( 'All Items', 'church-theme-content' ),
'view_item' => __( 'View Item', 'church-theme-content' ),
'search_items' => __( 'Search Items', 'church-theme-content' ),
'not_found' => __( 'No items found', 'church-theme-content' ),
'not_found_in_trash' => __( 'No items found in Trash', 'church-theme-content' )
),
'public' => ctc_feature_supported( 'items' ),
'has_archive' => ctc_feature_supported( 'items' ),
'rewrite' => array(
'slug' => 'items',
'with_front' => false,
'feeds' => ctc_feature_supported( 'items' )
),
'supports' => array( 'title', 'editor', 'excerpt', 'publicize', 'thumbnail', 'comments', 'author', 'revisions' ), // 'editor' required for media upload button (see Meta Boxes note below about hiding)
'taxonomies' => array( 'ctc_item_topic', 'ctc_item_book', 'ctc_item_series', 'ctc_item_speaker', 'ctc_item_tag' ),
'menu_icon' => 'dashicons-video-alt3'
);
$args = apply_filters( 'ctc_post_type_item_args', $args ); // allow filtering
// Registration
register_post_type(
'ctc_item',
$args
);
}
</code></pre>
|
[
{
"answer_id": 191014,
"author": "Evan Yeung",
"author_id": 1878,
"author_profile": "https://wordpress.stackexchange.com/users/1878",
"pm_score": 0,
"selected": false,
"text": "<p>Take a look at <a href=\"https://wordpress.stackexchange.com/a/42164/1878\">Tom's answer</a> on a similar question. He hooks into an action that adds a rewrite rule to the database so the post is accessible through both slugs. He was not actually able to redeclare the slug, but he shows how you can hide the old slug so that it appears the new one is the right one.</p>\n\n<p>Another <a href=\"https://wordpress.stackexchange.com/questions/41988/redeclare-change-slug-of-a-plugins-custom-post-type#comment129915_41988\">option suggested by Dustin</a> is to call <code>register_post_type</code> with the same $post_type but set the slug to the one you want. It sees to work for him, but no one else has confirmed if it throws problems down the line.</p>\n"
},
{
"answer_id": 261690,
"author": "JHoffmann",
"author_id": 63847,
"author_profile": "https://wordpress.stackexchange.com/users/63847",
"pm_score": 2,
"selected": false,
"text": "<p>In the code you posted, the filter <code>ctc_post_type_item_args</code> gets applied to the <code>$args</code> array before it is passed into <code>register_post_type()</code>.</p>\n\n<p>Putting a function into your themes <code>functions.php</code> and hooking it to the filter should do the trick:</p>\n\n<pre><code>function wpse_191003_ctc_post_type_item_args( $args ) {\n $args['rewrite']['slug'] = \"your_new_slug\";\n return $args;\n}\nadd_filter( 'ctc_post_type_item_args', 'wpse_191003_ctc_post_type_item_args' );\n</code></pre>\n"
}
] |
2015/06/10
|
[
"https://wordpress.stackexchange.com/questions/191003",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74448/"
] |
I use a plugin that creates a custom post type with a slug that I am wanting to change. I don't want to overwrite the plugin files, so I'm wondering how I can change the slug using a separate function? Thanks.
```
// Register post type
add_action( 'init', 'ctc_register_post_type_item' );
function ctc_register_post_type_item() {
// Arguments
$args = array(
'labels' => array(
'name' => _x( 'items', 'post type general name', 'church-theme-content' ),
'singular_name' => _x( 'item', 'post type singular name', 'church-theme-content' ),
'add_new' => _x( 'Add New', 'item', 'church-theme-content' ),
'add_new_item' => __( 'Add Item', 'church-theme-content' ),
'edit_item' => __( 'Edit Item', 'church-theme-content' ),
'new_item' => __( 'New Item', 'church-theme-content' ),
'all_items' => __( 'All Items', 'church-theme-content' ),
'view_item' => __( 'View Item', 'church-theme-content' ),
'search_items' => __( 'Search Items', 'church-theme-content' ),
'not_found' => __( 'No items found', 'church-theme-content' ),
'not_found_in_trash' => __( 'No items found in Trash', 'church-theme-content' )
),
'public' => ctc_feature_supported( 'items' ),
'has_archive' => ctc_feature_supported( 'items' ),
'rewrite' => array(
'slug' => 'items',
'with_front' => false,
'feeds' => ctc_feature_supported( 'items' )
),
'supports' => array( 'title', 'editor', 'excerpt', 'publicize', 'thumbnail', 'comments', 'author', 'revisions' ), // 'editor' required for media upload button (see Meta Boxes note below about hiding)
'taxonomies' => array( 'ctc_item_topic', 'ctc_item_book', 'ctc_item_series', 'ctc_item_speaker', 'ctc_item_tag' ),
'menu_icon' => 'dashicons-video-alt3'
);
$args = apply_filters( 'ctc_post_type_item_args', $args ); // allow filtering
// Registration
register_post_type(
'ctc_item',
$args
);
}
```
|
In the code you posted, the filter `ctc_post_type_item_args` gets applied to the `$args` array before it is passed into `register_post_type()`.
Putting a function into your themes `functions.php` and hooking it to the filter should do the trick:
```
function wpse_191003_ctc_post_type_item_args( $args ) {
$args['rewrite']['slug'] = "your_new_slug";
return $args;
}
add_filter( 'ctc_post_type_item_args', 'wpse_191003_ctc_post_type_item_args' );
```
|
191,035 |
<p>I would like to password protect a page on my blog. Wordpress allows me to give one single password to each protected page. Is there a way to create more than one valid password to access that page?</p>
|
[
{
"answer_id": 191014,
"author": "Evan Yeung",
"author_id": 1878,
"author_profile": "https://wordpress.stackexchange.com/users/1878",
"pm_score": 0,
"selected": false,
"text": "<p>Take a look at <a href=\"https://wordpress.stackexchange.com/a/42164/1878\">Tom's answer</a> on a similar question. He hooks into an action that adds a rewrite rule to the database so the post is accessible through both slugs. He was not actually able to redeclare the slug, but he shows how you can hide the old slug so that it appears the new one is the right one.</p>\n\n<p>Another <a href=\"https://wordpress.stackexchange.com/questions/41988/redeclare-change-slug-of-a-plugins-custom-post-type#comment129915_41988\">option suggested by Dustin</a> is to call <code>register_post_type</code> with the same $post_type but set the slug to the one you want. It sees to work for him, but no one else has confirmed if it throws problems down the line.</p>\n"
},
{
"answer_id": 261690,
"author": "JHoffmann",
"author_id": 63847,
"author_profile": "https://wordpress.stackexchange.com/users/63847",
"pm_score": 2,
"selected": false,
"text": "<p>In the code you posted, the filter <code>ctc_post_type_item_args</code> gets applied to the <code>$args</code> array before it is passed into <code>register_post_type()</code>.</p>\n\n<p>Putting a function into your themes <code>functions.php</code> and hooking it to the filter should do the trick:</p>\n\n<pre><code>function wpse_191003_ctc_post_type_item_args( $args ) {\n $args['rewrite']['slug'] = \"your_new_slug\";\n return $args;\n}\nadd_filter( 'ctc_post_type_item_args', 'wpse_191003_ctc_post_type_item_args' );\n</code></pre>\n"
}
] |
2015/06/10
|
[
"https://wordpress.stackexchange.com/questions/191035",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58599/"
] |
I would like to password protect a page on my blog. Wordpress allows me to give one single password to each protected page. Is there a way to create more than one valid password to access that page?
|
In the code you posted, the filter `ctc_post_type_item_args` gets applied to the `$args` array before it is passed into `register_post_type()`.
Putting a function into your themes `functions.php` and hooking it to the filter should do the trick:
```
function wpse_191003_ctc_post_type_item_args( $args ) {
$args['rewrite']['slug'] = "your_new_slug";
return $args;
}
add_filter( 'ctc_post_type_item_args', 'wpse_191003_ctc_post_type_item_args' );
```
|
191,045 |
<p>I have created a shortcode that retrives and displays a form.The content of the attribute in HTML. </p>
<pre><code>function check_my_login( $atts)
{
return '<form action="" name="" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="description">Project Description</label>
<textarea name="p_description" placeholder="Project Description" class="form-control"><?php if (isset($_POST['p_description']) && $_POST['p_description'] != '') echo $_POST['p_description'] ?></textarea>
</div>
<div class="form-group">
<label>Project Attachment</label>
<input type="file" name="p_attachment">
</div>
</form>';
}
add_shortcode( 'kentaUser', 'check_my_login' );
</code></pre>
<p>Now use this shortcode inside the Post/page. </p>
<p>Like this </p>
<pre><code> <div class='manage_page'>[kentaUser]</div>
But my shortcode content display out side the div.Display upper side in post/page content.
<div class='manage_page'></div>
</code></pre>
<p>Any one short out this problem.</p>
|
[
{
"answer_id": 191059,
"author": "David Labbe",
"author_id": 38434,
"author_profile": "https://wordpress.stackexchange.com/users/38434",
"pm_score": 3,
"selected": true,
"text": "<p>Use this instead:</p>\n\n<p>Concatenate the html then return it.</p>\n\n<pre><code>function check_my_login( $atts)\n{\n\n $html = '<form action=\"\" name=\"\" method=\"post\" enctype=\"multipart/form-data\">';\n $html .= '<div class=\"form-group\">';\n $html .= '<label for=\"description\">Project Description</label>';\n $html .= '<textarea name=\"p_description\" placeholder=\"Project Description\" class=\"form-control\">';\n\n if(isset($_POST['p_description']) && $_POST['p_description'] != ''){\n $html .= $_POST['p_description'];\n }\n\n $html .= '</textarea>';\n $html .= '</div>';\n $html .= '<div class=\"form-group\">';\n $html .= '<label>Project Attachment</label>';\n $html .= '<input type=\"file\" name=\"p_attachment\">';\n $html .= '</div>';\n $html .= '</form>';\n\n return $html;\n}\n\n add_shortcode( 'kentaUser', 'check_my_login' );\n</code></pre>\n"
},
{
"answer_id": 287791,
"author": "mfgmicha",
"author_id": 43174,
"author_profile": "https://wordpress.stackexchange.com/users/43174",
"pm_score": 1,
"selected": false,
"text": "<p>If you like me come to this answer because you get this error when using <strong>template parts</strong> in your <strong>shortcode</strong>, then I like more the answer from WordPress Core Developer <a href=\"https://konstantin.blog/2013/get_template_part-within-shortcodes/\" rel=\"nofollow noreferrer\">Konstantin Kovshenin</a> to buffer the output:</p>\n\n<p>In your shortcode function:</p>\n\n<pre><code>// start buffer\nob_start();\n\n// call template (with html output)\nget_template_part( '/path/to/template/file' );\n\n// return buffered output\nreturn ob_get_clean();\n</code></pre>\n"
}
] |
2015/06/10
|
[
"https://wordpress.stackexchange.com/questions/191045",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68882/"
] |
I have created a shortcode that retrives and displays a form.The content of the attribute in HTML.
```
function check_my_login( $atts)
{
return '<form action="" name="" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="description">Project Description</label>
<textarea name="p_description" placeholder="Project Description" class="form-control"><?php if (isset($_POST['p_description']) && $_POST['p_description'] != '') echo $_POST['p_description'] ?></textarea>
</div>
<div class="form-group">
<label>Project Attachment</label>
<input type="file" name="p_attachment">
</div>
</form>';
}
add_shortcode( 'kentaUser', 'check_my_login' );
```
Now use this shortcode inside the Post/page.
Like this
```
<div class='manage_page'>[kentaUser]</div>
But my shortcode content display out side the div.Display upper side in post/page content.
<div class='manage_page'></div>
```
Any one short out this problem.
|
Use this instead:
Concatenate the html then return it.
```
function check_my_login( $atts)
{
$html = '<form action="" name="" method="post" enctype="multipart/form-data">';
$html .= '<div class="form-group">';
$html .= '<label for="description">Project Description</label>';
$html .= '<textarea name="p_description" placeholder="Project Description" class="form-control">';
if(isset($_POST['p_description']) && $_POST['p_description'] != ''){
$html .= $_POST['p_description'];
}
$html .= '</textarea>';
$html .= '</div>';
$html .= '<div class="form-group">';
$html .= '<label>Project Attachment</label>';
$html .= '<input type="file" name="p_attachment">';
$html .= '</div>';
$html .= '</form>';
return $html;
}
add_shortcode( 'kentaUser', 'check_my_login' );
```
|
191,061 |
<p>For my theme development purposes I have a local WordPress installation that I run from a VM, accessed via, let's say, <code>http://local.app</code>. I also have a remote version of the site on a staging server, <code>http://staging.example.com</code>. </p>
<p>The staging site contains all the content that I design the theme around (i.e posts, pages, WooCommerce products etc).</p>
<p>All of this is in the MySQL database on the server as well as media (images, files etc) in <code>wp-content/uploads</code>.</p>
<p>Now, via the useful guide <a href="http://codex.wordpress.org/Running_a_Development_Copy_of_WordPress#Two_WordPresses.2C_One_Database">on the Codex</a> entitled "Two WordPresses, One Database" I have this mostly working, with a local copy of the theme, plugins and wordpress core on my vm, getting all its data from the remote staging server.</p>
<p>The only problem is that all media is getting 404 as for some reason all urls to the media files are linking to my local vm rather than the staging server. E.g. If I visit the media library and go to the "edit media" page, the "file url" reads as follows:</p>
<ul>
<li>On the staging server: <code>http://staging.example.com/wp-content/uploads/2015/04/greigh.jpg</code></li>
<li>On my local vm: <code>http://local.app/wp-content/uploads/2015/04/greigh.jpg</code></li>
</ul>
<p>When inspecting the database all <code>attachment</code> post types have guids with full urls, not relative. So how is WordPress building these urls, and is there a way to solve this without having to duplicate the entire media library onto my VM?</p>
|
[
{
"answer_id": 238412,
"author": "Kat",
"author_id": 58601,
"author_profile": "https://wordpress.stackexchange.com/users/58601",
"pm_score": 2,
"selected": false,
"text": "<p>Somewhere in the core, URLs get absolutely pathed when put into the database. </p>\n\n<p>Why don't you just load all your images from your staging server? Have the staging server hold the files while your local mirrors it. Add the following to your <code>.htaccess</code> to your local uploads folder and the contents are as follows:</p>\n\n<pre><code># Attempt to load files from production if they're not in our local version\n<IfModule mod_rewrite.c>\n RewriteEngine on\n RewriteCond %{REQUEST_FILENAME} !-d\n RewriteCond %{REQUEST_FILENAME} !-f\n # Replace http://example.com with your production site's domain name\n RewriteRule (.*) http://example.com/wp-content/uploads/$1\n</IfModule>\n</code></pre>\n"
},
{
"answer_id": 244757,
"author": "brothman01",
"author_id": 104630,
"author_profile": "https://wordpress.stackexchange.com/users/104630",
"pm_score": -1,
"selected": false,
"text": "<p>do a database search and replace where 'local.app' is changed to 'staging.example.com'</p>\n"
},
{
"answer_id": 254723,
"author": "DanielV",
"author_id": 27863,
"author_profile": "https://wordpress.stackexchange.com/users/27863",
"pm_score": 0,
"selected": false,
"text": "<p>For latecomers, if your development environment is LEMP, for your nginx (default) site this would go in your main server declaration to redirect most image 404 errors:</p>\n\n<pre><code> # Directives to send expires headers and turn off 404 error logging. Try images from production server\n location ~* \\.(png|jpe?g|gif|ico)$ {\n expires 24h;\n log_not_found off;\n try_files $uri $uri/ @production;\n }\n\n location @production {\n resolver 8.8.8.8;\n proxy_pass http://Production-or-StagingServerURL.com/$uri;\n }\n</code></pre>\n\n<p>Add other resource extensions ie: svg, to the location 'array' to cover other types of 404 resource errors.</p>\n\n<p>Or see this answer for another option:\n<a href=\"https://wordpress.stackexchange.com/questions/210899/how-to-configure-nginx-to-redirect-requests-to-the-uploads-directory-to-the-prod\">How to configure nginx to redirect requests to the uploads directory to the production server?</a> </p>\n"
},
{
"answer_id": 358026,
"author": "Nuno Sarmento",
"author_id": 75461,
"author_profile": "https://wordpress.stackexchange.com/users/75461",
"pm_score": 0,
"selected": false,
"text": "<p>Of course, you’ll need to replace www.example.com with your own site address but putting this above the WordPress rules in your .htaccess file will mean that any file on the production site will be displayed on the dev site, no questions asked, no files downloaded.</p>\n\n<pre><code>RewriteEngine On\nRewriteBase /\nRewriteRule ^wp-content/uploads(.*)$ http://www.example.com/wp-content/uploads/$1 [L,R]\n</code></pre>\n"
}
] |
2015/06/10
|
[
"https://wordpress.stackexchange.com/questions/191061",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/23620/"
] |
For my theme development purposes I have a local WordPress installation that I run from a VM, accessed via, let's say, `http://local.app`. I also have a remote version of the site on a staging server, `http://staging.example.com`.
The staging site contains all the content that I design the theme around (i.e posts, pages, WooCommerce products etc).
All of this is in the MySQL database on the server as well as media (images, files etc) in `wp-content/uploads`.
Now, via the useful guide [on the Codex](http://codex.wordpress.org/Running_a_Development_Copy_of_WordPress#Two_WordPresses.2C_One_Database) entitled "Two WordPresses, One Database" I have this mostly working, with a local copy of the theme, plugins and wordpress core on my vm, getting all its data from the remote staging server.
The only problem is that all media is getting 404 as for some reason all urls to the media files are linking to my local vm rather than the staging server. E.g. If I visit the media library and go to the "edit media" page, the "file url" reads as follows:
* On the staging server: `http://staging.example.com/wp-content/uploads/2015/04/greigh.jpg`
* On my local vm: `http://local.app/wp-content/uploads/2015/04/greigh.jpg`
When inspecting the database all `attachment` post types have guids with full urls, not relative. So how is WordPress building these urls, and is there a way to solve this without having to duplicate the entire media library onto my VM?
|
Somewhere in the core, URLs get absolutely pathed when put into the database.
Why don't you just load all your images from your staging server? Have the staging server hold the files while your local mirrors it. Add the following to your `.htaccess` to your local uploads folder and the contents are as follows:
```
# Attempt to load files from production if they're not in our local version
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
# Replace http://example.com with your production site's domain name
RewriteRule (.*) http://example.com/wp-content/uploads/$1
</IfModule>
```
|
191,081 |
<p>If a logged-out user visits a page, and then revisit it when logged-in, it will show the cached version. There's a <a href="https://wordpress.stackexchange.com/questions/112640/how-to-force-content-refresh-of-a-page-that-has-been-loaded-previously-by-the-us">closed question</a> similar to this with an answer that suggests to set Cache Control to <code>no-cache</code>. This will affect <strong>logged-out</strong> users, which defeats the purpose of caching in the first place.</p>
<h2>The problem</h2>
<p>When using page/browser caching with <a href="https://wordpress.org/plugins/w3-total-cache/" rel="nofollow noreferrer">T3 Total Cache</a> or likely other caching plugins, if you have already visited a page when logged out, you will be presented with the same logged-out version of the page, unless if you refresh the page. </p>
<p>You can reproduce this issue by:</p>
<ol>
<li><p>Have caching enabled. Then, in incognito mode, visit a post. </p></li>
<li><p>Login to the site and then manually type the URL of that post into the address bar. The logged-out version of the page should appear.</p></li>
</ol>
<p>This is obviously an issue you have any features available for logged-in users only (like comments, voting etc)...</p>
<h2>Potential solution</h2>
<p>The only potential solution I have is to add a query variable to the URL on every request. For example by adding a random value:</p>
<pre><code>$key = rand();
$new_url = esc_url( add_query_arg( 'foo', $key ) );
</code></pre>
<p>I know how to manually add this variable to single queries but instead of altering every single instant of links, is there a way how to force this to every URL for logged-in users?</p>
<p><strong>Note:</strong> I'm not sure if this is the ideal approach to solve this problem (it feels quite desperate) so feel free to post an answer with a better solution. </p>
|
[
{
"answer_id": 192546,
"author": "E. Serrano",
"author_id": 41259,
"author_profile": "https://wordpress.stackexchange.com/users/41259",
"pm_score": 2,
"selected": false,
"text": "<p>Since you already have the \"Don't cache pages for logged in users\" option activated, what about selecting <code>cache with validation</code> under <code>Cache Control Policy</code> for \"HTML\" content?</p>\n\n<p>Explanation: Essentially, the \"don't cache pages for logged in users\" option should already be sending a <code>no-cache</code> header for your logged users only.</p>\n\n<p>If a user has a cached page in its browser (as a non-logged user) and then tries to access the same page when logged in, the <code>cache with validation</code> option inside your \"Cache Control Policy\" setting for HTML contents should be sending the <code>must-revalidate</code> tag. </p>\n\n<p>Hence, a logged in user would send <code>no-cache,must-revalidate</code>, always requesting a fresh page.</p>\n\n<p>This is pretty much what @gmazzap explained with headers - but from a W3 Total Cache configuration perspective.</p>\n"
},
{
"answer_id": 401951,
"author": "dsmith63",
"author_id": 218526,
"author_profile": "https://wordpress.stackexchange.com/users/218526",
"pm_score": 0,
"selected": false,
"text": "<p>From my tests, "Don't cache pages for logged in users" only works with the "basic" disk caching type in W3 Total Cache. Assuming that's true, the only approaches I can think of are to switch the page cache type to Disk: Basic and either enable the "Don't cache for logged in users" setting or use Page Fragments:</p>\n<ul>\n<li><a href=\"https://github.com/W3EDGE/w3-total-cache/wiki/FAQ:-Developers#what-is-page-fragment-cache\" rel=\"nofollow noreferrer\">https://github.com/W3EDGE/w3-total-cache/wiki/FAQ:-Developers#what-is-page-fragment-cache</a></li>\n<li><a href=\"https://www.boldgrid.com/support/w3-total-cache/how-to-implement-page-fragment-caching-exception-in-w3-total-cache/\" rel=\"nofollow noreferrer\">https://www.boldgrid.com/support/w3-total-cache/how-to-implement-page-fragment-caching-exception-in-w3-total-cache/</a></li>\n</ul>\n<p>Because I'm using a shared host, I can't change the disk caching method. I've elected to redo many of my pages to ajax to pull in data that needs to be dynamically loaded. This approach has the benefit of quick page loads but will obviously involve more development. Hope that helps.</p>\n"
}
] |
2015/06/10
|
[
"https://wordpress.stackexchange.com/questions/191081",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/24875/"
] |
If a logged-out user visits a page, and then revisit it when logged-in, it will show the cached version. There's a [closed question](https://wordpress.stackexchange.com/questions/112640/how-to-force-content-refresh-of-a-page-that-has-been-loaded-previously-by-the-us) similar to this with an answer that suggests to set Cache Control to `no-cache`. This will affect **logged-out** users, which defeats the purpose of caching in the first place.
The problem
-----------
When using page/browser caching with [T3 Total Cache](https://wordpress.org/plugins/w3-total-cache/) or likely other caching plugins, if you have already visited a page when logged out, you will be presented with the same logged-out version of the page, unless if you refresh the page.
You can reproduce this issue by:
1. Have caching enabled. Then, in incognito mode, visit a post.
2. Login to the site and then manually type the URL of that post into the address bar. The logged-out version of the page should appear.
This is obviously an issue you have any features available for logged-in users only (like comments, voting etc)...
Potential solution
------------------
The only potential solution I have is to add a query variable to the URL on every request. For example by adding a random value:
```
$key = rand();
$new_url = esc_url( add_query_arg( 'foo', $key ) );
```
I know how to manually add this variable to single queries but instead of altering every single instant of links, is there a way how to force this to every URL for logged-in users?
**Note:** I'm not sure if this is the ideal approach to solve this problem (it feels quite desperate) so feel free to post an answer with a better solution.
|
Since you already have the "Don't cache pages for logged in users" option activated, what about selecting `cache with validation` under `Cache Control Policy` for "HTML" content?
Explanation: Essentially, the "don't cache pages for logged in users" option should already be sending a `no-cache` header for your logged users only.
If a user has a cached page in its browser (as a non-logged user) and then tries to access the same page when logged in, the `cache with validation` option inside your "Cache Control Policy" setting for HTML contents should be sending the `must-revalidate` tag.
Hence, a logged in user would send `no-cache,must-revalidate`, always requesting a fresh page.
This is pretty much what @gmazzap explained with headers - but from a W3 Total Cache configuration perspective.
|
191,083 |
<p>The <a href="https://codex.wordpress.org/Function_Reference/get_post_meta" rel="nofollow">documentation</a> from <code>get_post_meta</code> makes it sound as if the <code>single</code> argument will determine whether or not meta values are returned in an array or not. For example:</p>
<pre><code>// If I set single to false, or leave it blank it's returned as an array
[my-meta] => Array
(
[0] => my-value
)
// If I set single to true, it's returned as a string
[my-meta] = my-value
</code></pre>
<p>This works fine if I'm only returning data for a single meta key...but fails if I want to return all of the meta data, but return them all as strings (single).</p>
<p>It would seem that the proper call to get all of the meta values with string values would be:</p>
<pre><code>$meta = get_post_meta( $transaction->ID, false, true );
</code></pre>
<p>But this returns with the array values and completely ignores the <code>single</code> value.</p>
<p>Why? Is there a way to get all of the meta data, but without the single element arrays? Those are unnecessary in my case.</p>
<p>EDIT: Just to clarify what I'm asking, I'd lie to get all of the meta like this:</p>
<pre><code>array() {
[my-meta-1] = my-value
[my-meta-2] = my-value
[my-meta-3] = my-value
[my-meta-4] = my-value
}
</code></pre>
<p>Rather than like this (which is the only behavior I seem to be able to get):</p>
<pre><code>array() {
[my-meta-1] => Array
(
[0] => my-value
)
[my-meta-2] => Array
(
[0] => my-value
)
[my-meta-3] => Array
(
[0] => my-value
)
[my-meta-4] => Array
(
[0] => my-value
)
}
</code></pre>
|
[
{
"answer_id": 191086,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>This works fine if I'm only returning data for a single meta key...but\n fails if I want to return all of the meta data, but return them all as\n strings (single).</p>\n</blockquote>\n\n<p>This doesn't make a lot of sense. A function in PHP can only return a single value so there is no way to return <em>all</em> meta as <em>strings</em> (plural). It has to come out as an array, or an object. And that is what the function does-- you get a single value as a string or you get an array. If you don't specify a key then the code has no way to know which key you want so you get them all, by defaurl <strong><em>not</em></strong> single. When you are not retrieving single values, WordPress does not collapse the nested array. If that is what you want, take it up with the Core developers on Trac. In the meantime, collapse the array yourself:</p>\n\n<pre><code>$meta = get_post_meta(350);\nvar_dump($meta);\nforeach ($meta as $k => $v) {\n $meta[$k] = array_shift($v);\n}\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>foreach ($meta as &$v) {\n $v = array_shift($v);\n}\n</code></pre>\n\n<p>That may not bet he answer you hoped for, but I am pretty sure it is accurate. There might be a filter, but I doubt the effort would be worth it.</p>\n"
},
{
"answer_id": 214399,
"author": "Armstrongest",
"author_id": 37479,
"author_profile": "https://wordpress.stackexchange.com/users/37479",
"pm_score": 2,
"selected": false,
"text": "<p>A short little function, perhaps:</p>\n\n<pre><code>function get_post_meta_single( $id ) {\n $m = get_post_meta( $id, false, true ); // get post meta as singles\n foreach( $m as &$v ) $v = array_shift($v); // collapse value array\n return $m;\n}\n</code></pre>\n\n<p>As a side note, it's likely that the reason that WordPress doesn't collapse the array is to maintain consistency, so the same code can be reused for items with multiple values and single values. WordPress is all about the loop, remember. </p>\n"
}
] |
2015/06/10
|
[
"https://wordpress.stackexchange.com/questions/191083",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48162/"
] |
The [documentation](https://codex.wordpress.org/Function_Reference/get_post_meta) from `get_post_meta` makes it sound as if the `single` argument will determine whether or not meta values are returned in an array or not. For example:
```
// If I set single to false, or leave it blank it's returned as an array
[my-meta] => Array
(
[0] => my-value
)
// If I set single to true, it's returned as a string
[my-meta] = my-value
```
This works fine if I'm only returning data for a single meta key...but fails if I want to return all of the meta data, but return them all as strings (single).
It would seem that the proper call to get all of the meta values with string values would be:
```
$meta = get_post_meta( $transaction->ID, false, true );
```
But this returns with the array values and completely ignores the `single` value.
Why? Is there a way to get all of the meta data, but without the single element arrays? Those are unnecessary in my case.
EDIT: Just to clarify what I'm asking, I'd lie to get all of the meta like this:
```
array() {
[my-meta-1] = my-value
[my-meta-2] = my-value
[my-meta-3] = my-value
[my-meta-4] = my-value
}
```
Rather than like this (which is the only behavior I seem to be able to get):
```
array() {
[my-meta-1] => Array
(
[0] => my-value
)
[my-meta-2] => Array
(
[0] => my-value
)
[my-meta-3] => Array
(
[0] => my-value
)
[my-meta-4] => Array
(
[0] => my-value
)
}
```
|
>
> This works fine if I'm only returning data for a single meta key...but
> fails if I want to return all of the meta data, but return them all as
> strings (single).
>
>
>
This doesn't make a lot of sense. A function in PHP can only return a single value so there is no way to return *all* meta as *strings* (plural). It has to come out as an array, or an object. And that is what the function does-- you get a single value as a string or you get an array. If you don't specify a key then the code has no way to know which key you want so you get them all, by defaurl ***not*** single. When you are not retrieving single values, WordPress does not collapse the nested array. If that is what you want, take it up with the Core developers on Trac. In the meantime, collapse the array yourself:
```
$meta = get_post_meta(350);
var_dump($meta);
foreach ($meta as $k => $v) {
$meta[$k] = array_shift($v);
}
```
Or:
```
foreach ($meta as &$v) {
$v = array_shift($v);
}
```
That may not bet he answer you hoped for, but I am pretty sure it is accurate. There might be a filter, but I doubt the effort would be worth it.
|
191,101 |
<p>I'm looking for a way to move the "Visit Site" link from drop-down and add it to the main toolbar, just like in the image shown below:</p>
<p><a href="https://i.stack.imgur.com/04mLP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/04mLP.png" alt="enter image description here"></a></p>
|
[
{
"answer_id": 191108,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 4,
"selected": true,
"text": "<p>Not complicated, but a little tricky to get timing right.</p>\n\n<p>Something like this should work, but you might need to experiment with priority to get the link to specific position on the bar:</p>\n\n<pre><code>add_action( 'admin_bar_menu', function ( $wp_admin_bar ) {\n\n if ( ! is_admin() ) {\n return;\n }\n\n /** @var WP_Admin_Bar $wp_admin_bar */\n $wp_admin_bar->remove_node( 'view-site' );\n\n $wp_admin_bar->add_menu( array(\n 'id' => 'view-site',\n 'title' => __( 'Visit Site' ),\n 'href' => home_url( '/' ),\n ) );\n}, 31 ); // After `wp_admin_bar_site_menu()` at 30.\n</code></pre>\n"
},
{
"answer_id": 191110,
"author": "Gabriel",
"author_id": 54569,
"author_profile": "https://wordpress.stackexchange.com/users/54569",
"pm_score": 3,
"selected": false,
"text": "<p>Add this to your theme's <code>functions.php</code>:</p>\n\n<pre><code>add_action( 'admin_bar_menu', 'make_parent_node', 999 );\nfunction make_parent_node( $wp_admin_bar ) {\n if ( ! is_admin() ) { return; } // end function if not in admin back-end, credit @Rarst\n $args = array(\n 'id' => 'view-site', // id of the existing child node (View Site)\n 'title' => 'Visit Site', // alter the title of existing node (optional)\n 'parent' => false // set parent to false to make it a top level (parent) node\n );\n $wp_admin_bar->add_node( $args );\n}\n</code></pre>\n\n<p>This will move the \"View Site\" to just right of the Dashboard drop-down. For more information, see the <a href=\"https://codex.wordpress.org/Function_Reference/add_node\">Codex</a>; the code above is from the \"Make an Existing Child Node a Parent Node\" section. </p>\n"
}
] |
2015/06/10
|
[
"https://wordpress.stackexchange.com/questions/191101",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74500/"
] |
I'm looking for a way to move the "Visit Site" link from drop-down and add it to the main toolbar, just like in the image shown below:
[](https://i.stack.imgur.com/04mLP.png)
|
Not complicated, but a little tricky to get timing right.
Something like this should work, but you might need to experiment with priority to get the link to specific position on the bar:
```
add_action( 'admin_bar_menu', function ( $wp_admin_bar ) {
if ( ! is_admin() ) {
return;
}
/** @var WP_Admin_Bar $wp_admin_bar */
$wp_admin_bar->remove_node( 'view-site' );
$wp_admin_bar->add_menu( array(
'id' => 'view-site',
'title' => __( 'Visit Site' ),
'href' => home_url( '/' ),
) );
}, 31 ); // After `wp_admin_bar_site_menu()` at 30.
```
|
191,126 |
<p>The code on the page looks like this:</p>
<pre><code>if ( ! empty( $image ) ) : ?>
<div class="headshot">
<img src="<?php echo esc_url( $image ); ?>" alt="Photo of <?php echo esc_attr( $author_name ); ?>"/>
</div>
</code></pre>
<p>But when the image shows up on the page it's using http instead of https like the rest of the site.</p>
<p>When go to the <a href="https://codex.wordpress.org/Function_Reference/esc_url" rel="nofollow">WP codex</a> to see the usage for esc_url it shows me this under usage but I don't know the correct syntax to use to make the protocol forced to https:</p>
<pre><code><?php esc_url( $url, $protocols, $_context ); ?>
</code></pre>
|
[
{
"answer_id": 191130,
"author": "Serpentsoft",
"author_id": 74048,
"author_profile": "https://wordpress.stackexchange.com/users/74048",
"pm_score": 2,
"selected": false,
"text": "<p>esc_url never force the URL to protocol it's only checking and escaping the passed URL from invalid characters, the $protocols variable is an array of acceptable (white list) protocols not for forcing destination URL.</p>\n\n<pre><code>// Forcing URL to https instead of http\n\n$YOUR_URL = esc_url($YOUR_URL);\n\nif( 'http' == parse_url($YOUR_URL, PHP_URL_SCHEME) ){\n $NEW_URL = str_replace('http://', 'https://', $YOUR_URL); \n}\n</code></pre>\n"
},
{
"answer_id": 191131,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 0,
"selected": false,
"text": "<p>The <code>$protocols</code> parameter accepts an array, so:</p>\n\n<pre><code>$protocols = array(\n 'https'\n);\n</code></pre>\n\n<p>But \"https\" is listed as a default so I am not sure that is the problem. My guess is that there is a filter interfering... <code>clean_url</code> for example, or <code>kses_allowed_protocols</code></p>\n"
},
{
"answer_id": 301283,
"author": "Sajan",
"author_id": 142087,
"author_profile": "https://wordpress.stackexchange.com/users/142087",
"pm_score": 0,
"selected": false,
"text": "<p>Old thread but i had similar issue today. If you install SSL Insecure Content Fixer plugin, then go on setting once installed and select 'Capture All' and save.</p>\n\n<p>This fixed the issue for me. Make sure you back up your database and site beforehand just incase something goes wrong.</p>\n"
},
{
"answer_id": 385922,
"author": "MediaFormat",
"author_id": 87622,
"author_profile": "https://wordpress.stackexchange.com/users/87622",
"pm_score": 0,
"selected": false,
"text": "<p>The function you were looking for (but didn't land until dec 2015), is <a href=\"https://developer.wordpress.org/reference/functions/set_url_scheme/\" rel=\"nofollow noreferrer\">set_url_scheme</a></p>\n<p><code>set_url_scheme( $url, 'https' ) )</code></p>\n<p>Internally the function checks if is_ssl is true, will only set the url scheme if the passed url has a scheme.</p>\n"
}
] |
2015/06/10
|
[
"https://wordpress.stackexchange.com/questions/191126",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70686/"
] |
The code on the page looks like this:
```
if ( ! empty( $image ) ) : ?>
<div class="headshot">
<img src="<?php echo esc_url( $image ); ?>" alt="Photo of <?php echo esc_attr( $author_name ); ?>"/>
</div>
```
But when the image shows up on the page it's using http instead of https like the rest of the site.
When go to the [WP codex](https://codex.wordpress.org/Function_Reference/esc_url) to see the usage for esc\_url it shows me this under usage but I don't know the correct syntax to use to make the protocol forced to https:
```
<?php esc_url( $url, $protocols, $_context ); ?>
```
|
esc\_url never force the URL to protocol it's only checking and escaping the passed URL from invalid characters, the $protocols variable is an array of acceptable (white list) protocols not for forcing destination URL.
```
// Forcing URL to https instead of http
$YOUR_URL = esc_url($YOUR_URL);
if( 'http' == parse_url($YOUR_URL, PHP_URL_SCHEME) ){
$NEW_URL = str_replace('http://', 'https://', $YOUR_URL);
}
```
|
191,138 |
<p>I'm using wp_query to get all attachments, and it works, but I wonder how could I get attachments in full size because this query returns images in medium.</p>
<pre><code><?php
$args = array('post_status' => 'inherit', 'post_type' => 'attachment', 'posts_per_page' => 5 );
$wp_query = new WP_Query($args);
while (have_posts() ) : the_post(); ?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php
the_title( '<h2>', '</h2>' );
the_content();
?>
</article>
<?php endwhile; ?>
</code></pre>
|
[
{
"answer_id": 191140,
"author": "iridian",
"author_id": 43066,
"author_profile": "https://wordpress.stackexchange.com/users/43066",
"pm_score": 0,
"selected": false,
"text": "<p>You should be able to set your own image tag. You can replace the_content(); with this.</p>\n\n<pre><code><img src=\"<?= wp_get_attachment_url(get_the_ID()); ?>\"/>\n</code></pre>\n"
},
{
"answer_id": 191147,
"author": "Chinmay Chiranjeeb",
"author_id": 20916,
"author_profile": "https://wordpress.stackexchange.com/users/20916",
"pm_score": 1,
"selected": false,
"text": "<p>You can customize the wp_get_attachment_image function as per your need.\npass the image size you want to display.</p>\n\n<pre><code>wp_get_attachment_image( $attachment->ID, 'full' );\n</code></pre>\n\n<p>more info at:\n<a href=\"https://codex.wordpress.org/Function_Reference/wp_get_attachment_image\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/wp_get_attachment_image</a> </p>\n"
},
{
"answer_id": 191148,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 1,
"selected": true,
"text": "<p>If you look at the raw post data...</p>\n\n<pre><code>while (have_posts() ) { \n the_post(); ?>\n <article id=\"post-<?php the_ID(); ?>\" <?php post_class(); ?>><?php\n var_dump($post); ?>\n </article><?php \n}\n</code></pre>\n\n<p>You will see that there is nothing in there to specify \"medium\", so I went looking. <a href=\"https://core.trac.wordpress.org/browser/trunk/src/wp-includes/default-filters.php#L136\" rel=\"nofollow\">There is a filter on <code>the_content</code>...</a> </p>\n\n<pre><code>add_filter( 'the_content', 'prepend_attachment' );\n</code></pre>\n\n<p>... that <a href=\"https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/post-template.php#L1576\" rel=\"nofollow\">juggles data for \"attachment\" post types</a>.</p>\n\n<pre><code>1576 function prepend_attachment($content) {\n1577 $post = get_post();\n1578 \n1579 if ( empty($post->post_type) || $post->post_type != 'attachment' )\n1580 return $content;\n1581 \n1582 if ( wp_attachment_is( 'video', $post ) ) {\n1583 $meta = wp_get_attachment_metadata( get_the_ID() );\n1584 $atts = array( 'src' => wp_get_attachment_url() );\n1585 if ( ! empty( $meta['width'] ) && ! empty( $meta['height'] ) ) {\n1586 $atts['width'] = (int) $meta['width'];\n1587 $atts['height'] = (int) $meta['height'];\n1588 }\n1589 if ( has_post_thumbnail() ) {\n1590 $atts['poster'] = wp_get_attachment_url( get_post_thumbnail_id() );\n1591 }\n1592 $p = wp_video_shortcode( $atts );\n1593 } elseif ( wp_attachment_is( 'audio', $post ) ) {\n1594 $p = wp_audio_shortcode( array( 'src' => wp_get_attachment_url() ) );\n1595 } else {\n1596 $p = '<p class=\"attachment\">';\n1597 // show the medium sized image representation of the attachment if available, and link to the raw file\n1598 $p .= wp_get_attachment_link(0, 'medium', false);\n1599 $p .= '</p>';\n1600 }\n1601 \n1602 /**\n1603 * Filter the attachment markup to be prepended to the post content.\n1604 *\n1605 * @since 2.0.0\n1606 *\n1607 * @see prepend_attachment()\n1608 *\n1609 * @param string $p The attachment HTML output.\n1610 */\n1611 $p = apply_filters( 'prepend_attachment', $p );\n1612 \n1613 return \"$p\\n$content\";\n1614 }\n</code></pre>\n\n<p>The relevant lines are 1597 and 1598. <a href=\"https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/post-template.php#L1532\" rel=\"nofollow\"><code>wp_get_attachment_link()</code></a>, which in turn uses <a href=\"https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/media.php#L727\" rel=\"nofollow\"><code>wp_get_attachment_image()</code></a> (line 1545), which uses <a href=\"https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/media.php#L150\" rel=\"nofollow\"><code>image_downsize()</code></a>... and there is a promising filter:</p>\n\n<pre><code>167 if ( $out = apply_filters( 'image_downsize', false, $id, $size ) ) {\n168 return $out;\n169 }\n</code></pre>\n\n<p><em>Et viola!</em></p>\n\n<pre><code>function image_size_hack() {\n $img_url = wp_get_attachment_url();\n $meta = wp_get_attachment_metadata();\n $width= $height = '';\n if (!empty($meta['width'])) {\n $width = $meta['width'];\n }\n if (!empty($meta['height'])) {\n $width = $meta['height'];\n }\n return array( $img_url, $width, $height, false );\n}\nadd_filter( 'image_downsize', 'image_size_hack');\n</code></pre>\n"
}
] |
2015/06/10
|
[
"https://wordpress.stackexchange.com/questions/191138",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70495/"
] |
I'm using wp\_query to get all attachments, and it works, but I wonder how could I get attachments in full size because this query returns images in medium.
```
<?php
$args = array('post_status' => 'inherit', 'post_type' => 'attachment', 'posts_per_page' => 5 );
$wp_query = new WP_Query($args);
while (have_posts() ) : the_post(); ?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php
the_title( '<h2>', '</h2>' );
the_content();
?>
</article>
<?php endwhile; ?>
```
|
If you look at the raw post data...
```
while (have_posts() ) {
the_post(); ?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>><?php
var_dump($post); ?>
</article><?php
}
```
You will see that there is nothing in there to specify "medium", so I went looking. [There is a filter on `the_content`...](https://core.trac.wordpress.org/browser/trunk/src/wp-includes/default-filters.php#L136)
```
add_filter( 'the_content', 'prepend_attachment' );
```
... that [juggles data for "attachment" post types](https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/post-template.php#L1576).
```
1576 function prepend_attachment($content) {
1577 $post = get_post();
1578
1579 if ( empty($post->post_type) || $post->post_type != 'attachment' )
1580 return $content;
1581
1582 if ( wp_attachment_is( 'video', $post ) ) {
1583 $meta = wp_get_attachment_metadata( get_the_ID() );
1584 $atts = array( 'src' => wp_get_attachment_url() );
1585 if ( ! empty( $meta['width'] ) && ! empty( $meta['height'] ) ) {
1586 $atts['width'] = (int) $meta['width'];
1587 $atts['height'] = (int) $meta['height'];
1588 }
1589 if ( has_post_thumbnail() ) {
1590 $atts['poster'] = wp_get_attachment_url( get_post_thumbnail_id() );
1591 }
1592 $p = wp_video_shortcode( $atts );
1593 } elseif ( wp_attachment_is( 'audio', $post ) ) {
1594 $p = wp_audio_shortcode( array( 'src' => wp_get_attachment_url() ) );
1595 } else {
1596 $p = '<p class="attachment">';
1597 // show the medium sized image representation of the attachment if available, and link to the raw file
1598 $p .= wp_get_attachment_link(0, 'medium', false);
1599 $p .= '</p>';
1600 }
1601
1602 /**
1603 * Filter the attachment markup to be prepended to the post content.
1604 *
1605 * @since 2.0.0
1606 *
1607 * @see prepend_attachment()
1608 *
1609 * @param string $p The attachment HTML output.
1610 */
1611 $p = apply_filters( 'prepend_attachment', $p );
1612
1613 return "$p\n$content";
1614 }
```
The relevant lines are 1597 and 1598. [`wp_get_attachment_link()`](https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/post-template.php#L1532), which in turn uses [`wp_get_attachment_image()`](https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/media.php#L727) (line 1545), which uses [`image_downsize()`](https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/media.php#L150)... and there is a promising filter:
```
167 if ( $out = apply_filters( 'image_downsize', false, $id, $size ) ) {
168 return $out;
169 }
```
*Et viola!*
```
function image_size_hack() {
$img_url = wp_get_attachment_url();
$meta = wp_get_attachment_metadata();
$width= $height = '';
if (!empty($meta['width'])) {
$width = $meta['width'];
}
if (!empty($meta['height'])) {
$width = $meta['height'];
}
return array( $img_url, $width, $height, false );
}
add_filter( 'image_downsize', 'image_size_hack');
```
|
191,139 |
<p>I'm trying to add a new rewrite rule but it doesn't seem to be getting added to the array and it certainly isn't working.</p>
<p>I'm trying to get this URL, <code>dult.dev/lists/games/destiny</code>, to take me from a list view of <code>/lists/games/</code> (which works just fine) to a single post view of that particular post. My rewrite rule isn't even getting added:</p>
<pre><code>add_action( 'init', 'add_rewrite_tags', 10, 0 );
function add_rewrite_tags() {
global $wp_rewrite; // Global WP_Rewrite class object
$wp_rewrite->flush_rules();
add_rewrite_rule(
'^lists/([^/]*)/([^/]*)/?',
'index.php/lists=$matches[1]&post=$matches[2]',
'top'
);
print_r( $wp_rewrite->rewrite_rules() );
}
</code></pre>
<p>When I call the <code>$wp_rewrite->rewrite_rules()</code>, the rule I just made isn't there. I've tried flushing them a handful of different ways, and even tried an extremely simple rule just to see if it was added, and still nothing.</p>
|
[
{
"answer_id": 191141,
"author": "David Labbe",
"author_id": 38434,
"author_profile": "https://wordpress.stackexchange.com/users/38434",
"pm_score": 2,
"selected": false,
"text": "<p>Try this. You also don't want to include $wp_rewrite->flush_rules() inside your function as that would flush on every page load.</p>\n\n<pre><code>add_action('rewrite_rules_array', 'new_rewrite_rules');\n\nfunction new_rewrite_rules($rules){\n $newrules = array();\n $newrules[ '^lists/([^/]*)/([^/]*)/?' = 'index.php?lists=$matches[1]&post=$matches[2]';\n return $newrules + $rules;\n }\n</code></pre>\n\n<p>If you want to flush the rules only once then try this:</p>\n\n<pre><code>add_action('init', 'flush_new_rule');\n\nfunction flush_new_rule(){\n global $wp_rewrite;\n if(is_array(get_option('rewrite_rules')) && !array_key_exists('^lists/([^/]*)/([^/]*)/?$', get_option('rewrite_rules')){\n $wp_rewrite->flush_rules( true );\n };\n}\n</code></pre>\n"
},
{
"answer_id": 191157,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 1,
"selected": false,
"text": "<p>You had some errors in the regex that can make the rewrite rules. I don't know what \"lists\" or what kind of post you want to fetch, so I can not debug that, but this rewrite rule should be correct:</p>\n\n<pre><code>add_action( 'init', 'add_rewrite_tags' );\nfunction add_rewrite_tags() {\n\n add_rewrite_rule( \n '^lists/([^/]+)/([^/]+)/?$', \n 'index.php?lists=$matches[1]&post=$matches[2]', \n 'top' \n );\n\n}\n</code></pre>\n\n<p>Then you must to flush the rewrite rules; you can do that visiting the permalinks settings page on wp-admin. If you want to flush the rewrite rules within your code, you should do on plugin activation (or theme activation if you are adding the rewrite rules in a theme). For example, in the main file of a plugin:</p>\n\n<pre><code>register_activation_hook( __FILE__, function() {\n\n flush_rewrite_rules();\n\n} );\nregister_deactivation_hook( __FILE__, function() {\n\n flush_rewrite_rules();\n\n} );\n</code></pre>\n"
}
] |
2015/06/11
|
[
"https://wordpress.stackexchange.com/questions/191139",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74511/"
] |
I'm trying to add a new rewrite rule but it doesn't seem to be getting added to the array and it certainly isn't working.
I'm trying to get this URL, `dult.dev/lists/games/destiny`, to take me from a list view of `/lists/games/` (which works just fine) to a single post view of that particular post. My rewrite rule isn't even getting added:
```
add_action( 'init', 'add_rewrite_tags', 10, 0 );
function add_rewrite_tags() {
global $wp_rewrite; // Global WP_Rewrite class object
$wp_rewrite->flush_rules();
add_rewrite_rule(
'^lists/([^/]*)/([^/]*)/?',
'index.php/lists=$matches[1]&post=$matches[2]',
'top'
);
print_r( $wp_rewrite->rewrite_rules() );
}
```
When I call the `$wp_rewrite->rewrite_rules()`, the rule I just made isn't there. I've tried flushing them a handful of different ways, and even tried an extremely simple rule just to see if it was added, and still nothing.
|
Try this. You also don't want to include $wp\_rewrite->flush\_rules() inside your function as that would flush on every page load.
```
add_action('rewrite_rules_array', 'new_rewrite_rules');
function new_rewrite_rules($rules){
$newrules = array();
$newrules[ '^lists/([^/]*)/([^/]*)/?' = 'index.php?lists=$matches[1]&post=$matches[2]';
return $newrules + $rules;
}
```
If you want to flush the rules only once then try this:
```
add_action('init', 'flush_new_rule');
function flush_new_rule(){
global $wp_rewrite;
if(is_array(get_option('rewrite_rules')) && !array_key_exists('^lists/([^/]*)/([^/]*)/?$', get_option('rewrite_rules')){
$wp_rewrite->flush_rules( true );
};
}
```
|
191,160 |
<p>Because of the lack of documentation about <a href="https://codex.wordpress.org/Plugin_API/Filter_Reference/post_limits" rel="nofollow"><code>post_limits</code></a>, its hard to learn more about this function and when to use it. Never used it before or seen it used so maybe its not to be used?</p>
<pre><code>function wpcodex_filter_home_post_limits( $limit, $query ) {
if ( ! is_admin() && $query->is_main_query() && $query->is_home() ) {
return 'LIMIT 0, 25';
}
return $limit;
}
add_filter( 'post_limits', 'wpcodex_filter_home_post_limits', 10, 2 );
</code></pre>
<p>Based on my testing, post_limits does the same thing as using pre_get_posts </p>
<p>If i wanted to return 5 posts conditionally without paginating the remainder, would i use post_limits or pre_get_posts?</p>
|
[
{
"answer_id": 191163,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": false,
"text": "<p>Note that here you're overriding the paging of the main query, with the <code>posts_limits</code> filter, by using hardcoded values:</p>\n\n<pre><code>'LIMIT 0, 25'\n</code></pre>\n\n<p>where <code>0</code> is the offset and <code>25</code> is the number of posts to display.</p>\n\n<p>So in this case I would just use <code>pre_get_posts</code> with</p>\n\n<pre><code>$query->set( 'posts_per_page', 25 );\n</code></pre>\n\n<p>and we don't have to worry about the paging.</p>\n\n<blockquote>\n <p>If i wanted to return 5 posts conditionally without paginating the\n remainder, would i use post_limits or pre_get_posts?</p>\n</blockquote>\n\n<p>If we later decide that pagination is necessary, then we would need to rework your <code>posts_limits</code> code. The <code>pre_get_posts</code> filter would work as is and we could therefore say that it's at least a more \"future proofed\" method.</p>\n\n<p>Another thing: If you were using <code>get_posts()</code> or <code>WP_Query()</code> with <em>suppressed</em> filters, then the <code>posts_limits</code> filter wouldn't be available while the <code>pre_get_posts</code> hook would be accessible.</p>\n"
},
{
"answer_id": 191225,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 2,
"selected": false,
"text": "<p><code>pre_get_posts</code> allows you to alter the query arguments very early on in a request. You can modify anything that would be a valid <code>WP_Query</code> argument, including the <code>LIMIT</code> via the <code>posts_per_page</code> argument. This allows much, much broader range of effects than <code>posts_limits</code> which only allows you to alter one part of the database query SQL. </p>\n\n<p>In your case, use <code>pre_get_posts</code> as the Core code will manage pagination for you ( at least if this is the main query(). If you use <code>post_limits</code> you will need to track and manage the pagination -- the \"0,25\" part yourself, incrementing values as you page.</p>\n"
}
] |
2015/06/11
|
[
"https://wordpress.stackexchange.com/questions/191160",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/9884/"
] |
Because of the lack of documentation about [`post_limits`](https://codex.wordpress.org/Plugin_API/Filter_Reference/post_limits), its hard to learn more about this function and when to use it. Never used it before or seen it used so maybe its not to be used?
```
function wpcodex_filter_home_post_limits( $limit, $query ) {
if ( ! is_admin() && $query->is_main_query() && $query->is_home() ) {
return 'LIMIT 0, 25';
}
return $limit;
}
add_filter( 'post_limits', 'wpcodex_filter_home_post_limits', 10, 2 );
```
Based on my testing, post\_limits does the same thing as using pre\_get\_posts
If i wanted to return 5 posts conditionally without paginating the remainder, would i use post\_limits or pre\_get\_posts?
|
Note that here you're overriding the paging of the main query, with the `posts_limits` filter, by using hardcoded values:
```
'LIMIT 0, 25'
```
where `0` is the offset and `25` is the number of posts to display.
So in this case I would just use `pre_get_posts` with
```
$query->set( 'posts_per_page', 25 );
```
and we don't have to worry about the paging.
>
> If i wanted to return 5 posts conditionally without paginating the
> remainder, would i use post\_limits or pre\_get\_posts?
>
>
>
If we later decide that pagination is necessary, then we would need to rework your `posts_limits` code. The `pre_get_posts` filter would work as is and we could therefore say that it's at least a more "future proofed" method.
Another thing: If you were using `get_posts()` or `WP_Query()` with *suppressed* filters, then the `posts_limits` filter wouldn't be available while the `pre_get_posts` hook would be accessible.
|
191,169 |
<p>So I've been tasked with making an "Image Advert" to be placed on a sidebar on this website. The client wants to have the ability to upload 5 images on to the ACF Options Page and then have a random image be pulled from there and displayed on the sidebar at random everytime the page refreshes.</p>
<p>I was wondering if it was possible for anyone to help me.</p>
<pre><code><?php
$rows = get_field('image_advert_repeater'); // get all the rows
$rand_row = $rows[ array_rand($rows, 1) ]; // get a random row
$rand_row_image = $rand_row['image_advert_images']; // get the sub field value
// Note
// $first_row_image = 123 (image ID)
$image = wp_get_attachment_image_src( $rand_row_image, 'full' );
// url = $image[0];
// width = $image[1];
// height = $image[2];
?>
<img src="<?php echo $image[0]; ?>" />
</code></pre>
<p>This is the code I'm currently trying to use to display the images. It's taken from the ACF Repeater documentation and I've editied it to use my repeater but I can't seem to get it to work. I've also tried adding 'options' to the end of the field names to see if that's the isssue but it just white screens the website on refresh.</p>
|
[
{
"answer_id": 191171,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 1,
"selected": true,
"text": "<p>Just noticed the issue - since your ACF field is an options page, you need to pass the second argument <code>options</code> to <code>get_field</code> - add a bit of sanity checking too:</p>\n\n<pre><code>$rows = get_field( 'image_advert_repeater', 'options' );\nif ( ! empty( $rows ) && is_array( $rows ) ) {\n // Your code\n}\n</code></pre>\n"
},
{
"answer_id": 191197,
"author": "Roy Barber",
"author_id": 17628,
"author_profile": "https://wordpress.stackexchange.com/users/17628",
"pm_score": 1,
"selected": false,
"text": "<p>This should do it:</p>\n\n<pre><code><?php $rows = get_field( 'image_advert_repeater', 'options' );\n// Wrap in an if statement to prevent an empy image SRC if no rows exist\nif ( ! empty( $rows ) && is_array( $rows ) ) {\n // Get the row and ranomise\n $rand_row = $rows[ array_rand($rows) ];\n // get the image url from the array\n $rand_row_image = $rand_row['image_advert_images'];\n // make things easier to read\n $image = $rand_row_image;\n?>\n<!-- Echo out the image -->\n<img src=\"<?php echo $image ?>\" />\n</code></pre>\n\n \n"
}
] |
2015/06/11
|
[
"https://wordpress.stackexchange.com/questions/191169",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74521/"
] |
So I've been tasked with making an "Image Advert" to be placed on a sidebar on this website. The client wants to have the ability to upload 5 images on to the ACF Options Page and then have a random image be pulled from there and displayed on the sidebar at random everytime the page refreshes.
I was wondering if it was possible for anyone to help me.
```
<?php
$rows = get_field('image_advert_repeater'); // get all the rows
$rand_row = $rows[ array_rand($rows, 1) ]; // get a random row
$rand_row_image = $rand_row['image_advert_images']; // get the sub field value
// Note
// $first_row_image = 123 (image ID)
$image = wp_get_attachment_image_src( $rand_row_image, 'full' );
// url = $image[0];
// width = $image[1];
// height = $image[2];
?>
<img src="<?php echo $image[0]; ?>" />
```
This is the code I'm currently trying to use to display the images. It's taken from the ACF Repeater documentation and I've editied it to use my repeater but I can't seem to get it to work. I've also tried adding 'options' to the end of the field names to see if that's the isssue but it just white screens the website on refresh.
|
Just noticed the issue - since your ACF field is an options page, you need to pass the second argument `options` to `get_field` - add a bit of sanity checking too:
```
$rows = get_field( 'image_advert_repeater', 'options' );
if ( ! empty( $rows ) && is_array( $rows ) ) {
// Your code
}
```
|
191,176 |
<p>Based on <a href="https://wordpress.stackexchange.com/questions/191120/how-to-check-if-widget-has-automatic-title/191154">this question</a>, I'm getting an error <code>Warning: Missing argument 2 for...</code>.</p>
<p>This happens for some widgets those are created by plugins.</p>
<p>-- Edit 1 --</p>
<p>Here's a simple widget that causes the error:</p>
<pre><code>function my_new_widget_register() {
register_widget( 'my_new_widget' );
}
add_action('widgets_init', 'my_new_widget_register');
class my_new_widget extends WP_Widget {
function my_new_widget() {
// Instantiate the parent object
parent::__construct( false, 'my_new_widget' );
}
function widget( $args, $instance ) {
// Widget output
extract( $args );
$title = apply_filters('widget_title', $instance['title']);
echo $before_widget;
echo $title;
echo $after_widget;
}
}
</code></pre>
<p>The error is clearly caused by <code>$title</code>.</p>
|
[
{
"answer_id": 191403,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 3,
"selected": true,
"text": "<p>You don’t pass more than argument to that filter, so any callback expecting more than one will not get it. The core calls this filter always like this:</p>\n\n<pre><code>$title = apply_filters(\n 'widget_title', \n empty($instance['title']) ? '' : $instance['title'], \n $instance, \n $this->id_base\n);\n</code></pre>\n\n<p>But you are passing just <code>$instance['title']</code>. Add the missing parameters, and the error will vanish.</p>\n\n<p>If you cannot change the widget, change the registration for the callback for the filter, and make the other arguments optional by setting a default value:</p>\n\n<pre><code>add_filter( 'widget_title', 'my_widget_title_filter', 10, 3 );\n\nfunction my_widget_title_filter( $title, $instance = [], $id_base = '' ) {\n if ( '' === $id_base )\n return $title;\n\n // do something with the title, then\n return $title;\n}\n</code></pre>\n"
},
{
"answer_id": 191435,
"author": "Ahmed Saad",
"author_id": 37529,
"author_profile": "https://wordpress.stackexchange.com/users/37529",
"pm_score": 0,
"selected": false,
"text": "<p>The Missing Arguments error disappeared after making a small change to the parameters in the function:</p>\n\n<pre><code>function remove_widget_title($title, $instance)\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>function remove_widget_title($title, $instance = [])\n</code></pre>\n"
}
] |
2015/06/11
|
[
"https://wordpress.stackexchange.com/questions/191176",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37529/"
] |
Based on [this question](https://wordpress.stackexchange.com/questions/191120/how-to-check-if-widget-has-automatic-title/191154), I'm getting an error `Warning: Missing argument 2 for...`.
This happens for some widgets those are created by plugins.
-- Edit 1 --
Here's a simple widget that causes the error:
```
function my_new_widget_register() {
register_widget( 'my_new_widget' );
}
add_action('widgets_init', 'my_new_widget_register');
class my_new_widget extends WP_Widget {
function my_new_widget() {
// Instantiate the parent object
parent::__construct( false, 'my_new_widget' );
}
function widget( $args, $instance ) {
// Widget output
extract( $args );
$title = apply_filters('widget_title', $instance['title']);
echo $before_widget;
echo $title;
echo $after_widget;
}
}
```
The error is clearly caused by `$title`.
|
You don’t pass more than argument to that filter, so any callback expecting more than one will not get it. The core calls this filter always like this:
```
$title = apply_filters(
'widget_title',
empty($instance['title']) ? '' : $instance['title'],
$instance,
$this->id_base
);
```
But you are passing just `$instance['title']`. Add the missing parameters, and the error will vanish.
If you cannot change the widget, change the registration for the callback for the filter, and make the other arguments optional by setting a default value:
```
add_filter( 'widget_title', 'my_widget_title_filter', 10, 3 );
function my_widget_title_filter( $title, $instance = [], $id_base = '' ) {
if ( '' === $id_base )
return $title;
// do something with the title, then
return $title;
}
```
|
191,178 |
<p>I have an own class that deregisters all scripts and styles and creates 2 cached files one for scripts and one for styles that is registered in the end. This runs inside theme, my problem is that I cant move it into plugin, as soon as i move it into plugin it wont work.</p>
<p>currently this code works inside theme</p>
<pre><code>add_filter('wp_print_styles', array($this, 'optimize_styles'), 1);
add_filter('wp_print_scripts', array($this, 'optimize_scripts'), 1);
</code></pre>
<p>i have tried add action add filter, change priorities.... also i want some way to make my plugin load as last to ensure all plugin styles and scripts will be "compiled" into one.</p>
<p>Thankyou</p>
|
[
{
"answer_id": 192566,
"author": "Domain",
"author_id": 26523,
"author_profile": "https://wordpress.stackexchange.com/users/26523",
"pm_score": 0,
"selected": false,
"text": "<p>Since plugins are loaded by the alphabetical order of plugin's folder name (not by plugin's name), name your plugin folder ZZ.. and it should load last :-)</p>\n"
},
{
"answer_id": 192578,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 2,
"selected": true,
"text": "<p>There's a much better and more reliable way than naming your plugin \"ZZ\" - use a delayed hook on <code>plugins_loaded</code>, which fires after all plugins are loaded:</p>\n\n<pre><code>function wpse_191178_plugins_loaded() {\n // Do your stuff\n}\n\nadd_action( 'plugins_loaded', 'wpse_191178_plugins_loaded', 100 );\n</code></pre>\n"
}
] |
2015/06/11
|
[
"https://wordpress.stackexchange.com/questions/191178",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74531/"
] |
I have an own class that deregisters all scripts and styles and creates 2 cached files one for scripts and one for styles that is registered in the end. This runs inside theme, my problem is that I cant move it into plugin, as soon as i move it into plugin it wont work.
currently this code works inside theme
```
add_filter('wp_print_styles', array($this, 'optimize_styles'), 1);
add_filter('wp_print_scripts', array($this, 'optimize_scripts'), 1);
```
i have tried add action add filter, change priorities.... also i want some way to make my plugin load as last to ensure all plugin styles and scripts will be "compiled" into one.
Thankyou
|
There's a much better and more reliable way than naming your plugin "ZZ" - use a delayed hook on `plugins_loaded`, which fires after all plugins are loaded:
```
function wpse_191178_plugins_loaded() {
// Do your stuff
}
add_action( 'plugins_loaded', 'wpse_191178_plugins_loaded', 100 );
```
|
191,210 |
<p>Writing my first Wordpress plugin that uses a Class approach.</p>
<p>It is being called on a page via a shortcode. In testing, the shortcode is working and the shortcode specific php file is being loaded.</p>
<p>However, the 2 add_action calls are not firing:</p>
<pre><code>//Register Styles
add_action( 'wp_enqueue_style', array( $this, 'register_styles' ) );
//Register Scripts
add_action( 'wp_enqueue_script', array( $this, 'register_scripts' ) );
</code></pre>
<p>When I test with var_dump, the register_styles/scripts functions are not even running, yet all other functions called in __contruct() are.</p>
<p>Here is the full code:</p>
<pre><code><?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
add_action( 'plugins_loaded', array ( 'Lipstick_Consultation', 'init' ));
if (!class_exists('Lipstick_Consultation')){
class Lipstick_Consultation{
public static function init() {
$class = __CLASS__;
new $class;
}
/**
* @since 1.0
*/
public function __construct() {
//get contstants
$this->setup_constants();
//get file includes
$this->includes();
//Register Styles
add_action( 'wp_enqueue_style', array( $this, 'register_styles' ) );
//Register Scripts
add_action( 'wp_enqueue_script', array( $this, 'register_scripts' ) );
$this->register_shortcodes();
return $this;
}
/**
* Include our Class files
*
* @access private
* @since 1.0.0
* @return void
*/
private function includes() {
/****SHORTCODES****/
//[slider_person]
require_once LC_DIR . 'inc/shortcodes/slider.php';
}
/**
* Setup plugin constants
*
* @access private
* @since 1.0.0
* @return void
*/
private function setup_constants() {
// Plugin information
define( 'LC_VERSION', '1.0.0' ); // Current plugin version
define( 'LC_URL', plugin_dir_url( __FILE__ ) );
define( 'LC_DIR', plugin_dir_path( __FILE__ ) );
}
/**
* Register Styles
*
* @access public
* @since 1.0.0
* @return void
*/
public function register_styles() {
//main style file
wp_register_style( 'consultation_style', LC_URL . "assets/css/style.css", array(), time(), 'all' );
wp_enqueue_style( 'consultation_style' );
//styles for full page plugin
wp_register_style( 'lc_full_page_style', LC_URL . "assets/css/jquery.fullPage.css", array(), time(), 'all' );
wp_enqueue_style( 'lc_full_page_style' );
}
/**
* Register Scripts
*
* @access public
* @since 1.0.0
* @return void
*/
public function register_scripts() {
//Script that makes full width/height/page divs
wp_register_script( 'lc_full_page', LC_URL . "assets/js/jquery.fullPage{SUFFIX}.js", array( 'jquery' ), time() );
wp_enqueue_script( 'lc_full_page' );
}
private function register_shortcodes(){
add_shortcode("lipstick_person","shortcode_person_slider");
}
}
}?>
</code></pre>
|
[
{
"answer_id": 191212,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 3,
"selected": true,
"text": "<p>There is no action called <code>wp_enqueue_script</code>, it's <code>wp_enqueue_scripts</code>, plural, and both scripts and styles should be enqueued on that action.</p>\n"
},
{
"answer_id": 341732,
"author": "Jeffery Adams",
"author_id": 170905,
"author_profile": "https://wordpress.stackexchange.com/users/170905",
"pm_score": 0,
"selected": false,
"text": "<pre><code><?php\n\nif( !class_exists('SiteOrigin_Installer_Theme_Admin') ) {\n class SiteOrigin_Installer_Theme_Admin {\n\n function __construct(){\n add_action( 'admin_menu', array( $this, 'add_admin_page' ) );\n add_action( 'admin_menu', array( $this, 'add_admin_sub_page' ), 15 );\n add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ), 15 );\n add_action( 'wp_ajax_so_installer_theme_headers', array( $this, 'theme_headers_action' ) );\n }\n\n static function single(){\n static $single;\n if( empty($single) ) {\n $single = new SiteOrigin_Installer_Theme_Admin();\n }\n\n return $single;\n }\n\n /**\n * Add the theme admin page\n */\n function add_admin_page() {\n if ( empty ( $GLOBALS['admin_page_hooks']['siteorigin'] ) ) {\n add_menu_page(\n __( 'SiteOrigin', 'siteorigin-installer' ),\n __( 'SiteOrigin', 'siteorigin-installer' ),\n false,\n 'siteorigin',\n false,\n plugin_dir_url( __FILE__ ) . '/img/icon.svg',\n 66\n );\n }\n }\n\n function add_admin_sub_page(){\n add_submenu_page(\n 'siteorigin',\n __('Install Themes', 'siteorigin-installer'),\n __('Install Themes', 'siteorigin-installer'),\n 'install_themes',\n 'siteorigin-themes-installer',\n array( $this, 'display_themes_page' )\n );\n }\n\n /**\n * @param $prefix\n */\n function enqueue_scripts( $prefix ){\n if( $prefix !== 'siteorigin_page_siteorigin-themes-installer' ) return;\n wp_enqueue_style( 'siteorigin-installer-themes', plugin_dir_url(__FILE__) . '/css/themes.css', array( ), SITEORIGIN_INSTALLER_VERSION );\n wp_enqueue_script( 'siteorigin-installer-themes', plugin_dir_url(__FILE__) . '/js/themes.js', array( 'jquery' ), SITEORIGIN_INSTALLER_VERSION );\n }\n\n /**\n * Display the theme admin page\n */\n function display_themes_page(){\n\n if( !empty( $_GET['install_theme'] ) && !empty( $_GET['theme_version'] ) ) {\n // The user is installing a theme\n $this->display_install_page();\n return;\n }\n\n $themes = SiteOrigin_Installer::single()->registered_themes();\n $latest_versions = get_transient( 'siteorigin_installer_theme_versions' );\n if( empty($latest_versions) ) $latest_versions = array();\n $updated = false;\n\n foreach( $themes as $slug => $theme ) {\n if( !empty( $latest_versions[$slug] ) ) continue;\n\n $version = SiteOrigin_Installer::single()->get_theme_version( $slug );\n if( $version === false ) continue;\n\n $latest_versions[$slug] = $version;\n $updated = true;\n }\n\n if( $updated ) {\n // Cache for 12 hours\n set_transient( 'siteorigin_installer_theme_versions', $latest_versions, 43200 );\n }\n\n // We need to know the current theme\n $current_theme = wp_get_theme();\n\n // Increase the current themes weight\n foreach( $themes as $slug => $theme ) {\n if( $slug == $current_theme->get_stylesheet() ) $themes[$slug]['weight'] = 999;\n }\n\n // Sort the themes by weight\n uasort( $themes, array( $this, 'sort_theme_compare' ) );\n\n include plugin_dir_path( __FILE__ ) . '/tpl/themes.php';\n }\n\n /**\n * Comparison function for sorting\n *\n * @param $a\n * @param $b\n *\n * @return int\n */\n function sort_theme_compare( $a, $b ){\n if( empty($a['weight']) || empty($b['weight']) ) return 0;\n return $a['weight'] < $b['weight'] ? 1 : -1;\n }\n\n /**\n * Display the plugin install page\n */\n function display_install_page(){\n check_admin_referer( 'siteorigin-install-theme' );\n require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php'; // Need for upgrade classes\n\n $slug = !empty( $_GET['install_theme'] ) ? $_GET['install_theme'] : false;\n $version = !empty( $_GET['theme_version'] ) ? $_GET['theme_version'] : false;\n\n if( empty($slug) || empty($version) ) {\n wp_die( __('Error installing theme', 'siteorigin-installer') );\n }\n\n ?>\n <div class=\"wrap\">\n <?php\n // This is where we actually install the theme\n\n $theme_url = 'https://wordpress.org/themes/download/' . urlencode( $slug ) . '.' . urlencode( $version ) . '.zip';\n\n $title = sprintf( __('Installing Theme: %s'), $slug . ' ' . $version );\n $nonce = 'install-theme_' . $slug;\n $url = 'update.php?action=install-theme&theme=' . urlencode( $slug );\n $type = 'web'; //Install theme type, From Web or an Upload.\n\n $upgrader = new Theme_Upgrader( new Theme_Installer_Skin( compact('title', 'url', 'nonce', 'plugin', 'api', 'type') ) );\n $upgrader->install( $theme_url );\n\n ?>\n </div>\n <?php\n }\n\n function theme_headers_action(){\n if( empty($_GET['_sononce']) || !wp_verify_nonce( $_GET['_sononce'], 'theme_info' ) ) exit();\n if( empty( $_GET['theme_slug'] ) || empty( $_GET['theme_version'] ) ) exit();\n\n // header('content-type: application/json');\n $data = SiteOrigin_Installer::single()->get_theme_data( $_GET['theme_slug'], $_GET['theme_version'] );\n echo json_encode( $data );\n exit();\n }\n }\n}\nSiteOrigin_Installer_Theme_Admin::single();\n</code></pre>\n"
}
] |
2015/06/11
|
[
"https://wordpress.stackexchange.com/questions/191210",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68087/"
] |
Writing my first Wordpress plugin that uses a Class approach.
It is being called on a page via a shortcode. In testing, the shortcode is working and the shortcode specific php file is being loaded.
However, the 2 add\_action calls are not firing:
```
//Register Styles
add_action( 'wp_enqueue_style', array( $this, 'register_styles' ) );
//Register Scripts
add_action( 'wp_enqueue_script', array( $this, 'register_scripts' ) );
```
When I test with var\_dump, the register\_styles/scripts functions are not even running, yet all other functions called in \_\_contruct() are.
Here is the full code:
```
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
add_action( 'plugins_loaded', array ( 'Lipstick_Consultation', 'init' ));
if (!class_exists('Lipstick_Consultation')){
class Lipstick_Consultation{
public static function init() {
$class = __CLASS__;
new $class;
}
/**
* @since 1.0
*/
public function __construct() {
//get contstants
$this->setup_constants();
//get file includes
$this->includes();
//Register Styles
add_action( 'wp_enqueue_style', array( $this, 'register_styles' ) );
//Register Scripts
add_action( 'wp_enqueue_script', array( $this, 'register_scripts' ) );
$this->register_shortcodes();
return $this;
}
/**
* Include our Class files
*
* @access private
* @since 1.0.0
* @return void
*/
private function includes() {
/****SHORTCODES****/
//[slider_person]
require_once LC_DIR . 'inc/shortcodes/slider.php';
}
/**
* Setup plugin constants
*
* @access private
* @since 1.0.0
* @return void
*/
private function setup_constants() {
// Plugin information
define( 'LC_VERSION', '1.0.0' ); // Current plugin version
define( 'LC_URL', plugin_dir_url( __FILE__ ) );
define( 'LC_DIR', plugin_dir_path( __FILE__ ) );
}
/**
* Register Styles
*
* @access public
* @since 1.0.0
* @return void
*/
public function register_styles() {
//main style file
wp_register_style( 'consultation_style', LC_URL . "assets/css/style.css", array(), time(), 'all' );
wp_enqueue_style( 'consultation_style' );
//styles for full page plugin
wp_register_style( 'lc_full_page_style', LC_URL . "assets/css/jquery.fullPage.css", array(), time(), 'all' );
wp_enqueue_style( 'lc_full_page_style' );
}
/**
* Register Scripts
*
* @access public
* @since 1.0.0
* @return void
*/
public function register_scripts() {
//Script that makes full width/height/page divs
wp_register_script( 'lc_full_page', LC_URL . "assets/js/jquery.fullPage{SUFFIX}.js", array( 'jquery' ), time() );
wp_enqueue_script( 'lc_full_page' );
}
private function register_shortcodes(){
add_shortcode("lipstick_person","shortcode_person_slider");
}
}
}?>
```
|
There is no action called `wp_enqueue_script`, it's `wp_enqueue_scripts`, plural, and both scripts and styles should be enqueued on that action.
|
191,263 |
<p>I am working with woocomerce plugin. My woocomerce product display like this:</p>
<pre><code><div class="product-box">
<a href="http://localhost/ebhajipala_latest/shop/health/veg14/">
<img class="attachment-shop_catalog wp-post-image" width="150" height="150" alt="download" src="http://localhost/ebhajipala_latest/wp-content/uploads/2015/02/download-150x150.jpg">
</a>
</div>
</code></pre>
<p>But now I want to remove image tag from anchor tag. And use like this:</p>
<pre><code><img class="attachment-shop_catalog wp-post-image" width="150" height="150" alt="download" src="http://localhost/ebhajipala_latest/wp-content/uploads/2015/02/download-150x150.jpg">
<a href="http://localhost/ebhajipala_latest/shop/health/veg14/"></a>
</code></pre>
<p>So what should I have to do?
My archive_product.php page code is : </p>
<pre><code> <div class="pr_name">
<h2>Products</h2>
</div>
<div class="pr_slider">
<?php echo do_shortcode('[wpb-latest-product title="Latest Product"]'); ?>
</div>
</code></pre>
<pre><code> <?php if ( apply_filters( 'woocommerce_show_page_title', true ) ) : ?>
<!--<h1 class="page-title"><?php //woocommerce_page_title(); ?></h1>-->
<?php endif; ?>
<?php do_action( 'woocommerce_archive_description' ); ?>
<div class="pr_name">
</div>
<?php if ( have_posts() ) : ?>
<?php
/**
* woocommerce_before_shop_loop hook
*
* @hooked woocommerce_result_count - 20
* @hooked woocommerce_catalog_ordering - 30
*/
do_action( 'woocommerce_before_shop_loop' );
?>
<?php woocommerce_product_loop_start(); ?>
<?php woocommerce_product_subcategories(); ?>
<?php while ( have_posts() ) : the_post();
wc_get_template_part( 'content', 'product' );
endwhile; // end of the loop. ?>
<?php woocommerce_product_loop_end(); ?>
<?php
/**
* woocommerce_after_shop_loop hook
*
* @hooked woocommerce_pagination - 10
*/
do_action( 'woocommerce_after_shop_loop' );
?>
<?php elseif ( ! woocommerce_product_subcategories( array( 'before' => woocommerce_product_loop_start( false ), 'after' => woocommerce_product_loop_end( false ) ) ) ) : ?>
<?php wc_get_template( 'loop/no-products-found.php' ); ?>
<?php endif; ?>
<?php
/**
* woocommerce_after_main_content hook
*
* @hooked woocommerce_output_content_wrapper_end - 10 (outputs closing divs for the content)
*/
do_action( 'woocommerce_after_main_content' );
?>
<?php
/**
* woocommerce_sidebar hook
*
* @hooked woocommerce_get_sidebar - 10
*/
//do_action( 'woocommerce_sidebar' );
?>
</code></pre>
|
[
{
"answer_id": 191266,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 0,
"selected": false,
"text": "<p>you have <code>wc_get_template_part( 'content', 'product' );</code> so you have to look in the file <code>content-product.php</code></p>\n"
},
{
"answer_id": 191268,
"author": "sohan",
"author_id": 69017,
"author_profile": "https://wordpress.stackexchange.com/users/69017",
"pm_score": 2,
"selected": true,
"text": "<p>A quick solution: find your <code>content-product.php</code> find the below code</p>\n\n<pre><code><a href=\"<?php the_permalink(); ?>\">\n\n <?php\n /**\n * woocommerce_before_shop_loop_item_title hook\n *\n * @hooked woocommerce_show_product_loop_sale_flash - 10\n * @hooked woocommerce_template_loop_product_thumbnail - 10\n */\n do_action( 'woocommerce_before_shop_loop_item_title' );\n ?>\n\n <h3><?php the_title(); ?></h3>\n\n <?php\n /**\n * woocommerce_after_shop_loop_item_title hook\n *\n * @hooked woocommerce_template_loop_rating - 5\n * @hooked woocommerce_template_loop_price - 10\n */\n do_action( 'woocommerce_after_shop_loop_item_title' );\n ?>\n\n </a>\n</code></pre>\n\n<p>move the a tag like:</p>\n\n<pre><code><?php\n /**\n * woocommerce_before_shop_loop_item_title hook\n *\n * @hooked woocommerce_show_product_loop_sale_flash - 10\n * @hooked woocommerce_template_loop_product_thumbnail - 10\n */\n do_action( 'woocommerce_before_shop_loop_item_title' );\n ?>\n\n <h3><?php the_title(); ?></h3>\n\n <?php\n /**\n * woocommerce_after_shop_loop_item_title hook\n *\n * @hooked woocommerce_template_loop_rating - 5\n * @hooked woocommerce_template_loop_price - 10\n */\n do_action( 'woocommerce_after_shop_loop_item_title' );\n ?>\n<a href=\"<?php the_permalink(); ?>\"></a>\n</code></pre>\n\n<p>Note: Use the customization in your theme/woocommerce directory otherwise changes will undo if plugin got update.</p>\n\n<p>Hence above changes may depend on the theme you are using. if your theme already have woocommerce do changes accordingly.</p>\n"
}
] |
2015/06/12
|
[
"https://wordpress.stackexchange.com/questions/191263",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74574/"
] |
I am working with woocomerce plugin. My woocomerce product display like this:
```
<div class="product-box">
<a href="http://localhost/ebhajipala_latest/shop/health/veg14/">
<img class="attachment-shop_catalog wp-post-image" width="150" height="150" alt="download" src="http://localhost/ebhajipala_latest/wp-content/uploads/2015/02/download-150x150.jpg">
</a>
</div>
```
But now I want to remove image tag from anchor tag. And use like this:
```
<img class="attachment-shop_catalog wp-post-image" width="150" height="150" alt="download" src="http://localhost/ebhajipala_latest/wp-content/uploads/2015/02/download-150x150.jpg">
<a href="http://localhost/ebhajipala_latest/shop/health/veg14/"></a>
```
So what should I have to do?
My archive\_product.php page code is :
```
<div class="pr_name">
<h2>Products</h2>
</div>
<div class="pr_slider">
<?php echo do_shortcode('[wpb-latest-product title="Latest Product"]'); ?>
</div>
```
```
<?php if ( apply_filters( 'woocommerce_show_page_title', true ) ) : ?>
<!--<h1 class="page-title"><?php //woocommerce_page_title(); ?></h1>-->
<?php endif; ?>
<?php do_action( 'woocommerce_archive_description' ); ?>
<div class="pr_name">
</div>
<?php if ( have_posts() ) : ?>
<?php
/**
* woocommerce_before_shop_loop hook
*
* @hooked woocommerce_result_count - 20
* @hooked woocommerce_catalog_ordering - 30
*/
do_action( 'woocommerce_before_shop_loop' );
?>
<?php woocommerce_product_loop_start(); ?>
<?php woocommerce_product_subcategories(); ?>
<?php while ( have_posts() ) : the_post();
wc_get_template_part( 'content', 'product' );
endwhile; // end of the loop. ?>
<?php woocommerce_product_loop_end(); ?>
<?php
/**
* woocommerce_after_shop_loop hook
*
* @hooked woocommerce_pagination - 10
*/
do_action( 'woocommerce_after_shop_loop' );
?>
<?php elseif ( ! woocommerce_product_subcategories( array( 'before' => woocommerce_product_loop_start( false ), 'after' => woocommerce_product_loop_end( false ) ) ) ) : ?>
<?php wc_get_template( 'loop/no-products-found.php' ); ?>
<?php endif; ?>
<?php
/**
* woocommerce_after_main_content hook
*
* @hooked woocommerce_output_content_wrapper_end - 10 (outputs closing divs for the content)
*/
do_action( 'woocommerce_after_main_content' );
?>
<?php
/**
* woocommerce_sidebar hook
*
* @hooked woocommerce_get_sidebar - 10
*/
//do_action( 'woocommerce_sidebar' );
?>
```
|
A quick solution: find your `content-product.php` find the below code
```
<a href="<?php the_permalink(); ?>">
<?php
/**
* woocommerce_before_shop_loop_item_title hook
*
* @hooked woocommerce_show_product_loop_sale_flash - 10
* @hooked woocommerce_template_loop_product_thumbnail - 10
*/
do_action( 'woocommerce_before_shop_loop_item_title' );
?>
<h3><?php the_title(); ?></h3>
<?php
/**
* woocommerce_after_shop_loop_item_title hook
*
* @hooked woocommerce_template_loop_rating - 5
* @hooked woocommerce_template_loop_price - 10
*/
do_action( 'woocommerce_after_shop_loop_item_title' );
?>
</a>
```
move the a tag like:
```
<?php
/**
* woocommerce_before_shop_loop_item_title hook
*
* @hooked woocommerce_show_product_loop_sale_flash - 10
* @hooked woocommerce_template_loop_product_thumbnail - 10
*/
do_action( 'woocommerce_before_shop_loop_item_title' );
?>
<h3><?php the_title(); ?></h3>
<?php
/**
* woocommerce_after_shop_loop_item_title hook
*
* @hooked woocommerce_template_loop_rating - 5
* @hooked woocommerce_template_loop_price - 10
*/
do_action( 'woocommerce_after_shop_loop_item_title' );
?>
<a href="<?php the_permalink(); ?>"></a>
```
Note: Use the customization in your theme/woocommerce directory otherwise changes will undo if plugin got update.
Hence above changes may depend on the theme you are using. if your theme already have woocommerce do changes accordingly.
|
191,264 |
<p>I <em>need</em> a function that I can use that will remove <div> and </div> tags from a string. I have tried <em>esc_attr()</em>, and even <em>wp_strip_all_tags()</em> --- none of them work. They all leave the <div> and </div> tags in the string - which causes certain social-media buttons to turn out in ways that <em>really</em> do not look good.</p>
<p>Any suggestions what to do?</p>
|
[
{
"answer_id": 191269,
"author": "ChrisL",
"author_id": 70768,
"author_profile": "https://wordpress.stackexchange.com/users/70768",
"pm_score": 0,
"selected": false,
"text": "<p>If it's only <div></div> I would do a <a href=\"http://php.net/manual/de/function.preg-replace.php\" rel=\"nofollow\">preg_replace</a>, like this:</p>\n\n<pre><code>$string = preg_replace ( '|</?[^>]*>|i', '', $string );\n</code></pre>\n\n<p>This removes only the tags, not the text between the Tags. I understood this is what you wanted.</p>\n"
},
{
"answer_id": 191278,
"author": "Laurence Tuck",
"author_id": 1426,
"author_profile": "https://wordpress.stackexchange.com/users/1426",
"pm_score": 1,
"selected": false,
"text": "<p>Use a PHP function to do this: <a href=\"https://php.net/strip_tags\" rel=\"nofollow\">https://php.net/strip_tags</a></p>\n\n<p>example: </p>\n\n<pre><code>echo strip_tags(\"<div>my text</div>\");\n</code></pre>\n"
}
] |
2015/06/12
|
[
"https://wordpress.stackexchange.com/questions/191264",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/71557/"
] |
I *need* a function that I can use that will remove <div> and </div> tags from a string. I have tried *esc\_attr()*, and even *wp\_strip\_all\_tags()* --- none of them work. They all leave the <div> and </div> tags in the string - which causes certain social-media buttons to turn out in ways that *really* do not look good.
Any suggestions what to do?
|
Use a PHP function to do this: <https://php.net/strip_tags>
example:
```
echo strip_tags("<div>my text</div>");
```
|
191,273 |
<p>This is my first post on <em>WordPress StackExchange</em>, I'll try to be precise.</p>
<blockquote>
<p>My question is: <strong>Is there anything in particular I should do to the files I'm including in my theme's functions.php file?</strong></p>
</blockquote>
<p>I'm creating a WordPress theme and my <strong>functions.php</strong> file is getting very big now. I managed to remove a lot of code by turning some functions into plugins but it is still huge.</p>
<p>I would like to be able to organize the code with <em>includes</em>. I tried a couple of things but it didn't work. It's like the files I included in my functions.php file are being ignored.</p>
<pre><code>// Configure the WordPress Customizer
require(get_template_directory_uri() . '/admin/customizer/customizer.php');
</code></pre>
<p>The above code is supposed to call a file that's adding a function that creates sections, settings and controls in the WordPress Customizer. When the function is placed <strong>directly into my functions.php file</strong> everything works fine but when I try to include it, it does nothing.</p>
<p>The included file also contains <em>includes</em>, I don't know if this is of relevance.</p>
<p><em>The above code is hooked on <strong>after_setup_theme</strong>, if you think I should do anything differently please tell me, I want to learn.</em></p>
|
[
{
"answer_id": 191275,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>I always break my functions.php up into more managable, specific functionality files, for instance, all footer related functions goes into a file called <code>footer-functions.php</code> and pagination functions goes into a file called <code>pagination-functions.php</code>. This way, my code stays organised, managable and I don't kill my <code>functions.php</code>. This however, is only related to theme specific functions, site specific functions goes into plugins in much more the same type of method</p>\n\n<p>To come back to the point, at the end I include all my smaller specific function files into <code>functions.php</code> with <code>require_once()</code> as follow</p>\n\n<pre><code>require_once( 'footer-functions.php' );\nrequire_once( 'pagination-functions.php' );\n</code></pre>\n\n<p>This is all you need. You should not hook this to any hook or add it in any function, it can have expected behavior which can lead to a broken site</p>\n"
},
{
"answer_id": 191277,
"author": "Laurence Tuck",
"author_id": 1426,
"author_profile": "https://wordpress.stackexchange.com/users/1426",
"pm_score": 0,
"selected": false,
"text": "<p>In my opinion, your functions file can be as big as you want it, but organizing functions into includes is a very logical process. I would first check that get_template_directory_uri() is returning the correct path. You can also include files without the full path within your theme if /admin/ is in your theme root: require('/admin/customizer/customizer.php'); </p>\n"
},
{
"answer_id": 191286,
"author": "harryg",
"author_id": 23620,
"author_profile": "https://wordpress.stackexchange.com/users/23620",
"pm_score": 1,
"selected": false,
"text": "<p>Your problem is that you've used the <code>get_template_directory_uri()</code> function for your include path. As indicated by the function name, this returns a URI (not a path), which is no use for including one php file into another. </p>\n\n<p>Simply enter the relative path of the file to be included.</p>\n\n<p>E.g. if your structure is:</p>\n\n<pre><code>/my-theme\n |--functions.php\n |--/lib\n |--customizer.php\n |--tools.php\n |--style.css\n ...etc\n</code></pre>\n\n<p>In your functions.php simple put</p>\n\n<pre><code><?php\n\nrequire_once('lib/customizer.php');\nrequire_once('lib/tools.php');\n</code></pre>\n\n<p>The approach is the same whether using <code>require()</code>, <code>require_once()</code> or <code>include()</code></p>\n"
}
] |
2015/06/12
|
[
"https://wordpress.stackexchange.com/questions/191273",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74575/"
] |
This is my first post on *WordPress StackExchange*, I'll try to be precise.
>
> My question is: **Is there anything in particular I should do to the files I'm including in my theme's functions.php file?**
>
>
>
I'm creating a WordPress theme and my **functions.php** file is getting very big now. I managed to remove a lot of code by turning some functions into plugins but it is still huge.
I would like to be able to organize the code with *includes*. I tried a couple of things but it didn't work. It's like the files I included in my functions.php file are being ignored.
```
// Configure the WordPress Customizer
require(get_template_directory_uri() . '/admin/customizer/customizer.php');
```
The above code is supposed to call a file that's adding a function that creates sections, settings and controls in the WordPress Customizer. When the function is placed **directly into my functions.php file** everything works fine but when I try to include it, it does nothing.
The included file also contains *includes*, I don't know if this is of relevance.
*The above code is hooked on **after\_setup\_theme**, if you think I should do anything differently please tell me, I want to learn.*
|
I always break my functions.php up into more managable, specific functionality files, for instance, all footer related functions goes into a file called `footer-functions.php` and pagination functions goes into a file called `pagination-functions.php`. This way, my code stays organised, managable and I don't kill my `functions.php`. This however, is only related to theme specific functions, site specific functions goes into plugins in much more the same type of method
To come back to the point, at the end I include all my smaller specific function files into `functions.php` with `require_once()` as follow
```
require_once( 'footer-functions.php' );
require_once( 'pagination-functions.php' );
```
This is all you need. You should not hook this to any hook or add it in any function, it can have expected behavior which can lead to a broken site
|
191,279 |
<p>Is it possible to change permalinks on all posts created after a certain date? This because we don't want old URLs to break.</p>
<p>Now we have <code>/%year%/%month%/%postname%</code>
We want to have <code>/%postname</code></p>
|
[
{
"answer_id": 191343,
"author": "Bruno Monteiro",
"author_id": 36031,
"author_profile": "https://wordpress.stackexchange.com/users/36031",
"pm_score": -1,
"selected": false,
"text": "<p>You can create a new post type, under the name \"post\" and then add a rewrite slug. This will overwrite the default Wordpres post type.</p>\n\n<p>Here is a sample code:</p>\n\n<pre><code>add_action( 'init', 'my_new_default_post_type', 1 );\nfunction my_new_default_post_type() {\n\n register_post_type( 'post', array(\n 'labels' => array(\n 'name_admin_bar' => _x( 'Post', 'add new on admin bar' ),\n ),\n 'public' => true,\n '_builtin' => false, \n '_edit_link' => 'post.php?post=%d', \n 'capability_type' => 'post',\n 'map_meta_cap' => true,\n 'hierarchical' => false,\n 'rewrite' => array( 'slug' => 'post' ),\n 'query_var' => false,\n 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'post-formats' ),\n ) );\n}\n</code></pre>\n\n<p>This is not tested, but you can give it a try. It's better than changing the URL settings on htaccess - because it will apply to all posts and pages.</p>\n"
},
{
"answer_id": 191440,
"author": "Mathew Tinsley",
"author_id": 69793,
"author_profile": "https://wordpress.stackexchange.com/users/69793",
"pm_score": 4,
"selected": true,
"text": "<p>Your permalink structure is global; it is not a property of individual posts. There is no way to indicate that one post uses a certain permalink structure while another uses a different one.</p>\n\n<p>This makes sense when you think about how WordPress processes requests. Using the new structure, WordPress maps the request to <code>index.php?name=$1</code> where <code>$1</code> is the post slug portion of the request. WordPress then queries the database for a post with a slug that matches the request.</p>\n\n<p>If every post had its own permalink structure, WordPress would have to iterate over every single post until it found one with a permalink structure that matched the request.</p>\n\n<p>What you can do is redirect your old permalinks to the new permalinks. There are a couple of ways you can go about doing this:</p>\n\n<hr>\n\n<p><strong>.htaccess</strong></p>\n\n<p>You can add the following to your <code>.htaccess</code> file, before the WordPress rewrite rules:</p>\n\n<pre><code><IfModule mod_rewrite.c>\n RewriteEngine On\n RewriteBase /\n RewriteRule ^[0-9]{4}/[0-9]{2}/(.*)$ /$1 [R=301,L]\n</IfModule>\n</code></pre>\n\n<p>This will match the <code>year/month/postname</code> structure and redirect to the <code>postname</code> structure.</p>\n\n<p><strong>add_rewrite_rule</strong></p>\n\n<p>You can use <a href=\"https://codex.wordpress.org/Rewrite_API/add_rewrite_rule\"><code>add_rewrite_rule</code></a> to create an additional rule that matches your old permalink structure.</p>\n\n<pre><code>add_action('init', function() {\n flush_rewrite_rules();\n add_rewrite_rule('^([0-9]{4})/([0-9]{2})/(.*)$', 'index.php?name=$matches[3]', 'bottom');\n});\n</code></pre>\n\n<p>This accomplishes the same thing as the <code>.htaccess</code> method. If you use this approach make sure you flush your rewrite rules by visiting the <code>Settings > Permalinks</code> page in your backend.</p>\n\n<hr>\n\n<p>Regardless of which approach you use, the canonical URL for your posts will use the new permalink structure. Requests using the old permalink structure will be redirected to the new structure.</p>\n\n<p>Search engines will eventually catch on to the change and index the new structure rather than the old structure. At that point, you can drop the additional rewrite rules, <em>so long as you don't have any internal links using the old structure</em>.</p>\n\n<p>If you do have internal links using the old structure, I would use <a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\">this utility</a> to do a regex search and replace. Just make sure you make a backup of your database.</p>\n\n<p>If you are concerned about inbound links using the old structure, there isn't much you can do other than keep the rewrite rules indefinitely.</p>\n"
},
{
"answer_id": 191830,
"author": "Julien B.",
"author_id": 65672,
"author_profile": "https://wordpress.stackexchange.com/users/65672",
"pm_score": 0,
"selected": false,
"text": "<p>Depending on how many pages that represents (the old ones), you might consider creating a rewrite rule for every single page with a permanent redirect flag.</p>\n\n<p>If this is not an option, I think mtinsley's answer is your best bet.</p>\n"
},
{
"answer_id": 192173,
"author": "zaantar",
"author_id": 75006,
"author_profile": "https://wordpress.stackexchange.com/users/75006",
"pm_score": 0,
"selected": false,
"text": "<p>You might find the <a href=\"https://wordpress.org/plugins/redirection/\" rel=\"nofollow\">Redirection</a> plugin interesting. </p>\n\n<p>It should allow you to change the permalink structure while keeping old URLs valid.</p>\n"
}
] |
2015/06/12
|
[
"https://wordpress.stackexchange.com/questions/191279",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/19188/"
] |
Is it possible to change permalinks on all posts created after a certain date? This because we don't want old URLs to break.
Now we have `/%year%/%month%/%postname%`
We want to have `/%postname`
|
Your permalink structure is global; it is not a property of individual posts. There is no way to indicate that one post uses a certain permalink structure while another uses a different one.
This makes sense when you think about how WordPress processes requests. Using the new structure, WordPress maps the request to `index.php?name=$1` where `$1` is the post slug portion of the request. WordPress then queries the database for a post with a slug that matches the request.
If every post had its own permalink structure, WordPress would have to iterate over every single post until it found one with a permalink structure that matched the request.
What you can do is redirect your old permalinks to the new permalinks. There are a couple of ways you can go about doing this:
---
**.htaccess**
You can add the following to your `.htaccess` file, before the WordPress rewrite rules:
```
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^[0-9]{4}/[0-9]{2}/(.*)$ /$1 [R=301,L]
</IfModule>
```
This will match the `year/month/postname` structure and redirect to the `postname` structure.
**add\_rewrite\_rule**
You can use [`add_rewrite_rule`](https://codex.wordpress.org/Rewrite_API/add_rewrite_rule) to create an additional rule that matches your old permalink structure.
```
add_action('init', function() {
flush_rewrite_rules();
add_rewrite_rule('^([0-9]{4})/([0-9]{2})/(.*)$', 'index.php?name=$matches[3]', 'bottom');
});
```
This accomplishes the same thing as the `.htaccess` method. If you use this approach make sure you flush your rewrite rules by visiting the `Settings > Permalinks` page in your backend.
---
Regardless of which approach you use, the canonical URL for your posts will use the new permalink structure. Requests using the old permalink structure will be redirected to the new structure.
Search engines will eventually catch on to the change and index the new structure rather than the old structure. At that point, you can drop the additional rewrite rules, *so long as you don't have any internal links using the old structure*.
If you do have internal links using the old structure, I would use [this utility](https://interconnectit.com/products/search-and-replace-for-wordpress-databases/) to do a regex search and replace. Just make sure you make a backup of your database.
If you are concerned about inbound links using the old structure, there isn't much you can do other than keep the rewrite rules indefinitely.
|
191,293 |
<p>I have a page where, with shortcode, I queried multiple posts from a CPT - so the page is one kind of archive page to the general users.</p>
<pre><code>Page Title
- CPT Post Title #1
- CPT Post Title #2
- CPT Post Title #3
</code></pre>
<p>In certain condition I want to alter only the Page Title, not CPT Post Title. I tried:</p>
<pre><code>function wpse_change_page_title( $title ) {
//if( condition matched ) {
return 'Test ' . $title;
//}
}
add_filter( 'the_title', 'wpse_change_page_title' );
</code></pre>
<p>But it's altering the CPT Post Titles.</p>
<pre><code>Page Title
- Test CPT Post Title #1
- Test CPT Post Title #2
- Test CPT Post Title #3
</code></pre>
<p>How can I alter only the Page title, not those CPT Post Titles?</p>
<pre><code>Test Page Title
</code></pre>
|
[
{
"answer_id": 191297,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>I believe that the page title you are talking about is the title from the page from the main query. <code>the_title()</code> filter (and <code>the_content()</code> filter for that matter) targets all the respective template tags regardless of query. </p>\n\n<p>To avoid this, target only the main query and the specific page. </p>\n\n<p>You can try the following inside your filter</p>\n\n<pre><code>if ( in_the_loop() && is_page( 'specific page' ) ) {\n\n // Do what you need to do\n\n}\n</code></pre>\n\n<h2>EDIT</h2>\n\n<p>I just thought of this, haven't tested it, but you can check your title inside the filter against a known static title and then do something according to that</p>\n\n<p>Example:</p>\n\n<pre><code>if ( $title == 'My known title' ) {\n\n // Do something with the title\n\n}\n</code></pre>\n"
},
{
"answer_id": 191320,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 0,
"selected": false,
"text": "<p>I am not entirely sure I understand your project but it sounds to me like you should be using the <a href=\"https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/general-template.php#L897\" rel=\"nofollow\"><code>wp_title</code></a> filter, instead of the <code>the_title</code> filter. That is fired by the <code>wp_title()</code> function which outputs the page title, not the titles of the posts on the page. Something like:</p>\n\n<pre><code>function wpse_change_page_title( $title ) {\n if(is_page('some_page')) {\n return 'Test ' . $title;\n }\n}\nadd_filter( 'wp_title', 'wpse_change_page_title' );\n</code></pre>\n"
},
{
"answer_id": 191326,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 0,
"selected": false,
"text": "<p>The second argument for <code>the_title</code> is always a post ID. Use it.</p>\n\n<pre><code>add_filter( 'the_title', function( $title, $post_id) {\n\n $post = get_post( $post_id );\n\n if ( ! $post or 'your_cpt' !== $post->post_type )\n return $title;\n\n return 'Test ' . $title;\n}, 10, 2 );\n</code></pre>\n"
}
] |
2015/06/12
|
[
"https://wordpress.stackexchange.com/questions/191293",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/22728/"
] |
I have a page where, with shortcode, I queried multiple posts from a CPT - so the page is one kind of archive page to the general users.
```
Page Title
- CPT Post Title #1
- CPT Post Title #2
- CPT Post Title #3
```
In certain condition I want to alter only the Page Title, not CPT Post Title. I tried:
```
function wpse_change_page_title( $title ) {
//if( condition matched ) {
return 'Test ' . $title;
//}
}
add_filter( 'the_title', 'wpse_change_page_title' );
```
But it's altering the CPT Post Titles.
```
Page Title
- Test CPT Post Title #1
- Test CPT Post Title #2
- Test CPT Post Title #3
```
How can I alter only the Page title, not those CPT Post Titles?
```
Test Page Title
```
|
I believe that the page title you are talking about is the title from the page from the main query. `the_title()` filter (and `the_content()` filter for that matter) targets all the respective template tags regardless of query.
To avoid this, target only the main query and the specific page.
You can try the following inside your filter
```
if ( in_the_loop() && is_page( 'specific page' ) ) {
// Do what you need to do
}
```
EDIT
----
I just thought of this, haven't tested it, but you can check your title inside the filter against a known static title and then do something according to that
Example:
```
if ( $title == 'My known title' ) {
// Do something with the title
}
```
|
191,296 |
<p>So I'm trying to save the value of a custom term to my database.
The table is created as is the custom term. The code below outputs the text field onto my custom terms page but it just doesn't save any value to the database. </p>
<p>Can anyone see if there's anything wrong with this? (I'm sure there's something I've missed)</p>
<pre><code>add_action ( 'movie_edit_form_fields', 'movie_access_metabox' );
add_action ( 'edited_movie', 'save_movie_data' );
function movie_access_metabox($movie) {
global $wpdb;
$value = $wpdb->get_var('select meta_value from wp_termmeta where meta_value='.$movie->meta_value);
?>
<tr>
<th scope="row" valign="top"><label><?php _e('Movie year') ?></label></th>
<td>
<input type="text" id="year" name="year" value="" <?php echo $value ?>>
</td>
</tr>
<?php
}
function save_movie_data($term_id) {
global $wpdb;
$wpdb->termmeta = 'wp_termmeta';
if (isset($_POST['year'])) {
$wpdb->delete('wp_termmeta', array('meta_key' => '_year', 'term_id' => $term_id));
$wpdb->insert('wp_termmeta', array('term_id' => $term_id, ',meta_key' => '_year', 'meta_value' => $value));
}else{
$wpdb->delete('wp_termmeta', array('meta_key' => '_year', 'term_id' => $term_id));
}
}
</code></pre>
<h2>UPDATE #1:</h2>
<p>Failing to manage to get the answer provided by @Oleg Butuzov to work, I have put some more time into my original answer and got it to the stage where it saves the users input to the db. The problem now is that it only seems able to save one value, the value can be updated but only one row can be added at a time. If anyone has any ideas please bring them forward and I will continue to update the code so hopefully can help someone else in future.</p>
<h2>UPDATE #2:</h2>
<p>*Removed wrong code from post. </p>
<p>It turns out that the main reasons I was only able to add one value was due to the fact I had only used <code>delete</code> and <code>insert</code> - no <code>update</code> and had not used <code>AUTO_INCREMENT</code> on the create <code>termmeta</code> schema. Full working answer is provided below.</p>
|
[
{
"answer_id": 191297,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>I believe that the page title you are talking about is the title from the page from the main query. <code>the_title()</code> filter (and <code>the_content()</code> filter for that matter) targets all the respective template tags regardless of query. </p>\n\n<p>To avoid this, target only the main query and the specific page. </p>\n\n<p>You can try the following inside your filter</p>\n\n<pre><code>if ( in_the_loop() && is_page( 'specific page' ) ) {\n\n // Do what you need to do\n\n}\n</code></pre>\n\n<h2>EDIT</h2>\n\n<p>I just thought of this, haven't tested it, but you can check your title inside the filter against a known static title and then do something according to that</p>\n\n<p>Example:</p>\n\n<pre><code>if ( $title == 'My known title' ) {\n\n // Do something with the title\n\n}\n</code></pre>\n"
},
{
"answer_id": 191320,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 0,
"selected": false,
"text": "<p>I am not entirely sure I understand your project but it sounds to me like you should be using the <a href=\"https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/general-template.php#L897\" rel=\"nofollow\"><code>wp_title</code></a> filter, instead of the <code>the_title</code> filter. That is fired by the <code>wp_title()</code> function which outputs the page title, not the titles of the posts on the page. Something like:</p>\n\n<pre><code>function wpse_change_page_title( $title ) {\n if(is_page('some_page')) {\n return 'Test ' . $title;\n }\n}\nadd_filter( 'wp_title', 'wpse_change_page_title' );\n</code></pre>\n"
},
{
"answer_id": 191326,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 0,
"selected": false,
"text": "<p>The second argument for <code>the_title</code> is always a post ID. Use it.</p>\n\n<pre><code>add_filter( 'the_title', function( $title, $post_id) {\n\n $post = get_post( $post_id );\n\n if ( ! $post or 'your_cpt' !== $post->post_type )\n return $title;\n\n return 'Test ' . $title;\n}, 10, 2 );\n</code></pre>\n"
}
] |
2015/06/12
|
[
"https://wordpress.stackexchange.com/questions/191296",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67320/"
] |
So I'm trying to save the value of a custom term to my database.
The table is created as is the custom term. The code below outputs the text field onto my custom terms page but it just doesn't save any value to the database.
Can anyone see if there's anything wrong with this? (I'm sure there's something I've missed)
```
add_action ( 'movie_edit_form_fields', 'movie_access_metabox' );
add_action ( 'edited_movie', 'save_movie_data' );
function movie_access_metabox($movie) {
global $wpdb;
$value = $wpdb->get_var('select meta_value from wp_termmeta where meta_value='.$movie->meta_value);
?>
<tr>
<th scope="row" valign="top"><label><?php _e('Movie year') ?></label></th>
<td>
<input type="text" id="year" name="year" value="" <?php echo $value ?>>
</td>
</tr>
<?php
}
function save_movie_data($term_id) {
global $wpdb;
$wpdb->termmeta = 'wp_termmeta';
if (isset($_POST['year'])) {
$wpdb->delete('wp_termmeta', array('meta_key' => '_year', 'term_id' => $term_id));
$wpdb->insert('wp_termmeta', array('term_id' => $term_id, ',meta_key' => '_year', 'meta_value' => $value));
}else{
$wpdb->delete('wp_termmeta', array('meta_key' => '_year', 'term_id' => $term_id));
}
}
```
UPDATE #1:
----------
Failing to manage to get the answer provided by @Oleg Butuzov to work, I have put some more time into my original answer and got it to the stage where it saves the users input to the db. The problem now is that it only seems able to save one value, the value can be updated but only one row can be added at a time. If anyone has any ideas please bring them forward and I will continue to update the code so hopefully can help someone else in future.
UPDATE #2:
----------
\*Removed wrong code from post.
It turns out that the main reasons I was only able to add one value was due to the fact I had only used `delete` and `insert` - no `update` and had not used `AUTO_INCREMENT` on the create `termmeta` schema. Full working answer is provided below.
|
I believe that the page title you are talking about is the title from the page from the main query. `the_title()` filter (and `the_content()` filter for that matter) targets all the respective template tags regardless of query.
To avoid this, target only the main query and the specific page.
You can try the following inside your filter
```
if ( in_the_loop() && is_page( 'specific page' ) ) {
// Do what you need to do
}
```
EDIT
----
I just thought of this, haven't tested it, but you can check your title inside the filter against a known static title and then do something according to that
Example:
```
if ( $title == 'My known title' ) {
// Do something with the title
}
```
|
191,299 |
<p>I've been learning to convert HTML to WordPress and want to convert on to class like this:</p>
<pre><code><div class="mainmenu pull-left">
<ul class="nav navbar-nav collapse navbar-collapse">
<li><a href="index.html" class="active">Home</a></li>
<li class="dropdown"><a href="#">Shop<i class="fa fa-angle-down"></i></a>
<ul role="menu" class="sub-menu">
<li><a href="shop.html">Products</a></li>
<li><a href="product-details.html">Product Details</a></li>
<li><a href="checkout.html">Checkout</a></li>
<li><a href="cart.html">Cart</a></li>
<li><a href="login.html">Login</a></li>
</ul>
</li>
<li class="dropdown"><a href="#">Blog<i class="fa fa-angle-down"></i></a>
<ul role="menu" class="sub-menu">
<li><a href="blog.html">Blog List</a></li>
<li><a href="blog-single.html">Blog Single</a></li>
</ul>
</li>
<li><a href="404.html">404</a></li>
<li><a href="contact-us.html">Contact</a></li>
</ul>
</div>
</code></pre>
<p>This what I've done:</p>
<pre><code>if ( ! function_exists( 'mytheme_setup' ) ) :
function wpflex_setup() {
register_nav_menus( array(
'primary' => 'Primary Menu'
) );
}
endif;
wp_nav_menu( array(
'theme_location' => 'top-menu',
'container' => '',
'menu_class' => 'mainmenu pull-left',
) );
</code></pre>
<p>How to add class for <code>ul</code>?</p>
|
[
{
"answer_id": 191309,
"author": "ChrisL",
"author_id": 70768,
"author_profile": "https://wordpress.stackexchange.com/users/70768",
"pm_score": 3,
"selected": false,
"text": "<p>You already did it the right way. If you take a look in the Documentation for <a href=\"https://developer.wordpress.org/reference/functions/wp_nav_menu/\" rel=\"noreferrer\">wp_nav_menu</a>, you'll see that menu_class is the right option for the UL's class:</p>\n\n<pre><code>wp_nav_menu( array(\n 'theme_location' => 'top-menu',\n 'container' => '',\n 'menu_class'=> 'mainmenu pull-left *add-your-class-here*'\n ) );\n</code></pre>\n"
},
{
"answer_id": 191324,
"author": "Behzad",
"author_id": 70359,
"author_profile": "https://wordpress.stackexchange.com/users/70359",
"pm_score": 3,
"selected": false,
"text": "<p>It's simple just you need to add <code>items_wrap</code> parameter and add or edit class attr: </p>\n\n<pre><code>wp_nav_menu( array(\n 'theme_location' => 'top-menu',\n 'container' => false,\n 'items_wrap' => '<ul class=\"nav your_custom_class\">%3$s</ul>',\n));\n</code></pre>\n"
},
{
"answer_id": 257888,
"author": "Ted",
"author_id": 44012,
"author_profile": "https://wordpress.stackexchange.com/users/44012",
"pm_score": 1,
"selected": false,
"text": "<p>Wordpress creates the default page menu different from the active menus -- those which you create and assign in the backend. There is no direct way to add classes to the UL in page menus, but there are other ways. Try adding this to your functions.php</p>\n\n<pre><code>function add_id_and_classes_to_page_menu( $ulclass ) {\n return preg_replace( '/<ul>/', '<ul id=\"main-menu\" class=\"nav navbar-nav collapse navbar-collapse\">', $ulclass, 1 );\n}\nadd_filter( 'wp_page_menu', 'add_id_and_classes_to_page_menu' );\n</code></pre>\n\n<p>Keep in mind this will replace any existing id and classes, thus I re-added them in the above example. I also added an id=\"main-menu\" for completion.</p>\n"
},
{
"answer_id": 265158,
"author": "J. Shabu",
"author_id": 118124,
"author_profile": "https://wordpress.stackexchange.com/users/118124",
"pm_score": 1,
"selected": false,
"text": "<p>Here is your fixed code. I have tested it add class to ul</p>\n\n<pre><code>wp_nav_menu( array( \n 'theme_location' => 'top-menu',\n 'container' => 'ul',\n 'menu_class' => 'mainmenu pull-left',\n) );\n</code></pre>\n"
},
{
"answer_id": 268418,
"author": "Alpesh Navadiya",
"author_id": 116157,
"author_profile": "https://wordpress.stackexchange.com/users/116157",
"pm_score": 1,
"selected": false,
"text": "<pre><code> <?php \n wp_nav_menu( array('menu' => 'Main Menu' ,\n 'menu_class' => 'nav navbar-nav',\n 'container' => ''));\n ?>\n</code></pre>\n"
}
] |
2015/06/12
|
[
"https://wordpress.stackexchange.com/questions/191299",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74591/"
] |
I've been learning to convert HTML to WordPress and want to convert on to class like this:
```
<div class="mainmenu pull-left">
<ul class="nav navbar-nav collapse navbar-collapse">
<li><a href="index.html" class="active">Home</a></li>
<li class="dropdown"><a href="#">Shop<i class="fa fa-angle-down"></i></a>
<ul role="menu" class="sub-menu">
<li><a href="shop.html">Products</a></li>
<li><a href="product-details.html">Product Details</a></li>
<li><a href="checkout.html">Checkout</a></li>
<li><a href="cart.html">Cart</a></li>
<li><a href="login.html">Login</a></li>
</ul>
</li>
<li class="dropdown"><a href="#">Blog<i class="fa fa-angle-down"></i></a>
<ul role="menu" class="sub-menu">
<li><a href="blog.html">Blog List</a></li>
<li><a href="blog-single.html">Blog Single</a></li>
</ul>
</li>
<li><a href="404.html">404</a></li>
<li><a href="contact-us.html">Contact</a></li>
</ul>
</div>
```
This what I've done:
```
if ( ! function_exists( 'mytheme_setup' ) ) :
function wpflex_setup() {
register_nav_menus( array(
'primary' => 'Primary Menu'
) );
}
endif;
wp_nav_menu( array(
'theme_location' => 'top-menu',
'container' => '',
'menu_class' => 'mainmenu pull-left',
) );
```
How to add class for `ul`?
|
You already did it the right way. If you take a look in the Documentation for [wp\_nav\_menu](https://developer.wordpress.org/reference/functions/wp_nav_menu/), you'll see that menu\_class is the right option for the UL's class:
```
wp_nav_menu( array(
'theme_location' => 'top-menu',
'container' => '',
'menu_class'=> 'mainmenu pull-left *add-your-class-here*'
) );
```
|
191,310 |
<p>I have been developing a WordPress website for a client, working from my own machine utilizing WAMP to create a local environment on which to work.</p>
<p>Now, the problem is that the website needs to go live. I understand how to use an FTP client, and that's not a problem. I have the details for the domain etc. There is an existing website already there, and I would like to know if it's possible to upload the new website while keeping the old one running, but that is not the main issue. </p>
<p>I have been having trouble transferring the website from one machine to another, and I believe that this has to do with properly exporting/importing the database. This is the area that I am struggling with. To make things even more difficult, I wish to upload the new website to the server but use the database that is already in place with the existing website, for the client's benefit. Is this possible? How would I achieve this? If it is not, what are my alternatives? </p>
<p>Apologies for the short essay, but I thought it best to paint as clear a picture of my situation as possible. Thanks in advance for time taken to read/respond to this. </p>
|
[
{
"answer_id": 191323,
"author": "TheGentleman",
"author_id": 68563,
"author_profile": "https://wordpress.stackexchange.com/users/68563",
"pm_score": 0,
"selected": false,
"text": "<p>If your client's existing site is a wordpress site and you just want to use your new theme then you can just upload the theme from your local PC to the remote server and change the theme out in the remote backend.</p>\n\n<p>Either way, how you run both sites simultaneously will differ depending on your exact setup.</p>\n\n<p>As far as transferring your database goes, I assume you're exporting it as a <code>.sql</code> file? After you export it from your local database, open the file in a text editor (Notepad++ works well), do a search/replace on the file to replace <code>http://localhost</code> to <code>http://yourdomain.com</code>. Then upload the modified sql file to the remote database. You'll also have to open the <code>config.php</code> file in the root of your wordpress directory and change out the database credentials to be those of the remote database.</p>\n"
},
{
"answer_id": 191376,
"author": "Jbbhatti",
"author_id": 63179,
"author_profile": "https://wordpress.stackexchange.com/users/63179",
"pm_score": 0,
"selected": false,
"text": "<p>You can easy plugin transfer to other host\n<a href=\"https://wordpress.org/plugins/wp-clone-by-wp-academy/\" rel=\"nofollow\">https://wordpress.org/plugins/wp-clone-by-wp-academy/</a></p>\n\n<p>localhost \n1: first install plugin your localhost wordpress.\n2: goto wp clone create local backup.\n3: copy backup .zip upload any host/server.</p>\n\n<p>host/server\n1: first install plugin your host/server wordpress.\n2: goto wp clone select restore backup.\n3: localhost backup link paste. </p>\n\n<p>enjoy</p>\n"
},
{
"answer_id": 281405,
"author": "cstls",
"author_id": 81835,
"author_profile": "https://wordpress.stackexchange.com/users/81835",
"pm_score": 0,
"selected": false,
"text": "<p>When transferring a db from any origin to another in WordPress, you need to update some key tables to be replaced with the host's pathname and the domain.</p>\n\n<p>Here's a handy SQL snippet I use regularly when doing this manually.</p>\n\n<pre><code>-- Avoid updating serialized strings with \"NOT LIKE '%{%'\"\nUPDATE wp_options SET option_value = REPLACE(option_value, '//olddomain.com', '//newdomain.com') WHERE option_value NOT LIKE '%{%';\nUPDATE wp_postmeta SET meta_value = REPLACE(meta_value, '//olddomain.com', '//newdomain.com') WHERE meta_value NOT LIKE '%{%';\nUPDATE wp_posts SET post_content = REPLACE(post_content, '//olddomain.com', '//newdomain.com') WHERE post_content NOT LIKE '%{%';\nUPDATE wp_posts SET guid = REPLACE(guid, '//olddomain.com', '//newdomain.com') WHERE post_type = 'attachment';\n\n-- File paths\nUPDATE wp_options SET option_value = REPLACE(option_value, '/home/old/path', '/home/new/path') WHERE option_value NOT LIKE '%{%';\nUPDATE wp_postmeta SET meta_value = REPLACE(meta_value, '/home/old/path', '/home/new/path') WHERE meta_value NOT LIKE '%{%';\n</code></pre>\n\n<p>However, in most cases I use wp-sync-db to handle this for me. It can be found here: <a href=\"https://github.com/wp-sync-db/wp-sync-db\" rel=\"nofollow noreferrer\">https://github.com/wp-sync-db/wp-sync-db</a></p>\n\n<p>I would highly recommend using the plugin above if you are unfamiliar with SQL querie, though.</p>\n"
},
{
"answer_id": 281408,
"author": "dwcouch",
"author_id": 33411,
"author_profile": "https://wordpress.stackexchange.com/users/33411",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Moving your sites</strong></p>\n\n<p>My recommendation would be to use the the <a href=\"https://wordpress.org/plugins/duplicator/\" rel=\"nofollow noreferrer\">duplicator</a> plugin. Far and away the easiest method I've used to back-up, move, and restore sites from local to production or from one host to another.</p>\n\n<p>If the old site is WordPress - sounds like it is, you may want to consider creating a sub-domain and then using <a href=\"https://wordpress.org/plugins/duplicator/\" rel=\"nofollow noreferrer\">duplicator</a> on the old site to back-up and then restore the old site to the new sub-domain. </p>\n\n<pre><code>mysite.com -> old.mysite.com\n</code></pre>\n\n<p>Then use <a href=\"https://wordpress.org/plugins/duplicator/\" rel=\"nofollow noreferrer\">duplicator</a> to back-up your local dev site and then restore it to the location of the original site.</p>\n\n<p><strong>Connecting to the old DB</strong></p>\n\n<p>Once you have both sites on your host mysite.com and old.mysite.com you could change the settings in the wp-config.php of the new site (now mysite.com) to point to the db of the old site (old.mysite.com) like so:</p>\n\n<pre><code>// wp-config.php\n\ndefine ( 'DB_NAME', 'olddbname' );\ndefine ( 'DB_USER', 'olddbusername' );\ndefine ( 'DB_PASSWORD', 'olddbpassword' );\ndefine ( 'DB_HOST', 'old.mysite.com' ); \n</code></pre>\n\n<p>In fact you could probably just copy the DB definitions from the wp-config of old.mysite.com into the wp-config of the mysite.com. </p>\n\n<ul>\n<li><em>I'd comment out the db definitions present for mysite.com.</em></li>\n</ul>\n\n<p>Can you clarify what you want to accomplish by doing this? \nThe problem with pointing the new site to the old db is that it will also use the old site theme etc. A sum zero really. If your just trying to get the posts and pages from the old site to the new, I'd use the export/import tools that come packaged with WordPress. There are also syndicate plugins (<a href=\"https://wordpress.org/plugins/feedpress/\" rel=\"nofollow noreferrer\">FeedPress</a> is my preferred one) that seem to be more robust than the WordPress import/export tools.</p>\n"
}
] |
2015/06/12
|
[
"https://wordpress.stackexchange.com/questions/191310",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74597/"
] |
I have been developing a WordPress website for a client, working from my own machine utilizing WAMP to create a local environment on which to work.
Now, the problem is that the website needs to go live. I understand how to use an FTP client, and that's not a problem. I have the details for the domain etc. There is an existing website already there, and I would like to know if it's possible to upload the new website while keeping the old one running, but that is not the main issue.
I have been having trouble transferring the website from one machine to another, and I believe that this has to do with properly exporting/importing the database. This is the area that I am struggling with. To make things even more difficult, I wish to upload the new website to the server but use the database that is already in place with the existing website, for the client's benefit. Is this possible? How would I achieve this? If it is not, what are my alternatives?
Apologies for the short essay, but I thought it best to paint as clear a picture of my situation as possible. Thanks in advance for time taken to read/respond to this.
|
**Moving your sites**
My recommendation would be to use the the [duplicator](https://wordpress.org/plugins/duplicator/) plugin. Far and away the easiest method I've used to back-up, move, and restore sites from local to production or from one host to another.
If the old site is WordPress - sounds like it is, you may want to consider creating a sub-domain and then using [duplicator](https://wordpress.org/plugins/duplicator/) on the old site to back-up and then restore the old site to the new sub-domain.
```
mysite.com -> old.mysite.com
```
Then use [duplicator](https://wordpress.org/plugins/duplicator/) to back-up your local dev site and then restore it to the location of the original site.
**Connecting to the old DB**
Once you have both sites on your host mysite.com and old.mysite.com you could change the settings in the wp-config.php of the new site (now mysite.com) to point to the db of the old site (old.mysite.com) like so:
```
// wp-config.php
define ( 'DB_NAME', 'olddbname' );
define ( 'DB_USER', 'olddbusername' );
define ( 'DB_PASSWORD', 'olddbpassword' );
define ( 'DB_HOST', 'old.mysite.com' );
```
In fact you could probably just copy the DB definitions from the wp-config of old.mysite.com into the wp-config of the mysite.com.
* *I'd comment out the db definitions present for mysite.com.*
Can you clarify what you want to accomplish by doing this?
The problem with pointing the new site to the old db is that it will also use the old site theme etc. A sum zero really. If your just trying to get the posts and pages from the old site to the new, I'd use the export/import tools that come packaged with WordPress. There are also syndicate plugins ([FeedPress](https://wordpress.org/plugins/feedpress/) is my preferred one) that seem to be more robust than the WordPress import/export tools.
|
191,313 |
<p>I have a plugin that is using Class style programming. I'm completely stumped - scripts are being loaded on every single page, even if the plugin is not being used on that page.</p>
<p>Since the plugin should only run when one of its shortcodes are called, I don't understand why they are always being enqueued. The code is:</p>
<pre><code><?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
add_action( 'plugins_loaded', array ( 'Lipstick_Consultation', 'init' ));
if (!class_exists('Lipstick_Consultation')){
//used for the script loader, to load custom jquery at the footer
$plugin_script = "";
class Lipstick_Consultation{
public static function init() {
$class = __CLASS__;
new $class;
}
/**
* @since 1.0
*/
public function __construct() {
//get contstants
$this->setup_constants();
//get file includes
$this->includes();
//register plugin shortcodes
$this->register_shortcodes();
//Register Styles
add_action( 'wp_enqueue_scripts', array( $this, 'register_styles' ) );
//Register Scripts
add_action( 'wp_enqueue_scripts', array( $this, 'register_scripts' ) );
$this->page_scripts();
return $this;
}
/**
* Include our Class files
*
* @access private
* @since 1.0.0
* @return void
*/
private function includes() {
/****SHORTCODES****/
//[slider_person]
require_once LC_DIR . 'inc/shortcodes/slider.php';
//[suggested_colors]
require_once LC_DIR . 'inc/templates/tmpl-suggestedcolors.php';
}
/**
* Setup plugin constants
*
* @access private
* @since 1.0.0
* @return void
*/
private function setup_constants() {
// Plugin information
define( 'LC_VERSION', '1.0.0' ); // Current plugin version
define( 'LC_URL', plugin_dir_url( __FILE__ ) );
define( 'LC_DIR', plugin_dir_path( __FILE__ ) );
}
/**
* Register Styles
*
* @access private
* @since 1.0.0
* @return void
*/
public function register_styles() {
//main style file
wp_register_style( 'consultation_style', LC_URL . "assets/css/style.css", array(), time(), 'all' );
wp_enqueue_style( 'consultation_style' );
//styles for full page plugin
wp_register_style( 'lc_full_page_style', LC_URL . "assets/css/jquery.fullPage.css", array(), time(), 'all' );
wp_enqueue_style( 'lc_full_page_style' );
}
/**
* Register Scripts
*
* @access private
* @since 1.0.0
* @return void
*/
public function register_scripts() {
//Script that makes div have a scrollbar
wp_register_script( 'lc_slim_scroll', LC_URL . "assets/js/jquery.slimscroll". SUFFIX . ".js", array( 'jquery' ), time() );
wp_enqueue_script( 'lc_slim_scroll' );
//Script that makes full width/height/page divs
wp_register_script( 'lc_full_page', LC_URL . "assets/js/jquery.fullPage". SUFFIX . ".js", array( 'jquery' ), time() );
wp_enqueue_script( 'lc_full_page' );
}
private function register_shortcodes(){
//slider for "Choose You" Slider
add_shortcode("lipstick_person", array('Lipstick_Consultation', "shortcode_person_slider"));
//Template for lipstick color suggestions
add_shortcode("suggested_colors", array($this, "suggested_colors_template"));
}
private function page_scripts(){
//load fullPage jquery code
$this->add_full_page_script();
}
/*
*function to echo the script that triggers the plugin
*/
public function add_script_footer(){
echo $this->plugin_script;
}
/**********************************************************************/
/**********************************************************************/
/*************MAY BE BETTER TO INCLUDE THIS IN ITS OWN FILE************/
/**********************************************************************/
/**********************************************************************/
/*
* Add script to get the full page effect on all page elements (this is for the page content)
*/
private function add_full_page_script(){
ob_start();
?>
<!--jQuery Function to Trigger the plugin for this page-->
<script type="text/javascript">
//on document ready
jQuery(document).ready(function($){
$('#fullpage').fullpage({
anchors:['instructions', 'choose-you', 'consultation-suggested-colors', 'all-colors'],
scrollOverflow: true
//look into the menu option https://github.com/alvarotrigo/fullPage.js
});
});
</script>
<?php
//get jQuery script, set it as global script variable and call the WP callback
$script = ob_get_contents();
ob_end_clean();
//set variable to the script above
$this->plugin_script = $script;
//call hook to add script to footer.
add_action('wp_footer', array($this,'add_script_footer'),20);
}
}
}
?>
</code></pre>
<p>If I understand what is happening, on the plugins_loaded hook the plugin is being instantiated. When the construct method is being called it is enqueing the scripts. That all makes sense.</p>
<p>When looking at other plugins it looks as though they use a similar structure, yet - their script files are only loaded when their plugin is being invoked on that page.</p>
<p>What am I doing wrong? Thanks!</p>
<p><strong>UPDATE #1</strong></p>
<p>Guys, I just cannot figure out how to do this. I made the following edits to the code:</p>
<pre><code> public function __construct() {
//get contstants
$this->setup_constants();
//get file includes
$this->includes();
//register plugin shortcodes
$this->register_shortcodes();
return $this;
}
/**
* Registers the styles and scripts for the shortcodes
*/
private function register_shortcode_requirements() {
//Register Styles
add_action( 'wp_enqueue_scripts', array( $this, 'register_styles' ) );
//Register Scripts
add_action( 'wp_enqueue_scripts', array( $this, 'register_scripts' ) );
}
/**
* Register Styles
*/
public function register_styles() {
//main style file
wp_register_script( 'consultation_style', LC_URL . "assets/css/style.css", array(), time(), 'all' );
wp_enqueue_script( 'consultation_style' );
//styles for full page plugin
wp_register_script( 'lc_full_page_style', LC_URL . "assets/css/jquery.fullPage.css", array(), time(), 'all' );
wp_enqueue_script( 'lc_full_page_style' );
}
/**
* Register Scripts
*/
public function register_scripts() {
//Script that makes div have a scrollbar
wp_register_script( 'lc_slim_scroll', LC_URL . "assets/js/jquery.slimscroll". SUFFIX . ".js", array( 'jquery' ), time() );
wp_enqueue_script( 'lc_slim_scroll' );
//Script that makes full width/height/page divs
wp_register_script( 'lc_full_page', LC_URL . "assets/js/jquery.fullPage". SUFFIX . ".js", array( 'jquery' ), time() );
wp_enqueue_script( 'lc_full_page' );
}
private function register_shortcodes(){
//slider for "Choose You" Slider
add_shortcode("lipstick_person", array($this,"shortcode_person_slider_caller"));
}
/*
* Calling Function to include scripts and then fire the actual shortcode function contained in separate .php file
*/
public function shortcode_person_slider_caller($atts, $content){
//register styles/scripts
$this->register_shortcode_requirements();
//run actual function for rendering
$content = shortcode_person_slider($atts);
return $content;
}
</code></pre>
<p>Then in the caller function the <code>shortcode_person_slider</code> is a function included in one of the require_once loaded files.</p>
<p>The function is firing (tested with a var_dump) in that function and it displays. Yet, the content is not displaying on the page (even though $content has all of the html markup).</p>
<p>Further, the script/style files are not being enqueued.</p>
<p>When testing, the <code>register_shortcode_requirements()</code> is firing, but each of the wp_enqueue_script hooks are not.</p>
<p>Any advice? Thank you!</p>
|
[
{
"answer_id": 191314,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 0,
"selected": false,
"text": "<p>You are answering your own question — scripts are being enqueued because that's what plugin does every load <em>unconditionally</em>.</p>\n\n<p>There is no logic that controls when should it happen or not happen, it simply happens always.</p>\n\n<p>If you take a closer look at a plugin that does it more intelligently you will usually notice one of these things:</p>\n\n<ul>\n<li>there are conditional check for hooking methods or inside methods themselves</li>\n<li>the hooks being used are specific to certain context</li>\n<li>the enqueue is being called from code with related function, for example scripts needed by shortcode might be queued when from inside shortcode's handler</li>\n</ul>\n"
},
{
"answer_id": 191316,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 3,
"selected": true,
"text": "<p>As Rarst already noted, you answered your question. You are telling the software to load those scripts all the time. You need to control that process. Software is stupid. It can't decide when a good time is to load the code. SO...</p>\n\n<blockquote>\n <p>Since the plugin should only run when one of its shortcodes are\n called, ...</p>\n</blockquote>\n\n<p>Since you say the script should load only when a shortcode is used, go ahead and register your scripts but enqueue then in the shortcode handler, like <a href=\"https://wordpress.stackexchange.com/a/123549/21376\">this from another question</a>:</p>\n\n<pre><code>function my_shortcode( $atts, $content = null ) {\n extract(shortcode_atts(array(\n 'title' => '',\n ), $atts));\n static $counter = 0;\n echo $counter++;\n wp_enqueue_script('wp-mediaelement'); \n\n}\nadd_shortcode('enq','my_shortcode');\n</code></pre>\n\n<p>Your script will load in the footer of the page, so make sure the Javascript can manage that. </p>\n\n<p>As for your stylesheet, </p>\n\n<ol>\n<li>You can load those in the footer of the page similarly to the\nscripts. This is invalid markup but tends to work.</li>\n<li>You can load the styles inline in the shortcode, which is a decent\noption, maybe the best one.</li>\n<li>You can have the javascript insert the styles dynamically</li>\n<li>You can \"pre-process\" the shortcode, similarly to this (which is a\nresource intensive solution):\n<a href=\"https://wordpress.stackexchange.com/a/101515/21376\">https://wordpress.stackexchange.com/a/101515/21376</a></li>\n</ol>\n"
}
] |
2015/06/12
|
[
"https://wordpress.stackexchange.com/questions/191313",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68087/"
] |
I have a plugin that is using Class style programming. I'm completely stumped - scripts are being loaded on every single page, even if the plugin is not being used on that page.
Since the plugin should only run when one of its shortcodes are called, I don't understand why they are always being enqueued. The code is:
```
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
add_action( 'plugins_loaded', array ( 'Lipstick_Consultation', 'init' ));
if (!class_exists('Lipstick_Consultation')){
//used for the script loader, to load custom jquery at the footer
$plugin_script = "";
class Lipstick_Consultation{
public static function init() {
$class = __CLASS__;
new $class;
}
/**
* @since 1.0
*/
public function __construct() {
//get contstants
$this->setup_constants();
//get file includes
$this->includes();
//register plugin shortcodes
$this->register_shortcodes();
//Register Styles
add_action( 'wp_enqueue_scripts', array( $this, 'register_styles' ) );
//Register Scripts
add_action( 'wp_enqueue_scripts', array( $this, 'register_scripts' ) );
$this->page_scripts();
return $this;
}
/**
* Include our Class files
*
* @access private
* @since 1.0.0
* @return void
*/
private function includes() {
/****SHORTCODES****/
//[slider_person]
require_once LC_DIR . 'inc/shortcodes/slider.php';
//[suggested_colors]
require_once LC_DIR . 'inc/templates/tmpl-suggestedcolors.php';
}
/**
* Setup plugin constants
*
* @access private
* @since 1.0.0
* @return void
*/
private function setup_constants() {
// Plugin information
define( 'LC_VERSION', '1.0.0' ); // Current plugin version
define( 'LC_URL', plugin_dir_url( __FILE__ ) );
define( 'LC_DIR', plugin_dir_path( __FILE__ ) );
}
/**
* Register Styles
*
* @access private
* @since 1.0.0
* @return void
*/
public function register_styles() {
//main style file
wp_register_style( 'consultation_style', LC_URL . "assets/css/style.css", array(), time(), 'all' );
wp_enqueue_style( 'consultation_style' );
//styles for full page plugin
wp_register_style( 'lc_full_page_style', LC_URL . "assets/css/jquery.fullPage.css", array(), time(), 'all' );
wp_enqueue_style( 'lc_full_page_style' );
}
/**
* Register Scripts
*
* @access private
* @since 1.0.0
* @return void
*/
public function register_scripts() {
//Script that makes div have a scrollbar
wp_register_script( 'lc_slim_scroll', LC_URL . "assets/js/jquery.slimscroll". SUFFIX . ".js", array( 'jquery' ), time() );
wp_enqueue_script( 'lc_slim_scroll' );
//Script that makes full width/height/page divs
wp_register_script( 'lc_full_page', LC_URL . "assets/js/jquery.fullPage". SUFFIX . ".js", array( 'jquery' ), time() );
wp_enqueue_script( 'lc_full_page' );
}
private function register_shortcodes(){
//slider for "Choose You" Slider
add_shortcode("lipstick_person", array('Lipstick_Consultation', "shortcode_person_slider"));
//Template for lipstick color suggestions
add_shortcode("suggested_colors", array($this, "suggested_colors_template"));
}
private function page_scripts(){
//load fullPage jquery code
$this->add_full_page_script();
}
/*
*function to echo the script that triggers the plugin
*/
public function add_script_footer(){
echo $this->plugin_script;
}
/**********************************************************************/
/**********************************************************************/
/*************MAY BE BETTER TO INCLUDE THIS IN ITS OWN FILE************/
/**********************************************************************/
/**********************************************************************/
/*
* Add script to get the full page effect on all page elements (this is for the page content)
*/
private function add_full_page_script(){
ob_start();
?>
<!--jQuery Function to Trigger the plugin for this page-->
<script type="text/javascript">
//on document ready
jQuery(document).ready(function($){
$('#fullpage').fullpage({
anchors:['instructions', 'choose-you', 'consultation-suggested-colors', 'all-colors'],
scrollOverflow: true
//look into the menu option https://github.com/alvarotrigo/fullPage.js
});
});
</script>
<?php
//get jQuery script, set it as global script variable and call the WP callback
$script = ob_get_contents();
ob_end_clean();
//set variable to the script above
$this->plugin_script = $script;
//call hook to add script to footer.
add_action('wp_footer', array($this,'add_script_footer'),20);
}
}
}
?>
```
If I understand what is happening, on the plugins\_loaded hook the plugin is being instantiated. When the construct method is being called it is enqueing the scripts. That all makes sense.
When looking at other plugins it looks as though they use a similar structure, yet - their script files are only loaded when their plugin is being invoked on that page.
What am I doing wrong? Thanks!
**UPDATE #1**
Guys, I just cannot figure out how to do this. I made the following edits to the code:
```
public function __construct() {
//get contstants
$this->setup_constants();
//get file includes
$this->includes();
//register plugin shortcodes
$this->register_shortcodes();
return $this;
}
/**
* Registers the styles and scripts for the shortcodes
*/
private function register_shortcode_requirements() {
//Register Styles
add_action( 'wp_enqueue_scripts', array( $this, 'register_styles' ) );
//Register Scripts
add_action( 'wp_enqueue_scripts', array( $this, 'register_scripts' ) );
}
/**
* Register Styles
*/
public function register_styles() {
//main style file
wp_register_script( 'consultation_style', LC_URL . "assets/css/style.css", array(), time(), 'all' );
wp_enqueue_script( 'consultation_style' );
//styles for full page plugin
wp_register_script( 'lc_full_page_style', LC_URL . "assets/css/jquery.fullPage.css", array(), time(), 'all' );
wp_enqueue_script( 'lc_full_page_style' );
}
/**
* Register Scripts
*/
public function register_scripts() {
//Script that makes div have a scrollbar
wp_register_script( 'lc_slim_scroll', LC_URL . "assets/js/jquery.slimscroll". SUFFIX . ".js", array( 'jquery' ), time() );
wp_enqueue_script( 'lc_slim_scroll' );
//Script that makes full width/height/page divs
wp_register_script( 'lc_full_page', LC_URL . "assets/js/jquery.fullPage". SUFFIX . ".js", array( 'jquery' ), time() );
wp_enqueue_script( 'lc_full_page' );
}
private function register_shortcodes(){
//slider for "Choose You" Slider
add_shortcode("lipstick_person", array($this,"shortcode_person_slider_caller"));
}
/*
* Calling Function to include scripts and then fire the actual shortcode function contained in separate .php file
*/
public function shortcode_person_slider_caller($atts, $content){
//register styles/scripts
$this->register_shortcode_requirements();
//run actual function for rendering
$content = shortcode_person_slider($atts);
return $content;
}
```
Then in the caller function the `shortcode_person_slider` is a function included in one of the require\_once loaded files.
The function is firing (tested with a var\_dump) in that function and it displays. Yet, the content is not displaying on the page (even though $content has all of the html markup).
Further, the script/style files are not being enqueued.
When testing, the `register_shortcode_requirements()` is firing, but each of the wp\_enqueue\_script hooks are not.
Any advice? Thank you!
|
As Rarst already noted, you answered your question. You are telling the software to load those scripts all the time. You need to control that process. Software is stupid. It can't decide when a good time is to load the code. SO...
>
> Since the plugin should only run when one of its shortcodes are
> called, ...
>
>
>
Since you say the script should load only when a shortcode is used, go ahead and register your scripts but enqueue then in the shortcode handler, like [this from another question](https://wordpress.stackexchange.com/a/123549/21376):
```
function my_shortcode( $atts, $content = null ) {
extract(shortcode_atts(array(
'title' => '',
), $atts));
static $counter = 0;
echo $counter++;
wp_enqueue_script('wp-mediaelement');
}
add_shortcode('enq','my_shortcode');
```
Your script will load in the footer of the page, so make sure the Javascript can manage that.
As for your stylesheet,
1. You can load those in the footer of the page similarly to the
scripts. This is invalid markup but tends to work.
2. You can load the styles inline in the shortcode, which is a decent
option, maybe the best one.
3. You can have the javascript insert the styles dynamically
4. You can "pre-process" the shortcode, similarly to this (which is a
resource intensive solution):
<https://wordpress.stackexchange.com/a/101515/21376>
|
191,349 |
<p>The problem began with the wp upgrade redirect loop</p>
<p>I tried to fix it by renaming one of the table value fors wp_options on php admin </p>
<p>As a result of this I cannot log into my site anymore ..it gives the redirect loop. Furthermore, there is a bunch of gibberish all over my site with error messages hen I try to debug. </p>
<p>Here is what the debug says:</p>
<pre><code>WordPress database error: [Can't create/write to file '/tmp/#sql_f944c_0.MAI' (Errcode: 13 "Permission denied")]
SHOW FULL COLUMNS FROM `wp_options`
WordPress database error: [Can't create/write to file '/tmp/#sql_f944c_0.MAI' (Errcode: 13 "Permission denied")]
SELECT t.*, tt.*, tr.object_id FROM wp_terms AS t INNER JOIN wp_term_taxonomy AS tt ON tt.term_id = t.term_id INNER JOIN wp_term_relationships AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy IN ('category', 'post_tag', 'post_format') AND tr.object_id IN (3165) ORDER BY t.name ASC
</code></pre>
<p>I have no idea where to begin to fix this. I have database backups but I don't know which files are messed up. </p>
<p>Is there a way to put up a simple static html page on top of my index.php page without affecting the rest of the site? I need to alert readers that my site is malfunctioning and show them a link to a new version while I try to fix the old version. </p>
<p>I can't login , can't post..cant do anything </p>
|
[
{
"answer_id": 191378,
"author": "tman16",
"author_id": 74622,
"author_profile": "https://wordpress.stackexchange.com/users/74622",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried creating a new database, upload your backup to it - then redirect wordpress to use this instead?</p>\n\n<p>In the meantime you could create a basic html document in your root folder then use .htaccess to redirect when ever anyone without your ip address enters site</p>\n\n<p>Add this to your .htaccess file and change the ip address to yours and the newhtmlfile name to the one you created</p>\n\n<pre><code>RewriteEngine on\nRewriteCond %{REMOTE_ADDR} !=xxx.xxx.xxx.xxx\nRewriteRule index.php$ /newhtmlfile.php [R=301,L]\n</code></pre>\n"
},
{
"answer_id": 191577,
"author": "Thomas Baert",
"author_id": 74611,
"author_profile": "https://wordpress.stackexchange.com/users/74611",
"pm_score": 1,
"selected": false,
"text": "<p>After 6 hours of trial and error, I deleted my site, uploaded an older version of wordpress, made a new database, re-named the plugin folder (so that there would be no plugins), and uploaded my most recent database back-up..and then it worked. I was able to login and all my page were restored. The problem may have been the plugin file, or my host, or my version of wordpress causing problems. </p>\n"
},
{
"answer_id": 329322,
"author": "Fabrizio Mele",
"author_id": 40463,
"author_profile": "https://wordpress.stackexchange.com/users/40463",
"pm_score": 1,
"selected": false,
"text": "<p>As you can see from the error itself (<code>Can't create/write to file '/tmp/#sql_f944c_0.MAI' (Errcode: 13 \"Permission denied\"</code>) this is a system issue. Your mysql instance cannot write to the linux <code>/tmp</code> directory because either the disk is full or the <code>mysqld</code> process has no security permissions to write to <code>tmp</code>.</p>\n\n<p>If you are self-hosting Wordpress on a server you have <code>ssh</code> access to you should take a look at the mysql configuration (usually <code>/etc/my.cnf</code>) and find what is declared as <code>tmpdir</code> (<code>cat /etc/my.cnf | grep tmpdir</code>). It should be <code>/tmp</code>, and again the permissions for <code>/tmp</code> should be set as follows: <code>chmod 1777 /tmp</code>. </p>\n\n<p>If your Wordpress is not self-hosted I suggest to contact your hosting provider to find out what's happening.</p>\n"
}
] |
2015/06/12
|
[
"https://wordpress.stackexchange.com/questions/191349",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74611/"
] |
The problem began with the wp upgrade redirect loop
I tried to fix it by renaming one of the table value fors wp\_options on php admin
As a result of this I cannot log into my site anymore ..it gives the redirect loop. Furthermore, there is a bunch of gibberish all over my site with error messages hen I try to debug.
Here is what the debug says:
```
WordPress database error: [Can't create/write to file '/tmp/#sql_f944c_0.MAI' (Errcode: 13 "Permission denied")]
SHOW FULL COLUMNS FROM `wp_options`
WordPress database error: [Can't create/write to file '/tmp/#sql_f944c_0.MAI' (Errcode: 13 "Permission denied")]
SELECT t.*, tt.*, tr.object_id FROM wp_terms AS t INNER JOIN wp_term_taxonomy AS tt ON tt.term_id = t.term_id INNER JOIN wp_term_relationships AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy IN ('category', 'post_tag', 'post_format') AND tr.object_id IN (3165) ORDER BY t.name ASC
```
I have no idea where to begin to fix this. I have database backups but I don't know which files are messed up.
Is there a way to put up a simple static html page on top of my index.php page without affecting the rest of the site? I need to alert readers that my site is malfunctioning and show them a link to a new version while I try to fix the old version.
I can't login , can't post..cant do anything
|
After 6 hours of trial and error, I deleted my site, uploaded an older version of wordpress, made a new database, re-named the plugin folder (so that there would be no plugins), and uploaded my most recent database back-up..and then it worked. I was able to login and all my page were restored. The problem may have been the plugin file, or my host, or my version of wordpress causing problems.
|
191,384 |
<p>I have the following working code for a query on a specific category and tag slug:</p>
<pre><code>$args = array(
'category_name' => $cat_name,
'tag' => $tag_name,
'post__not_in' => $sticky
);
$my_query = new WP_Query( $args );
</code></pre>
<p>I can't figure out how to exclude a specific tag name from the query. Do I need the tag ID? How do I get it? Thank you in advance.</p>
|
[
{
"answer_id": 191385,
"author": "sakibmoon",
"author_id": 23214,
"author_profile": "https://wordpress.stackexchange.com/users/23214",
"pm_score": 3,
"selected": false,
"text": "<p>Use <code>tag__not_in</code> parameter. You have to use tag ID for this parameter</p>\n\n<pre><code>$args = array(\n 'category_name' => $cat_name,\n 'tag' => $tag_name,\n 'post__not_in' => $sticky,\n 'tag__not_in' => array($tag_id_1, $tag_id_2)\n);\n\n$my_query = new WP_Query( $args );\n</code></pre>\n"
},
{
"answer_id": 191386,
"author": "websupporter",
"author_id": 48693,
"author_profile": "https://wordpress.stackexchange.com/users/48693",
"pm_score": 0,
"selected": false,
"text": "<p>You need to use 'tag__not_in' and you need the ID of the Tag. Have a look into <a href=\"https://codex.wordpress.org/Function_Reference/get_term_by\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/get_term_by</a> to retrieve the term object, where the ID is contained.</p>\n"
}
] |
2015/06/13
|
[
"https://wordpress.stackexchange.com/questions/191384",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/45758/"
] |
I have the following working code for a query on a specific category and tag slug:
```
$args = array(
'category_name' => $cat_name,
'tag' => $tag_name,
'post__not_in' => $sticky
);
$my_query = new WP_Query( $args );
```
I can't figure out how to exclude a specific tag name from the query. Do I need the tag ID? How do I get it? Thank you in advance.
|
Use `tag__not_in` parameter. You have to use tag ID for this parameter
```
$args = array(
'category_name' => $cat_name,
'tag' => $tag_name,
'post__not_in' => $sticky,
'tag__not_in' => array($tag_id_1, $tag_id_2)
);
$my_query = new WP_Query( $args );
```
|
191,418 |
<p>I am struggling with a common issue that many people appear to have encountered over the years. In creating a widget I need a series of radio buttons. Using the code below I can create and show the radio buttons, yet it does not seem to save the value to the database, showing all as unchecked when I hit the save button and nothing is returned on the widget front end.</p>
<p>I believe it is how the radio buttons themselves are declared but do struggle with this level of coding. Is it to do with the <strong>$this->get_field_id('')</strong> tags not properly declared? I have tried many different permutations but with no luck.</p>
<p>I appreciate any help you can provide.</p>
<pre><code>// 1
function Widget_case_study() {
parent::WP_Widget(false, $name = __('Radio buttons', 'radio_buttons') );
}
// 2
function form($instance) {
$radio_buttons = esc_attr($instance['radio_buttons']);
?>
<p>
<label for="<?php echo $this->get_field_id('text_area'); ?>">
<?php echo('Radio buttons'); ?>
</label><br>
<label for="<?php echo $this->get_field_id('radio_option_1'); ?>">
<?php _e('Option 1:'.$radio_buttons); ?>
<input class="" id="<?php echo $this->get_field_id('radio_option_1'); ?>" name="<?php echo $this->get_field_id('radio_buttons'); ?>" type="radio" value="radio_option_1" <?php if($radio_buttons === 'radio_option_1'){ echo 'checked="checked"'; } ?> />
</label><br>
<label for="<?php echo $this->get_field_id('radio_option_2'); ?>">
<?php _e('Option 2:'.$radio_buttons); ?>
<input class="" id="<?php echo $this->get_field_id('radio_option_2'); ?>" name="<?php echo $this->get_field_id('radio_buttons'); ?>" type="radio" value="radio_option_2" <?php if($radio_option_1 === 'radio_option_2'){ echo 'checked="checked"'; } ?> />
</label>
</p>
<?php
}
// 3
function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance['radio_buttons'] = strip_tags($new_instance['radio_buttons']);
return $instance;
}
// 4
function widget($args, $instance) {
extract( $args );
$radio_buttons = $instance['radio_buttons'];
?>
<?php echo $before_widget; ?>
<p>Radio button value/status: <?php echo $radio_buttons; ?></p>
<?php echo $after_widget; ?>
<?php
}
</code></pre>
|
[
{
"answer_id": 191447,
"author": "Allen Tullett",
"author_id": 63400,
"author_profile": "https://wordpress.stackexchange.com/users/63400",
"pm_score": 2,
"selected": false,
"text": "<p>Got it, it turns out...</p>\n\n<ol>\n<li>The label for each radio button must be the field id / variable, in my example is 'radio_buttons'</li>\n<li>The IF statement for each radio button must refer to this same ID - <strong>$radio_buttons === 'radio_option_1'</strong> & <strong>$radio_buttons === 'radio_option_2'</strong></li>\n</ol>\n\n<p>My new code which works is...</p>\n\n<pre><code><p>\n <label for=\"<?php echo $this->get_field_id('text_area'); ?>\">\n <?php echo('Radio buttons'); ?>\n </label><br>\n <label for=\"<?php echo $this->get_field_id('radio_buttons'); ?>\">\n <?php _e('Option 1:'); ?>\n <input class=\"\" id=\"<?php echo $this->get_field_id('radio_option_1'); ?>\" name=\"<?php echo $this->get_field_name('radio_buttons'); ?>\" type=\"radio\" value=\"radio_option_1\" <?php if($radio_buttons === 'radio_option_1'){ echo 'checked=\"checked\"'; } ?> />\n </label><br>\n <label for=\"<?php echo $this->get_field_id('radio_buttons'); ?>\">\n <?php _e('Option 2:'); ?>\n <input class=\"\" id=\"<?php echo $this->get_field_id('radio_option_2'); ?>\" name=\"<?php echo $this->get_field_name('radio_buttons'); ?>\" type=\"radio\" value=\"radio_option_2\" <?php if($radio_buttons === 'radio_option_2'){ echo 'checked=\"checked\"'; } ?> />\n </label>\n </p>\n</code></pre>\n"
},
{
"answer_id": 288325,
"author": "Jonas Lundman",
"author_id": 43172,
"author_profile": "https://wordpress.stackexchange.com/users/43172",
"pm_score": 0,
"selected": false,
"text": "<p>For anyone struggles with javascript issue, <strong>wrong checked gets checked</strong>, make shure the HTML not have empty <code>checked=\"\"</code> attributes. Only add the attribute on selected radio button.</p>\n\n<p>This code works for a widget with radio-buttons <strong>without if-statements:</strong></p>\n\n<pre><code>function form( $instance ) {\n\n /* Option carrier is 'ecw_column' */\n $ecw_column = isset( $instance['ecw_column'] ) ? $instance['ecw_column'] : 'ecw_column_none';\n\n echo '<p>';\n\n $value = 'ecw_column_1';\n\n echo '<input value=\"'. $value .'\" class=\"widefat\" id=\"'. $this->get_field_id($value) .'\" name=\"'. $this->get_field_name('ecw_column') .'\" type=\"radio\"'. ($ecw_column == $value ? ' checked=\"checked\"' : '') .' />';\n echo '<label for=\"'. $this->get_field_id($value) .'\">'. __('Column start') .'</label>';\n echo '<br/>';\n\n $value = 'ecw_column_2';\n\n echo '<input value=\"'. $value .'\" class=\"widefat\" id=\"'. $this->get_field_id($value) .'\" name=\"'. $this->get_field_name('ecw_column') .'\" type=\"radio\"'. ($ecw_column == $value ? ' checked=\"checked\"' : '') .' />';\n echo '<label for=\"'. $this->get_field_id($value) .'\">'. __('Breakpoint') .'</label>';\n echo '<br/>';\n\n $value = 'ecw_column_3';\n\n echo '<input value=\"'. $value .'\" class=\"widefat\" id=\"'. $this->get_field_id($value) .'\" name=\"'. $this->get_field_name('ecw_column') .'\" type=\"radio\"'. ($ecw_column == $value ? ' checked=\"checked\"' : '') .' />';\n echo '<label for=\"'. $this->get_field_id($value) .'\">'. __('Column end') .'</label>';\n echo '<br/>';\n\n /* Default value */\n $value = 'ecw_column_none';\n\n echo '<input value=\"'. $value .'\" class=\"widefat\" id=\"'. $this->get_field_id($value) .'\" name=\"'. $this->get_field_name('ecw_column') .'\" type=\"radio\"'. ($ecw_column == $value ? ' checked=\"checked\"' : '') .' />';\n echo '<label for=\"'. $this->get_field_id($value) .'\">'. __('Current') .'</label>';\n\n echo '</p>';\n}\n</code></pre>\n"
}
] |
2015/06/14
|
[
"https://wordpress.stackexchange.com/questions/191418",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63400/"
] |
I am struggling with a common issue that many people appear to have encountered over the years. In creating a widget I need a series of radio buttons. Using the code below I can create and show the radio buttons, yet it does not seem to save the value to the database, showing all as unchecked when I hit the save button and nothing is returned on the widget front end.
I believe it is how the radio buttons themselves are declared but do struggle with this level of coding. Is it to do with the **$this->get\_field\_id('')** tags not properly declared? I have tried many different permutations but with no luck.
I appreciate any help you can provide.
```
// 1
function Widget_case_study() {
parent::WP_Widget(false, $name = __('Radio buttons', 'radio_buttons') );
}
// 2
function form($instance) {
$radio_buttons = esc_attr($instance['radio_buttons']);
?>
<p>
<label for="<?php echo $this->get_field_id('text_area'); ?>">
<?php echo('Radio buttons'); ?>
</label><br>
<label for="<?php echo $this->get_field_id('radio_option_1'); ?>">
<?php _e('Option 1:'.$radio_buttons); ?>
<input class="" id="<?php echo $this->get_field_id('radio_option_1'); ?>" name="<?php echo $this->get_field_id('radio_buttons'); ?>" type="radio" value="radio_option_1" <?php if($radio_buttons === 'radio_option_1'){ echo 'checked="checked"'; } ?> />
</label><br>
<label for="<?php echo $this->get_field_id('radio_option_2'); ?>">
<?php _e('Option 2:'.$radio_buttons); ?>
<input class="" id="<?php echo $this->get_field_id('radio_option_2'); ?>" name="<?php echo $this->get_field_id('radio_buttons'); ?>" type="radio" value="radio_option_2" <?php if($radio_option_1 === 'radio_option_2'){ echo 'checked="checked"'; } ?> />
</label>
</p>
<?php
}
// 3
function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance['radio_buttons'] = strip_tags($new_instance['radio_buttons']);
return $instance;
}
// 4
function widget($args, $instance) {
extract( $args );
$radio_buttons = $instance['radio_buttons'];
?>
<?php echo $before_widget; ?>
<p>Radio button value/status: <?php echo $radio_buttons; ?></p>
<?php echo $after_widget; ?>
<?php
}
```
|
Got it, it turns out...
1. The label for each radio button must be the field id / variable, in my example is 'radio\_buttons'
2. The IF statement for each radio button must refer to this same ID - **$radio\_buttons === 'radio\_option\_1'** & **$radio\_buttons === 'radio\_option\_2'**
My new code which works is...
```
<p>
<label for="<?php echo $this->get_field_id('text_area'); ?>">
<?php echo('Radio buttons'); ?>
</label><br>
<label for="<?php echo $this->get_field_id('radio_buttons'); ?>">
<?php _e('Option 1:'); ?>
<input class="" id="<?php echo $this->get_field_id('radio_option_1'); ?>" name="<?php echo $this->get_field_name('radio_buttons'); ?>" type="radio" value="radio_option_1" <?php if($radio_buttons === 'radio_option_1'){ echo 'checked="checked"'; } ?> />
</label><br>
<label for="<?php echo $this->get_field_id('radio_buttons'); ?>">
<?php _e('Option 2:'); ?>
<input class="" id="<?php echo $this->get_field_id('radio_option_2'); ?>" name="<?php echo $this->get_field_name('radio_buttons'); ?>" type="radio" value="radio_option_2" <?php if($radio_buttons === 'radio_option_2'){ echo 'checked="checked"'; } ?> />
</label>
</p>
```
|
191,423 |
<p>I've checked any threads here regarding this and did a debug test which worked, I'd like to understand why my own code doesn't work as it presents the same functionality explained in every possible thread created about this issue.</p>
<p>I'm trying to send AJAX request when clicking on a checkbox and do some work with MySQL.</p>
<p>Here are some details to understand the scope and what was done:</p>
<pre><code>var $ = jQuery;
$(function() {
$('table.table').on('click', '[name="term-id"]', function() {
var t = $(this),
id = t.val(),
checked = t.is(':checked');
checkCategory(id, checked);
});
});
function checkCategory(id, checked) {
$.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: {action: 'setAsyncCheckProduct', id: id, checked: checked},
success: function(response) {
alert(response);
},
error: function(errorThrown) {
alert(errorThrown);
}
})
}
</code></pre>
<p>This script is included in my plugin via:</p>
<pre><code>wp_enqueue_script('settings-manager', $this->pluginUrl . '/assets/js/SettingsManager.js');
</code></pre>
<p>In my main (abstract) plugin class (It is instantiated and is getting called, so I omit this code sample), but I add my async events assigned to admin_init:</p>
<pre><code>add_action('admin_init', [$this, 'assignAsyncEvents']);
</code></pre>
<p>In my concrete classes, I implement this method like:</p>
<pre><code>public function setAsyncCheckProduct()
{
var_dump($_REQUEST);
echo 123123123;
wp_die();
}
public function assignAsyncEvents()
{
add_action('wp_ajax_setAsyncCheckProduct', [$this, 'setAsyncCheckProduct']);
}
</code></pre>
<p>Which basically means:</p>
<blockquote>
<p>Send AJAX request to whatever is "ajaxurl" (which returns correct: /wp-admin/admin-ajax.php), action: setAsyncCheckProduct is sent along to the server, on the server, the assignAsyncEvents should be already done and a wp_ajax_MY_ACTION_NAME assigned.</p>
</blockquote>
<p>Why do I still get a 0 in response?</p>
<p>Thanks</p>
<p><strong>UPDATE</strong>
I've been manually putting debug output in admin-ajax.php just for the sake of curiosity.</p>
<pre><code>if ( is_user_logged_in() ) {
/**
* Fires authenticated AJAX actions for logged-in users.
*
* The dynamic portion of the hook name, `$_REQUEST['action']`,
* refers to the name of the AJAX action callback being fired.
*
* @since 2.1.0
*/
do_action( 'wp_ajax_' . $_REQUEST['action'] );
var_dump('wp_ajax_' . $_REQUEST['action']);
} else {
/**
* Fires non-authenticated AJAX actions for logged-out users.
*
* The dynamic portion of the hook name, `$_REQUEST['action']`,
* refers to the name of the AJAX action callback being fired.
*
* @since 2.8.0
*/
do_action( 'wp_ajax_nopriv_' . $_REQUEST['action'] );
}
// Default status
die( '0' );
</code></pre>
<p>This is the core functionality with my var_dump added. My AJAX call GETS THERE and the output is CORRECT ACTION NAME defined in add_action in my plugin files, thought nothing is returned from my action/it's not being called and I get to the default <code>die( '0' );</code></p>
<p>Bummer. Don't know what to do further.</p>
|
[
{
"answer_id": 195869,
"author": "Y. E.",
"author_id": 76640,
"author_profile": "https://wordpress.stackexchange.com/users/76640",
"pm_score": 1,
"selected": false,
"text": "<p>Placing this answer for those people who're trying to fix the same issue.</p>\n\n<p>It's important where </p>\n\n<p><code>add_action('wp_ajax_setAsyncCheckProduct', [$this, 'setAsyncCheckProduct']);</code> </p>\n\n<p>resides.</p>\n\n<p>In my case the issue was finally fixed moving a similar line to the main plugin file, where all concrete classes are included and initialised. Of course the line had to be changed to this form:</p>\n\n<p><code>add_action('wp_ajax_setAsyncCheckProduct', ['ClassName', 'setAsyncCheckProduct']);</code></p>\n"
},
{
"answer_id": 208348,
"author": "Margareto",
"author_id": 83425,
"author_profile": "https://wordpress.stackexchange.com/users/83425",
"pm_score": 2,
"selected": false,
"text": "<p>The problem is where you place the add_action of your wp_ajax_*</p>\n\n<p>Try to put it at the start of everything, and ensuring that it is being loaded in a /wp-admin/ route.</p>\n\n<p>Try your url: <a href=\"http://xxx/wp-admin/admin-ajax.php?action=your_action\" rel=\"nofollow\">http://xxx/wp-admin/admin-ajax.php?action=your_action</a> until it gives you something different than zero.</p>\n"
}
] |
2015/06/14
|
[
"https://wordpress.stackexchange.com/questions/191423",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74605/"
] |
I've checked any threads here regarding this and did a debug test which worked, I'd like to understand why my own code doesn't work as it presents the same functionality explained in every possible thread created about this issue.
I'm trying to send AJAX request when clicking on a checkbox and do some work with MySQL.
Here are some details to understand the scope and what was done:
```
var $ = jQuery;
$(function() {
$('table.table').on('click', '[name="term-id"]', function() {
var t = $(this),
id = t.val(),
checked = t.is(':checked');
checkCategory(id, checked);
});
});
function checkCategory(id, checked) {
$.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: {action: 'setAsyncCheckProduct', id: id, checked: checked},
success: function(response) {
alert(response);
},
error: function(errorThrown) {
alert(errorThrown);
}
})
}
```
This script is included in my plugin via:
```
wp_enqueue_script('settings-manager', $this->pluginUrl . '/assets/js/SettingsManager.js');
```
In my main (abstract) plugin class (It is instantiated and is getting called, so I omit this code sample), but I add my async events assigned to admin\_init:
```
add_action('admin_init', [$this, 'assignAsyncEvents']);
```
In my concrete classes, I implement this method like:
```
public function setAsyncCheckProduct()
{
var_dump($_REQUEST);
echo 123123123;
wp_die();
}
public function assignAsyncEvents()
{
add_action('wp_ajax_setAsyncCheckProduct', [$this, 'setAsyncCheckProduct']);
}
```
Which basically means:
>
> Send AJAX request to whatever is "ajaxurl" (which returns correct: /wp-admin/admin-ajax.php), action: setAsyncCheckProduct is sent along to the server, on the server, the assignAsyncEvents should be already done and a wp\_ajax\_MY\_ACTION\_NAME assigned.
>
>
>
Why do I still get a 0 in response?
Thanks
**UPDATE**
I've been manually putting debug output in admin-ajax.php just for the sake of curiosity.
```
if ( is_user_logged_in() ) {
/**
* Fires authenticated AJAX actions for logged-in users.
*
* The dynamic portion of the hook name, `$_REQUEST['action']`,
* refers to the name of the AJAX action callback being fired.
*
* @since 2.1.0
*/
do_action( 'wp_ajax_' . $_REQUEST['action'] );
var_dump('wp_ajax_' . $_REQUEST['action']);
} else {
/**
* Fires non-authenticated AJAX actions for logged-out users.
*
* The dynamic portion of the hook name, `$_REQUEST['action']`,
* refers to the name of the AJAX action callback being fired.
*
* @since 2.8.0
*/
do_action( 'wp_ajax_nopriv_' . $_REQUEST['action'] );
}
// Default status
die( '0' );
```
This is the core functionality with my var\_dump added. My AJAX call GETS THERE and the output is CORRECT ACTION NAME defined in add\_action in my plugin files, thought nothing is returned from my action/it's not being called and I get to the default `die( '0' );`
Bummer. Don't know what to do further.
|
The problem is where you place the add\_action of your wp\_ajax\_\*
Try to put it at the start of everything, and ensuring that it is being loaded in a /wp-admin/ route.
Try your url: <http://xxx/wp-admin/admin-ajax.php?action=your_action> until it gives you something different than zero.
|
191,461 |
<p>I am currently developing a one-page based layout with WordPress where the actual content is split up into separate pages in the backend, which are all knit together to a one-page layout in my front-page template file. </p>
<p>The WordPress menus allow for custom URLs which is probably the easiest way to cater a one-pager by referring to #hash-based links which lead to the corresponding divs.</p>
<p>However, I am looking for the probably cleanest solution to organise the menu and its anchors so that the actual editors/admins of a site can simply link to an actual page and have a custom walker translate that into a hash that leads to the right section on the frontend.</p>
<p>So far I would go with the slug of the single pages, let the wp_query pick up the slug and add it as an ID to the wrapping div, e.g.</p>
<p>Page 1 called 'The about page' has a slug 'about-page', so the div then looks like</p>
<p><code><div class="section_wrapper" id="about-page"></div></code></p>
<p>and type that slug as the hash URL in the menu editor. </p>
<p>Is there a simple walker or another solution that helps out in this case, i.e. turns links to pages into simple hashes? Or an even better practice?</p>
|
[
{
"answer_id": 191496,
"author": "Kristoffer",
"author_id": 74683,
"author_profile": "https://wordpress.stackexchange.com/users/74683",
"pm_score": 0,
"selected": false,
"text": "<p>I'm currently doing this on a project.</p>\n\n<p>First, I use the slug to create the anchor on the onepage-template:</p>\n\n<p><code><article id=\"post-<?= get_slug(get_the_ID()); ?>\" class=\"container\"></code></p>\n\n<p>Then. I use the following code in a custom menu walker class to replace the url in the href attribute of the menu item.</p>\n\n<pre><code>/**\n* Figure out if the current item is on the page - replace anchor\n*/\nif (is_page_template('template-forside.php')) {\n $onepageID = get_the_ID();\n} else {\n $onepageID = get_option('page_on_front');\n}\n\n\n// Build array of IDs that are on the page\n$onepageids = array($onepageID);\n$pages = get_pages('child_of='.$onepageID);\nforeach($pages as $child) {\n array_push($onepageids, $child->ID);\n}\n\nif( in_array($item->object_id,$onepageids) ) {\n if ( is_page_template('template-forside.php') ) {\n // The menu item links to the current page\n $atts['href'] = '#post-'.get_slug($item->object_id);\n } else {\n $atts['href'] = get_home_url().'#post-'.get_slug($item->object_id);\n }\n\n\n} else {\n $atts['href'] = ! empty( $item->url ) ? $item->url : '';\n}\n</code></pre>\n\n<p>Notice that I do three things:</p>\n\n<ol>\n<li>Figure out if this actually is the one-page-template (template-forside.php) or not. If not, then the front-page of the site is the onepage-page.</li>\n<li>Build an array of page-id's that are on the front page</li>\n<li>Use that array to check if the menu-objects id is on the one-page template.</li>\n<li>If it is, then I either change the href to the slug anchor (if the onepage is the current page). Or add the home url befor the slug anchor (of not on the onepage as of now)</li>\n</ol>\n\n<p>NOTE - this code is kind of flawed because it assumes that the one-page template <em>is</em> the front page, so it can not completely be generalized.</p>\n"
},
{
"answer_id": 191562,
"author": "physalis",
"author_id": 25245,
"author_profile": "https://wordpress.stackexchange.com/users/25245",
"pm_score": 3,
"selected": true,
"text": "<p>Well, after some more intense research I finally found a viable solution that is clean and simple and works flawless so far. </p>\n\n<p>Just put this into your functions.php to create a custom walker which turns classic permalinks into hashes (e.g. page.com/mypage to page.com/#mypage):</p>\n\n<pre><code>/* Custom nav walker */\n\nclass Single_Page_Walker extends Walker_Nav_Menu{\n function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0) {\n global $wp_query;\n $indent = ( $depth ) ? str_repeat( \"\\t\", $depth ) : '';\n $class_names = $value = '';\n $classes = empty( $item->classes ) ? array() : (array) $item->classes;\n $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) );\n $class_names = ' class=\"'. esc_attr( $class_names ) . '\"';\n $output .= $indent . '<li id=\"menu-item-'. $item->ID . '\"' . $value . $class_names .'>';\n $attributes = ! empty( $item->attr_title ) ? ' title=\"' . esc_attr( $item->attr_title ) .'\"' : '';\n $attributes .= ! empty( $item->target ) ? ' target=\"' . esc_attr( $item->target ) .'\"' : '';\n $attributes .= ! empty( $item->xfn ) ? ' rel=\"' . esc_attr( $item->xfn ) .'\"' : '';\n if($item->object == 'page')\n {\n $varpost = get_post($item->object_id);\n if(is_home()){\n $attributes .= ' href=\"#' . $varpost->post_name . '\"';\n }else{\n $attributes .= ' href=\"'.home_url().'/#' . $varpost->post_name . '\"';\n }\n }\n else\n $attributes .= ! empty( $item->url ) ? ' href=\"' . esc_attr( $item->url ) .'\"' : '';\n $item_output = $args->before;\n $item_output .= '<a'. $attributes .'>';\n $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID );\n $item_output .= $args->link_after;\n $item_output .= '</a>';\n $item_output .= $args->after;\n $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args, $id );\n }\n}\n</code></pre>\n\n<p>Then, where you want your menu to appear, put the following code to call your menu (which you should have defined as a menu position before in your functions.php), and adjust the options to your liking, apart from the 'walker' part: </p>\n\n<pre><code><?php \n wp_nav_menu(array(\n 'theme_location' => 'onepage',\n 'echo' => true,\n 'container' => false,\n 'walker'=> new Single_Page_Walker,\n 'depth' => 1) );\n?>\n</code></pre>\n\n<p>— that’s it already. Now you can fill up your menu in the backend without caring about hashes anymore :).</p>\n"
}
] |
2015/06/14
|
[
"https://wordpress.stackexchange.com/questions/191461",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25245/"
] |
I am currently developing a one-page based layout with WordPress where the actual content is split up into separate pages in the backend, which are all knit together to a one-page layout in my front-page template file.
The WordPress menus allow for custom URLs which is probably the easiest way to cater a one-pager by referring to #hash-based links which lead to the corresponding divs.
However, I am looking for the probably cleanest solution to organise the menu and its anchors so that the actual editors/admins of a site can simply link to an actual page and have a custom walker translate that into a hash that leads to the right section on the frontend.
So far I would go with the slug of the single pages, let the wp\_query pick up the slug and add it as an ID to the wrapping div, e.g.
Page 1 called 'The about page' has a slug 'about-page', so the div then looks like
`<div class="section_wrapper" id="about-page"></div>`
and type that slug as the hash URL in the menu editor.
Is there a simple walker or another solution that helps out in this case, i.e. turns links to pages into simple hashes? Or an even better practice?
|
Well, after some more intense research I finally found a viable solution that is clean and simple and works flawless so far.
Just put this into your functions.php to create a custom walker which turns classic permalinks into hashes (e.g. page.com/mypage to page.com/#mypage):
```
/* Custom nav walker */
class Single_Page_Walker extends Walker_Nav_Menu{
function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0) {
global $wp_query;
$indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
$class_names = $value = '';
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
$class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) );
$class_names = ' class="'. esc_attr( $class_names ) . '"';
$output .= $indent . '<li id="menu-item-'. $item->ID . '"' . $value . $class_names .'>';
$attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : '';
$attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : '';
$attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : '';
if($item->object == 'page')
{
$varpost = get_post($item->object_id);
if(is_home()){
$attributes .= ' href="#' . $varpost->post_name . '"';
}else{
$attributes .= ' href="'.home_url().'/#' . $varpost->post_name . '"';
}
}
else
$attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url ) .'"' : '';
$item_output = $args->before;
$item_output .= '<a'. $attributes .'>';
$item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID );
$item_output .= $args->link_after;
$item_output .= '</a>';
$item_output .= $args->after;
$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args, $id );
}
}
```
Then, where you want your menu to appear, put the following code to call your menu (which you should have defined as a menu position before in your functions.php), and adjust the options to your liking, apart from the 'walker' part:
```
<?php
wp_nav_menu(array(
'theme_location' => 'onepage',
'echo' => true,
'container' => false,
'walker'=> new Single_Page_Walker,
'depth' => 1) );
?>
```
— that’s it already. Now you can fill up your menu in the backend without caring about hashes anymore :).
|
191,471 |
<p>I'm trying to set up my custom template for a custom taxonomy. When I click on a category link to display the custom posts in that specific category, I get the 404 page. My custom post type file name is template-features.php and my taxonomy archive file is archive-features.php. Here is my code to register the taxonomy and post type:</p>
<p>Custom post type and taxonomy:</p>
<pre><code>add_action( 'init', 'post_type_features', 0 );
function post_type_features() {
$labels = array(
'name' => _x( 'Features', 'Post Type General Name', 'text_domain' ),
'singular_name' => _x( 'Feature', 'Post Type Singular Name', 'text_domain' ),
'menu_name' => __( 'Features', 'text_domain' ),
'parent_item_colon' => __( 'Parent Feature:', 'text_domain' ),
'all_items' => __( 'All Features', 'text_domain' ),
'view_item' => __( 'View Feature', 'text_domain' ),
'add_new_item' => __( 'Add New Feature', 'text_domain' ),
'add_new' => __( 'Add New', 'text_domain' ),
'edit_item' => __( 'Edit Feature', 'text_domain' ),
'update_item' => __( 'Update Feature', 'text_domain' ),
'search_items' => __( 'Search Features', 'text_domain' ),
'not_found' => __( 'Not found', 'text_domain' ),
'not_found_in_trash' => __( 'Not found in Trash', 'text_domain' ),
);
$args = array(
'label' => __( 'post_features', 'text_domain' ),
'description' => __( 'White Glove Labs Features', 'text_domain' ),
'labels' => $labels,
'supports' => array( 'title', 'editor', 'thumbnail', 'custom-fields', ),
'taxonomies' => array( 'Features' ),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'show_in_admin_bar' => true,
'menu_icon' => 'dashicons-star-empty',
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'page',
);
register_post_type( 'post_features', $args );
}
add_action( 'init', 'lv_features_taxonomy', 0 );
function lv_features_taxonomy() {
$labels = array(
'name' => _x( 'Features', 'Features Taxonomy' ),
'singular_name' => _x( 'Feature', 'Feature singular name' ),
'search_items' => __( 'Search Features' ),
'all_items' => __( 'All Features' ),
'parent_item' => __( 'Parent Feature' ),
'parent_item_colon' => __( 'Parent Feature:' ),
'edit_item' => __( 'Edit Feature' ),
'update_item' => __( 'Update Feature' ),
'add_new_item' => __( 'Add New Feature' ),
'new_item_name' => __( 'New Feature Name' ),
'menu_name' => __( 'Features Categories' ),
);
register_taxonomy('features',array('post_features'), array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'features' ),
));
}
</code></pre>
<p>Just for testing, I have a very basic custom archive file. Here is the code:</p>
<pre><code> <?php get_header(); ?>
<div id="main-content" class="main-content">
<div id="primary" class="content-area">
<div id="content" class="site-content" role="main">
<header class="archive-header">
<h1 class="archive-title">
<?php post_type_archive_title(); ?>
</h1>
</header>
</div>
</div>
</div>
<?php
get_sidebar();
get_footer();
</code></pre>
|
[
{
"answer_id": 191473,
"author": "Hareesh Sivasubramanian",
"author_id": 59124,
"author_profile": "https://wordpress.stackexchange.com/users/59124",
"pm_score": 0,
"selected": false,
"text": "<p>Did you remember to <a href=\"https://codex.wordpress.org/Function_Reference/flush_rewrite_rules\" rel=\"nofollow\">flush the rewrite rules</a> after creating your custom post type?\nVisit Settings > Permalinks and hit save. ( No need to change anything)</p>\n"
},
{
"answer_id": 191474,
"author": "Nilambar Sharma",
"author_id": 27998,
"author_profile": "https://wordpress.stackexchange.com/users/27998",
"pm_score": 2,
"selected": true,
"text": "<p>From code for post type and custom taxonomy, your CPT is <code>post_features</code> and taxonomy is <code>features</code>.</p>\n\n<p>For single <code>post_features</code>, you need to have file named <code>single-post_features.php</code>. For archive, create file <code>taxonomy-features.php</code>.</p>\n\n<p>See documentation for detail. <a href=\"https://codex.wordpress.org/Post_Type_Templates\" rel=\"nofollow\">https://codex.wordpress.org/Post_Type_Templates</a></p>\n\n<p><strong>Example for single(single-post_features.php):</strong></p>\n\n<pre><code><?php get_header(); ?>\n<?php\nif ( have_posts() ) {\n while ( have_posts() ) {\n the_post();\n\n the_title();\n the_content();\n } // end while\n} // end if\n?>\n<?php get_footer(); ?>\n</code></pre>\n\n<p><strong>Example for Archive(taxonomy-features.php):</strong></p>\n\n<pre><code><?php get_header(); ?>\n<?php\nif ( have_posts() ) {\n the_archive_title( '<h1>', '</h1>' );\n while ( have_posts() ) {\n the_post();\n the_title();\n the_content();\n } // end while\n} // end if\n?>\n<?php get_footer(); ?>\n</code></pre>\n\n<p><strong>Note:</strong> Please flush your permalink if you are getting 404 error.</p>\n"
}
] |
2015/06/15
|
[
"https://wordpress.stackexchange.com/questions/191471",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/13096/"
] |
I'm trying to set up my custom template for a custom taxonomy. When I click on a category link to display the custom posts in that specific category, I get the 404 page. My custom post type file name is template-features.php and my taxonomy archive file is archive-features.php. Here is my code to register the taxonomy and post type:
Custom post type and taxonomy:
```
add_action( 'init', 'post_type_features', 0 );
function post_type_features() {
$labels = array(
'name' => _x( 'Features', 'Post Type General Name', 'text_domain' ),
'singular_name' => _x( 'Feature', 'Post Type Singular Name', 'text_domain' ),
'menu_name' => __( 'Features', 'text_domain' ),
'parent_item_colon' => __( 'Parent Feature:', 'text_domain' ),
'all_items' => __( 'All Features', 'text_domain' ),
'view_item' => __( 'View Feature', 'text_domain' ),
'add_new_item' => __( 'Add New Feature', 'text_domain' ),
'add_new' => __( 'Add New', 'text_domain' ),
'edit_item' => __( 'Edit Feature', 'text_domain' ),
'update_item' => __( 'Update Feature', 'text_domain' ),
'search_items' => __( 'Search Features', 'text_domain' ),
'not_found' => __( 'Not found', 'text_domain' ),
'not_found_in_trash' => __( 'Not found in Trash', 'text_domain' ),
);
$args = array(
'label' => __( 'post_features', 'text_domain' ),
'description' => __( 'White Glove Labs Features', 'text_domain' ),
'labels' => $labels,
'supports' => array( 'title', 'editor', 'thumbnail', 'custom-fields', ),
'taxonomies' => array( 'Features' ),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'show_in_admin_bar' => true,
'menu_icon' => 'dashicons-star-empty',
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'page',
);
register_post_type( 'post_features', $args );
}
add_action( 'init', 'lv_features_taxonomy', 0 );
function lv_features_taxonomy() {
$labels = array(
'name' => _x( 'Features', 'Features Taxonomy' ),
'singular_name' => _x( 'Feature', 'Feature singular name' ),
'search_items' => __( 'Search Features' ),
'all_items' => __( 'All Features' ),
'parent_item' => __( 'Parent Feature' ),
'parent_item_colon' => __( 'Parent Feature:' ),
'edit_item' => __( 'Edit Feature' ),
'update_item' => __( 'Update Feature' ),
'add_new_item' => __( 'Add New Feature' ),
'new_item_name' => __( 'New Feature Name' ),
'menu_name' => __( 'Features Categories' ),
);
register_taxonomy('features',array('post_features'), array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'features' ),
));
}
```
Just for testing, I have a very basic custom archive file. Here is the code:
```
<?php get_header(); ?>
<div id="main-content" class="main-content">
<div id="primary" class="content-area">
<div id="content" class="site-content" role="main">
<header class="archive-header">
<h1 class="archive-title">
<?php post_type_archive_title(); ?>
</h1>
</header>
</div>
</div>
</div>
<?php
get_sidebar();
get_footer();
```
|
From code for post type and custom taxonomy, your CPT is `post_features` and taxonomy is `features`.
For single `post_features`, you need to have file named `single-post_features.php`. For archive, create file `taxonomy-features.php`.
See documentation for detail. <https://codex.wordpress.org/Post_Type_Templates>
**Example for single(single-post\_features.php):**
```
<?php get_header(); ?>
<?php
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
the_title();
the_content();
} // end while
} // end if
?>
<?php get_footer(); ?>
```
**Example for Archive(taxonomy-features.php):**
```
<?php get_header(); ?>
<?php
if ( have_posts() ) {
the_archive_title( '<h1>', '</h1>' );
while ( have_posts() ) {
the_post();
the_title();
the_content();
} // end while
} // end if
?>
<?php get_footer(); ?>
```
**Note:** Please flush your permalink if you are getting 404 error.
|
191,479 |
<p>In <a href="https://make.wordpress.org/core/2015/04/23/spinners-and-dismissible-admin-notices-in-4-2/" rel="noreferrer">WordPress 4.2</a> the <code>is-dismissible</code> class was introduced to allow notices to be dismissed.</p>
<p>This code is working to add the notice.</p>
<pre><code>function prefix_deprecated_hook_admin_notice() {
if ( has_filter( 'prefix_filter' ) ) { ?>
<div class="updated notice is-dismissible">
<p><?php _e( 'Notice', 'my-text-domain' ); ?></p>
</div>
<?php }
}
add_action( 'admin_notices', 'prefix_deprecated_hook_admin_notice' );
</code></pre>
<p>I am able to dismiss the notice but I am unsure how I can save the state when the notice is dismissed with AJAX.</p>
|
[
{
"answer_id": 193573,
"author": "grappler",
"author_id": 17937,
"author_profile": "https://wordpress.stackexchange.com/users/17937",
"pm_score": 0,
"selected": false,
"text": "<p>The best solution I found was a small library. <a href=\"https://github.com/CalderaWP/dismissible_notice\" rel=\"nofollow\">https://github.com/CalderaWP/dismissible_notice</a></p>\n\n<p>It is backward compatible till WordPress 3.8. </p>\n"
},
{
"answer_id": 251191,
"author": "random_user_name",
"author_id": 11704,
"author_profile": "https://wordpress.stackexchange.com/users/11704",
"pm_score": 3,
"selected": false,
"text": "<p>There's no need for a library, it's fairly straightforward to accomplish. If you are coding your own plugin (which it appears you are), then you can do this in a fairly lightweight way:</p>\n\n<p>A slightly modified version of the notice, which checks if it's been dismissed before displaying, and stores the \"type\" of notice in the markup for access in javascript:</p>\n\n<pre><code>function prefix_deprecated_hook_admin_notice() {\n if ( has_filter( 'prefix_filter' ) ) { \n // Check if it's been dismissed...\n if ( ! get_option('dismissed-prefix_deprecated', FALSE ) ) { \n // Added the class \"notice-my-class\" so jQuery pick it up and pass via AJAX,\n // and added \"data-notice\" attribute in order to track multiple / different notices\n // multiple dismissible notice states ?>\n <div class=\"updated notice notice-my-class is-dismissible\" data-notice=\"prefix_deprecated\">\n <p><?php _e( 'Notice', 'my-text-domain' ); ?></p>\n </div>\n <?php }\n }\n}\n\nadd_action( 'admin_notices', 'prefix_deprecated_hook_admin_notice' );\n</code></pre>\n\n<p>And then, the following jQuery</p>\n\n<pre><code> // shorthand no-conflict safe document-ready function\n jQuery(function($) {\n // Hook into the \"notice-my-class\" class we added to the notice, so\n // Only listen to YOUR notices being dismissed\n $( document ).on( 'click', '.notice-my-class .notice-dismiss', function () {\n // Read the \"data-notice\" information to track which notice\n // is being dismissed and send it via AJAX\n var type = $( this ).closest( '.notice-my-class' ).data( 'notice' );\n // Make an AJAX call\n // Since WP 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php\n $.ajax( ajaxurl,\n {\n type: 'POST',\n data: {\n action: 'dismissed_notice_handler',\n type: type,\n }\n } );\n } );\n });\n</code></pre>\n\n<p>In PHP, set up the AJAX hooks to capture the AJAX call:</p>\n\n<pre><code>add_action( 'wp_ajax_dismissed_notice_handler', 'ajax_notice_handler' );\n\n/**\n * AJAX handler to store the state of dismissible notices.\n */\nfunction ajax_notice_handler() {\n // Pick up the notice \"type\" - passed via jQuery (the \"data-notice\" attribute on the notice)\n $type = self::request( 'type' );\n // Store it in the options table\n update_option( 'dismissed-' . $type, TRUE );\n}\n</code></pre>\n\n<p>And that's it! No library needed - especially if you've already got PHP and javascript files loading.</p>\n\n<p>This method is per the <a href=\"https://make.wordpress.org/core/2015/04/23/spinners-and-dismissible-admin-notices-in-4-2/\" rel=\"noreferrer\">WordPress Core dev team blog</a></p>\n"
},
{
"answer_id": 411111,
"author": "Entretoize",
"author_id": 166674,
"author_profile": "https://wordpress.stackexchange.com/users/166674",
"pm_score": 0,
"selected": false,
"text": "<p>I doing that, no library needed:</p>\n<pre><code>function general_admin_notice()\n{\n global $pagenow;\n \n if ( $pagenow == 'admin.php' )\n {\n $todaykey="somekey".date("Ymd");\n \n if ( $_COOKIE[$todaykey]??0 ) \n return;\n \n print "<div class='notice notice-warning is-dismissible' onmousedown='document.cookie=\\"$todaykey=1\\";'>";\n print '<p>Something to tell</p>';\n print '</div>';\n }\n}\nadd_action('admin_notices', 'general_admin_notice');\n</code></pre>\n<p>I just check for a <code>mousedown</code> inside for more simplicity but you can check for a <code>mousedown</code> in the dismiss button too, with a bit more javascript...</p>\n"
}
] |
2015/06/15
|
[
"https://wordpress.stackexchange.com/questions/191479",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/17937/"
] |
In [WordPress 4.2](https://make.wordpress.org/core/2015/04/23/spinners-and-dismissible-admin-notices-in-4-2/) the `is-dismissible` class was introduced to allow notices to be dismissed.
This code is working to add the notice.
```
function prefix_deprecated_hook_admin_notice() {
if ( has_filter( 'prefix_filter' ) ) { ?>
<div class="updated notice is-dismissible">
<p><?php _e( 'Notice', 'my-text-domain' ); ?></p>
</div>
<?php }
}
add_action( 'admin_notices', 'prefix_deprecated_hook_admin_notice' );
```
I am able to dismiss the notice but I am unsure how I can save the state when the notice is dismissed with AJAX.
|
There's no need for a library, it's fairly straightforward to accomplish. If you are coding your own plugin (which it appears you are), then you can do this in a fairly lightweight way:
A slightly modified version of the notice, which checks if it's been dismissed before displaying, and stores the "type" of notice in the markup for access in javascript:
```
function prefix_deprecated_hook_admin_notice() {
if ( has_filter( 'prefix_filter' ) ) {
// Check if it's been dismissed...
if ( ! get_option('dismissed-prefix_deprecated', FALSE ) ) {
// Added the class "notice-my-class" so jQuery pick it up and pass via AJAX,
// and added "data-notice" attribute in order to track multiple / different notices
// multiple dismissible notice states ?>
<div class="updated notice notice-my-class is-dismissible" data-notice="prefix_deprecated">
<p><?php _e( 'Notice', 'my-text-domain' ); ?></p>
</div>
<?php }
}
}
add_action( 'admin_notices', 'prefix_deprecated_hook_admin_notice' );
```
And then, the following jQuery
```
// shorthand no-conflict safe document-ready function
jQuery(function($) {
// Hook into the "notice-my-class" class we added to the notice, so
// Only listen to YOUR notices being dismissed
$( document ).on( 'click', '.notice-my-class .notice-dismiss', function () {
// Read the "data-notice" information to track which notice
// is being dismissed and send it via AJAX
var type = $( this ).closest( '.notice-my-class' ).data( 'notice' );
// Make an AJAX call
// Since WP 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
$.ajax( ajaxurl,
{
type: 'POST',
data: {
action: 'dismissed_notice_handler',
type: type,
}
} );
} );
});
```
In PHP, set up the AJAX hooks to capture the AJAX call:
```
add_action( 'wp_ajax_dismissed_notice_handler', 'ajax_notice_handler' );
/**
* AJAX handler to store the state of dismissible notices.
*/
function ajax_notice_handler() {
// Pick up the notice "type" - passed via jQuery (the "data-notice" attribute on the notice)
$type = self::request( 'type' );
// Store it in the options table
update_option( 'dismissed-' . $type, TRUE );
}
```
And that's it! No library needed - especially if you've already got PHP and javascript files loading.
This method is per the [WordPress Core dev team blog](https://make.wordpress.org/core/2015/04/23/spinners-and-dismissible-admin-notices-in-4-2/)
|
191,481 |
<p>I know there are userID, username in the database, but I want a formatted and unique number for physical world use. For example: "2014xxxx" 201414:year,xxxx:generate randomly when registering a user. </p>
<p>Is it possible and if possible, what is the simplest way and fastest way to do so? </p>
|
[
{
"answer_id": 193573,
"author": "grappler",
"author_id": 17937,
"author_profile": "https://wordpress.stackexchange.com/users/17937",
"pm_score": 0,
"selected": false,
"text": "<p>The best solution I found was a small library. <a href=\"https://github.com/CalderaWP/dismissible_notice\" rel=\"nofollow\">https://github.com/CalderaWP/dismissible_notice</a></p>\n\n<p>It is backward compatible till WordPress 3.8. </p>\n"
},
{
"answer_id": 251191,
"author": "random_user_name",
"author_id": 11704,
"author_profile": "https://wordpress.stackexchange.com/users/11704",
"pm_score": 3,
"selected": false,
"text": "<p>There's no need for a library, it's fairly straightforward to accomplish. If you are coding your own plugin (which it appears you are), then you can do this in a fairly lightweight way:</p>\n\n<p>A slightly modified version of the notice, which checks if it's been dismissed before displaying, and stores the \"type\" of notice in the markup for access in javascript:</p>\n\n<pre><code>function prefix_deprecated_hook_admin_notice() {\n if ( has_filter( 'prefix_filter' ) ) { \n // Check if it's been dismissed...\n if ( ! get_option('dismissed-prefix_deprecated', FALSE ) ) { \n // Added the class \"notice-my-class\" so jQuery pick it up and pass via AJAX,\n // and added \"data-notice\" attribute in order to track multiple / different notices\n // multiple dismissible notice states ?>\n <div class=\"updated notice notice-my-class is-dismissible\" data-notice=\"prefix_deprecated\">\n <p><?php _e( 'Notice', 'my-text-domain' ); ?></p>\n </div>\n <?php }\n }\n}\n\nadd_action( 'admin_notices', 'prefix_deprecated_hook_admin_notice' );\n</code></pre>\n\n<p>And then, the following jQuery</p>\n\n<pre><code> // shorthand no-conflict safe document-ready function\n jQuery(function($) {\n // Hook into the \"notice-my-class\" class we added to the notice, so\n // Only listen to YOUR notices being dismissed\n $( document ).on( 'click', '.notice-my-class .notice-dismiss', function () {\n // Read the \"data-notice\" information to track which notice\n // is being dismissed and send it via AJAX\n var type = $( this ).closest( '.notice-my-class' ).data( 'notice' );\n // Make an AJAX call\n // Since WP 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php\n $.ajax( ajaxurl,\n {\n type: 'POST',\n data: {\n action: 'dismissed_notice_handler',\n type: type,\n }\n } );\n } );\n });\n</code></pre>\n\n<p>In PHP, set up the AJAX hooks to capture the AJAX call:</p>\n\n<pre><code>add_action( 'wp_ajax_dismissed_notice_handler', 'ajax_notice_handler' );\n\n/**\n * AJAX handler to store the state of dismissible notices.\n */\nfunction ajax_notice_handler() {\n // Pick up the notice \"type\" - passed via jQuery (the \"data-notice\" attribute on the notice)\n $type = self::request( 'type' );\n // Store it in the options table\n update_option( 'dismissed-' . $type, TRUE );\n}\n</code></pre>\n\n<p>And that's it! No library needed - especially if you've already got PHP and javascript files loading.</p>\n\n<p>This method is per the <a href=\"https://make.wordpress.org/core/2015/04/23/spinners-and-dismissible-admin-notices-in-4-2/\" rel=\"noreferrer\">WordPress Core dev team blog</a></p>\n"
},
{
"answer_id": 411111,
"author": "Entretoize",
"author_id": 166674,
"author_profile": "https://wordpress.stackexchange.com/users/166674",
"pm_score": 0,
"selected": false,
"text": "<p>I doing that, no library needed:</p>\n<pre><code>function general_admin_notice()\n{\n global $pagenow;\n \n if ( $pagenow == 'admin.php' )\n {\n $todaykey="somekey".date("Ymd");\n \n if ( $_COOKIE[$todaykey]??0 ) \n return;\n \n print "<div class='notice notice-warning is-dismissible' onmousedown='document.cookie=\\"$todaykey=1\\";'>";\n print '<p>Something to tell</p>';\n print '</div>';\n }\n}\nadd_action('admin_notices', 'general_admin_notice');\n</code></pre>\n<p>I just check for a <code>mousedown</code> inside for more simplicity but you can check for a <code>mousedown</code> in the dismiss button too, with a bit more javascript...</p>\n"
}
] |
2015/06/15
|
[
"https://wordpress.stackexchange.com/questions/191481",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74676/"
] |
I know there are userID, username in the database, but I want a formatted and unique number for physical world use. For example: "2014xxxx" 201414:year,xxxx:generate randomly when registering a user.
Is it possible and if possible, what is the simplest way and fastest way to do so?
|
There's no need for a library, it's fairly straightforward to accomplish. If you are coding your own plugin (which it appears you are), then you can do this in a fairly lightweight way:
A slightly modified version of the notice, which checks if it's been dismissed before displaying, and stores the "type" of notice in the markup for access in javascript:
```
function prefix_deprecated_hook_admin_notice() {
if ( has_filter( 'prefix_filter' ) ) {
// Check if it's been dismissed...
if ( ! get_option('dismissed-prefix_deprecated', FALSE ) ) {
// Added the class "notice-my-class" so jQuery pick it up and pass via AJAX,
// and added "data-notice" attribute in order to track multiple / different notices
// multiple dismissible notice states ?>
<div class="updated notice notice-my-class is-dismissible" data-notice="prefix_deprecated">
<p><?php _e( 'Notice', 'my-text-domain' ); ?></p>
</div>
<?php }
}
}
add_action( 'admin_notices', 'prefix_deprecated_hook_admin_notice' );
```
And then, the following jQuery
```
// shorthand no-conflict safe document-ready function
jQuery(function($) {
// Hook into the "notice-my-class" class we added to the notice, so
// Only listen to YOUR notices being dismissed
$( document ).on( 'click', '.notice-my-class .notice-dismiss', function () {
// Read the "data-notice" information to track which notice
// is being dismissed and send it via AJAX
var type = $( this ).closest( '.notice-my-class' ).data( 'notice' );
// Make an AJAX call
// Since WP 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
$.ajax( ajaxurl,
{
type: 'POST',
data: {
action: 'dismissed_notice_handler',
type: type,
}
} );
} );
});
```
In PHP, set up the AJAX hooks to capture the AJAX call:
```
add_action( 'wp_ajax_dismissed_notice_handler', 'ajax_notice_handler' );
/**
* AJAX handler to store the state of dismissible notices.
*/
function ajax_notice_handler() {
// Pick up the notice "type" - passed via jQuery (the "data-notice" attribute on the notice)
$type = self::request( 'type' );
// Store it in the options table
update_option( 'dismissed-' . $type, TRUE );
}
```
And that's it! No library needed - especially if you've already got PHP and javascript files loading.
This method is per the [WordPress Core dev team blog](https://make.wordpress.org/core/2015/04/23/spinners-and-dismissible-admin-notices-in-4-2/)
|
191,522 |
<p>I search a lot that how can i re-size images that upload with meta field but i get nothing instead of <code>wp_get_image_editor</code>. I read from codex about it but nothing helpful so I search about this function and found these links</p>
<p><a href="http://bhoover.com/wp_image_editor-wordpress-image-editing-tutorial/" rel="nofollow">http://bhoover.com/wp_image_editor-wordpress-image-editing-tutorial/</a></p>
<p><a href="http://wpunknown.com/wp_image_editor/" rel="nofollow">http://wpunknown.com/wp_image_editor/</a></p>
<p>but it also not usefull for me.</p>
<p>I tried scripts from first link. First i upload an image from media and then create a page template and write this code in my template in while loop:</p>
<pre><code>if(have_posts()) :
while(have_posts()) :
the_post();
the_title();
// wp editor image script
$testing_img_src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full');
$img = wp_get_image_editor( $testing_img_src[0] );
if ( ! is_wp_error( $img ) ) {
$img->resize( 500, NULL, false );
$img->set_quality( 100 );
$img->stream();
}
endwhile;
</code></pre>
<p>When i fresh the page it gives me this kind of crap:</p>
<pre><code>����JFIF��,��gf8�R�����;�8'���Z�v� F��`q�q� <+�g�51N��`NO���2�Bo���Jֵ��>����o3����M]�(��]�[�u���^핺��_�#;U�,OLs��$�� �F �+XΪ�|�rx�v���p |�&�����s�u<H��a��=r�}�X��dR�� ������07`qھk�r� ���$����tvw�l����朴�B�i]�-R��}.�N)6���>ҵ�,na��G9-���8�#��Kik6 �$y>�w�� �N��~=��1�y8!�ʂ:��v��1����V(U%r6�e��Ns��'�7t �x��1�yF2�I]Y���ˢ~�����5��Z�T��m5&����u+�^��^�} 7���\ЎGL�����`�� ��jm�Q�s� gn���#8�p���Um#�v�rQZu�d����N@� `�3�s^�a�:�����2G�<�A��njz�'�fx+Ƣ����;��>�.�6֎��1Y�:sS�MYI[E�v\�����j��5τk)>\!K���덤�@�둞�9�|)����u9 ��\c9��v<�_�>�y���㿠����98��_M�S�FK��� ��`�!H#�������IENSi+ZZ��o��V������=���sx��MNWmӌcZO�i�=��馺/��� �Zk�h���#pʶHc�J����1Y?oլ���]F2�(�BN�1�Q�A�2 �����:�IKt,s� 9(��m�n�^;�|�Us�������9$� �3���@?k���"1X�T�t�������o}ZX�G�>��U2�UJmk9;+-4�\R��QM�eu��ŏ��9[�����`���O�9� �$q�[kZu�+�N����O\���� {����f��@�pH%Hϧ$����$�~�c���L�B�7#��gvO�k�)b�{2Iӯ R��rV�u�M+lܞ������4�㍲5(���S�q����f�ҋ~�W~���[�R++�J��۹O^:�|����`֟��\�����$�`7:���s۟e � ����)$E�X�H$��(U>�v'Z���[��H��q�~��T�G}�B�&� S����I�W 4��N-Żi�O[�O��ή�Y������Fp��qJ|��V���w�m�j�5[��|��!Nv��� ����>�����,��*q��w)1�8�U��y�]mJ�8�bX��$��O%�����K�$�������9���FO�f|��̱XJ7j�M=5��o9h�����`�2r�bR��V�Y9��n�'e��)s$���>5�~�F��*rQJ`�@�d�9 s���;�I*:1;Y�}�8�@��~�d�i�Hط�)�����8=�Y7���!�c>�YT|��c��20r3�+���^�y��q�䞼�릯f�k6��.�����pxz괕���8�YFq�KmaukJ��?���V�yɀ� ��c��\pH=����'Z�^��U`@#~Cd��N�;���>��~9I0 ��'v8�$�����כj��`ge����rp0xۏ�q���q��{�z��s�[]ӓ��T��dӳv�}U���{8~ ���X������V��)FQk�����e�O��[k�����3�������5�Ť�q����Q���$Ԍ����>j���ʥC�v�f@;JF@Rs�A�y�KA`q�����|W�%e�#q���^>� ����ONģk$�7��i.���m�~���t�Ғ��<�����wvwm[僫�&�2�$��g�gh���ӷ`���R��:b�@�RX+)~FyNppæ �F?NY��C��@w`��2G^ �9��<�N���/Ԝ������8$��<�� �_9��̯u[N�j��M����w���{��$�҇���R�mG����V���[Kk�$��g�2�D���n#v N�nRޘ) ���<�1̖�|���dF�����A�a�}�xL��D/�w�)w(<B_rO���4��0�!l��9�9��H����f���ܝ�ݚZ���}l읬���s��\�u^*�7k5{Yr�]�[;�d���ic�գȡ��t�b0����4W��| �\8��TN�Q�|o�:gМ�E|��n7v�G������S��[y�|B�JXuk���ݾ�|��~W������eN��pI�2p�A�y8Ÿ��$����5<jM�袢�3i�Y��>Vm:��$y8�z�`{���7m5k�"���B1���1��x�������xV�l����nI�9����s�����\� ���q�В@�{�./�NΣJ���j�I�����|�g��W���UU��ۊ��i%u������_��|n��9�O�q��20���Ѵ�i�!6ʀ��<��lr�v�OB8[���� ���?־�o1�I$+G$���F '$� 0���֘�|�@BH*��� �a�6?H��L�P�S �8���d��+#Q�{�_���lp@�����GO�zc�'�r�/�pR����dՒz5���]U�}�WG�Q�tʳHԞ� �+�8��V|�N�_���H���>������y9 0�$,��F���.Y��U�I�#vOB}��{��~[�dx! ��( ��H#�s�pG`>Q�����F�sE�c�8����{�,q�+����� ��V��*KI���]7ItIj�Vg���s�S��N-6��<*Z��W��vmEݞ��x�O�Dt9#��������8�� ���ep�R[� dH�G98�prB�·����Љ�#d�� �8<����Cm��i,�h@@9�F <�r@��@�'���!�_�8��5eg'^�umY�Y�|���!�?�'/k��(A��)�OM�v�^��d�W�Gߥ,��)�������ッ���xr)�h����;�����3��z'Ư,�]�NH;�A��K:��kۼ;�oL�T t�w_�c�I ���Pk�ܫ��||aɊ�$���I_f����Y����q�?���ƥ)F\��yӳJ�RM'�z(�v3�z�����v��^:q�`t$� UY5{i�Pz�OA?78�3���w_�t���G;�猯�\����/c��~��2O�H�Br8� �������p��q����ee���OG��F�}���4� �E)^5h����%is-�ꬵj�S�4ψ:�ˉ� >z�����q�zz���=^٘��\��s�8 )$���������j�S�R~�`�L��~E]xg[��x��6rp ���r:>���-��)I�B��,8#���o�5�s<��y� �+I�k�N�2[�%n�a�iAr>WN+N��������c���Uӯv�x�89[+���'�x$��kO���9����^�b���Ɵ�K�r�r <�K�y�c�\ӼW��F�M�2�p'9��N�c95������R ��Q����kU}ԗe��r~����J,����u��Oe��}U�5]h��IE���ns�_��T�`@�*�>1���3L��K��z�mـ � ����G�a��#6#9��c�����C�ޓ�F�"��0>U9��;�
</code></pre>
<p>I also tried to add hard coded image path like:</p>
<pre><code>//$testing_img_src = ABSPATH.'wp-content/uploads/2015/06/colorful-background-31.jpg';
</code></pre>
<p>but it gives me same result. So please help me that how can i use <code>wp_get_image_editor()</code> so that my image resized or crop OR there is an other way for this.</p>
<p><strong><em>NOTE:</em></strong> I don't want to use <code>add_image_size()</code></p>
|
[
{
"answer_id": 220660,
"author": "iantsch",
"author_id": 90220,
"author_profile": "https://wordpress.stackexchange.com/users/90220",
"pm_score": 2,
"selected": true,
"text": "<h2>A possible solution:</h2>\n\n<p><strong>Goal:</strong> Don't use <code>add_image_size()</code> to show a custom sized image.</p>\n\n<p>If you calculate the image without saving it, all requests will sum up to a huge page load due to repeated unnecessary processing time. So caching or saving the results should be an additional goal.</p>\n\n<p>Add a <strong>image-processor.php</strong> in your template/plugin:</p>\n\n<pre><code>//Load your WordPress enviroment\n$path = dirname(__FILE__);\n$path = substr($path, 0, stripos($path, \"wp-content\") );\nrequire( $path . \"wp-load.php\");\n\n//TODO: filter and handle your $_GET params\n$post_id = absint($_GET['post_id']);\n\n$testing_img_url = wp_get_attachment_image_url(\n get_post_thumbnail_id($post->ID), 'full'\n);\n\nif (!$testing_img_url)\n $testing_img_url = 'http://domain.tld/path/to/defaul-image.jpg';\n\n$img = wp_get_image_editor( $testing_img_url );\n\nif ( ! is_wp_error( $img ) ) {\n header('Content-type:'.finfo_file ($testing_img_url));\n $img->resize( 500, NULL, false );\n $img->set_quality( 100 );\n $img->stream();\n}\n</code></pre>\n\n<p>You can display the image in a loop now like this: </p>\n\n<p><strong>Template</strong>: </p>\n\n<pre><code><img src=\"<?= get_template_directory_uri()?>/image-processor.php?post_id=<?= get_the_ID()?>\">\n</code></pre>\n\n<p><strong>Plugin</strong>: </p>\n\n<pre><code><img src=\"<?= plugin_dir_path(__FILE__)?>image-processor.php?post_id=<?= get_the_ID()?>\">\n</code></pre>\n\n<h2>Possible improvements:</h2>\n\n<ul>\n<li>Caching/saving the processed images.</li>\n<li>Better error handling.</li>\n</ul>\n"
},
{
"answer_id": 352765,
"author": "Najeeb zulfiqar",
"author_id": 178491,
"author_profile": "https://wordpress.stackexchange.com/users/178491",
"pm_score": 0,
"selected": false,
"text": "<p>I have used wp_get_image_editor for Instagram images resizing. You can use it in similar fashion for posts or any </p>\n"
}
] |
2015/06/15
|
[
"https://wordpress.stackexchange.com/questions/191522",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/64316/"
] |
I search a lot that how can i re-size images that upload with meta field but i get nothing instead of `wp_get_image_editor`. I read from codex about it but nothing helpful so I search about this function and found these links
<http://bhoover.com/wp_image_editor-wordpress-image-editing-tutorial/>
<http://wpunknown.com/wp_image_editor/>
but it also not usefull for me.
I tried scripts from first link. First i upload an image from media and then create a page template and write this code in my template in while loop:
```
if(have_posts()) :
while(have_posts()) :
the_post();
the_title();
// wp editor image script
$testing_img_src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full');
$img = wp_get_image_editor( $testing_img_src[0] );
if ( ! is_wp_error( $img ) ) {
$img->resize( 500, NULL, false );
$img->set_quality( 100 );
$img->stream();
}
endwhile;
```
When i fresh the page it gives me this kind of crap:
```
����JFIF��,��gf8�R�����;�8'���Z�v� F��`q�q� <+�g�51N��`NO���2�Bo���Jֵ��>����o3����M]�(��]�[�u���^핺��_�#;U�,OLs��$�� �F �+XΪ�|�rx�v���p |�&�����s�u<H��a��=r�}�X��dR�� ������07`qھk�r� ���$����tvw�l����朴�B�i]�-R��}.�N)6���>ҵ�,na��G9-���8�#��Kik6 �$y>�w�� �N��~=��1�y8!�ʂ:��v��1����V(U%r6�e��Ns��'�7t �x��1�yF2�I]Y���ˢ~�����5��Z�T��m5&����u+�^��^�} 7���\ЎGL�����`�� ��jm�Q�s� gn���#8�p���Um#�v�rQZu�d����N@� `�3�s^�a�:�����2G�<�A��njz�'�fx+Ƣ����;��>�.�6֎��1Y�:sS�MYI[E�v\�����j��5τk)>\!K���덤�@�둞�9�|)����u9 ��\c9��v<�_�>�y���㿠����98��_M�S�FK��� ��`�!H#�������IENSi+ZZ��o��V������=���sx��MNWmӌcZO�i�=��馺/��� �Zk�h���#pʶHc�J����1Y?oլ���]F2�(�BN�1�Q�A�2 �����:�IKt,s� 9(��m�n�^;�|�Us�������9$� �3���@?k���"1X�T�t�������o}ZX�G�>��U2�UJmk9;+-4�\R��QM�eu��ŏ��9[�����`���O�9� �$q�[kZu�+�N����O\���� {����f��@�pH%Hϧ$����$�~�c���L�B�7#��gvO�k�)b�{2Iӯ R��rV�u�M+lܞ������4�㍲5(���S�q����f�ҋ~�W~���[�R++�J��۹O^:�|����`֟��\�����$�`7:���s۟e � ����)$E�X�H$��(U>�v'Z���[��H��q�~��T�G}�B�&� S����I�W 4��N-Żi�O[�O��ή�Y������Fp��qJ|��V���w�m�j�5[��|��!Nv��� ����>�����,��*q��w)1�8�U��y�]mJ�8�bX��$��O%�����K�$�������9���FO�f|��̱XJ7j�M=5��o9h�����`�2r�bR��V�Y9��n�'e��)s$���>5�~�F��*rQJ`�@�d�9 s���;�I*:1;Y�}�8�@��~�d�i�Hط�)�����8=�Y7���!�c>�YT|��c��20r3�+���^�y��q�䞼�릯f�k6��.�����pxz괕���8�YFq�KmaukJ��?���V�yɀ� ��c��\pH=����'Z�^��U`@#~Cd��N�;���>��~9I0 ��'v8�$�����כj��`ge����rp0xۏ�q���q��{�z��s�[]ӓ��T��dӳv�}U���{8~ ���X������V��)FQk�����e�O��[k�����3�������5�Ť�q����Q���$Ԍ����>j���ʥC�v�f@;JF@Rs�A�y�KA`q�����|W�%e�#q���^>� ����ONģk$�7��i.���m�~���t�Ғ��<�����wvwm[僫�&�2�$��g�gh���ӷ`���R��:b�@�RX+)~FyNppæ �F?NY��C��@w`��2G^ �9��<�N���/Ԝ������8$��<�� �_9��̯u[N�j��M����w���{��$�҇���R�mG����V���[Kk�$��g�2�D���n#v N�nRޘ) ���<�1̖�|���dF�����A�a�}�xL��D/�w�)w(<B_rO���4��0�!l��9�9��H����f���ܝ�ݚZ���}l읬���s��\�u^*�7k5{Yr�]�[;�d���ic�գȡ��t�b0����4W��| �\8��TN�Q�|o�:gМ�E|��n7v�G������S��[y�|B�JXuk���ݾ�|��~W������eN��pI�2p�A�y8Ÿ��$����5<jM�袢�3i�Y��>Vm:��$y8�z�`{���7m5k�"���B1���1��x�������xV�l����nI�9����s�����\� ���q�В@�{�./�NΣJ���j�I�����|�g��W���UU��ۊ��i%u������_��|n��9�O�q��20���Ѵ�i�!6ʀ��<��lr�v�OB8[���� ���?־�o1�I$+G$���F '$� 0���֘�|�@BH*��� �a�6?H��L�P�S �8���d��+#Q�{�_���lp@�����GO�zc�'�r�/�pR����dՒz5���]U�}�WG�Q�tʳHԞ� �+�8��V|�N�_���H���>������y9 0�$,��F���.Y��U�I�#vOB}��{��~[�dx! ��( ��H#�s�pG`>Q�����F�sE�c�8����{�,q�+����� ��V��*KI���]7ItIj�Vg���s�S��N-6��<*Z��W��vmEݞ��x�O�Dt9#��������8�� ���ep�R[� dH�G98�prB�·����Љ�#d�� �8<����Cm��i,�h@@9�F <�r@��@�'���!�_�8��5eg'^�umY�Y�|���!�?�'/k��(A��)�OM�v�^��d�W�Gߥ,��)�������ッ���xr)�h����;�����3��z'Ư,�]�NH;�A��K:��kۼ;�oL�T t�w_�c�I ���Pk�ܫ��||aɊ�$���I_f����Y����q�?���ƥ)F\��yӳJ�RM'�z(�v3�z�����v��^:q�`t$� UY5{i�Pz�OA?78�3���w_�t���G;�猯�\����/c��~��2O�H�Br8� �������p��q����ee���OG��F�}���4� �E)^5h����%is-�ꬵj�S�4ψ:�ˉ� >z�����q�zz���=^٘��\��s�8 )$���������j�S�R~�`�L��~E]xg[��x��6rp ���r:>���-��)I�B��,8#���o�5�s<��y� �+I�k�N�2[�%n�a�iAr>WN+N��������c���Uӯv�x�89[+���'�x$��kO���9����^�b���Ɵ�K�r�r <�K�y�c�\ӼW��F�M�2�p'9��N�c95������R ��Q����kU}ԗe��r~����J,����u��Oe��}U�5]h��IE���ns�_��T�`@�*�>1���3L��K��z�mـ � ����G�a��#6#9��c�����C�ޓ�F�"��0>U9��;�
```
I also tried to add hard coded image path like:
```
//$testing_img_src = ABSPATH.'wp-content/uploads/2015/06/colorful-background-31.jpg';
```
but it gives me same result. So please help me that how can i use `wp_get_image_editor()` so that my image resized or crop OR there is an other way for this.
***NOTE:*** I don't want to use `add_image_size()`
|
A possible solution:
--------------------
**Goal:** Don't use `add_image_size()` to show a custom sized image.
If you calculate the image without saving it, all requests will sum up to a huge page load due to repeated unnecessary processing time. So caching or saving the results should be an additional goal.
Add a **image-processor.php** in your template/plugin:
```
//Load your WordPress enviroment
$path = dirname(__FILE__);
$path = substr($path, 0, stripos($path, "wp-content") );
require( $path . "wp-load.php");
//TODO: filter and handle your $_GET params
$post_id = absint($_GET['post_id']);
$testing_img_url = wp_get_attachment_image_url(
get_post_thumbnail_id($post->ID), 'full'
);
if (!$testing_img_url)
$testing_img_url = 'http://domain.tld/path/to/defaul-image.jpg';
$img = wp_get_image_editor( $testing_img_url );
if ( ! is_wp_error( $img ) ) {
header('Content-type:'.finfo_file ($testing_img_url));
$img->resize( 500, NULL, false );
$img->set_quality( 100 );
$img->stream();
}
```
You can display the image in a loop now like this:
**Template**:
```
<img src="<?= get_template_directory_uri()?>/image-processor.php?post_id=<?= get_the_ID()?>">
```
**Plugin**:
```
<img src="<?= plugin_dir_path(__FILE__)?>image-processor.php?post_id=<?= get_the_ID()?>">
```
Possible improvements:
----------------------
* Caching/saving the processed images.
* Better error handling.
|
191,523 |
<p>In my themes functions.php file I have put:</p>
<pre><code>add_action('wp_footer', 'method');
function method()
{
echo "this is being called";
die();
}
</code></pre>
<p>My wordpress footer.php file looks like this:</p>
<pre><code><?php wp_footer(); ?>
</body>
</html>
</code></pre>
<p>What could be the reason my add_action hook is not being called?</p>
<p>I can provide additional code or information if needed.</p>
<h2>EDIT:</h2>
<p>Instead of <code>die()</code> if I echo a script it won't appear in the pages footer</p>
<pre><code>add_action('wp_footer', 'method');
function method()
{
echo "<script>...</script>";
}
</code></pre>
|
[
{
"answer_id": 191535,
"author": "Brad Elsmore",
"author_id": 69036,
"author_profile": "https://wordpress.stackexchange.com/users/69036",
"pm_score": 0,
"selected": false,
"text": "<p>With such a general function name like <code>method()</code> a collision could be happening. Try something a little more unique than that. Also, if you have access to the server you could also print it to the error log so you don't have to worry when the page is being rendered.</p>\n"
},
{
"answer_id": 191610,
"author": "Domain",
"author_id": 26523,
"author_profile": "https://wordpress.stackexchange.com/users/26523",
"pm_score": 5,
"selected": true,
"text": "<p>In a WordPress footer hooks are different for back-end(dashboard) and front-end.</p>\n\n<p>In Dashboard use \"<code>admin_footer</code>\" hook.</p>\n\n<p>In Front-end use \"<code>wp_footer</code>\" hook.</p>\n"
}
] |
2015/06/15
|
[
"https://wordpress.stackexchange.com/questions/191523",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73967/"
] |
In my themes functions.php file I have put:
```
add_action('wp_footer', 'method');
function method()
{
echo "this is being called";
die();
}
```
My wordpress footer.php file looks like this:
```
<?php wp_footer(); ?>
</body>
</html>
```
What could be the reason my add\_action hook is not being called?
I can provide additional code or information if needed.
EDIT:
-----
Instead of `die()` if I echo a script it won't appear in the pages footer
```
add_action('wp_footer', 'method');
function method()
{
echo "<script>...</script>";
}
```
|
In a WordPress footer hooks are different for back-end(dashboard) and front-end.
In Dashboard use "`admin_footer`" hook.
In Front-end use "`wp_footer`" hook.
|
191,558 |
<p>Is there any way to disable the installation/updating of plugins in Wordpress?</p>
<p>I am deploying by Github, and therefore changes on server, does not replicate on my development environment. </p>
<p>I need to disable this, and make all updates and installations on my local Git repository, and THEN push to production, with the changes.</p>
|
[
{
"answer_id": 191559,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 0,
"selected": false,
"text": "<p>There are quite a few related bits you can tinker with, but the one most comprehensive setting for version controlled stack is <code>define( 'DISALLOW_FILE_MODS', true );</code>. It will disable anything related to changing code files, core or extensions either.</p>\n"
},
{
"answer_id": 191560,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 4,
"selected": true,
"text": "<p>Set the constant <code>DISALLOW_FILE_MODS</code> to <code>TRUE</code> in your <code>wp-config.php</code>:</p>\n\n<pre><code>const DISALLOW_FILE_MODS = TRUE;\n</code></pre>\n\n<p>See <a href=\"https://codex.wordpress.org/Editing_wp-config.php#Disable_the_Plugin_and_Theme_Editor\">the Codex</a> for background information:</p>\n\n<blockquote>\n <p>Setting this constant also disables the Plugin and Theme editor (i.e. you don't need to set <code>DISALLOW_FILE_MODS</code> and <code>DISALLOW_FILE_EDIT</code>, as on its own <code>DISALLOW_FILE_MODS</code> will have the same effect).</p>\n</blockquote>\n\n<p>It will also prevent installing or uninstalling plugins, themes and updating the WordPress core.</p>\n\n<p>This will not affect the Git deployment.</p>\n"
}
] |
2015/06/15
|
[
"https://wordpress.stackexchange.com/questions/191558",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25242/"
] |
Is there any way to disable the installation/updating of plugins in Wordpress?
I am deploying by Github, and therefore changes on server, does not replicate on my development environment.
I need to disable this, and make all updates and installations on my local Git repository, and THEN push to production, with the changes.
|
Set the constant `DISALLOW_FILE_MODS` to `TRUE` in your `wp-config.php`:
```
const DISALLOW_FILE_MODS = TRUE;
```
See [the Codex](https://codex.wordpress.org/Editing_wp-config.php#Disable_the_Plugin_and_Theme_Editor) for background information:
>
> Setting this constant also disables the Plugin and Theme editor (i.e. you don't need to set `DISALLOW_FILE_MODS` and `DISALLOW_FILE_EDIT`, as on its own `DISALLOW_FILE_MODS` will have the same effect).
>
>
>
It will also prevent installing or uninstalling plugins, themes and updating the WordPress core.
This will not affect the Git deployment.
|
191,571 |
<p>I have many post with multiple tags ex: <code>AMOS LEE, FOO FIGHTERS,TAYLOR SWIFT</code></p>
<p>Post only have one of the tags in the title ex: <code>“The Man Who Wants You” – Amos Lee</code></p>
<p>How would I scan the_title() and go through the tags and store the matching tag in a variable? </p>
<p>Ive tried</p>
<pre><code> <?php
$id = get_the_title();
$posttags = get_the_tags();
if ($posttags) {
foreach($posttags as $tag) {
$tag = $tag->name . '<br>';
}
}
if (stripos($id,$tag) !== false) {
echo 'true<br>';
}else{
echo 'false';
}
</code></pre>
<p>?></p>
|
[
{
"answer_id": 191619,
"author": "James Barrett",
"author_id": 74733,
"author_profile": "https://wordpress.stackexchange.com/users/74733",
"pm_score": 2,
"selected": true,
"text": "<p>Put this in your loop:</p>\n\n<pre><code><?php\n$title = get_the_title();\n$posttags = get_the_tags();\n\nif( $title && $posttags ) {\n $result = find_tag_in_title( $title, $posttags );\n var_dump( $result ); // dump result\n}\n?>\n</code></pre>\n\n<p>Put this in your functions.php file:</p>\n\n<pre><code><?php\nfunction find_tag_in_title( $title, $posttags ) {\n\n foreach( $posttags as $tag ){\n if( strpos( strtolower($title), strtolower($tag->name) ) !== false ) return $tag->name;\n }\n\nreturn false; \n}\n?>\n</code></pre>\n"
},
{
"answer_id": 191732,
"author": "Domain",
"author_id": 26523,
"author_profile": "https://wordpress.stackexchange.com/users/26523",
"pm_score": 0,
"selected": false,
"text": "<p>Small changes in your code:</p>\n\n<pre><code>//$id = get_the_title();\n$title = '\"The Man Who Wants You\" – Amos Lee';\n//$posttags = get_the_tags();\n$posttags = array('AMOS LEE', 'FOO FIGHTERS', 'TAYLOR SWIFT');\n$matched_tags = array();\nif ($posttags) {\n foreach ($posttags as $tag) {\n if (stripos($title, $tag) !== false) {\n array_push($matched_tags, $tag);\n }\n }\n}\nprint_r($matched_tags);\n</code></pre>\n\n<p>OUTPUT: your matched tags</p>\n\n<pre><code>Array\n(\n [0] => AMOS LEE\n)\n</code></pre>\n"
}
] |
2015/06/15
|
[
"https://wordpress.stackexchange.com/questions/191571",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63922/"
] |
I have many post with multiple tags ex: `AMOS LEE, FOO FIGHTERS,TAYLOR SWIFT`
Post only have one of the tags in the title ex: `“The Man Who Wants You” – Amos Lee`
How would I scan the\_title() and go through the tags and store the matching tag in a variable?
Ive tried
```
<?php
$id = get_the_title();
$posttags = get_the_tags();
if ($posttags) {
foreach($posttags as $tag) {
$tag = $tag->name . '<br>';
}
}
if (stripos($id,$tag) !== false) {
echo 'true<br>';
}else{
echo 'false';
}
```
?>
|
Put this in your loop:
```
<?php
$title = get_the_title();
$posttags = get_the_tags();
if( $title && $posttags ) {
$result = find_tag_in_title( $title, $posttags );
var_dump( $result ); // dump result
}
?>
```
Put this in your functions.php file:
```
<?php
function find_tag_in_title( $title, $posttags ) {
foreach( $posttags as $tag ){
if( strpos( strtolower($title), strtolower($tag->name) ) !== false ) return $tag->name;
}
return false;
}
?>
```
|
191,587 |
<p>I'll admit, I'm not a PHP expert, nor am I familiar with all of the WordPress functions and hooks. I've been stuck on an issue, searching for help without much success, and I was hoping that someone could help point me in the right direction.</p>
<p>I have a form. The user selects a specialty, location, and distance (10 miles, 20, 50, etc). The results are queried from a custom post type and filtered to match the specialty. The posts have their latitude and longitude in the meta data but I am not sure how to bring this into the query. I want the posts to only show if their latitude/longitude is within proximity from the specified distance. I have the functionality written already to get their distance. The trouble I'm having is with the query and displaying the data properly.</p>
<p>Here are my current query arguments:</p>
<pre><code>$args = array(
'post_type' => 'team-members',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'specialties',
'value' => $_GET['specialization'],
'compare' => 'LIKE'
)
)
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
</code></pre>
<p>This currently will display all the posts with the matching specialization, however, does not include anything involving the distance. So what I initially did was then set a conditional to check if the post was within the distance specified (don't worry about these variables, they are displaying the correct data):</p>
<pre><code>if ( $distance < $_GET['within'] ) {
</code></pre>
<p>The issue is that this condition is not factored into the query, and I am unable to sort by distance. Additionally, I have to set a counter in order to get a correct post "count", plus it just feels hacked together. I feel like there is a foundational error here, and I can't pinpoint it.</p>
<p>I hope this information was sufficient, and if you need anything clarified, please comment. I didn't want to overwhelmingly provide more than was necessary.</p>
|
[
{
"answer_id": 192175,
"author": "zaantar",
"author_id": 75006,
"author_profile": "https://wordpress.stackexchange.com/users/75006",
"pm_score": -1,
"selected": false,
"text": "<p>It seems that you could use Types and Views plugins (with Views \"Parametric search\" feature). Views is commercial, but unless you are building your personal website, I think it's worth it.</p>\n\n<p>Nice writeup about those plugins is, for example, here: <a href=\"http://www.neilcurtis.me/guides/best-wordpress-plugins/\" rel=\"nofollow\">http://www.neilcurtis.me/guides/best-wordpress-plugins/</a> </p>\n"
},
{
"answer_id": 192207,
"author": "Mitul",
"author_id": 74728,
"author_profile": "https://wordpress.stackexchange.com/users/74728",
"pm_score": 0,
"selected": false,
"text": "<p>here is the mysql query you can use to get the result having distance less then your value.</p>\n\n<pre><code>SELECT * , pm1.meta_value as latitude, pm2.meta_value as longitude , \n (((acos(sin(([latitude]*pi()/180)) * \n sin((pm1.meta_value * pi()/180)) + cos(([latitude]*pi()/180)) * \n cos((pm1.meta_value * pi()/180)) * cos((([longitude] - pm2.meta_value)* \n pi()/180))))*180/pi())*60*1.1515\n ) as distance\n\nFROM wp_posts p\nJOIN wp_postmeta pm1 ON pm1.post_id = p.ID AND pm1.meta_key = 'latitude'\nJOIN wp_postmeta pm2 ON pm2.post_id = p.ID AND pm2.meta_key = 'longitude'\nWHERE ID = 98\nhaving distance < $_GET['within']\n</code></pre>\n\n<p>It will return all the post with distance is less then your $_GET['within'] value.</p>\n"
}
] |
2015/06/16
|
[
"https://wordpress.stackexchange.com/questions/191587",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] |
I'll admit, I'm not a PHP expert, nor am I familiar with all of the WordPress functions and hooks. I've been stuck on an issue, searching for help without much success, and I was hoping that someone could help point me in the right direction.
I have a form. The user selects a specialty, location, and distance (10 miles, 20, 50, etc). The results are queried from a custom post type and filtered to match the specialty. The posts have their latitude and longitude in the meta data but I am not sure how to bring this into the query. I want the posts to only show if their latitude/longitude is within proximity from the specified distance. I have the functionality written already to get their distance. The trouble I'm having is with the query and displaying the data properly.
Here are my current query arguments:
```
$args = array(
'post_type' => 'team-members',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'specialties',
'value' => $_GET['specialization'],
'compare' => 'LIKE'
)
)
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
```
This currently will display all the posts with the matching specialization, however, does not include anything involving the distance. So what I initially did was then set a conditional to check if the post was within the distance specified (don't worry about these variables, they are displaying the correct data):
```
if ( $distance < $_GET['within'] ) {
```
The issue is that this condition is not factored into the query, and I am unable to sort by distance. Additionally, I have to set a counter in order to get a correct post "count", plus it just feels hacked together. I feel like there is a foundational error here, and I can't pinpoint it.
I hope this information was sufficient, and if you need anything clarified, please comment. I didn't want to overwhelmingly provide more than was necessary.
|
here is the mysql query you can use to get the result having distance less then your value.
```
SELECT * , pm1.meta_value as latitude, pm2.meta_value as longitude ,
(((acos(sin(([latitude]*pi()/180)) *
sin((pm1.meta_value * pi()/180)) + cos(([latitude]*pi()/180)) *
cos((pm1.meta_value * pi()/180)) * cos((([longitude] - pm2.meta_value)*
pi()/180))))*180/pi())*60*1.1515
) as distance
FROM wp_posts p
JOIN wp_postmeta pm1 ON pm1.post_id = p.ID AND pm1.meta_key = 'latitude'
JOIN wp_postmeta pm2 ON pm2.post_id = p.ID AND pm2.meta_key = 'longitude'
WHERE ID = 98
having distance < $_GET['within']
```
It will return all the post with distance is less then your $\_GET['within'] value.
|
191,592 |
<p>I have an archive that shows all the post on monthly now i want is to group them per year like</p>
<pre><code>2015
Jan
Feb
March
2014
April
May
</code></pre>
<p>I'm using this code.</p>
<pre><code><?php wp_get_archives( array( 'type' => 'monthly' ) ); ?>
</code></pre>
<p>This displays all the archive monthly from the beginning. i tried to add a monthly and yearly but they are on a separate group...</p>
|
[
{
"answer_id": 191602,
"author": "Robert hue",
"author_id": 22461,
"author_profile": "https://wordpress.stackexchange.com/users/22461",
"pm_score": 1,
"selected": false,
"text": "<p>To display monthly archives arranged by year, you can use this code. It checks through each month if WordPress have any post in that month and create archive.</p>\n\n<pre><code><?php\n global $wpdb;\n $limit = 0;\n $year_prev = null;\n $months = $wpdb->get_results( \"SELECT DISTINCT MONTH( post_date ) AS month , YEAR( post_date ) AS year, COUNT( id ) as post_count FROM $wpdb->posts WHERE post_status = 'publish' and post_date <= now( ) and post_type = 'post' GROUP BY month , year ORDER BY post_date DESC\" );\n foreach( $months as $month ) :\n $year_current = $month->year;\n if ( $year_current != $year_prev ) {\n if ( $year_prev != null ) { ?>\n <?php } ?>\n <h3><a href=\"<?php bloginfo('url') ?>/<?php echo $month->year; ?>/\"><?php echo $month->year; ?></a></h3>\n <?php } ?>\n <li><a href=\"<?php bloginfo('url') ?>/<?php echo $month->year; ?>/<?php echo date(\"m\", mktime(0, 0, 0, $month->month, 1, $month->year)) ?>\"><span class=\"archive-month\"><?php echo date_i18n(\"F\", mktime(0, 0, 0, $month->month, 1, $month->year)) ?></span></a></li>\n <?php $year_prev = $year_current;\n if( ++$limit >= 18 ) { break; }\n endforeach;\n?>\n</code></pre>\n"
},
{
"answer_id": 355864,
"author": "Biplab Chakraborty",
"author_id": 161288,
"author_profile": "https://wordpress.stackexchange.com/users/161288",
"pm_score": 0,
"selected": false,
"text": "<pre><code><?php\n global $wpdb;\n $limit = 0;\n $year_prev = null;\n $months = $wpdb->get_results( \"SELECT DISTINCT MONTH( post_date ) AS month , YEAR( post_date ) AS year, COUNT( id ) as post_count FROM $wpdb->posts WHERE post_status = 'publish' and post_date <= now( ) and post_type = 'newses' GROUP BY month , year ORDER BY post_date DESC\" );\n foreach( $months as $month ) :\n $year_current = $month->year;\n if ( $year_current != $year_prev ) {\n if ( $year_prev != null ) { ?>\n <?php } ?>\n <dt><i class=\"fa fa-fw fa-plus-square-o\" aria-hidden=\"true\"></i><a href=\"<?php bloginfo('url') ?>/<?php echo $month->year; ?>/\"><?php echo $month->year; ?></a></dt>\n <?php } ?>\n <dd class=\"post_month\"><a href=\"<?php bloginfo('url') ?>/<?php echo $month->year; ?>/<?php echo date(\"m\", mktime(0, 0, 0, $month->month, 1, $month->year)) ?>\"><span class=\"archive-month\"><?php echo date_i18n(\"F\", mktime(0, 0, 0, $month->month, 1, $month->year)) ?></span></a></dd>\n <?php $year_prev = $year_current;\n if( ++$limit >= 18 ) { break; }\n endforeach;\n?>\n</code></pre>\n"
}
] |
2015/06/16
|
[
"https://wordpress.stackexchange.com/questions/191592",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/62183/"
] |
I have an archive that shows all the post on monthly now i want is to group them per year like
```
2015
Jan
Feb
March
2014
April
May
```
I'm using this code.
```
<?php wp_get_archives( array( 'type' => 'monthly' ) ); ?>
```
This displays all the archive monthly from the beginning. i tried to add a monthly and yearly but they are on a separate group...
|
To display monthly archives arranged by year, you can use this code. It checks through each month if WordPress have any post in that month and create archive.
```
<?php
global $wpdb;
$limit = 0;
$year_prev = null;
$months = $wpdb->get_results( "SELECT DISTINCT MONTH( post_date ) AS month , YEAR( post_date ) AS year, COUNT( id ) as post_count FROM $wpdb->posts WHERE post_status = 'publish' and post_date <= now( ) and post_type = 'post' GROUP BY month , year ORDER BY post_date DESC" );
foreach( $months as $month ) :
$year_current = $month->year;
if ( $year_current != $year_prev ) {
if ( $year_prev != null ) { ?>
<?php } ?>
<h3><a href="<?php bloginfo('url') ?>/<?php echo $month->year; ?>/"><?php echo $month->year; ?></a></h3>
<?php } ?>
<li><a href="<?php bloginfo('url') ?>/<?php echo $month->year; ?>/<?php echo date("m", mktime(0, 0, 0, $month->month, 1, $month->year)) ?>"><span class="archive-month"><?php echo date_i18n("F", mktime(0, 0, 0, $month->month, 1, $month->year)) ?></span></a></li>
<?php $year_prev = $year_current;
if( ++$limit >= 18 ) { break; }
endforeach;
?>
```
|
191,658 |
<p>I would want to allow certain user to edit only one page and it's subpages. How would this be possible? I tried the old Role Scoper, but it seems to have a lot of problems and bugs.</p>
|
[
{
"answer_id": 191661,
"author": "user2319361",
"author_id": 74760,
"author_profile": "https://wordpress.stackexchange.com/users/74760",
"pm_score": -1,
"selected": false,
"text": "<p>I used <code>User Role Editor</code> a couple of times and is pretty good.\nMaybe it could help you too.\nHere is the link <a href=\"https://wordpress.org/plugins/user-role-editor/\" rel=\"nofollow\">User Role Editor</a></p>\n"
},
{
"answer_id": 259975,
"author": "ricotheque",
"author_id": 34238,
"author_profile": "https://wordpress.stackexchange.com/users/34238",
"pm_score": 3,
"selected": false,
"text": "<p>It does take a small amount of code to implement this feature, even if you use a PHP class to avoid global variables. I also didn't want to hide the prohibited pages for the user in the Dashboard. What if they added content that was already on the site?</p>\n\n<pre><code>$user_edit_limit = new NS_User_Edit_Limit(\n 15, // User ID we want to limit\n [2, 17] // Array of parent page IDs user is allowed to edit\n (also accepts sub-page IDs)\n);\n\nclass NS_User_Edit_Limit {\n\n /**\n * Store the ID of the user we want to control, and the\n * posts we will let the user edit.\n */\n private $user_id = 0;\n private $allowed = array();\n\n public function __construct( $user_id, $allowed ) {\n\n // Save the ID of the user we want to limit.\n $this->user_id = $user_id;\n\n // Expand the list of allowed pages to include sub pages\n $all_pages = new WP_Query( array(\n 'post_type' => 'page',\n 'posts_per_page' => -1,\n ) ); \n foreach ( $allowed as $page ) {\n $this->allowed[] = $page;\n $sub_pages = get_page_children( $page, $all_pages );\n foreach ( $sub_pages as $sub_page ) {\n $this->allowed[] = $sub_page->ID;\n }\n }\n\n // For the prohibited user...\n // Remove the edit link from the front-end as needed\n add_filter( 'get_edit_post_link', array( $this, 'remove_edit_link' ), 10, 3 );\n add_action( 'admin_bar_menu', array( $this, 'remove_wp_admin_edit_link' ), 10, 1 );\n // Remove the edit link from wp-admin as needed\n add_action( 'page_row_actions', array( $this, 'remove_page_list_edit_link' ), 10, 2 );\n }\n\n /**\n * Helper functions that check if the current user is the one\n * we want to limit, and check if a specific post is in our\n * list of posts that we allow the user to edit.\n */\n private function is_user_limited() {\n $current_user = wp_get_current_user();\n return ( $current_user->ID == $this->user_id );\n }\n private function is_page_allowed( $post_id ) {\n return in_array( $post_id, $this->allowed );\n }\n\n /**\n * Removes the edit link from the front-end as needed.\n */\n public function remove_edit_link( $link, $post_id, $test ) {\n /**\n * If...\n * - The limited user is logged in\n * - The page the edit link is being created for is not in the allowed list\n * ...return an empty $link. This also causes edit_post_link() to show nothing.\n *\n * Otherwise, return link as normal.\n */\n if ( $this->is_user_limited() && !$this->is_page_allowed( $post_id ) ) {\n return '';\n }\n return $link;\n }\n\n /**\n * Removes the edit link from WP Admin Bar\n */\n public function remove_wp_admin_edit_link( $wp_admin_bar ) {\n /**\n * If:\n * - We're on a single page\n * - The limited user is logged in\n * - The page is not in the allowed list\n * ...Remove the edit link from the WP Admin Bar\n */\n if ( \n is_page() &&\n $this->is_user_limited() &&\n !$this->is_page_allowed( get_post()->ID )\n ) {\n $wp_admin_bar->remove_node( 'edit' );\n }\n }\n\n /**\n * Removes the edit link from WP Admin's edit.php\n */\n public function remove_page_list_edit_link( $actions, $post ) {\n /**\n * If:\n * -The limited user is logged in\n * -The page is not in the allowed list\n * ...Remove the \"Edit\", \"Quick Edit\", and \"Trash\" quick links.\n */\n if ( \n $this->is_user_limited() &&\n !$this->is_page_allowed( $post->ID )\n ) {\n unset( $actions['edit'] );\n unset( $actions['inline hide-if-no-js']);\n unset( $actions['trash'] );\n }\n return $actions;\n }\n}\n</code></pre>\n\n<p>What the code above does is prevent the following from working or appearing as needed:</p>\n\n<ol>\n<li><code>get_edit_post_link</code></li>\n<li><code>Edit Page</code> link on the WP Admin Bar that appears for the Pages</li>\n<li><code>Edit</code>, <code>Quick Edit</code>, and <code>Trash</code> quick links that appear underneath the Pages in <code>/wp-admin/edit.php?post_type=page</code></li>\n</ol>\n\n<p>This worked on my local WordPress 4.7 install. Assuming that the pages on the site won't change often, it might be better to hardcode the IDs of the page and its sub-pages, and remove the <code>WP_Query</code> inside the <code>__construct</code> method. This will save a lot on database calls.</p>\n"
},
{
"answer_id": 259976,
"author": "Ben Casey",
"author_id": 114997,
"author_profile": "https://wordpress.stackexchange.com/users/114997",
"pm_score": 3,
"selected": false,
"text": "<p>If you wanted to keep away from plugins, you could a variation of the code below in a functions.php file or a custom plugin. </p>\n\n<p>There are 2 seperate parts to this code, You would only need to use 1 of them, but which one depends on the complexity of the requirements.</p>\n\n<p>Part 1 is specifying a single user and restricting them to a specific post. </p>\n\n<p>Part 2 allows you to create a map of users and post ID's and allows multiple posts</p>\n\n<p>The code below is for a page only, but if you wanted to change that to a post, or a custom post type, you would need to change the string in <code>$screen->id == 'page'</code> to something else. </p>\n\n<p>You can find a reference to the screen ID's around wp-admin <a href=\"https://codex.wordpress.org/Plugin_API/Admin_Screen_Reference\" rel=\"noreferrer\">here</a></p>\n\n<pre><code>function my_pre_get_posts( $query ){\n\n $screen = get_current_screen();\n $current_user = wp_get_current_user();\n\n /**\n * Specify a single user and restrict to a single page\n */\n $restricted_user_id = 10; //User ID of the restricted user\n $allowed_post_id = 1234; //Post ID of the allowed post\n\n $current_post_id = isset( $_GET['post'] ) ? (int)$_GET['post'] : false ;\n\n //Only affecting a specific user\n if( $current_user->ID !== $restricted_user_id ){\n return;\n }\n\n //Only Affecting EDIT page.\n if( ! $current_post_id ){\n return;\n }\n\n if( $screen->id == 'page' && $current_post_id !== $allowed_post_id ){\n wp_redirect( admin_url( ) );\n exit;\n }\n\n /**\n * Specify a map of user_id => $allowed_posts\n */\n $restrictions_map = [\n 10 => [ 123 ], //Allow user ID to edit Page ID 123\n 11 => [ 152, 186 ] //Allow user ID to edit Page ID 123 and 186\n ];\n\n if( array_key_exists( $current_user->ID, $restrictions_map ) ){\n\n $allowed_posts = $restrictions_map[$current_user->ID];\n\n if( $screen->id == 'page' && ! in_array( $current_user->ID, $allowed_posts ) ){\n wp_redirect( admin_url( ) );\n exit;\n }\n\n }\n\n}\nadd_action( 'pre_get_posts', 'my_pre_get_posts' );\n</code></pre>\n"
},
{
"answer_id": 259982,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 5,
"selected": true,
"text": "<p>The first thing to do to implements such task is to be able to recognise which page an user can edit.</p>\n\n<p>There are different ways to do it. It could be a user meta, some configuration value... For the sake of this answer, I will assume that a function lile this exists:</p>\n\n<pre><code>function wpse_user_can_edit( $user_id, $page_id ) {\n\n $page = get_post( $page_id );\n\n // let's find the topmost page in the hierarchy\n while( $page && (int) $page->parent ) {\n $page = get_post( $page->parent );\n }\n\n if ( ! $page ) {\n return false;\n }\n\n // now $page is the top page in the hierarchy\n // how to know if an user can edit it, it's up to you...\n\n}\n</code></pre>\n\n<p>Now that we have a way to determine if an user can edit a page we just need to tell WordPress to use this function to check useer capability to edit a page.</p>\n\n<p>That can be done via <a href=\"https://developer.wordpress.org/reference/hooks/map_meta_cap/\" rel=\"nofollow noreferrer\"><code>'map_meta_cap'</code></a> filter.</p>\n\n<p>Something like:</p>\n\n<pre><code>add_filter( 'map_meta_cap', function ( $caps, $cap, $user_id, $args ) {\n\n $to_filter = [ 'edit_post', 'delete_post', 'edit_page', 'delete_page' ];\n\n // If the capability being filtered isn't of our interest, just return current value\n if ( ! in_array( $cap, $to_filter, true ) ) {\n return $caps;\n }\n\n // First item in $args array should be page ID\n if ( ! $args || empty( $args[0] ) || ! wpse_user_can_edit( $user_id, $args[0] ) ) {\n // User is not allowed, let's tell that to WP\n return [ 'do_not_allow' ];\n }\n // Otherwise just return current value\n return $caps;\n\n}, 10, 4 );\n</code></pre>\n\n<p>At this point, we need only a way to <em>connect</em> an user to one or more pages.</p>\n\n<p>There might be different solutions depending on use case.</p>\n\n<p>A flexible solution could be to add a dropdown of \"root\" pages (see <a href=\"https://developer.wordpress.org/reference/functions/wp_dropdown_pages/\" rel=\"nofollow noreferrer\"><code>wp_dropdown_pages</code></a>) to the edit user admin screen, and save selected page(s) as user meta.</p>\n\n<p>We could leverage <a href=\"https://developer.wordpress.org/reference/hooks/edit_user_profile/\" rel=\"nofollow noreferrer\"><code>'edit_user_profile'</code></a> to add the pages dropdown field and <a href=\"https://developer.wordpress.org/reference/hooks/edit_user_profile_update/\" rel=\"nofollow noreferrer\"><code>'edit_user_profile_update'</code></a> to store the selected value as user meta.</p>\n\n<p>I am sure that in this website there's enough guidance on how to that in detail.</p>\n\n<p>When page(s) are stored as user meta, the <code>wpse_user_can_edit()</code> function from above can be finished by checking if the page id is part of the user meta value.</p>\n\n<p>Removing capability to edit the page, WordPress will do the rest: will remove any edit link from backend and frontend, will prevent direct access... and so on.</p>\n"
}
] |
2015/06/16
|
[
"https://wordpress.stackexchange.com/questions/191658",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74762/"
] |
I would want to allow certain user to edit only one page and it's subpages. How would this be possible? I tried the old Role Scoper, but it seems to have a lot of problems and bugs.
|
The first thing to do to implements such task is to be able to recognise which page an user can edit.
There are different ways to do it. It could be a user meta, some configuration value... For the sake of this answer, I will assume that a function lile this exists:
```
function wpse_user_can_edit( $user_id, $page_id ) {
$page = get_post( $page_id );
// let's find the topmost page in the hierarchy
while( $page && (int) $page->parent ) {
$page = get_post( $page->parent );
}
if ( ! $page ) {
return false;
}
// now $page is the top page in the hierarchy
// how to know if an user can edit it, it's up to you...
}
```
Now that we have a way to determine if an user can edit a page we just need to tell WordPress to use this function to check useer capability to edit a page.
That can be done via [`'map_meta_cap'`](https://developer.wordpress.org/reference/hooks/map_meta_cap/) filter.
Something like:
```
add_filter( 'map_meta_cap', function ( $caps, $cap, $user_id, $args ) {
$to_filter = [ 'edit_post', 'delete_post', 'edit_page', 'delete_page' ];
// If the capability being filtered isn't of our interest, just return current value
if ( ! in_array( $cap, $to_filter, true ) ) {
return $caps;
}
// First item in $args array should be page ID
if ( ! $args || empty( $args[0] ) || ! wpse_user_can_edit( $user_id, $args[0] ) ) {
// User is not allowed, let's tell that to WP
return [ 'do_not_allow' ];
}
// Otherwise just return current value
return $caps;
}, 10, 4 );
```
At this point, we need only a way to *connect* an user to one or more pages.
There might be different solutions depending on use case.
A flexible solution could be to add a dropdown of "root" pages (see [`wp_dropdown_pages`](https://developer.wordpress.org/reference/functions/wp_dropdown_pages/)) to the edit user admin screen, and save selected page(s) as user meta.
We could leverage [`'edit_user_profile'`](https://developer.wordpress.org/reference/hooks/edit_user_profile/) to add the pages dropdown field and [`'edit_user_profile_update'`](https://developer.wordpress.org/reference/hooks/edit_user_profile_update/) to store the selected value as user meta.
I am sure that in this website there's enough guidance on how to that in detail.
When page(s) are stored as user meta, the `wpse_user_can_edit()` function from above can be finished by checking if the page id is part of the user meta value.
Removing capability to edit the page, WordPress will do the rest: will remove any edit link from backend and frontend, will prevent direct access... and so on.
|
191,674 |
<p>I have a property website with a custom search form for minimum and maximum square feet.</p>
<p>A registered user executes a search with a min(i.e. 150 sqft) and max(i.e. 300 sqft) select option value. </p>
<p>I managed already to store inside cookies the min and max values. </p>
<p>Then the user is able to click on a "save this search" button. </p>
<p>I would like to save those values inside the database and show them on each user's profile page (that I already created). </p>
<p>When the user goes to its profile page I'd like to have a list of all the saved searches. </p>
<p>I hope this makes sense.</p>
<p>Ideally the custom user page would look like this:</p>
<p>Saved Search 1: 150sq ft - 300 sq ft</p>
<p>Saved Search 2: 500sq ft - 800 sq ft</p>
<p>...</p>
<p>Is this possible? How would I do this?</p>
<p>I'm quite new at customising WordPress templates, I would really appreciate any help.</p>
|
[
{
"answer_id": 191661,
"author": "user2319361",
"author_id": 74760,
"author_profile": "https://wordpress.stackexchange.com/users/74760",
"pm_score": -1,
"selected": false,
"text": "<p>I used <code>User Role Editor</code> a couple of times and is pretty good.\nMaybe it could help you too.\nHere is the link <a href=\"https://wordpress.org/plugins/user-role-editor/\" rel=\"nofollow\">User Role Editor</a></p>\n"
},
{
"answer_id": 259975,
"author": "ricotheque",
"author_id": 34238,
"author_profile": "https://wordpress.stackexchange.com/users/34238",
"pm_score": 3,
"selected": false,
"text": "<p>It does take a small amount of code to implement this feature, even if you use a PHP class to avoid global variables. I also didn't want to hide the prohibited pages for the user in the Dashboard. What if they added content that was already on the site?</p>\n\n<pre><code>$user_edit_limit = new NS_User_Edit_Limit(\n 15, // User ID we want to limit\n [2, 17] // Array of parent page IDs user is allowed to edit\n (also accepts sub-page IDs)\n);\n\nclass NS_User_Edit_Limit {\n\n /**\n * Store the ID of the user we want to control, and the\n * posts we will let the user edit.\n */\n private $user_id = 0;\n private $allowed = array();\n\n public function __construct( $user_id, $allowed ) {\n\n // Save the ID of the user we want to limit.\n $this->user_id = $user_id;\n\n // Expand the list of allowed pages to include sub pages\n $all_pages = new WP_Query( array(\n 'post_type' => 'page',\n 'posts_per_page' => -1,\n ) ); \n foreach ( $allowed as $page ) {\n $this->allowed[] = $page;\n $sub_pages = get_page_children( $page, $all_pages );\n foreach ( $sub_pages as $sub_page ) {\n $this->allowed[] = $sub_page->ID;\n }\n }\n\n // For the prohibited user...\n // Remove the edit link from the front-end as needed\n add_filter( 'get_edit_post_link', array( $this, 'remove_edit_link' ), 10, 3 );\n add_action( 'admin_bar_menu', array( $this, 'remove_wp_admin_edit_link' ), 10, 1 );\n // Remove the edit link from wp-admin as needed\n add_action( 'page_row_actions', array( $this, 'remove_page_list_edit_link' ), 10, 2 );\n }\n\n /**\n * Helper functions that check if the current user is the one\n * we want to limit, and check if a specific post is in our\n * list of posts that we allow the user to edit.\n */\n private function is_user_limited() {\n $current_user = wp_get_current_user();\n return ( $current_user->ID == $this->user_id );\n }\n private function is_page_allowed( $post_id ) {\n return in_array( $post_id, $this->allowed );\n }\n\n /**\n * Removes the edit link from the front-end as needed.\n */\n public function remove_edit_link( $link, $post_id, $test ) {\n /**\n * If...\n * - The limited user is logged in\n * - The page the edit link is being created for is not in the allowed list\n * ...return an empty $link. This also causes edit_post_link() to show nothing.\n *\n * Otherwise, return link as normal.\n */\n if ( $this->is_user_limited() && !$this->is_page_allowed( $post_id ) ) {\n return '';\n }\n return $link;\n }\n\n /**\n * Removes the edit link from WP Admin Bar\n */\n public function remove_wp_admin_edit_link( $wp_admin_bar ) {\n /**\n * If:\n * - We're on a single page\n * - The limited user is logged in\n * - The page is not in the allowed list\n * ...Remove the edit link from the WP Admin Bar\n */\n if ( \n is_page() &&\n $this->is_user_limited() &&\n !$this->is_page_allowed( get_post()->ID )\n ) {\n $wp_admin_bar->remove_node( 'edit' );\n }\n }\n\n /**\n * Removes the edit link from WP Admin's edit.php\n */\n public function remove_page_list_edit_link( $actions, $post ) {\n /**\n * If:\n * -The limited user is logged in\n * -The page is not in the allowed list\n * ...Remove the \"Edit\", \"Quick Edit\", and \"Trash\" quick links.\n */\n if ( \n $this->is_user_limited() &&\n !$this->is_page_allowed( $post->ID )\n ) {\n unset( $actions['edit'] );\n unset( $actions['inline hide-if-no-js']);\n unset( $actions['trash'] );\n }\n return $actions;\n }\n}\n</code></pre>\n\n<p>What the code above does is prevent the following from working or appearing as needed:</p>\n\n<ol>\n<li><code>get_edit_post_link</code></li>\n<li><code>Edit Page</code> link on the WP Admin Bar that appears for the Pages</li>\n<li><code>Edit</code>, <code>Quick Edit</code>, and <code>Trash</code> quick links that appear underneath the Pages in <code>/wp-admin/edit.php?post_type=page</code></li>\n</ol>\n\n<p>This worked on my local WordPress 4.7 install. Assuming that the pages on the site won't change often, it might be better to hardcode the IDs of the page and its sub-pages, and remove the <code>WP_Query</code> inside the <code>__construct</code> method. This will save a lot on database calls.</p>\n"
},
{
"answer_id": 259976,
"author": "Ben Casey",
"author_id": 114997,
"author_profile": "https://wordpress.stackexchange.com/users/114997",
"pm_score": 3,
"selected": false,
"text": "<p>If you wanted to keep away from plugins, you could a variation of the code below in a functions.php file or a custom plugin. </p>\n\n<p>There are 2 seperate parts to this code, You would only need to use 1 of them, but which one depends on the complexity of the requirements.</p>\n\n<p>Part 1 is specifying a single user and restricting them to a specific post. </p>\n\n<p>Part 2 allows you to create a map of users and post ID's and allows multiple posts</p>\n\n<p>The code below is for a page only, but if you wanted to change that to a post, or a custom post type, you would need to change the string in <code>$screen->id == 'page'</code> to something else. </p>\n\n<p>You can find a reference to the screen ID's around wp-admin <a href=\"https://codex.wordpress.org/Plugin_API/Admin_Screen_Reference\" rel=\"noreferrer\">here</a></p>\n\n<pre><code>function my_pre_get_posts( $query ){\n\n $screen = get_current_screen();\n $current_user = wp_get_current_user();\n\n /**\n * Specify a single user and restrict to a single page\n */\n $restricted_user_id = 10; //User ID of the restricted user\n $allowed_post_id = 1234; //Post ID of the allowed post\n\n $current_post_id = isset( $_GET['post'] ) ? (int)$_GET['post'] : false ;\n\n //Only affecting a specific user\n if( $current_user->ID !== $restricted_user_id ){\n return;\n }\n\n //Only Affecting EDIT page.\n if( ! $current_post_id ){\n return;\n }\n\n if( $screen->id == 'page' && $current_post_id !== $allowed_post_id ){\n wp_redirect( admin_url( ) );\n exit;\n }\n\n /**\n * Specify a map of user_id => $allowed_posts\n */\n $restrictions_map = [\n 10 => [ 123 ], //Allow user ID to edit Page ID 123\n 11 => [ 152, 186 ] //Allow user ID to edit Page ID 123 and 186\n ];\n\n if( array_key_exists( $current_user->ID, $restrictions_map ) ){\n\n $allowed_posts = $restrictions_map[$current_user->ID];\n\n if( $screen->id == 'page' && ! in_array( $current_user->ID, $allowed_posts ) ){\n wp_redirect( admin_url( ) );\n exit;\n }\n\n }\n\n}\nadd_action( 'pre_get_posts', 'my_pre_get_posts' );\n</code></pre>\n"
},
{
"answer_id": 259982,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 5,
"selected": true,
"text": "<p>The first thing to do to implements such task is to be able to recognise which page an user can edit.</p>\n\n<p>There are different ways to do it. It could be a user meta, some configuration value... For the sake of this answer, I will assume that a function lile this exists:</p>\n\n<pre><code>function wpse_user_can_edit( $user_id, $page_id ) {\n\n $page = get_post( $page_id );\n\n // let's find the topmost page in the hierarchy\n while( $page && (int) $page->parent ) {\n $page = get_post( $page->parent );\n }\n\n if ( ! $page ) {\n return false;\n }\n\n // now $page is the top page in the hierarchy\n // how to know if an user can edit it, it's up to you...\n\n}\n</code></pre>\n\n<p>Now that we have a way to determine if an user can edit a page we just need to tell WordPress to use this function to check useer capability to edit a page.</p>\n\n<p>That can be done via <a href=\"https://developer.wordpress.org/reference/hooks/map_meta_cap/\" rel=\"nofollow noreferrer\"><code>'map_meta_cap'</code></a> filter.</p>\n\n<p>Something like:</p>\n\n<pre><code>add_filter( 'map_meta_cap', function ( $caps, $cap, $user_id, $args ) {\n\n $to_filter = [ 'edit_post', 'delete_post', 'edit_page', 'delete_page' ];\n\n // If the capability being filtered isn't of our interest, just return current value\n if ( ! in_array( $cap, $to_filter, true ) ) {\n return $caps;\n }\n\n // First item in $args array should be page ID\n if ( ! $args || empty( $args[0] ) || ! wpse_user_can_edit( $user_id, $args[0] ) ) {\n // User is not allowed, let's tell that to WP\n return [ 'do_not_allow' ];\n }\n // Otherwise just return current value\n return $caps;\n\n}, 10, 4 );\n</code></pre>\n\n<p>At this point, we need only a way to <em>connect</em> an user to one or more pages.</p>\n\n<p>There might be different solutions depending on use case.</p>\n\n<p>A flexible solution could be to add a dropdown of \"root\" pages (see <a href=\"https://developer.wordpress.org/reference/functions/wp_dropdown_pages/\" rel=\"nofollow noreferrer\"><code>wp_dropdown_pages</code></a>) to the edit user admin screen, and save selected page(s) as user meta.</p>\n\n<p>We could leverage <a href=\"https://developer.wordpress.org/reference/hooks/edit_user_profile/\" rel=\"nofollow noreferrer\"><code>'edit_user_profile'</code></a> to add the pages dropdown field and <a href=\"https://developer.wordpress.org/reference/hooks/edit_user_profile_update/\" rel=\"nofollow noreferrer\"><code>'edit_user_profile_update'</code></a> to store the selected value as user meta.</p>\n\n<p>I am sure that in this website there's enough guidance on how to that in detail.</p>\n\n<p>When page(s) are stored as user meta, the <code>wpse_user_can_edit()</code> function from above can be finished by checking if the page id is part of the user meta value.</p>\n\n<p>Removing capability to edit the page, WordPress will do the rest: will remove any edit link from backend and frontend, will prevent direct access... and so on.</p>\n"
}
] |
2015/06/16
|
[
"https://wordpress.stackexchange.com/questions/191674",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74398/"
] |
I have a property website with a custom search form for minimum and maximum square feet.
A registered user executes a search with a min(i.e. 150 sqft) and max(i.e. 300 sqft) select option value.
I managed already to store inside cookies the min and max values.
Then the user is able to click on a "save this search" button.
I would like to save those values inside the database and show them on each user's profile page (that I already created).
When the user goes to its profile page I'd like to have a list of all the saved searches.
I hope this makes sense.
Ideally the custom user page would look like this:
Saved Search 1: 150sq ft - 300 sq ft
Saved Search 2: 500sq ft - 800 sq ft
...
Is this possible? How would I do this?
I'm quite new at customising WordPress templates, I would really appreciate any help.
|
The first thing to do to implements such task is to be able to recognise which page an user can edit.
There are different ways to do it. It could be a user meta, some configuration value... For the sake of this answer, I will assume that a function lile this exists:
```
function wpse_user_can_edit( $user_id, $page_id ) {
$page = get_post( $page_id );
// let's find the topmost page in the hierarchy
while( $page && (int) $page->parent ) {
$page = get_post( $page->parent );
}
if ( ! $page ) {
return false;
}
// now $page is the top page in the hierarchy
// how to know if an user can edit it, it's up to you...
}
```
Now that we have a way to determine if an user can edit a page we just need to tell WordPress to use this function to check useer capability to edit a page.
That can be done via [`'map_meta_cap'`](https://developer.wordpress.org/reference/hooks/map_meta_cap/) filter.
Something like:
```
add_filter( 'map_meta_cap', function ( $caps, $cap, $user_id, $args ) {
$to_filter = [ 'edit_post', 'delete_post', 'edit_page', 'delete_page' ];
// If the capability being filtered isn't of our interest, just return current value
if ( ! in_array( $cap, $to_filter, true ) ) {
return $caps;
}
// First item in $args array should be page ID
if ( ! $args || empty( $args[0] ) || ! wpse_user_can_edit( $user_id, $args[0] ) ) {
// User is not allowed, let's tell that to WP
return [ 'do_not_allow' ];
}
// Otherwise just return current value
return $caps;
}, 10, 4 );
```
At this point, we need only a way to *connect* an user to one or more pages.
There might be different solutions depending on use case.
A flexible solution could be to add a dropdown of "root" pages (see [`wp_dropdown_pages`](https://developer.wordpress.org/reference/functions/wp_dropdown_pages/)) to the edit user admin screen, and save selected page(s) as user meta.
We could leverage [`'edit_user_profile'`](https://developer.wordpress.org/reference/hooks/edit_user_profile/) to add the pages dropdown field and [`'edit_user_profile_update'`](https://developer.wordpress.org/reference/hooks/edit_user_profile_update/) to store the selected value as user meta.
I am sure that in this website there's enough guidance on how to that in detail.
When page(s) are stored as user meta, the `wpse_user_can_edit()` function from above can be finished by checking if the page id is part of the user meta value.
Removing capability to edit the page, WordPress will do the rest: will remove any edit link from backend and frontend, will prevent direct access... and so on.
|
191,694 |
<p>From the <code>get_posts</code> docs I see it takes categories as a parameter.</p>
<p>However, is this an <code>AND</code> or an <code>OR</code>?</p>
<p>i.e. if you specify 2 categories do posts have to be in both to be returned?</p>
<p>If not, how do you specify an <code>AND</code> relation? I only want posts that match ALL categories.</p>
|
[
{
"answer_id": 191661,
"author": "user2319361",
"author_id": 74760,
"author_profile": "https://wordpress.stackexchange.com/users/74760",
"pm_score": -1,
"selected": false,
"text": "<p>I used <code>User Role Editor</code> a couple of times and is pretty good.\nMaybe it could help you too.\nHere is the link <a href=\"https://wordpress.org/plugins/user-role-editor/\" rel=\"nofollow\">User Role Editor</a></p>\n"
},
{
"answer_id": 259975,
"author": "ricotheque",
"author_id": 34238,
"author_profile": "https://wordpress.stackexchange.com/users/34238",
"pm_score": 3,
"selected": false,
"text": "<p>It does take a small amount of code to implement this feature, even if you use a PHP class to avoid global variables. I also didn't want to hide the prohibited pages for the user in the Dashboard. What if they added content that was already on the site?</p>\n\n<pre><code>$user_edit_limit = new NS_User_Edit_Limit(\n 15, // User ID we want to limit\n [2, 17] // Array of parent page IDs user is allowed to edit\n (also accepts sub-page IDs)\n);\n\nclass NS_User_Edit_Limit {\n\n /**\n * Store the ID of the user we want to control, and the\n * posts we will let the user edit.\n */\n private $user_id = 0;\n private $allowed = array();\n\n public function __construct( $user_id, $allowed ) {\n\n // Save the ID of the user we want to limit.\n $this->user_id = $user_id;\n\n // Expand the list of allowed pages to include sub pages\n $all_pages = new WP_Query( array(\n 'post_type' => 'page',\n 'posts_per_page' => -1,\n ) ); \n foreach ( $allowed as $page ) {\n $this->allowed[] = $page;\n $sub_pages = get_page_children( $page, $all_pages );\n foreach ( $sub_pages as $sub_page ) {\n $this->allowed[] = $sub_page->ID;\n }\n }\n\n // For the prohibited user...\n // Remove the edit link from the front-end as needed\n add_filter( 'get_edit_post_link', array( $this, 'remove_edit_link' ), 10, 3 );\n add_action( 'admin_bar_menu', array( $this, 'remove_wp_admin_edit_link' ), 10, 1 );\n // Remove the edit link from wp-admin as needed\n add_action( 'page_row_actions', array( $this, 'remove_page_list_edit_link' ), 10, 2 );\n }\n\n /**\n * Helper functions that check if the current user is the one\n * we want to limit, and check if a specific post is in our\n * list of posts that we allow the user to edit.\n */\n private function is_user_limited() {\n $current_user = wp_get_current_user();\n return ( $current_user->ID == $this->user_id );\n }\n private function is_page_allowed( $post_id ) {\n return in_array( $post_id, $this->allowed );\n }\n\n /**\n * Removes the edit link from the front-end as needed.\n */\n public function remove_edit_link( $link, $post_id, $test ) {\n /**\n * If...\n * - The limited user is logged in\n * - The page the edit link is being created for is not in the allowed list\n * ...return an empty $link. This also causes edit_post_link() to show nothing.\n *\n * Otherwise, return link as normal.\n */\n if ( $this->is_user_limited() && !$this->is_page_allowed( $post_id ) ) {\n return '';\n }\n return $link;\n }\n\n /**\n * Removes the edit link from WP Admin Bar\n */\n public function remove_wp_admin_edit_link( $wp_admin_bar ) {\n /**\n * If:\n * - We're on a single page\n * - The limited user is logged in\n * - The page is not in the allowed list\n * ...Remove the edit link from the WP Admin Bar\n */\n if ( \n is_page() &&\n $this->is_user_limited() &&\n !$this->is_page_allowed( get_post()->ID )\n ) {\n $wp_admin_bar->remove_node( 'edit' );\n }\n }\n\n /**\n * Removes the edit link from WP Admin's edit.php\n */\n public function remove_page_list_edit_link( $actions, $post ) {\n /**\n * If:\n * -The limited user is logged in\n * -The page is not in the allowed list\n * ...Remove the \"Edit\", \"Quick Edit\", and \"Trash\" quick links.\n */\n if ( \n $this->is_user_limited() &&\n !$this->is_page_allowed( $post->ID )\n ) {\n unset( $actions['edit'] );\n unset( $actions['inline hide-if-no-js']);\n unset( $actions['trash'] );\n }\n return $actions;\n }\n}\n</code></pre>\n\n<p>What the code above does is prevent the following from working or appearing as needed:</p>\n\n<ol>\n<li><code>get_edit_post_link</code></li>\n<li><code>Edit Page</code> link on the WP Admin Bar that appears for the Pages</li>\n<li><code>Edit</code>, <code>Quick Edit</code>, and <code>Trash</code> quick links that appear underneath the Pages in <code>/wp-admin/edit.php?post_type=page</code></li>\n</ol>\n\n<p>This worked on my local WordPress 4.7 install. Assuming that the pages on the site won't change often, it might be better to hardcode the IDs of the page and its sub-pages, and remove the <code>WP_Query</code> inside the <code>__construct</code> method. This will save a lot on database calls.</p>\n"
},
{
"answer_id": 259976,
"author": "Ben Casey",
"author_id": 114997,
"author_profile": "https://wordpress.stackexchange.com/users/114997",
"pm_score": 3,
"selected": false,
"text": "<p>If you wanted to keep away from plugins, you could a variation of the code below in a functions.php file or a custom plugin. </p>\n\n<p>There are 2 seperate parts to this code, You would only need to use 1 of them, but which one depends on the complexity of the requirements.</p>\n\n<p>Part 1 is specifying a single user and restricting them to a specific post. </p>\n\n<p>Part 2 allows you to create a map of users and post ID's and allows multiple posts</p>\n\n<p>The code below is for a page only, but if you wanted to change that to a post, or a custom post type, you would need to change the string in <code>$screen->id == 'page'</code> to something else. </p>\n\n<p>You can find a reference to the screen ID's around wp-admin <a href=\"https://codex.wordpress.org/Plugin_API/Admin_Screen_Reference\" rel=\"noreferrer\">here</a></p>\n\n<pre><code>function my_pre_get_posts( $query ){\n\n $screen = get_current_screen();\n $current_user = wp_get_current_user();\n\n /**\n * Specify a single user and restrict to a single page\n */\n $restricted_user_id = 10; //User ID of the restricted user\n $allowed_post_id = 1234; //Post ID of the allowed post\n\n $current_post_id = isset( $_GET['post'] ) ? (int)$_GET['post'] : false ;\n\n //Only affecting a specific user\n if( $current_user->ID !== $restricted_user_id ){\n return;\n }\n\n //Only Affecting EDIT page.\n if( ! $current_post_id ){\n return;\n }\n\n if( $screen->id == 'page' && $current_post_id !== $allowed_post_id ){\n wp_redirect( admin_url( ) );\n exit;\n }\n\n /**\n * Specify a map of user_id => $allowed_posts\n */\n $restrictions_map = [\n 10 => [ 123 ], //Allow user ID to edit Page ID 123\n 11 => [ 152, 186 ] //Allow user ID to edit Page ID 123 and 186\n ];\n\n if( array_key_exists( $current_user->ID, $restrictions_map ) ){\n\n $allowed_posts = $restrictions_map[$current_user->ID];\n\n if( $screen->id == 'page' && ! in_array( $current_user->ID, $allowed_posts ) ){\n wp_redirect( admin_url( ) );\n exit;\n }\n\n }\n\n}\nadd_action( 'pre_get_posts', 'my_pre_get_posts' );\n</code></pre>\n"
},
{
"answer_id": 259982,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 5,
"selected": true,
"text": "<p>The first thing to do to implements such task is to be able to recognise which page an user can edit.</p>\n\n<p>There are different ways to do it. It could be a user meta, some configuration value... For the sake of this answer, I will assume that a function lile this exists:</p>\n\n<pre><code>function wpse_user_can_edit( $user_id, $page_id ) {\n\n $page = get_post( $page_id );\n\n // let's find the topmost page in the hierarchy\n while( $page && (int) $page->parent ) {\n $page = get_post( $page->parent );\n }\n\n if ( ! $page ) {\n return false;\n }\n\n // now $page is the top page in the hierarchy\n // how to know if an user can edit it, it's up to you...\n\n}\n</code></pre>\n\n<p>Now that we have a way to determine if an user can edit a page we just need to tell WordPress to use this function to check useer capability to edit a page.</p>\n\n<p>That can be done via <a href=\"https://developer.wordpress.org/reference/hooks/map_meta_cap/\" rel=\"nofollow noreferrer\"><code>'map_meta_cap'</code></a> filter.</p>\n\n<p>Something like:</p>\n\n<pre><code>add_filter( 'map_meta_cap', function ( $caps, $cap, $user_id, $args ) {\n\n $to_filter = [ 'edit_post', 'delete_post', 'edit_page', 'delete_page' ];\n\n // If the capability being filtered isn't of our interest, just return current value\n if ( ! in_array( $cap, $to_filter, true ) ) {\n return $caps;\n }\n\n // First item in $args array should be page ID\n if ( ! $args || empty( $args[0] ) || ! wpse_user_can_edit( $user_id, $args[0] ) ) {\n // User is not allowed, let's tell that to WP\n return [ 'do_not_allow' ];\n }\n // Otherwise just return current value\n return $caps;\n\n}, 10, 4 );\n</code></pre>\n\n<p>At this point, we need only a way to <em>connect</em> an user to one or more pages.</p>\n\n<p>There might be different solutions depending on use case.</p>\n\n<p>A flexible solution could be to add a dropdown of \"root\" pages (see <a href=\"https://developer.wordpress.org/reference/functions/wp_dropdown_pages/\" rel=\"nofollow noreferrer\"><code>wp_dropdown_pages</code></a>) to the edit user admin screen, and save selected page(s) as user meta.</p>\n\n<p>We could leverage <a href=\"https://developer.wordpress.org/reference/hooks/edit_user_profile/\" rel=\"nofollow noreferrer\"><code>'edit_user_profile'</code></a> to add the pages dropdown field and <a href=\"https://developer.wordpress.org/reference/hooks/edit_user_profile_update/\" rel=\"nofollow noreferrer\"><code>'edit_user_profile_update'</code></a> to store the selected value as user meta.</p>\n\n<p>I am sure that in this website there's enough guidance on how to that in detail.</p>\n\n<p>When page(s) are stored as user meta, the <code>wpse_user_can_edit()</code> function from above can be finished by checking if the page id is part of the user meta value.</p>\n\n<p>Removing capability to edit the page, WordPress will do the rest: will remove any edit link from backend and frontend, will prevent direct access... and so on.</p>\n"
}
] |
2015/06/16
|
[
"https://wordpress.stackexchange.com/questions/191694",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48904/"
] |
From the `get_posts` docs I see it takes categories as a parameter.
However, is this an `AND` or an `OR`?
i.e. if you specify 2 categories do posts have to be in both to be returned?
If not, how do you specify an `AND` relation? I only want posts that match ALL categories.
|
The first thing to do to implements such task is to be able to recognise which page an user can edit.
There are different ways to do it. It could be a user meta, some configuration value... For the sake of this answer, I will assume that a function lile this exists:
```
function wpse_user_can_edit( $user_id, $page_id ) {
$page = get_post( $page_id );
// let's find the topmost page in the hierarchy
while( $page && (int) $page->parent ) {
$page = get_post( $page->parent );
}
if ( ! $page ) {
return false;
}
// now $page is the top page in the hierarchy
// how to know if an user can edit it, it's up to you...
}
```
Now that we have a way to determine if an user can edit a page we just need to tell WordPress to use this function to check useer capability to edit a page.
That can be done via [`'map_meta_cap'`](https://developer.wordpress.org/reference/hooks/map_meta_cap/) filter.
Something like:
```
add_filter( 'map_meta_cap', function ( $caps, $cap, $user_id, $args ) {
$to_filter = [ 'edit_post', 'delete_post', 'edit_page', 'delete_page' ];
// If the capability being filtered isn't of our interest, just return current value
if ( ! in_array( $cap, $to_filter, true ) ) {
return $caps;
}
// First item in $args array should be page ID
if ( ! $args || empty( $args[0] ) || ! wpse_user_can_edit( $user_id, $args[0] ) ) {
// User is not allowed, let's tell that to WP
return [ 'do_not_allow' ];
}
// Otherwise just return current value
return $caps;
}, 10, 4 );
```
At this point, we need only a way to *connect* an user to one or more pages.
There might be different solutions depending on use case.
A flexible solution could be to add a dropdown of "root" pages (see [`wp_dropdown_pages`](https://developer.wordpress.org/reference/functions/wp_dropdown_pages/)) to the edit user admin screen, and save selected page(s) as user meta.
We could leverage [`'edit_user_profile'`](https://developer.wordpress.org/reference/hooks/edit_user_profile/) to add the pages dropdown field and [`'edit_user_profile_update'`](https://developer.wordpress.org/reference/hooks/edit_user_profile_update/) to store the selected value as user meta.
I am sure that in this website there's enough guidance on how to that in detail.
When page(s) are stored as user meta, the `wpse_user_can_edit()` function from above can be finished by checking if the page id is part of the user meta value.
Removing capability to edit the page, WordPress will do the rest: will remove any edit link from backend and frontend, will prevent direct access... and so on.
|
191,704 |
<p>I have a form:</p>
<pre><code><form name="customer_details" method="POST" onsubmit="return form_validation()"
action="../customer-details.php">
</code></pre>
<p>I placed the PHP file in my theme folder, but WordPress gives me an error:</p>
<blockquote>
<p>404 — Fancy meeting you here!</p>
</blockquote>
|
[
{
"answer_id": 191661,
"author": "user2319361",
"author_id": 74760,
"author_profile": "https://wordpress.stackexchange.com/users/74760",
"pm_score": -1,
"selected": false,
"text": "<p>I used <code>User Role Editor</code> a couple of times and is pretty good.\nMaybe it could help you too.\nHere is the link <a href=\"https://wordpress.org/plugins/user-role-editor/\" rel=\"nofollow\">User Role Editor</a></p>\n"
},
{
"answer_id": 259975,
"author": "ricotheque",
"author_id": 34238,
"author_profile": "https://wordpress.stackexchange.com/users/34238",
"pm_score": 3,
"selected": false,
"text": "<p>It does take a small amount of code to implement this feature, even if you use a PHP class to avoid global variables. I also didn't want to hide the prohibited pages for the user in the Dashboard. What if they added content that was already on the site?</p>\n\n<pre><code>$user_edit_limit = new NS_User_Edit_Limit(\n 15, // User ID we want to limit\n [2, 17] // Array of parent page IDs user is allowed to edit\n (also accepts sub-page IDs)\n);\n\nclass NS_User_Edit_Limit {\n\n /**\n * Store the ID of the user we want to control, and the\n * posts we will let the user edit.\n */\n private $user_id = 0;\n private $allowed = array();\n\n public function __construct( $user_id, $allowed ) {\n\n // Save the ID of the user we want to limit.\n $this->user_id = $user_id;\n\n // Expand the list of allowed pages to include sub pages\n $all_pages = new WP_Query( array(\n 'post_type' => 'page',\n 'posts_per_page' => -1,\n ) ); \n foreach ( $allowed as $page ) {\n $this->allowed[] = $page;\n $sub_pages = get_page_children( $page, $all_pages );\n foreach ( $sub_pages as $sub_page ) {\n $this->allowed[] = $sub_page->ID;\n }\n }\n\n // For the prohibited user...\n // Remove the edit link from the front-end as needed\n add_filter( 'get_edit_post_link', array( $this, 'remove_edit_link' ), 10, 3 );\n add_action( 'admin_bar_menu', array( $this, 'remove_wp_admin_edit_link' ), 10, 1 );\n // Remove the edit link from wp-admin as needed\n add_action( 'page_row_actions', array( $this, 'remove_page_list_edit_link' ), 10, 2 );\n }\n\n /**\n * Helper functions that check if the current user is the one\n * we want to limit, and check if a specific post is in our\n * list of posts that we allow the user to edit.\n */\n private function is_user_limited() {\n $current_user = wp_get_current_user();\n return ( $current_user->ID == $this->user_id );\n }\n private function is_page_allowed( $post_id ) {\n return in_array( $post_id, $this->allowed );\n }\n\n /**\n * Removes the edit link from the front-end as needed.\n */\n public function remove_edit_link( $link, $post_id, $test ) {\n /**\n * If...\n * - The limited user is logged in\n * - The page the edit link is being created for is not in the allowed list\n * ...return an empty $link. This also causes edit_post_link() to show nothing.\n *\n * Otherwise, return link as normal.\n */\n if ( $this->is_user_limited() && !$this->is_page_allowed( $post_id ) ) {\n return '';\n }\n return $link;\n }\n\n /**\n * Removes the edit link from WP Admin Bar\n */\n public function remove_wp_admin_edit_link( $wp_admin_bar ) {\n /**\n * If:\n * - We're on a single page\n * - The limited user is logged in\n * - The page is not in the allowed list\n * ...Remove the edit link from the WP Admin Bar\n */\n if ( \n is_page() &&\n $this->is_user_limited() &&\n !$this->is_page_allowed( get_post()->ID )\n ) {\n $wp_admin_bar->remove_node( 'edit' );\n }\n }\n\n /**\n * Removes the edit link from WP Admin's edit.php\n */\n public function remove_page_list_edit_link( $actions, $post ) {\n /**\n * If:\n * -The limited user is logged in\n * -The page is not in the allowed list\n * ...Remove the \"Edit\", \"Quick Edit\", and \"Trash\" quick links.\n */\n if ( \n $this->is_user_limited() &&\n !$this->is_page_allowed( $post->ID )\n ) {\n unset( $actions['edit'] );\n unset( $actions['inline hide-if-no-js']);\n unset( $actions['trash'] );\n }\n return $actions;\n }\n}\n</code></pre>\n\n<p>What the code above does is prevent the following from working or appearing as needed:</p>\n\n<ol>\n<li><code>get_edit_post_link</code></li>\n<li><code>Edit Page</code> link on the WP Admin Bar that appears for the Pages</li>\n<li><code>Edit</code>, <code>Quick Edit</code>, and <code>Trash</code> quick links that appear underneath the Pages in <code>/wp-admin/edit.php?post_type=page</code></li>\n</ol>\n\n<p>This worked on my local WordPress 4.7 install. Assuming that the pages on the site won't change often, it might be better to hardcode the IDs of the page and its sub-pages, and remove the <code>WP_Query</code> inside the <code>__construct</code> method. This will save a lot on database calls.</p>\n"
},
{
"answer_id": 259976,
"author": "Ben Casey",
"author_id": 114997,
"author_profile": "https://wordpress.stackexchange.com/users/114997",
"pm_score": 3,
"selected": false,
"text": "<p>If you wanted to keep away from plugins, you could a variation of the code below in a functions.php file or a custom plugin. </p>\n\n<p>There are 2 seperate parts to this code, You would only need to use 1 of them, but which one depends on the complexity of the requirements.</p>\n\n<p>Part 1 is specifying a single user and restricting them to a specific post. </p>\n\n<p>Part 2 allows you to create a map of users and post ID's and allows multiple posts</p>\n\n<p>The code below is for a page only, but if you wanted to change that to a post, or a custom post type, you would need to change the string in <code>$screen->id == 'page'</code> to something else. </p>\n\n<p>You can find a reference to the screen ID's around wp-admin <a href=\"https://codex.wordpress.org/Plugin_API/Admin_Screen_Reference\" rel=\"noreferrer\">here</a></p>\n\n<pre><code>function my_pre_get_posts( $query ){\n\n $screen = get_current_screen();\n $current_user = wp_get_current_user();\n\n /**\n * Specify a single user and restrict to a single page\n */\n $restricted_user_id = 10; //User ID of the restricted user\n $allowed_post_id = 1234; //Post ID of the allowed post\n\n $current_post_id = isset( $_GET['post'] ) ? (int)$_GET['post'] : false ;\n\n //Only affecting a specific user\n if( $current_user->ID !== $restricted_user_id ){\n return;\n }\n\n //Only Affecting EDIT page.\n if( ! $current_post_id ){\n return;\n }\n\n if( $screen->id == 'page' && $current_post_id !== $allowed_post_id ){\n wp_redirect( admin_url( ) );\n exit;\n }\n\n /**\n * Specify a map of user_id => $allowed_posts\n */\n $restrictions_map = [\n 10 => [ 123 ], //Allow user ID to edit Page ID 123\n 11 => [ 152, 186 ] //Allow user ID to edit Page ID 123 and 186\n ];\n\n if( array_key_exists( $current_user->ID, $restrictions_map ) ){\n\n $allowed_posts = $restrictions_map[$current_user->ID];\n\n if( $screen->id == 'page' && ! in_array( $current_user->ID, $allowed_posts ) ){\n wp_redirect( admin_url( ) );\n exit;\n }\n\n }\n\n}\nadd_action( 'pre_get_posts', 'my_pre_get_posts' );\n</code></pre>\n"
},
{
"answer_id": 259982,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 5,
"selected": true,
"text": "<p>The first thing to do to implements such task is to be able to recognise which page an user can edit.</p>\n\n<p>There are different ways to do it. It could be a user meta, some configuration value... For the sake of this answer, I will assume that a function lile this exists:</p>\n\n<pre><code>function wpse_user_can_edit( $user_id, $page_id ) {\n\n $page = get_post( $page_id );\n\n // let's find the topmost page in the hierarchy\n while( $page && (int) $page->parent ) {\n $page = get_post( $page->parent );\n }\n\n if ( ! $page ) {\n return false;\n }\n\n // now $page is the top page in the hierarchy\n // how to know if an user can edit it, it's up to you...\n\n}\n</code></pre>\n\n<p>Now that we have a way to determine if an user can edit a page we just need to tell WordPress to use this function to check useer capability to edit a page.</p>\n\n<p>That can be done via <a href=\"https://developer.wordpress.org/reference/hooks/map_meta_cap/\" rel=\"nofollow noreferrer\"><code>'map_meta_cap'</code></a> filter.</p>\n\n<p>Something like:</p>\n\n<pre><code>add_filter( 'map_meta_cap', function ( $caps, $cap, $user_id, $args ) {\n\n $to_filter = [ 'edit_post', 'delete_post', 'edit_page', 'delete_page' ];\n\n // If the capability being filtered isn't of our interest, just return current value\n if ( ! in_array( $cap, $to_filter, true ) ) {\n return $caps;\n }\n\n // First item in $args array should be page ID\n if ( ! $args || empty( $args[0] ) || ! wpse_user_can_edit( $user_id, $args[0] ) ) {\n // User is not allowed, let's tell that to WP\n return [ 'do_not_allow' ];\n }\n // Otherwise just return current value\n return $caps;\n\n}, 10, 4 );\n</code></pre>\n\n<p>At this point, we need only a way to <em>connect</em> an user to one or more pages.</p>\n\n<p>There might be different solutions depending on use case.</p>\n\n<p>A flexible solution could be to add a dropdown of \"root\" pages (see <a href=\"https://developer.wordpress.org/reference/functions/wp_dropdown_pages/\" rel=\"nofollow noreferrer\"><code>wp_dropdown_pages</code></a>) to the edit user admin screen, and save selected page(s) as user meta.</p>\n\n<p>We could leverage <a href=\"https://developer.wordpress.org/reference/hooks/edit_user_profile/\" rel=\"nofollow noreferrer\"><code>'edit_user_profile'</code></a> to add the pages dropdown field and <a href=\"https://developer.wordpress.org/reference/hooks/edit_user_profile_update/\" rel=\"nofollow noreferrer\"><code>'edit_user_profile_update'</code></a> to store the selected value as user meta.</p>\n\n<p>I am sure that in this website there's enough guidance on how to that in detail.</p>\n\n<p>When page(s) are stored as user meta, the <code>wpse_user_can_edit()</code> function from above can be finished by checking if the page id is part of the user meta value.</p>\n\n<p>Removing capability to edit the page, WordPress will do the rest: will remove any edit link from backend and frontend, will prevent direct access... and so on.</p>\n"
}
] |
2015/06/16
|
[
"https://wordpress.stackexchange.com/questions/191704",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74798/"
] |
I have a form:
```
<form name="customer_details" method="POST" onsubmit="return form_validation()"
action="../customer-details.php">
```
I placed the PHP file in my theme folder, but WordPress gives me an error:
>
> 404 — Fancy meeting you here!
>
>
>
|
The first thing to do to implements such task is to be able to recognise which page an user can edit.
There are different ways to do it. It could be a user meta, some configuration value... For the sake of this answer, I will assume that a function lile this exists:
```
function wpse_user_can_edit( $user_id, $page_id ) {
$page = get_post( $page_id );
// let's find the topmost page in the hierarchy
while( $page && (int) $page->parent ) {
$page = get_post( $page->parent );
}
if ( ! $page ) {
return false;
}
// now $page is the top page in the hierarchy
// how to know if an user can edit it, it's up to you...
}
```
Now that we have a way to determine if an user can edit a page we just need to tell WordPress to use this function to check useer capability to edit a page.
That can be done via [`'map_meta_cap'`](https://developer.wordpress.org/reference/hooks/map_meta_cap/) filter.
Something like:
```
add_filter( 'map_meta_cap', function ( $caps, $cap, $user_id, $args ) {
$to_filter = [ 'edit_post', 'delete_post', 'edit_page', 'delete_page' ];
// If the capability being filtered isn't of our interest, just return current value
if ( ! in_array( $cap, $to_filter, true ) ) {
return $caps;
}
// First item in $args array should be page ID
if ( ! $args || empty( $args[0] ) || ! wpse_user_can_edit( $user_id, $args[0] ) ) {
// User is not allowed, let's tell that to WP
return [ 'do_not_allow' ];
}
// Otherwise just return current value
return $caps;
}, 10, 4 );
```
At this point, we need only a way to *connect* an user to one or more pages.
There might be different solutions depending on use case.
A flexible solution could be to add a dropdown of "root" pages (see [`wp_dropdown_pages`](https://developer.wordpress.org/reference/functions/wp_dropdown_pages/)) to the edit user admin screen, and save selected page(s) as user meta.
We could leverage [`'edit_user_profile'`](https://developer.wordpress.org/reference/hooks/edit_user_profile/) to add the pages dropdown field and [`'edit_user_profile_update'`](https://developer.wordpress.org/reference/hooks/edit_user_profile_update/) to store the selected value as user meta.
I am sure that in this website there's enough guidance on how to that in detail.
When page(s) are stored as user meta, the `wpse_user_can_edit()` function from above can be finished by checking if the page id is part of the user meta value.
Removing capability to edit the page, WordPress will do the rest: will remove any edit link from backend and frontend, will prevent direct access... and so on.
|
191,711 |
<p>I have a WordPress install using a Comodo SSL certificate. I have the <a href="https://wordpress.org/plugins/wordpress-https/" rel="nofollow noreferrer">WordPress HTTPS plugin</a> installed and I'm using the AZ theme, and the admin is set to load over HTTPS. So far so good.</p>
<p>On the theme customizer, I get a perpetual loading icon (not to be confused with a WSOD). The AJAX call that brings back the homepage content is empty, save for the <code>WP_CUSTOMIZER_SIGNATURE</code> token. That is all the response includes. When I disable the WordPress HTTPS plugin (or otherwise disable loading the admin over SSL), the customizer works great. Disabling/enabling other plugins has no effect. This occurs with the stock Twenty Fifteen theme as well (pictured below).</p>
<p>Here is a screenshot of what I'm seeing in Firebug (and is reproducible across browsers, as well as on Browserstack VMs):</p>
<p><img src="https://i.stack.imgur.com/8FQfw.jpg" alt="Screenshot of Firebug console in customizer view"></p>
<p>In case it's relevant, the site is hosted on a DigitalOcean droplet, using ServerPilot. I have other WordPress sites hosted on the same droplet, and the other SSL-enabled one exhibits the same behavior. <code>ModSecurity</code> is not installed, to my knowledge, and I'm getting a 200 status code so I don't think it's <a href="https://wordpress.org/support/topic/customizer-preview-hits-standard-comodo-mod_security-rules" rel="nofollow noreferrer">this issue</a>.</p>
<p>Also, the <code>SHA-1</code> messaging appears to be a false positive, so far as I can tell (and I don't think Firefox is yet at the point of blocking content based on <code>SHA-1</code> usage anyhow?). I don't think it's <a href="https://core.trac.wordpress.org/ticket/22430" rel="nofollow noreferrer"><code>zlib.output_compression bug</code></a> either, as I have turned it off explicitly to test, and attempted the fix listed in that ticket, which didn't work.</p>
<p>I haven't found anything that quite matches my problem, which makes me think there is something stupid I have overlooked. Any help is greatly appreciated, and please let me know what additional information may be helpful.</p>
|
[
{
"answer_id": 236160,
"author": "Ethan O'Sullivan",
"author_id": 98212,
"author_profile": "https://wordpress.stackexchange.com/users/98212",
"pm_score": 2,
"selected": true,
"text": "<p>Based on your question, I assume this is the plugin you are using to enable SSL: <a href=\"https://wordpress.org/plugins/wordpress-https\" rel=\"nofollow\">WordPress HTTPS</a>.</p>\n\n<p>Considering that the plugin hasn't been updated in two years and their support questions haven't been resolved, there may be some compatibility issues with the latest version of WordPress (4.6 at the time of this writing). My recommendation to make sure your website's URL is running HTTPS everywhere.</p>\n\n<p>THis can be done by executing the following SQL query in your database (<em>phpMyAdmin</em>):</p>\n\n<pre><code>UPDATE wp_options SET option_value = replace(option_value, 'HTTP_URL', 'HTTPS_URL') WHERE option_name = 'home' OR option_name = 'siteurl';\nUPDATE wp_posts SET guid = replace(guid, 'HTTP_URL','HTTPS_URL');\nUPDATE wp_posts SET post_content = replace(post_content, 'HTTP_URL', 'HTTPS_URL');\nUPDATE wp_postmeta SET meta_value = replace(meta_value,'HTTP_URL','HTTPS_URL');\n</code></pre>\n\n<p>Replace the values with the following:</p>\n\n<ul>\n<li><code>HTTP_URL</code> > your HTTP link (<code>http://some.site</code>)</li>\n<li><code>HTTPS_URL</code> your HTTPS link (<code>https://some.site</code>)</li>\n</ul>\n\n<p>This way, it prevents any mixed-content links from breaking things. I've also found a WordPress thread with a similar issue and not sure if you've already taken a look at it:</p>\n\n<p><a href=\"https://wordpress.org/support/topic/theme-customizer-problem\" rel=\"nofollow\">Theme Customizer Problem</a></p>\n"
},
{
"answer_id": 236162,
"author": "Luis",
"author_id": 83500,
"author_profile": "https://wordpress.stackexchange.com/users/83500",
"pm_score": 0,
"selected": false,
"text": "<p><strong>ANSWER</strong>:\nThis is due an inconsistency on your global URLs</p>\n\n<p>I guess at some point the string customizer of your plugin doesn't recognize some elements that are still called through <code>http</code> instead of <code>https</code>, many plugins contains absolute paths instead of relatives so, in order to fix the whole platform: admin, content and includes you can do the following.</p>\n\n<ol>\n<li>Install a plugin called <a href=\"https://wordpress.org/plugins/wp-migrate-db/\" rel=\"nofollow\">WP Migrate DB</a></li>\n<li>Once installed and activated Go to Tools -> Migrate DB</li>\n<li>The new url must be the same, and so the file path.</li>\n<li>Download the backup (why did I tell you this instead of just export directly of your phpmyadmin or dbms?, because is a safer way to get that info, that's all, in the export you can avoid some instructions to drop, this makes the \"backup\" an error proof method).</li>\n<li>Save it to an specific directory, alone, an uncompressed copy of it.</li>\n<li>In terminal go to that directory and execute the following command:</li>\n</ol>\n\n<p><code>sudo find . -type f -name '*.sql' -exec sed -i '' s,http://yoursite,https://yoursite,g {} +</code></p>\n\n<ol start=\"7\">\n<li><p>Upload the new file importing it to your phpmyadmin or web dbms.</p></li>\n<li><p>The error must be gone.</p></li>\n</ol>\n\n<p><strong>IMPORTANT</strong>.</p>\n\n<p>In case it didn't work you have your backup untouched copy remaining of step 5.</p>\n\n<p><strong>ADDITIONAL INFO</strong>.\nDid you check that the website root URL begins with <code>https</code> instead of <code>http</code>?</p>\n\n<p>You can check that on Settings -> General</p>\n\n<p><em>WordPress Address (URL)</em></p>\n\n<p><em>Site Address (URL)</em></p>\n\n<p>Good luck.</p>\n"
}
] |
2015/06/17
|
[
"https://wordpress.stackexchange.com/questions/191711",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74800/"
] |
I have a WordPress install using a Comodo SSL certificate. I have the [WordPress HTTPS plugin](https://wordpress.org/plugins/wordpress-https/) installed and I'm using the AZ theme, and the admin is set to load over HTTPS. So far so good.
On the theme customizer, I get a perpetual loading icon (not to be confused with a WSOD). The AJAX call that brings back the homepage content is empty, save for the `WP_CUSTOMIZER_SIGNATURE` token. That is all the response includes. When I disable the WordPress HTTPS plugin (or otherwise disable loading the admin over SSL), the customizer works great. Disabling/enabling other plugins has no effect. This occurs with the stock Twenty Fifteen theme as well (pictured below).
Here is a screenshot of what I'm seeing in Firebug (and is reproducible across browsers, as well as on Browserstack VMs):

In case it's relevant, the site is hosted on a DigitalOcean droplet, using ServerPilot. I have other WordPress sites hosted on the same droplet, and the other SSL-enabled one exhibits the same behavior. `ModSecurity` is not installed, to my knowledge, and I'm getting a 200 status code so I don't think it's [this issue](https://wordpress.org/support/topic/customizer-preview-hits-standard-comodo-mod_security-rules).
Also, the `SHA-1` messaging appears to be a false positive, so far as I can tell (and I don't think Firefox is yet at the point of blocking content based on `SHA-1` usage anyhow?). I don't think it's [`zlib.output_compression bug`](https://core.trac.wordpress.org/ticket/22430) either, as I have turned it off explicitly to test, and attempted the fix listed in that ticket, which didn't work.
I haven't found anything that quite matches my problem, which makes me think there is something stupid I have overlooked. Any help is greatly appreciated, and please let me know what additional information may be helpful.
|
Based on your question, I assume this is the plugin you are using to enable SSL: [WordPress HTTPS](https://wordpress.org/plugins/wordpress-https).
Considering that the plugin hasn't been updated in two years and their support questions haven't been resolved, there may be some compatibility issues with the latest version of WordPress (4.6 at the time of this writing). My recommendation to make sure your website's URL is running HTTPS everywhere.
THis can be done by executing the following SQL query in your database (*phpMyAdmin*):
```
UPDATE wp_options SET option_value = replace(option_value, 'HTTP_URL', 'HTTPS_URL') WHERE option_name = 'home' OR option_name = 'siteurl';
UPDATE wp_posts SET guid = replace(guid, 'HTTP_URL','HTTPS_URL');
UPDATE wp_posts SET post_content = replace(post_content, 'HTTP_URL', 'HTTPS_URL');
UPDATE wp_postmeta SET meta_value = replace(meta_value,'HTTP_URL','HTTPS_URL');
```
Replace the values with the following:
* `HTTP_URL` > your HTTP link (`http://some.site`)
* `HTTPS_URL` your HTTPS link (`https://some.site`)
This way, it prevents any mixed-content links from breaking things. I've also found a WordPress thread with a similar issue and not sure if you've already taken a look at it:
[Theme Customizer Problem](https://wordpress.org/support/topic/theme-customizer-problem)
|
191,715 |
<p>I built a custom post type "shop" with <a href="https://wordpress.org/plugins/custom-post-type-ui/" rel="nofollow">Custom Post Type UI</a> plugin and added a field "address" (Google Map type) with <a href="https://wordpress.org/plugins/advanced-custom-fields/" rel="nofollow">Advanced Custom Fields</a> plugin.</p>
<p>From the response of <code>WP_Query('post_type=shop');</code>, I got the following:</p>
<pre><code>$shop = WP_Query('post_type=shop');
while($shop->have_post()) {
$shop->the_post();
$location = get_field('map-location');
if($location != null) {
echo $location['address'];
}
}
</code></pre>
<p>Here I got a list of addresses. How do I search with this "address"? Let's say user wants to search shop that is in "London", how can I achieve this?</p>
<p>Thanks.</p>
<hr>
<p><strong>UPDATE</strong></p>
<p>Sample result of searching "15":</p>
<ul>
<li>筲箕灣東大街15號B地下</li>
<li>九龍觀塘偉業街103號振邦工業大廈地鋪</li>
<li>九龍土瓜灣旭日街一號 瑞英工業大廈第一期A座地下</li>
</ul>
|
[
{
"answer_id": 191717,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 3,
"selected": true,
"text": "<p>You need a <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters\" rel=\"nofollow\"><code>meta_query</code></a> something like this:</p>\n\n<pre><code>$args = array(\n 'post_type' => 'shop',\n 'meta_query' => array(\n array(\n 'key' => 'map-location',\n 'value' => 'London',\n 'compare' => 'LIKE' // the = operator might work depending on how your data is stored\n ),\n )\n);\n</code></pre>\n\n<p>Note: I am making some assumptions about how ACF stores data.</p>\n"
},
{
"answer_id": 191720,
"author": "Shrikant D",
"author_id": 74746,
"author_profile": "https://wordpress.stackexchange.com/users/74746",
"pm_score": 0,
"selected": false,
"text": "<p>You can use meta query to search for a particular field text. </p>\n\n<pre><code> $val = 'London';\n $args = array(\n 'post_type' => 'shop',\n 'meta_query' => array(\n array(\n 'key' => 'map-location',\n 'value' => $val,\n 'compare' => 'LIKE' \n ),\n )\n );\n $query = new WP_Query($arg);\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters\" rel=\"nofollow\">Class Reference/WP Query</a></p>\n"
},
{
"answer_id": 191770,
"author": "bonger",
"author_id": 57034,
"author_profile": "https://wordpress.stackexchange.com/users/57034",
"pm_score": 1,
"selected": false,
"text": "<p>You could use regular expression <code>RLIKE</code>:</p>\n\n<pre><code>$val = '15';\n$args = array(\n 'post_type' => 'shop',\n 'meta_query' => array(\n array(\n 'key' => 'map-location',\n 'value' => 's:7:\"address\";s:[0-9]+:\"[^\"]*' . preg_quote( $val ) . '[^\"]*\";',\n 'compare' => 'RLIKE'\n ),\n )\n);\n</code></pre>\n\n<p>although it can fail if your address data contains a double quote. If you always have a <code>lat</code> and a <code>lng</code> field following the <code>address</code> then you could extend the expression to match these and do away with the need for the <code>[^\"]</code> bits (replacing them with dots).</p>\n"
}
] |
2015/06/17
|
[
"https://wordpress.stackexchange.com/questions/191715",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3608/"
] |
I built a custom post type "shop" with [Custom Post Type UI](https://wordpress.org/plugins/custom-post-type-ui/) plugin and added a field "address" (Google Map type) with [Advanced Custom Fields](https://wordpress.org/plugins/advanced-custom-fields/) plugin.
From the response of `WP_Query('post_type=shop');`, I got the following:
```
$shop = WP_Query('post_type=shop');
while($shop->have_post()) {
$shop->the_post();
$location = get_field('map-location');
if($location != null) {
echo $location['address'];
}
}
```
Here I got a list of addresses. How do I search with this "address"? Let's say user wants to search shop that is in "London", how can I achieve this?
Thanks.
---
**UPDATE**
Sample result of searching "15":
* 筲箕灣東大街15號B地下
* 九龍觀塘偉業街103號振邦工業大廈地鋪
* 九龍土瓜灣旭日街一號 瑞英工業大廈第一期A座地下
|
You need a [`meta_query`](https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters) something like this:
```
$args = array(
'post_type' => 'shop',
'meta_query' => array(
array(
'key' => 'map-location',
'value' => 'London',
'compare' => 'LIKE' // the = operator might work depending on how your data is stored
),
)
);
```
Note: I am making some assumptions about how ACF stores data.
|
191,729 |
<p>Since WP3.5, <code>prepare()</code> accepts placeholders as a security measure, instead of just appending the argument to the query. Therefore, <code>$wpdb->prefix</code> needs to become a second parameter, called by <code>%s</code>:</p>
<pre><code>$count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(id) FROM %s WHERE answer !=' '", $wpdb->prefix . "faq_questions" ) );
</code></pre>
<p>However, doing that returns the table name in quotes: </p>
<p><code>SELECT COUNT(id) FROM 'wp_faq_questions' WHERE answer !=' '</code> </p>
<p>How can I fix this?</p>
|
[
{
"answer_id": 191731,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 4,
"selected": true,
"text": "<blockquote>\n <p>How can I fix this?</p>\n</blockquote>\n\n<p>You can't, but it isn't broken. You are telling <code>prepare</code> to use a string. A string will be quoted. It isn't meant to generate MySQL syntax, which is what you are asking it to do. Your tablename is more a MySQL command or keyword than a string value. That isn't what <code>prepare</code> is for. </p>\n\n<p><code>prepare</code> is meant to operate on user supplied data. Your tablename is not-- well, shouldn't be-- user supplied data so you don't need to \"prepare\" it. It is unnecessary. Just construct the tablename in the SQL itself:</p>\n\n<pre><code>\"SELECT COUNT(id) FROM \".$wpdb->prefix.\"faq_questions WHERE answer !=' '\"\n</code></pre>\n\n<p>See: <a href=\"https://wordpress.stackexchange.com/a/93861/21376\">https://wordpress.stackexchange.com/a/93861/21376</a></p>\n"
},
{
"answer_id": 333773,
"author": "Tom Auger",
"author_id": 3687,
"author_profile": "https://wordpress.stackexchange.com/users/3687",
"pm_score": 0,
"selected": false,
"text": "<p>You have some choices. Whitelisting is a good option - that is, check against an array of allowed field names and only add the ORDERBY clause if one of the field names is recognized.</p>\n\n<p><code>if ( in_array( $table_name, ['faq_questions', 'faq_responses', 'some_other_table'] ) )...</code></p>\n\n<p>Otherwise, WordPress has a nice function built just for you:\n<a href=\"https://codex.wordpress.org/Function_Reference/sanitize_sql_orderby\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/sanitize_sql_orderby</a></p>\n"
}
] |
2015/06/17
|
[
"https://wordpress.stackexchange.com/questions/191729",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/373/"
] |
Since WP3.5, `prepare()` accepts placeholders as a security measure, instead of just appending the argument to the query. Therefore, `$wpdb->prefix` needs to become a second parameter, called by `%s`:
```
$count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(id) FROM %s WHERE answer !=' '", $wpdb->prefix . "faq_questions" ) );
```
However, doing that returns the table name in quotes:
`SELECT COUNT(id) FROM 'wp_faq_questions' WHERE answer !=' '`
How can I fix this?
|
>
> How can I fix this?
>
>
>
You can't, but it isn't broken. You are telling `prepare` to use a string. A string will be quoted. It isn't meant to generate MySQL syntax, which is what you are asking it to do. Your tablename is more a MySQL command or keyword than a string value. That isn't what `prepare` is for.
`prepare` is meant to operate on user supplied data. Your tablename is not-- well, shouldn't be-- user supplied data so you don't need to "prepare" it. It is unnecessary. Just construct the tablename in the SQL itself:
```
"SELECT COUNT(id) FROM ".$wpdb->prefix."faq_questions WHERE answer !=' '"
```
See: <https://wordpress.stackexchange.com/a/93861/21376>
|
191,730 |
<p>I am running a dwfocus news website, I would like to split my li loop catagory in two section, can some let me know how can i proceed forward, thanks.</p>
<pre><code><div class="headlines" data-interval="<?php echo ($interval>0)?$interval*1000:'false'; ?>">
<ul>
<?php
$i = 0;
while ( $r->have_posts() ) {
$r->the_post();
?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><span class="time_diff"><?php echo ' - ' . dw_human_time_diff( get_the_time('U'), current_time('timestamp') ); ?></span></li>
<?php } ?>
</ul>
</div>
</code></pre>
|
[
{
"answer_id": 191733,
"author": "Junaid",
"author_id": 73812,
"author_profile": "https://wordpress.stackexchange.com/users/73812",
"pm_score": 3,
"selected": true,
"text": "<p>You will need to create <code>css</code> classes for a left and right column (you can use bootstrap if you like) after creating the classes try this</p>\n\n<pre><code><div class=\"headlines\" data-interval=\"<?php echo ($interval>0)?$interval*1000:'false'; ?>\">\n <ul>\n <?php \n $i = 0;\n while ( $r->have_posts() ) {\n $r->the_post();\n if($i % 2 == 0){ //even line\n ?>\n <li class=\"left-col\"><a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a><span class=\"time_diff\"><?php echo ' - ' . dw_human_time_diff( get_the_time('U'), current_time('timestamp') ); ?></span></li>\n <?php } else { ?>\n <li class=\"right-col\"><a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a><span class=\"time_diff\"><?php echo ' - ' . dw_human_time_diff( get_the_time('U'), current_time('timestamp') ); ?></span></li>\n <?php };\n $i++; }\n ?>\n </ul>\n</div>\n</code></pre>\n"
},
{
"answer_id": 191760,
"author": "Mitul",
"author_id": 74728,
"author_profile": "https://wordpress.stackexchange.com/users/74728",
"pm_score": 0,
"selected": false,
"text": "<p>Here is the code which you can get it show first 10 on left and after that show right side </p>\n\n<pre><code><div class=\"headlines\" data-interval=\"<?php echo ($interval>0)?$interval*1000:'false'; ?>\">\n<ul class=\"headline_left\">\n<?php \n $i = 1;\n while ( $r->have_posts() ) {\n $r->the_post(); ?>\n <li>\n <?php the_title( '<a href=\"' . get_permalink() . '\">', '</a>' ); ?>\n <span class=\"time_diff\"><?php echo ' - ' . dw_human_time_diff( get_the_time('U'), current_time('timestamp') ); ?></span>\n </li>\n <?php \n if($i == 10){ \n echo \"</ul><ul class='headline_right'>\";\n } \n $i++; \n }\n?>\n</ul> \n</div> \n</code></pre>\n\n<p>CSS code:</p>\n\n<pre><code>.headline_left{\n float:left;\n width:42%;\n padding-right:6%;\n /* margin:1px;*/\n min-height:40px;\n /*padding-left: 1px;*/\n}\n.headline_right{\n float:left;\n width:42%;\n padding-right:6%;\n margin:0;\n min-height:40px;\n}\n</code></pre>\n"
}
] |
2015/06/17
|
[
"https://wordpress.stackexchange.com/questions/191730",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74812/"
] |
I am running a dwfocus news website, I would like to split my li loop catagory in two section, can some let me know how can i proceed forward, thanks.
```
<div class="headlines" data-interval="<?php echo ($interval>0)?$interval*1000:'false'; ?>">
<ul>
<?php
$i = 0;
while ( $r->have_posts() ) {
$r->the_post();
?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><span class="time_diff"><?php echo ' - ' . dw_human_time_diff( get_the_time('U'), current_time('timestamp') ); ?></span></li>
<?php } ?>
</ul>
</div>
```
|
You will need to create `css` classes for a left and right column (you can use bootstrap if you like) after creating the classes try this
```
<div class="headlines" data-interval="<?php echo ($interval>0)?$interval*1000:'false'; ?>">
<ul>
<?php
$i = 0;
while ( $r->have_posts() ) {
$r->the_post();
if($i % 2 == 0){ //even line
?>
<li class="left-col"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><span class="time_diff"><?php echo ' - ' . dw_human_time_diff( get_the_time('U'), current_time('timestamp') ); ?></span></li>
<?php } else { ?>
<li class="right-col"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><span class="time_diff"><?php echo ' - ' . dw_human_time_diff( get_the_time('U'), current_time('timestamp') ); ?></span></li>
<?php };
$i++; }
?>
</ul>
</div>
```
|
191,748 |
<p>I have custom post type called <code>event</code>, which has custom fields for <code>start_date</code> and <code>end_date</code>. For the event archive, I'm filtering out "expired" events using the following meta query added to the main query inside a <code>pre_get_posts</code> filter, which works fine:</p>
<pre><code>if ( is_post_type_archive( 'event' ) ) {
$query->set( 'meta_query', array(
'relation' => 'OR',
array(
'key' => 'start_date',
'value' => $today = date( 'Ymd' ),
'compare' => '>='
),
array(
'key' => 'end_date',
'value' => $today = date( 'Ymd' ),
'compare' => '>='
),
) );
}
</code></pre>
<p>I'd like to do the same for search queries. Is it possible to add a meta query to the main query and have it only apply to a certain post type (i.e. <code>event</code>)? Pseudocode (I know this doesn't work, but to illustrate):</p>
<pre><code>if ( is_search() ) {
$query->set( 'meta_query', array(
'relation' => 'OR',
array(
'key' => 'post_type',
'value' => 'event',
'compare' => '!=',
),
array(
....
}
</code></pre>
|
[
{
"answer_id": 191750,
"author": "Mats Mikkel Rummelhoff",
"author_id": 68466,
"author_profile": "https://wordpress.stackexchange.com/users/68466",
"pm_score": 3,
"selected": true,
"text": "<p>In the case that the <code>start_date</code> custom field only exists for the <code>event</code> post type, this works:</p>\n\n<pre><code>$query->set( 'meta_query', array(\n 'relation' => 'OR',\n array(\n 'key' => 'start_date',\n 'compare' => 'NOT EXISTS',\n ),\n array(\n 'key' => 'start_date',\n 'value' => $today = date( 'Ymd' ),\n 'compare' => '>=',\n ),\n array(\n 'key' => 'end_date',\n 'value' => $today = date( 'Ymd' ),\n 'compare' => '>=',\n ),\n) );\n</code></pre>\n\n<p>By comparing the <code>start_date</code> key to <code>NOT EXISTS</code>, the other post types are not filtered out. Obviously this is not an ideal solution, so I'm still curious if there are better ideas out there.</p>\n"
},
{
"answer_id": 237160,
"author": "italiansoda",
"author_id": 71608,
"author_profile": "https://wordpress.stackexchange.com/users/71608",
"pm_score": 1,
"selected": false,
"text": "<p>Your given answer is pretty smart!!</p>\n\n<p>Another way I think you could accomplish the same thing and be a little bit more specific would be to pick a new key that exists only on the second post type and compare with EXISTS. </p>\n\n<p>So your second post type is <code>search</code> (not exactly sure from your example). Your first post type is <code>event</code>. If your main query is searching through both post types, then this meta_query would include all posts of the second post type.</p>\n\n<pre><code>$query->set( 'meta_query', array(\n'relation' => 'OR',\n array(\n 'key' => 'my_exclusive_meta_key_for_my_other_post_type',\n 'compare' => 'EXISTS',\n ),\n ...\n) );\n</code></pre>\n"
}
] |
2015/06/17
|
[
"https://wordpress.stackexchange.com/questions/191748",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68466/"
] |
I have custom post type called `event`, which has custom fields for `start_date` and `end_date`. For the event archive, I'm filtering out "expired" events using the following meta query added to the main query inside a `pre_get_posts` filter, which works fine:
```
if ( is_post_type_archive( 'event' ) ) {
$query->set( 'meta_query', array(
'relation' => 'OR',
array(
'key' => 'start_date',
'value' => $today = date( 'Ymd' ),
'compare' => '>='
),
array(
'key' => 'end_date',
'value' => $today = date( 'Ymd' ),
'compare' => '>='
),
) );
}
```
I'd like to do the same for search queries. Is it possible to add a meta query to the main query and have it only apply to a certain post type (i.e. `event`)? Pseudocode (I know this doesn't work, but to illustrate):
```
if ( is_search() ) {
$query->set( 'meta_query', array(
'relation' => 'OR',
array(
'key' => 'post_type',
'value' => 'event',
'compare' => '!=',
),
array(
....
}
```
|
In the case that the `start_date` custom field only exists for the `event` post type, this works:
```
$query->set( 'meta_query', array(
'relation' => 'OR',
array(
'key' => 'start_date',
'compare' => 'NOT EXISTS',
),
array(
'key' => 'start_date',
'value' => $today = date( 'Ymd' ),
'compare' => '>=',
),
array(
'key' => 'end_date',
'value' => $today = date( 'Ymd' ),
'compare' => '>=',
),
) );
```
By comparing the `start_date` key to `NOT EXISTS`, the other post types are not filtered out. Obviously this is not an ideal solution, so I'm still curious if there are better ideas out there.
|
191,752 |
<p>We have 2 WordPress sites in 2 different sub-domains like <strong>test1.abc.com</strong> and <strong>test2.abc.com</strong> . Both sites have <strong>wp-require</strong> plugin activated and only logged-in users can see the site. We want to make a system where if a user logged into one site, he should be auto-login into the other one.</p>
<p><strong>What I did:</strong></p>
<p>After some searching I know I need to use one database for both sites. So I have done these steps:</p>
<ol>
<li>I have download the whole database of <strong>test2.abc.com</strong> site and change all prefix <code>wp_</code> to <code>wpmo_</code>, replace it in whole database and upload it into first site's database.</li>
<li><p>I added these 2 lines in <code>wp-config.php</code> of the second site, to define that second site should use first site's user table not its own one.</p>
<pre><code> define('CUSTOM_USERMETA_TABLE', 'wp_usermeta');
define('CUSTOM_USER_TABLE', 'wp_users');
</code></pre></li>
<li><p>Now, the second site is using the first site's users and I am able to login to the second site by the user details of first site.</p></li>
<li><p>The next problem is cookies, so I added these lines in <code>wp-config</code> of both sites.</p>
<pre><code>define('COOKIE_DOMAIN', '.abc.com');
define('COOKIEPATH', '/');
</code></pre></li>
<li><p>Now I logged in into <strong>test1.abc.com</strong> and when I go to <strong>test2.abc.com</strong> , it asks me to login. That means cookies are not passing from the first site to the second one.</p></li>
</ol>
<p>Both subdomains are on same server and sharing same database user table. </p>
<p>I know it is a cookie issue and I have gone through many articles on that, but they all talk about sharing cookies between a domain and its subdomains. Here I am having 2 subdomains. </p>
|
[
{
"answer_id": 191753,
"author": "Mitul",
"author_id": 74728,
"author_profile": "https://wordpress.stackexchange.com/users/74728",
"pm_score": 0,
"selected": false,
"text": "<p>Hi Multisite User Management plugin will help you </p>\n\n<p><a href=\"https://wordpress.org/plugins/multisite-user-management/\" rel=\"nofollow\">https://wordpress.org/plugins/multisite-user-management/</a></p>\n"
},
{
"answer_id": 191755,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 1,
"selected": false,
"text": "<p>See <a href=\"https://wordpress.stackexchange.com/a/183750/1685\">my answer on this exact problem</a>. Long story short, you also need to define <code>COOKIEHASH</code>, otherwise the login cookie names will be different for each site:</p>\n\n<pre><code>define( 'COOKIEHASH', 'randomhash' );\n</code></pre>\n\n<p>Make sure to change <code>randomhash</code> to a real hash, you can <a href=\"http://md5.my-addr.com/online_random_md5_hash_generator-and-md5_random_hash.php\" rel=\"nofollow noreferrer\">grab one here</a>.</p>\n"
}
] |
2015/06/17
|
[
"https://wordpress.stackexchange.com/questions/191752",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74820/"
] |
We have 2 WordPress sites in 2 different sub-domains like **test1.abc.com** and **test2.abc.com** . Both sites have **wp-require** plugin activated and only logged-in users can see the site. We want to make a system where if a user logged into one site, he should be auto-login into the other one.
**What I did:**
After some searching I know I need to use one database for both sites. So I have done these steps:
1. I have download the whole database of **test2.abc.com** site and change all prefix `wp_` to `wpmo_`, replace it in whole database and upload it into first site's database.
2. I added these 2 lines in `wp-config.php` of the second site, to define that second site should use first site's user table not its own one.
```
define('CUSTOM_USERMETA_TABLE', 'wp_usermeta');
define('CUSTOM_USER_TABLE', 'wp_users');
```
3. Now, the second site is using the first site's users and I am able to login to the second site by the user details of first site.
4. The next problem is cookies, so I added these lines in `wp-config` of both sites.
```
define('COOKIE_DOMAIN', '.abc.com');
define('COOKIEPATH', '/');
```
5. Now I logged in into **test1.abc.com** and when I go to **test2.abc.com** , it asks me to login. That means cookies are not passing from the first site to the second one.
Both subdomains are on same server and sharing same database user table.
I know it is a cookie issue and I have gone through many articles on that, but they all talk about sharing cookies between a domain and its subdomains. Here I am having 2 subdomains.
|
See [my answer on this exact problem](https://wordpress.stackexchange.com/a/183750/1685). Long story short, you also need to define `COOKIEHASH`, otherwise the login cookie names will be different for each site:
```
define( 'COOKIEHASH', 'randomhash' );
```
Make sure to change `randomhash` to a real hash, you can [grab one here](http://md5.my-addr.com/online_random_md5_hash_generator-and-md5_random_hash.php).
|
191,771 |
<p>I have static front page for my WP installation set from <code>settings > reading</code>. Then I have added a URL endpoint using.</p>
<pre><code>add_rewrite_endpoint('foo', EP_ALL);
</code></pre>
<p>So, the front page should be accessible via</p>
<pre><code>http://example.com/
http://example.com/foo
http://example.com/foo/bar
</code></pre>
<p>For #1 Everything works fine but for #2 and #3 default <code>home.php</code> is shown instead of static home page. Tested locally in both single and multisite installation.</p>
<p>Is it a desired behavior or I hit something unusual? More importantly how can I make WP to show the static homepage in the given condition?</p>
<h2>Solution</h2>
<p>I was already hooking into <code>parse_request</code> to process part of code if <code>foo</code> exists. so, as per @gmazzap's solution. I only need to unset it afterwards. No need for extra hooked function is needed to bypass the bug.</p>
<pre><code>add_action('parse_request', function(&wp){
$key = 'foo';
if (!array_key_exists( $key, $wp->query_vars ) ) {
return;
}
// do things when foo exists
// we no longer need 'foo'
unset($wp->query_vars[$key]);
});
</code></pre>
|
[
{
"answer_id": 191753,
"author": "Mitul",
"author_id": 74728,
"author_profile": "https://wordpress.stackexchange.com/users/74728",
"pm_score": 0,
"selected": false,
"text": "<p>Hi Multisite User Management plugin will help you </p>\n\n<p><a href=\"https://wordpress.org/plugins/multisite-user-management/\" rel=\"nofollow\">https://wordpress.org/plugins/multisite-user-management/</a></p>\n"
},
{
"answer_id": 191755,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 1,
"selected": false,
"text": "<p>See <a href=\"https://wordpress.stackexchange.com/a/183750/1685\">my answer on this exact problem</a>. Long story short, you also need to define <code>COOKIEHASH</code>, otherwise the login cookie names will be different for each site:</p>\n\n<pre><code>define( 'COOKIEHASH', 'randomhash' );\n</code></pre>\n\n<p>Make sure to change <code>randomhash</code> to a real hash, you can <a href=\"http://md5.my-addr.com/online_random_md5_hash_generator-and-md5_random_hash.php\" rel=\"nofollow noreferrer\">grab one here</a>.</p>\n"
}
] |
2015/06/17
|
[
"https://wordpress.stackexchange.com/questions/191771",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3094/"
] |
I have static front page for my WP installation set from `settings > reading`. Then I have added a URL endpoint using.
```
add_rewrite_endpoint('foo', EP_ALL);
```
So, the front page should be accessible via
```
http://example.com/
http://example.com/foo
http://example.com/foo/bar
```
For #1 Everything works fine but for #2 and #3 default `home.php` is shown instead of static home page. Tested locally in both single and multisite installation.
Is it a desired behavior or I hit something unusual? More importantly how can I make WP to show the static homepage in the given condition?
Solution
--------
I was already hooking into `parse_request` to process part of code if `foo` exists. so, as per @gmazzap's solution. I only need to unset it afterwards. No need for extra hooked function is needed to bypass the bug.
```
add_action('parse_request', function(&wp){
$key = 'foo';
if (!array_key_exists( $key, $wp->query_vars ) ) {
return;
}
// do things when foo exists
// we no longer need 'foo'
unset($wp->query_vars[$key]);
});
```
|
See [my answer on this exact problem](https://wordpress.stackexchange.com/a/183750/1685). Long story short, you also need to define `COOKIEHASH`, otherwise the login cookie names will be different for each site:
```
define( 'COOKIEHASH', 'randomhash' );
```
Make sure to change `randomhash` to a real hash, you can [grab one here](http://md5.my-addr.com/online_random_md5_hash_generator-and-md5_random_hash.php).
|
191,772 |
<p>I have created a theme for one of our clients using bootstrap framework!</p>
<p>When i was working on it on Localhost it works Correctly, but when I Uploaded it doesn't work. When I Activate it from Appearance I Saw A blank white Page; Also when I Try to Post a new Comment, post, page or custom post type.</p>
<p>Is there any Help for this Problem?</p>
<p>References will send if ask?</p>
|
[
{
"answer_id": 191774,
"author": "Bruno Monteiro",
"author_id": 36031,
"author_profile": "https://wordpress.stackexchange.com/users/36031",
"pm_score": 3,
"selected": true,
"text": "<p>This answer will be long, but can be helpful in some way.</p>\n<h1>First of all, detect why you're getting this error:</h1>\n<p>Majority of the time when you see a <strong>Wordpress' White Screen of Death</strong>, it means that you <strong>exhausted the memory limit</strong> of your server settings.</p>\n<p>This could be <strong>caused by a plugin</strong> that you may be using that is not functioning properly.</p>\n<p>It could also be caused by a <strong>poorly coded theme</strong> that you are using - usually free themes download on the web.</p>\n<p>It could also mean that there is an <strong>issue with your web hosting server</strong>.</p>\n<p>Since the problem can be caused by any number of things, it may require a lot of troubleshooting.</p>\n<h1>Detect if the problem occur in other Wordpress websites:</h1>\n<p>If you have multiple sites, then the first thing you should do is to make sure that the white screen of death is happening across the board or just on this one domain.</p>\n<p>If the issue is with all of your sites, then it is a strong indicator that your web hosting provider is having some issues.</p>\n<p>However, if the issue is only with one of your sites, then this could be an issue with a plugin or theme that you are running. If the issue is only happening with a single post or page, then you know it is definitely a problem with your specific site.</p>\n<h1>If possible, increase the Memory Limit:</h1>\n<p>Usually this issue happens because your memory is being exhausted.</p>\n<p>If increasing the memory limit did not help, or if you have a high memory limit like 256M or 512M, then you need to start troubleshooting. In our experience of troubleshooting this issue, we have always found that the issue is either with a specific plugin or a theme. Go ahead and disable all the plugins.</p>\n<p>If this fixes the issue, then enable one plugin at a time to get to the bottom of the issue.</p>\n<h1>Try to replace Theme with a Default Theme and see if the problem persists:</h1>\n<p>If the plugin troubleshooting doesn’t fix the issue, then you should try <strong>replacing your current theme with a default twenty ten theme</strong>.</p>\n<p>The best way to do this is by backing up your theme folder. Then deleting the theme. WordPress will automatically fall back to the default theme.</p>\n<p>Alternatively, you can go in your phpMyAdmin and update the database tables in wp_options table. The following table names would have to be updated:</p>\n<p><code>template, stylesheet, and current_theme</code>. Change the value to twentyeleven.</p>\n<p>If this fixes the issue, then you should look at your theme’s <code>functions.php</code> file.</p>\n<p>If there are extra spaces at the bottom, then you should consider fixing it.</p>\n<p>If you are using a poorly coded function in your theme’s <code>functions.php</code> file, then it can cause this as well.</p>\n<h1>Debug your code:</h1>\n<p>If none of the above fixes it, then you should try to re-install a <strong>fresh copy of WordPress</strong>. While it is unlikely, but it is always possible that a core file may have been corrupted.</p>\n<p>You can also use the WordPress debug function to see what type of errors are being outputted. Add the following code in your wp-config.php file.</p>\n<pre><code>define( 'WP_DEBUG', true);\n</code></pre>\n<p>Once you add this, the blank screen will now have errors, warnings, and notices generated by PHP. These may be able to help you determine the root cause of the problem.</p>\n<h1>Make sure you're running on a Linux server:</h1>\n<p>Wordpress usually don't work well on servers running Windows - so make sure you're using a server running Linux (this can be checked with your hosting company).</p>\n"
},
{
"answer_id": 191867,
"author": "Ali Qorbani",
"author_id": 73590,
"author_profile": "https://wordpress.stackexchange.com/users/73590",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks a lot.\nI have checked and i found that the problem is on the <strong>Theme-options</strong> code.\ni have used <strong>Option tree</strong> plugin inside of my theme instead of installing the plugin.</p>\n\n<p>But I don't know why it works on local and doesn't work on website.</p>\n"
}
] |
2015/06/17
|
[
"https://wordpress.stackexchange.com/questions/191772",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73590/"
] |
I have created a theme for one of our clients using bootstrap framework!
When i was working on it on Localhost it works Correctly, but when I Uploaded it doesn't work. When I Activate it from Appearance I Saw A blank white Page; Also when I Try to Post a new Comment, post, page or custom post type.
Is there any Help for this Problem?
References will send if ask?
|
This answer will be long, but can be helpful in some way.
First of all, detect why you're getting this error:
===================================================
Majority of the time when you see a **Wordpress' White Screen of Death**, it means that you **exhausted the memory limit** of your server settings.
This could be **caused by a plugin** that you may be using that is not functioning properly.
It could also be caused by a **poorly coded theme** that you are using - usually free themes download on the web.
It could also mean that there is an **issue with your web hosting server**.
Since the problem can be caused by any number of things, it may require a lot of troubleshooting.
Detect if the problem occur in other Wordpress websites:
========================================================
If you have multiple sites, then the first thing you should do is to make sure that the white screen of death is happening across the board or just on this one domain.
If the issue is with all of your sites, then it is a strong indicator that your web hosting provider is having some issues.
However, if the issue is only with one of your sites, then this could be an issue with a plugin or theme that you are running. If the issue is only happening with a single post or page, then you know it is definitely a problem with your specific site.
If possible, increase the Memory Limit:
=======================================
Usually this issue happens because your memory is being exhausted.
If increasing the memory limit did not help, or if you have a high memory limit like 256M or 512M, then you need to start troubleshooting. In our experience of troubleshooting this issue, we have always found that the issue is either with a specific plugin or a theme. Go ahead and disable all the plugins.
If this fixes the issue, then enable one plugin at a time to get to the bottom of the issue.
Try to replace Theme with a Default Theme and see if the problem persists:
==========================================================================
If the plugin troubleshooting doesn’t fix the issue, then you should try **replacing your current theme with a default twenty ten theme**.
The best way to do this is by backing up your theme folder. Then deleting the theme. WordPress will automatically fall back to the default theme.
Alternatively, you can go in your phpMyAdmin and update the database tables in wp\_options table. The following table names would have to be updated:
`template, stylesheet, and current_theme`. Change the value to twentyeleven.
If this fixes the issue, then you should look at your theme’s `functions.php` file.
If there are extra spaces at the bottom, then you should consider fixing it.
If you are using a poorly coded function in your theme’s `functions.php` file, then it can cause this as well.
Debug your code:
================
If none of the above fixes it, then you should try to re-install a **fresh copy of WordPress**. While it is unlikely, but it is always possible that a core file may have been corrupted.
You can also use the WordPress debug function to see what type of errors are being outputted. Add the following code in your wp-config.php file.
```
define( 'WP_DEBUG', true);
```
Once you add this, the blank screen will now have errors, warnings, and notices generated by PHP. These may be able to help you determine the root cause of the problem.
Make sure you're running on a Linux server:
===========================================
Wordpress usually don't work well on servers running Windows - so make sure you're using a server running Linux (this can be checked with your hosting company).
|
191,775 |
<p>I got a fatal error in existing code, when I debug deeper I found that it was coming from bellow line.</p>
<pre><code>get_posts( array("posts_per_page"=>-1) );
</code></pre>
<p>Can anyone explain why is that and how to overcome it?</p>
<p>Error : </p>
<pre><code>Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes) in /var/www/web0/html/blog/wp-includes/wp-db.php on line 2204
</code></pre>
|
[
{
"answer_id": 191777,
"author": "Bruno Monteiro",
"author_id": 36031,
"author_profile": "https://wordpress.stackexchange.com/users/36031",
"pm_score": 2,
"selected": false,
"text": "<p>Running a no limit query is very likely the cause of your memory issues. So you might want to change your query.</p>\n\n<p>If still you need to do this way, you can use the <code>fields</code> option, it returns post IDs only and will save a lot of memory usage - example below:</p>\n\n<pre><code>$your_query = get_posts(\n array(\n 'posts_per_page' => -1,\n 'post_type' => 'post',\n 'fields' => 'ids',\n )\n);\n</code></pre>\n"
},
{
"answer_id": 282634,
"author": "Trevor Mills",
"author_id": 28991,
"author_profile": "https://wordpress.stackexchange.com/users/28991",
"pm_score": 1,
"selected": false,
"text": "<p>If your circumstances require getting all posts, try adding <code>'cache_results' => false</code> to the array of arguments. So, this. </p>\n\n<pre><code>$your_query = get_posts(\n array(\n 'posts_per_page' => -1,\n 'post_type' => 'post',\n 'cache_results' => false,\n )\n);\n</code></pre>\n\n<p>That tells <code>WP_Query</code> to NOT cache the results, according to this line in <code>wp-includes/class-wp-query.php</code>:</p>\n\n<pre><code>if ( $q['cache_results'] )\n update_post_caches($this->posts, $post_type, $q['update_post_term_cache'], $q['update_post_meta_cache']);\n</code></pre>\n\n<p>That caching, though it can be a big help for speed if you happen to query the same post multiple times in the same request, is a memory hog and could well be the source of the memory error.</p>\n"
}
] |
2015/06/17
|
[
"https://wordpress.stackexchange.com/questions/191775",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68403/"
] |
I got a fatal error in existing code, when I debug deeper I found that it was coming from bellow line.
```
get_posts( array("posts_per_page"=>-1) );
```
Can anyone explain why is that and how to overcome it?
Error :
```
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes) in /var/www/web0/html/blog/wp-includes/wp-db.php on line 2204
```
|
Running a no limit query is very likely the cause of your memory issues. So you might want to change your query.
If still you need to do this way, you can use the `fields` option, it returns post IDs only and will save a lot of memory usage - example below:
```
$your_query = get_posts(
array(
'posts_per_page' => -1,
'post_type' => 'post',
'fields' => 'ids',
)
);
```
|
191,779 |
<p>Just a few days ago I've started working on my new wordpress based website.</p>
<p>I have a plugin which provides a Cars Database. I want to auto-fill my custom fields and taxonomies by taking info from this plugin.</p>
<p>So, I've created a custom function in functions.php. I put an ID from car's database plugin and my function autofills my fields when I PUBLISH or UPDATE the post (wp_insert_post). Everything seems to be working fine but... </p>
<p>In my function, I have this code: </p>
<pre><code>if ( isset( $cardet['marks'] ) )
wp_set_object_terms( $post_id, implode(', ', $cardet["marks"]), 'mark' );
</code></pre>
<p>What does this function do? It simply gets 3-4 different car marks from $cardet['marks'] and implodes it. This is required only for taxonomies.</p>
<p><strong>So, after I click publish or update the post:</strong></p>
<p>This is OK, this is how it looks like in "post edit" page. Created 3 different terms.</p>
<p><img src="https://i.stack.imgur.com/OKhcS.jpg" alt="works fine"></p>
<p>And this is my problem. When I go to my taxonomy page, I got this:
It created just one term:</p>
<p><img src="https://i.stack.imgur.com/QRpiK.jpg" alt="only 1 term, why?"></p>
<p>I really need your help. I need to have different terms. Can't find a solution for this.</p>
|
[
{
"answer_id": 191782,
"author": "unknowndomain",
"author_id": 8490,
"author_profile": "https://wordpress.stackexchange.com/users/8490",
"pm_score": 2,
"selected": false,
"text": "<p>Implode turns your array like this <code>array( 'Audi', 'BMW', 'Mercedes-Benz' )</code> into a string separated by the delimiter set in the first parameter of the function, in this case <code>,</code> a comma and a space. In a way you can turn an array into a CSV from this. The result is this: <code>Audi, BMW, Mercedes-Benz</code>.</p>\n\n<p>The way WordPress works, it looks for an existing term (within that taxonomy) and if none exists it creates a new one...</p>\n\n<p>In the <a href=\"https://codex.wordpress.org/Function_Reference/wp_set_object_terms\" rel=\"nofollow\">WordPress Codex</a> it says that the terms can be provided as an array, integer or string, however I think the integer and string options may be for adding a single term at a time, I don't think it will re-explode the string, and more importantly this is a pointless process of imploding and exploding an array when it takes an array anyway and thats what you have in your <code>$cardet['marks']</code> variable.</p>\n"
},
{
"answer_id": 191784,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 2,
"selected": true,
"text": "<p>The second parameter to <a href=\"https://codex.wordpress.org/Function_Reference/wp_set_object_terms\" rel=\"nofollow\"><code>wp_set_object_terms()</code></a> takes an array, integer, or string. </p>\n\n<blockquote>\n <p>(<i>array/int/string</i>)\n (<i>required</i>) The slug or id of the term (such as category or tag\n IDs), will replace all existing related terms in this taxonomy. To\n clear or remove all terms from an object, pass an empty string or\n NULL. Integers are interpreted as tag IDs. <b>Warning:</b> some\n functions may return term_ids as strings which will be interpreted as\n slugs consisting of numeric characters!</p>\n</blockquote>\n\n<p>You create an array (<code>$cardet[\"marks\"]</code>) but then <code>implode()</code> it. When you <code>implode()</code> it you turn that array into a comma separated string, which <code>wp_set_object_terms()</code> interprets as a single value. <code>wp_set_object_terms()</code> will not break the string on commas and create multiple terms for you, but the solution is simple as you've added a step that is breaking things. Remove that step and pass the array to <code>wp_set_object_terms()</code>.</p>\n\n<pre><code>if ( isset( $cardet['marks'] ) )\n wp_set_object_terms( $post_id, $cardet[\"marks\"], 'mark' );\n</code></pre>\n\n<p>There is sample code in the Codex doing exactly this, but with IDs:</p>\n\n<pre><code>// An array of IDs of categories we want this post to have.\n$cat_ids = array( 6, 8 );\n\n/*\n * If this was coming from the database or another source, we would need to make sure\n * these where integers:\n\n$cat_ids = array_map( 'intval', $cat_ids );\n$cat_ids = array_unique( $cat_ids );\n\n */\n\n$term_taxonomy_ids = wp_set_object_terms( 42, $cat_ids, 'category' );\n</code></pre>\n\n<p>If <code>$cardet[\"marks\"]</code> is user supplied data please <a href=\"https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data\" rel=\"nofollow\">sanitize</a> it before using it.</p>\n"
}
] |
2015/06/17
|
[
"https://wordpress.stackexchange.com/questions/191779",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74827/"
] |
Just a few days ago I've started working on my new wordpress based website.
I have a plugin which provides a Cars Database. I want to auto-fill my custom fields and taxonomies by taking info from this plugin.
So, I've created a custom function in functions.php. I put an ID from car's database plugin and my function autofills my fields when I PUBLISH or UPDATE the post (wp\_insert\_post). Everything seems to be working fine but...
In my function, I have this code:
```
if ( isset( $cardet['marks'] ) )
wp_set_object_terms( $post_id, implode(', ', $cardet["marks"]), 'mark' );
```
What does this function do? It simply gets 3-4 different car marks from $cardet['marks'] and implodes it. This is required only for taxonomies.
**So, after I click publish or update the post:**
This is OK, this is how it looks like in "post edit" page. Created 3 different terms.

And this is my problem. When I go to my taxonomy page, I got this:
It created just one term:

I really need your help. I need to have different terms. Can't find a solution for this.
|
The second parameter to [`wp_set_object_terms()`](https://codex.wordpress.org/Function_Reference/wp_set_object_terms) takes an array, integer, or string.
>
> (*array/int/string*)
> (*required*) The slug or id of the term (such as category or tag
> IDs), will replace all existing related terms in this taxonomy. To
> clear or remove all terms from an object, pass an empty string or
> NULL. Integers are interpreted as tag IDs. **Warning:** some
> functions may return term\_ids as strings which will be interpreted as
> slugs consisting of numeric characters!
>
>
>
You create an array (`$cardet["marks"]`) but then `implode()` it. When you `implode()` it you turn that array into a comma separated string, which `wp_set_object_terms()` interprets as a single value. `wp_set_object_terms()` will not break the string on commas and create multiple terms for you, but the solution is simple as you've added a step that is breaking things. Remove that step and pass the array to `wp_set_object_terms()`.
```
if ( isset( $cardet['marks'] ) )
wp_set_object_terms( $post_id, $cardet["marks"], 'mark' );
```
There is sample code in the Codex doing exactly this, but with IDs:
```
// An array of IDs of categories we want this post to have.
$cat_ids = array( 6, 8 );
/*
* If this was coming from the database or another source, we would need to make sure
* these where integers:
$cat_ids = array_map( 'intval', $cat_ids );
$cat_ids = array_unique( $cat_ids );
*/
$term_taxonomy_ids = wp_set_object_terms( 42, $cat_ids, 'category' );
```
If `$cardet["marks"]` is user supplied data please [sanitize](https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data) it before using it.
|
191,801 |
<p>I always run into an issue with creating archive or landing pages for custom post types and wanted to know how others handle this.</p>
<p>If I want to have a landing page for a custom post type, however I want the archive page to contain editable content (i.e. be a physical page). I will need to make a custom template for my archive page. This issue with this is that there are no relationship of this page to the custom post type. So now I need to set archive to false and the rewrite rule to match the slug of the custom post type. Also when viewing a custom post type single page, the menu doesn't know the custom landing page is active. </p>
<p>Does anyone have a logical solution for this?</p>
|
[
{
"answer_id": 191803,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 0,
"selected": false,
"text": "<p>I would...</p>\n\n<ol>\n<li>Create a CPT registered with <code>'has_archive' => false</code> and use that\nas your \"editable content\" source.</li>\n<li>Or use a simple \"Page\" if you prefer</li>\n<li>Then create <code>archive-{cpt-name}.php</code> in the theme and query in that template for the\ncontent CPT data, or for the \"Page\" data.</li>\n</ol>\n"
},
{
"answer_id": 191805,
"author": "luke",
"author_id": 34790,
"author_profile": "https://wordpress.stackexchange.com/users/34790",
"pm_score": 2,
"selected": false,
"text": "<p>For this situation, I create a custom page template, say <code>tpl-archive-page.php</code>.\nFor example using <a href=\"http://www.advancedcustomfields.com/\" rel=\"nofollow\">Advanced Custom Fields</a> and the <a href=\"https://github.com/TimPerry/acf-post-type-selector\" rel=\"nofollow\">Post Type Selector Field</a>(*) the user can choose a post type to connect to.</p>\n\n<pre><code><?php\n/**\n * Template Name: CPT Archive Page\n */\n\nget_header();\n\nwhile (have_posts()) :\n\n the_post();\n\n get_template_part('content', 'page');\n\n $archive_query_post_type = get_post_meta(get_queried_object_id(), 'cpt_archive_query_post_type', true);\n\n if( $archive_query_post_type && is_string($archive_query_post_type) ) {\n $args = array(\n 'post_type' => $archive_query_post_type,\n 'posts_per_page'=> -1,\n 'orderby' => 'title',\n );\n\n $archive_query = new WP_Query( $args );\n\n if ( $archive_query->have_posts() ) {\n while ( $archive_query->have_posts() ) {\n $archive_query->the_post();\n get_template_part('content', get_post_type() );\n }\n }\n\n wp_reset_postdata();\n }\n\nendwhile;\n\nget_footer();\n</code></pre>\n\n<p>The <code>has_archive</code> option when registering the custom post type must be set to <code>false</code>.</p>\n\n<hr>\n\n<p>(*) If you are using ACF5/Pro, consider <a href=\"https://github.com/thomasdebruin/acf-post-type-selector\" rel=\"nofollow\">this</a> fork of the field.</p>\n"
}
] |
2015/06/17
|
[
"https://wordpress.stackexchange.com/questions/191801",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/35203/"
] |
I always run into an issue with creating archive or landing pages for custom post types and wanted to know how others handle this.
If I want to have a landing page for a custom post type, however I want the archive page to contain editable content (i.e. be a physical page). I will need to make a custom template for my archive page. This issue with this is that there are no relationship of this page to the custom post type. So now I need to set archive to false and the rewrite rule to match the slug of the custom post type. Also when viewing a custom post type single page, the menu doesn't know the custom landing page is active.
Does anyone have a logical solution for this?
|
For this situation, I create a custom page template, say `tpl-archive-page.php`.
For example using [Advanced Custom Fields](http://www.advancedcustomfields.com/) and the [Post Type Selector Field](https://github.com/TimPerry/acf-post-type-selector)(\*) the user can choose a post type to connect to.
```
<?php
/**
* Template Name: CPT Archive Page
*/
get_header();
while (have_posts()) :
the_post();
get_template_part('content', 'page');
$archive_query_post_type = get_post_meta(get_queried_object_id(), 'cpt_archive_query_post_type', true);
if( $archive_query_post_type && is_string($archive_query_post_type) ) {
$args = array(
'post_type' => $archive_query_post_type,
'posts_per_page'=> -1,
'orderby' => 'title',
);
$archive_query = new WP_Query( $args );
if ( $archive_query->have_posts() ) {
while ( $archive_query->have_posts() ) {
$archive_query->the_post();
get_template_part('content', get_post_type() );
}
}
wp_reset_postdata();
}
endwhile;
get_footer();
```
The `has_archive` option when registering the custom post type must be set to `false`.
---
(\*) If you are using ACF5/Pro, consider [this](https://github.com/thomasdebruin/acf-post-type-selector) fork of the field.
|
191,802 |
<p>I already created a custom post type with post-format support declared.</p>
<pre><code>register_post_type('portfolio', array(
'labels' => array(
'name' => __('Portfolio', "xxx"),
'singular_name' => __('Portfolio', "xxx")
),
'public' => true,
'menu_position' => 5,
'rewrite' => array('slug' => 'portfolio'),
'supports' => array( 'title', 'editor', 'thumbnail', 'excerpt', 'comments', 'revisions', 'custom-fields', 'post-formats' )
)
);
</code></pre>
<p>However, when I go to Wordpress Export tool and try to export posts under this custom post type, I checked the exported xml file and saw that it doesn't export post-format value of posts.</p>
<p>Is there any solution for this?</p>
|
[
{
"answer_id": 191841,
"author": "Atthapon Junpun-eak",
"author_id": 28340,
"author_profile": "https://wordpress.stackexchange.com/users/28340",
"pm_score": 1,
"selected": false,
"text": "<p>After spending time debugging export.php, I found that we have to register post_format taxonomy for our custom post type.</p>\n\n<pre><code>register_taxonomy( 'post_format', 'portfolio', array(\n 'public' => true,\n 'hierarchical' => false,\n 'labels' => array(\n 'name' => _x( 'Format', 'post format' ),\n 'singular_name' => _x( 'Format', 'post format' ),\n ),\n 'query_var' => true,\n 'rewrite' => $rewrite['post_format'],\n 'show_ui' => false,\n '_builtin' => true,\n 'show_in_nav_menus' => current_theme_supports( 'post-formats' ),\n ) );\n</code></pre>\n\n<p>Easy as that! </p>\n"
},
{
"answer_id": 207235,
"author": "Alex N",
"author_id": 47429,
"author_profile": "https://wordpress.stackexchange.com/users/47429",
"pm_score": 0,
"selected": false,
"text": "<p>I was struggling with this as well. Your solution worked, until I found out that it will <em>remove</em> the post format taxonomy for normal post types! </p>\n\n<p>After digging around the core files, I found this function which does exactly what we need: </p>\n\n<pre><code>register_taxonomy_for_object_type( 'post_format', 'portfolio' );\n</code></pre>\n\n<p>See <a href=\"https://codex.wordpress.org/Function_Reference/register_taxonomy_for_object_type\" rel=\"nofollow\">Codex</a>.</p>\n"
}
] |
2015/06/17
|
[
"https://wordpress.stackexchange.com/questions/191802",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/28340/"
] |
I already created a custom post type with post-format support declared.
```
register_post_type('portfolio', array(
'labels' => array(
'name' => __('Portfolio', "xxx"),
'singular_name' => __('Portfolio', "xxx")
),
'public' => true,
'menu_position' => 5,
'rewrite' => array('slug' => 'portfolio'),
'supports' => array( 'title', 'editor', 'thumbnail', 'excerpt', 'comments', 'revisions', 'custom-fields', 'post-formats' )
)
);
```
However, when I go to Wordpress Export tool and try to export posts under this custom post type, I checked the exported xml file and saw that it doesn't export post-format value of posts.
Is there any solution for this?
|
After spending time debugging export.php, I found that we have to register post\_format taxonomy for our custom post type.
```
register_taxonomy( 'post_format', 'portfolio', array(
'public' => true,
'hierarchical' => false,
'labels' => array(
'name' => _x( 'Format', 'post format' ),
'singular_name' => _x( 'Format', 'post format' ),
),
'query_var' => true,
'rewrite' => $rewrite['post_format'],
'show_ui' => false,
'_builtin' => true,
'show_in_nav_menus' => current_theme_supports( 'post-formats' ),
) );
```
Easy as that!
|
191,804 |
<p>I would like to remove all posts with a post type of <code>nf_sub</code> from showing up in any RSS feeds, including comment feeds, how can I do this?</p>
|
[
{
"answer_id": 191807,
"author": "luke",
"author_id": 34790,
"author_profile": "https://wordpress.stackexchange.com/users/34790",
"pm_score": 1,
"selected": false,
"text": "<p>Paste this in your <code>functions.php</code>of the active Theme or leave it in a custom plugin. Replace <code>your-cpt</code> string.</p>\n<pre><code>/**\n * Filter the feed, exclude specific custom post type \n *\n * @param WP_Query object $query\n * @return void \n */ \nfunction wpse_191804_pre_get_posts( $query ) \n{\n // only for feeds\n if( !$query->is_feed || !$query->is_main_query() )\n return query;\n \n $exclude = 'your-cpt';\n $post_types = $query->get('post_type');\n \n if (($key = array_search($exclude, $post_types)) !== false)\n unset($post_types[$key]);\n \n $query->set( 'post_type', $post_types );\n \n return $query;\n}\nadd_action( 'pre_get_posts', 'wpse_191804_pre_get_posts' );\n</code></pre>\n"
},
{
"answer_id": 295120,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>Only actual posts appear by default in the RSS feeds. If you have other types of posts in them it is an indication that you have a plugin which is responsible for doing that and you will need to consult its author to learn how to disable the inclusion of the specific post type.</p>\n"
}
] |
2015/06/17
|
[
"https://wordpress.stackexchange.com/questions/191804",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/66435/"
] |
I would like to remove all posts with a post type of `nf_sub` from showing up in any RSS feeds, including comment feeds, how can I do this?
|
Paste this in your `functions.php`of the active Theme or leave it in a custom plugin. Replace `your-cpt` string.
```
/**
* Filter the feed, exclude specific custom post type
*
* @param WP_Query object $query
* @return void
*/
function wpse_191804_pre_get_posts( $query )
{
// only for feeds
if( !$query->is_feed || !$query->is_main_query() )
return query;
$exclude = 'your-cpt';
$post_types = $query->get('post_type');
if (($key = array_search($exclude, $post_types)) !== false)
unset($post_types[$key]);
$query->set( 'post_type', $post_types );
return $query;
}
add_action( 'pre_get_posts', 'wpse_191804_pre_get_posts' );
```
|
191,809 |
<p>I have several post types "Courses", "Institutes" having same taxonomy "country". I am using this to get term on single-courses.php</p>
<pre><code><?php
$terms = get_the_terms( $post->ID , 'country' );
foreach ( $terms as $term ) {
$term_link = get_term_link( $term, 'country' );
if( is_wp_error( $term_link ) )
continue;
echo '<a href="' . $term_link . '">' . $term->name . '</a>';
}
?>
</code></pre>
<p>When I click term, it get all post types having "country" taxonomy. How can I use it to get ONLY CURRENT POST TYPE.</p>
|
[
{
"answer_id": 191810,
"author": "Bruno Monteiro",
"author_id": 36031,
"author_profile": "https://wordpress.stackexchange.com/users/36031",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe you can try this:</p>\n\n<pre><code><?php\n$post_type = 'your_current_post_type_name';\n$tax = 'your_taxonomy_name';\n$tax_terms = get_terms($tax);\nif ($tax_terms) {\n foreach ($tax_terms as $tax_term) {\n $args=array(\n 'post_type' => $post_type, // Here you will tell Wordpress only query on this post type\n \"$tax\" => $tax_term->slug,\n 'post_status' => 'publish',\n 'posts_per_page' => -1,\n 'caller_get_posts'=> 1\n );\n\n $my_query = null;\n $my_query = new WP_Query($args);\n if( $my_query->have_posts() ) {\n while ($my_query->have_posts()) : $my_query->the_post(); ?>\n ...\n <?php\n endwhile;\n }\n wp_reset_query();\n }\n}\n?>\n</code></pre>\n\n<p>Using <code>var_dump($tax_term)</code> you can verify exactly what is available to use (name, slug, ID, count, etc) - if everything run as expected, all these attributes should be available to use:</p>\n\n<pre><code>stdClass Object\n(\n [term_id] =>\n [name] =>\n [slug] =>\n [term_group] => \n [term_order] => \n [term_taxonomy_id] =>\n [taxonomy] =>\n [description] => \n [parent] =>\n [count] =>\n [object_id] =>\n)\n</code></pre>\n"
},
{
"answer_id": 191848,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 2,
"selected": true,
"text": "<p><a href=\"https://codex.wordpress.org/WordPress_Query_Vars#Query_variables\" rel=\"nofollow noreferrer\">If you look at WordPress' available query variables</a>, you will notice <code>post_type</code>. You will need to add that to your URL:</p>\n<pre><code>$terms = get_the_terms( $post->ID , 'category' ); \nforeach ( $terms as $term ) {\n $term_link = get_term_link( $term, 'category' );\n if( is_wp_error( $term_link ) ) \n continue;\n $term_link = add_query_arg(\n array(\n 'post_type' => $post->post_type\n ),\n $term_link\n );\n echo '<a href="' . $term_link . '">' . $term->name . '</a>';\n} \n</code></pre>\n<p>Reference:<br />\n<a href=\"https://developer.wordpress.org/reference/functions/add_query_arg/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/add_query_arg/</a></p>\n"
}
] |
2015/06/17
|
[
"https://wordpress.stackexchange.com/questions/191809",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/9711/"
] |
I have several post types "Courses", "Institutes" having same taxonomy "country". I am using this to get term on single-courses.php
```
<?php
$terms = get_the_terms( $post->ID , 'country' );
foreach ( $terms as $term ) {
$term_link = get_term_link( $term, 'country' );
if( is_wp_error( $term_link ) )
continue;
echo '<a href="' . $term_link . '">' . $term->name . '</a>';
}
?>
```
When I click term, it get all post types having "country" taxonomy. How can I use it to get ONLY CURRENT POST TYPE.
|
[If you look at WordPress' available query variables](https://codex.wordpress.org/WordPress_Query_Vars#Query_variables), you will notice `post_type`. You will need to add that to your URL:
```
$terms = get_the_terms( $post->ID , 'category' );
foreach ( $terms as $term ) {
$term_link = get_term_link( $term, 'category' );
if( is_wp_error( $term_link ) )
continue;
$term_link = add_query_arg(
array(
'post_type' => $post->post_type
),
$term_link
);
echo '<a href="' . $term_link . '">' . $term->name . '</a>';
}
```
Reference:
<https://developer.wordpress.org/reference/functions/add_query_arg/>
|
191,824 |
<p>I'm creating a plugin that adds a custom feed. I am using a <code>pre_get_posts</code> filter to change the <code>posts_per_page</code> query var to -1 (to get all items of a custom post type). However, if I dump the <code>$wp_query</code> in the render function, <code>posts_per_page</code> remains the default. I tested also changing <code>posts_per_rss</code> to -1, and I <em>do</em> see that as changed in the query (though it, of course, doesn't have any effect on the resulting posts). I also tried changing my theme to a default one and testing, but I had the same results. Can anyone explain why I can't change the <code>posts_per_page</code> query var?</p>
<pre><code>defined( 'ABSPATH' ) OR exit;
if(!class_exists('My_Custom_Feeds'))
{
class My_Custom_Feeds {
protected $feed_slug = 'theslug';
function __construct() {
add_action( 'init', array($this, 'mcf_add_feed'));
add_filter( 'pre_get_posts', array($this, 'mcf_pre_get_posts'));
}
function mcf_add_feed() {
add_feed($this->feed_slug, array($this, 'mcf_render'));
}
function mcf_render(){
//just output query to ensure it is as expected - but it's not
global $wp_query;
var_dump($wp_query);
exit();
}
function mcf_pre_get_posts( $query ) {
if ( $query->is_main_query() && $query->is_feed( $this->feed_slug ) ) {
// modify query here to show all posts
$query->set( 'posts_per_page', -1);
$query->set( 'posts_per_rss', -1);
}
}
}
}
if ( class_exists('My_Custom_Feeds') ){
$my_custom_feeds = new My_Custom_Feeds();
}
</code></pre>
<hr>
<p><strong>Update one:</strong>
Realized I was using <code>add_filter</code> instead of <code>add_action</code> for <code>pre_get_posts</code>. I've updated that, though I still see the same issue.</p>
<pre><code>add_action( 'pre_get_posts', array($this, 'mcf_pre_get_posts'));
</code></pre>
<hr>
<p><strong>Update two (and final):</strong>
Per @ialocin's answer, I realized changing the <code>posts_per_page</code> query var is futile since it is overwritten by the <code>posts_per_rss</code> option in a feed query (my scenario). So, the answer is to use a filter to alter that option. (-1 is not a valid <code>posts_per_rss</code> value, thus the arbitrary one used below.)</p>
<pre><code>function mcf_posts_per_rss( $option_name ) {
global $wp_query;
if ( $wp_query->is_main_query() && $wp_query->is_feed( $this->feed_slug ) ) {
return 100; //arbitrarily large value that, while not ideal, works for me
}
return $option_name;
}
</code></pre>
<p>Then in my plugin class constructor I added the following (and removed the <code>pre_get_posts</code> action):</p>
<pre><code>add_filter( 'pre_option_posts_per_rss', array( $this, 'mcf_posts_per_rss') );
</code></pre>
|
[
{
"answer_id": 191847,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_a_Typical_Request\" rel=\"nofollow\">The <code>init</code> hook runs well before <code>pre_get_posts</code></a> so dumping the query at that point-- on <code>init</code>-- isn't going to reflect anything that will be done much later. I don't think there is anything wrong with your code, you misunderstand the sequence of actions. What you expect to happen isn't what actually happens.</p>\n"
},
{
"answer_id": 191945,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 1,
"selected": false,
"text": "<p><code>posts_per_rss</code> is <strong>not</strong> a <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow\"><code>WP_Query</code></a> parameter. It is the name of the <a href=\"https://codex.wordpress.org/Options_API\" rel=\"nofollow\"><code>option</code></a> that is saved into the database. It can be addresses via the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/pre_option_%28option_name%29\" rel=\"nofollow\"><code>pre_option_{$option_name}</code></a>:</p>\n\n<pre><code>function wpse191824_posts_per_rss( $option_name ) {\n return 999;\n}\nadd_filter( 'pre_option_posts_per_rss', 'wpse191824_posts_per_rss' );\n</code></pre>\n"
},
{
"answer_id": 192047,
"author": "Nicole",
"author_id": 74507,
"author_profile": "https://wordpress.stackexchange.com/users/74507",
"pm_score": 2,
"selected": true,
"text": "<p>Per the discussion/help in this thread, below is the basic code that ended up working for my purposes. Setting the <code>posts_per_page</code> query var was a futile exercise since it is overwritten by the <code>posts_per_rss</code> option in a feed query (my scenario). <code>posts_per_rss</code> is not a query var and must be set a different way, thus the <code>pre_option_posts_per_rss</code> filter added. (-1 is not a valid <code>posts_per_rss</code> value, thus the arbitrary one used below.)</p>\n\n<pre><code>defined( 'ABSPATH' ) OR exit;\n\nif(!class_exists('My_Custom_Feeds'))\n{\n\n class My_Custom_Feeds { \n\n protected $feed_slug = 'theslug';\n\n function __construct() {\n\n add_filter( 'pre_option_posts_per_rss', array( $this, 'mcf_posts_per_rss') );\n add_action( 'init', array($this, 'mcf_add_feed'));\n }\n\n function mcf_add_feed() {\n\n add_feed($this->feed_slug, array($this, 'mcf_render'));\n }\n\n function mcf_render(){\n\n //put rendering stuff here\n exit();\n }\n\n function mcf_posts_per_rss( $option_name ) {\n\n global $wp_query;\n if ( $wp_query->is_main_query() && $wp_query->is_feed( $this->feed_slug ) ) {\n return 100; //arbitrarily large value that, while not ideal, worked for my purposes\n }\n return $option_name;\n }\n }\n}\nif ( class_exists('My_Custom_Feeds') ) {\n\n //instantiate class\n $my_custom_feeds = new My_Custom_Feeds();\n}\n</code></pre>\n"
}
] |
2015/06/17
|
[
"https://wordpress.stackexchange.com/questions/191824",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74507/"
] |
I'm creating a plugin that adds a custom feed. I am using a `pre_get_posts` filter to change the `posts_per_page` query var to -1 (to get all items of a custom post type). However, if I dump the `$wp_query` in the render function, `posts_per_page` remains the default. I tested also changing `posts_per_rss` to -1, and I *do* see that as changed in the query (though it, of course, doesn't have any effect on the resulting posts). I also tried changing my theme to a default one and testing, but I had the same results. Can anyone explain why I can't change the `posts_per_page` query var?
```
defined( 'ABSPATH' ) OR exit;
if(!class_exists('My_Custom_Feeds'))
{
class My_Custom_Feeds {
protected $feed_slug = 'theslug';
function __construct() {
add_action( 'init', array($this, 'mcf_add_feed'));
add_filter( 'pre_get_posts', array($this, 'mcf_pre_get_posts'));
}
function mcf_add_feed() {
add_feed($this->feed_slug, array($this, 'mcf_render'));
}
function mcf_render(){
//just output query to ensure it is as expected - but it's not
global $wp_query;
var_dump($wp_query);
exit();
}
function mcf_pre_get_posts( $query ) {
if ( $query->is_main_query() && $query->is_feed( $this->feed_slug ) ) {
// modify query here to show all posts
$query->set( 'posts_per_page', -1);
$query->set( 'posts_per_rss', -1);
}
}
}
}
if ( class_exists('My_Custom_Feeds') ){
$my_custom_feeds = new My_Custom_Feeds();
}
```
---
**Update one:**
Realized I was using `add_filter` instead of `add_action` for `pre_get_posts`. I've updated that, though I still see the same issue.
```
add_action( 'pre_get_posts', array($this, 'mcf_pre_get_posts'));
```
---
**Update two (and final):**
Per @ialocin's answer, I realized changing the `posts_per_page` query var is futile since it is overwritten by the `posts_per_rss` option in a feed query (my scenario). So, the answer is to use a filter to alter that option. (-1 is not a valid `posts_per_rss` value, thus the arbitrary one used below.)
```
function mcf_posts_per_rss( $option_name ) {
global $wp_query;
if ( $wp_query->is_main_query() && $wp_query->is_feed( $this->feed_slug ) ) {
return 100; //arbitrarily large value that, while not ideal, works for me
}
return $option_name;
}
```
Then in my plugin class constructor I added the following (and removed the `pre_get_posts` action):
```
add_filter( 'pre_option_posts_per_rss', array( $this, 'mcf_posts_per_rss') );
```
|
Per the discussion/help in this thread, below is the basic code that ended up working for my purposes. Setting the `posts_per_page` query var was a futile exercise since it is overwritten by the `posts_per_rss` option in a feed query (my scenario). `posts_per_rss` is not a query var and must be set a different way, thus the `pre_option_posts_per_rss` filter added. (-1 is not a valid `posts_per_rss` value, thus the arbitrary one used below.)
```
defined( 'ABSPATH' ) OR exit;
if(!class_exists('My_Custom_Feeds'))
{
class My_Custom_Feeds {
protected $feed_slug = 'theslug';
function __construct() {
add_filter( 'pre_option_posts_per_rss', array( $this, 'mcf_posts_per_rss') );
add_action( 'init', array($this, 'mcf_add_feed'));
}
function mcf_add_feed() {
add_feed($this->feed_slug, array($this, 'mcf_render'));
}
function mcf_render(){
//put rendering stuff here
exit();
}
function mcf_posts_per_rss( $option_name ) {
global $wp_query;
if ( $wp_query->is_main_query() && $wp_query->is_feed( $this->feed_slug ) ) {
return 100; //arbitrarily large value that, while not ideal, worked for my purposes
}
return $option_name;
}
}
}
if ( class_exists('My_Custom_Feeds') ) {
//instantiate class
$my_custom_feeds = new My_Custom_Feeds();
}
```
|
191,854 |
<p>I have a blog in WordPress. I have multiple categories. I want to use a specific layout for all posts under a category and all of its sub categories.</p>
<p><strong>Example :</strong> My categories organized as bellow.</p>
<ol>
<li><p>Guide(parent category)</p>
<p>1.1 Electical</p>
<p>1.1.1 TV</p>
<p>1.1.2 Radio</p>
<p>1.2 Plumbing</p>
<p>1.3 Home Repair</p>
<p>1.3.1 Kitchen</p>
<p>1.3.2 Bathroom</p></li>
</ol>
|
[
{
"answer_id": 191857,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 2,
"selected": false,
"text": "<h2>EDIT</h2>\n\n<p><strong><em>NOTE</strong> If you need only the parent and first level child terms, the answer from @Roberthue should work great. If you need all level child terms, then my solution should work</em>)</p>\n\n<p>I have updated my code to be more effecient. </p>\n\n<ul>\n<li><p>Run <code>get_ancestors()</code> only if we cannot find the parent term or its direct children </p></li>\n<li><p>Stop the execution of the foreach loop immediately when we find our parent term from the <code>get_ancestor</code> function</p></li>\n<li><p>Broke my checks up into smaller pieces and immediately stop execution when my checks return true</p></li>\n</ul>\n\n<h2>ORIGINAL ANSWER</h2>\n\n<p>By default, there is no option to set a specific template for posts from a specific category. This said, it doesn't mean it can't be done. To achieve this, you need to use the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/single_template\" rel=\"nofollow\"><code>single_template</code> filter</a> to set your custom single template page to posts with a specific set of categories.</p>\n\n<p>You can try something like the following: (<strong><em>CAVEAT:</strong> The code is untested and needs at least PHP 5.3</em>)</p>\n\n<pre><code>add_filter( 'single_template', function ( $template ) \n{\n // Get the current queried post id\n $current_post = get_queried_object_id();\n\n // Get the post terms. Change category to the correct taxonomy name if your post terms is from a custom taxonomy\n $terms = wp_get_post_terms( $current_post, 'category' );\n\n // Check if we have terms and we don't have an error. If we do, return default single template\n if ( !$terms || is_wp_error( $terms ) )\n return $template;\n\n // Check if our custom template exists before going through all the trouble to find out terms\n $new_template = locate_template( 'single-custom.php' );\n if ( !$new_template ) \n return $template;\n\n // Get al the term ids in an array and check if we can find our parent term\n $term_ids = wp_list_pluck( $terms, 'term_id' );\n if ( in_array( 10, $term_ids ) )\n return $template = $new_template;\n\n // Get all the parent ids in an array and look for our parent term if we could not find it using term ids\n $parent_ids = wp_list_pluck( $terms, 'parent' );\n if ( in_array( 10, $parent_ids ) )\n return $template = $new_template;\n\n // If we cannot find the parent or direct children, lets look for lower level children\n $bool = false;\n foreach ( $term_ids as $term ) {\n // Use get_ancestors and check if we can find our parent term id\n if ( in_array( 10, get_ancestors( $term, 'category' ) ) ) {\n $bool = true;\n // If we found our parent, stop execution of our foreach loop\n break;\n }\n }\n\n // If $bool is true, return our custom single template\n if ( $bool )\n return $template = $new_template;\n\n // If all our conditions failed, return the default single template\n return $template;\n});\n</code></pre>\n\n<h2>EDIT 2</h2>\n\n<p>The above code is now tested and working. Fixed a couple of small bugs :-)</p>\n"
},
{
"answer_id": 191862,
"author": "Robert hue",
"author_id": 22461,
"author_profile": "https://wordpress.stackexchange.com/users/22461",
"pm_score": 3,
"selected": true,
"text": "<p>You can do that with <code>single_template</code> filter. First you will need to check if a post belongs to a top level category. So here is the function.</p>\n\n<pre><code>// custom single template for specific category\nfunction wpse_custom_category_single_template( $single_template ) {\n\n global $post;\n\n // get all categories of current post\n $categories = get_the_category( $post->ID );\n $top_categories = array();\n\n // get top level categories\n foreach( $categories as $cat ) {\n if ( $cat->parent != 0 ) {\n $top_categories[] = $cat->parent;\n } else {\n $top_categories[] = $cat->term_id;\n }\n }\n\n // check if specific category exists in array\n if ( in_array( '8', $top_categories ) ) {\n if ( file_exists( get_template_directory() . '/single-custom.php' ) ) return get_template_directory() . '/single-custom.php';\n }\n\n return $single_template;\n\n}\n\nadd_filter( 'single_template', 'wpse_custom_category_single_template' );\n</code></pre>\n\n<p>In similar situation usually people check for parent category with <code>$categories[0]->category_parent;</code>, which is right but only works if you have assigned one category to each post. If you have 2 and more categories then this solution will always work.</p>\n"
}
] |
2015/06/18
|
[
"https://wordpress.stackexchange.com/questions/191854",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/64976/"
] |
I have a blog in WordPress. I have multiple categories. I want to use a specific layout for all posts under a category and all of its sub categories.
**Example :** My categories organized as bellow.
1. Guide(parent category)
1.1 Electical
1.1.1 TV
1.1.2 Radio
1.2 Plumbing
1.3 Home Repair
1.3.1 Kitchen
1.3.2 Bathroom
|
You can do that with `single_template` filter. First you will need to check if a post belongs to a top level category. So here is the function.
```
// custom single template for specific category
function wpse_custom_category_single_template( $single_template ) {
global $post;
// get all categories of current post
$categories = get_the_category( $post->ID );
$top_categories = array();
// get top level categories
foreach( $categories as $cat ) {
if ( $cat->parent != 0 ) {
$top_categories[] = $cat->parent;
} else {
$top_categories[] = $cat->term_id;
}
}
// check if specific category exists in array
if ( in_array( '8', $top_categories ) ) {
if ( file_exists( get_template_directory() . '/single-custom.php' ) ) return get_template_directory() . '/single-custom.php';
}
return $single_template;
}
add_filter( 'single_template', 'wpse_custom_category_single_template' );
```
In similar situation usually people check for parent category with `$categories[0]->category_parent;`, which is right but only works if you have assigned one category to each post. If you have 2 and more categories then this solution will always work.
|
191,856 |
<p>As per my requirement I need to show a page say <code>firstpage.php</code> for user who visit my site for <code>first time</code> else should show home page say <code>homepage.php</code></p>
<p>I created both this pages as <code>page-templates</code></p>
<p>For this so far I have managed to set using cookies using below code</p>
<pre><code>if (!isset($_COOKIE['visited'])) { // no cookie, so probably the first time here
setcookie ('visited', 'yes', time() + 3600); // set visited cookie
header("Location: index.php");
exit(); // always use exit after redirect to prevent further loading of the page
}
else{
header("Location: index.php/first-page/");
}
</code></pre>
<p>When I use above code it is not being redirected to required URL and resulting an error.</p>
<blockquote>
<p>The page isn't redirecting properly</p>
</blockquote>
|
[
{
"answer_id": 191857,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 2,
"selected": false,
"text": "<h2>EDIT</h2>\n\n<p><strong><em>NOTE</strong> If you need only the parent and first level child terms, the answer from @Roberthue should work great. If you need all level child terms, then my solution should work</em>)</p>\n\n<p>I have updated my code to be more effecient. </p>\n\n<ul>\n<li><p>Run <code>get_ancestors()</code> only if we cannot find the parent term or its direct children </p></li>\n<li><p>Stop the execution of the foreach loop immediately when we find our parent term from the <code>get_ancestor</code> function</p></li>\n<li><p>Broke my checks up into smaller pieces and immediately stop execution when my checks return true</p></li>\n</ul>\n\n<h2>ORIGINAL ANSWER</h2>\n\n<p>By default, there is no option to set a specific template for posts from a specific category. This said, it doesn't mean it can't be done. To achieve this, you need to use the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/single_template\" rel=\"nofollow\"><code>single_template</code> filter</a> to set your custom single template page to posts with a specific set of categories.</p>\n\n<p>You can try something like the following: (<strong><em>CAVEAT:</strong> The code is untested and needs at least PHP 5.3</em>)</p>\n\n<pre><code>add_filter( 'single_template', function ( $template ) \n{\n // Get the current queried post id\n $current_post = get_queried_object_id();\n\n // Get the post terms. Change category to the correct taxonomy name if your post terms is from a custom taxonomy\n $terms = wp_get_post_terms( $current_post, 'category' );\n\n // Check if we have terms and we don't have an error. If we do, return default single template\n if ( !$terms || is_wp_error( $terms ) )\n return $template;\n\n // Check if our custom template exists before going through all the trouble to find out terms\n $new_template = locate_template( 'single-custom.php' );\n if ( !$new_template ) \n return $template;\n\n // Get al the term ids in an array and check if we can find our parent term\n $term_ids = wp_list_pluck( $terms, 'term_id' );\n if ( in_array( 10, $term_ids ) )\n return $template = $new_template;\n\n // Get all the parent ids in an array and look for our parent term if we could not find it using term ids\n $parent_ids = wp_list_pluck( $terms, 'parent' );\n if ( in_array( 10, $parent_ids ) )\n return $template = $new_template;\n\n // If we cannot find the parent or direct children, lets look for lower level children\n $bool = false;\n foreach ( $term_ids as $term ) {\n // Use get_ancestors and check if we can find our parent term id\n if ( in_array( 10, get_ancestors( $term, 'category' ) ) ) {\n $bool = true;\n // If we found our parent, stop execution of our foreach loop\n break;\n }\n }\n\n // If $bool is true, return our custom single template\n if ( $bool )\n return $template = $new_template;\n\n // If all our conditions failed, return the default single template\n return $template;\n});\n</code></pre>\n\n<h2>EDIT 2</h2>\n\n<p>The above code is now tested and working. Fixed a couple of small bugs :-)</p>\n"
},
{
"answer_id": 191862,
"author": "Robert hue",
"author_id": 22461,
"author_profile": "https://wordpress.stackexchange.com/users/22461",
"pm_score": 3,
"selected": true,
"text": "<p>You can do that with <code>single_template</code> filter. First you will need to check if a post belongs to a top level category. So here is the function.</p>\n\n<pre><code>// custom single template for specific category\nfunction wpse_custom_category_single_template( $single_template ) {\n\n global $post;\n\n // get all categories of current post\n $categories = get_the_category( $post->ID );\n $top_categories = array();\n\n // get top level categories\n foreach( $categories as $cat ) {\n if ( $cat->parent != 0 ) {\n $top_categories[] = $cat->parent;\n } else {\n $top_categories[] = $cat->term_id;\n }\n }\n\n // check if specific category exists in array\n if ( in_array( '8', $top_categories ) ) {\n if ( file_exists( get_template_directory() . '/single-custom.php' ) ) return get_template_directory() . '/single-custom.php';\n }\n\n return $single_template;\n\n}\n\nadd_filter( 'single_template', 'wpse_custom_category_single_template' );\n</code></pre>\n\n<p>In similar situation usually people check for parent category with <code>$categories[0]->category_parent;</code>, which is right but only works if you have assigned one category to each post. If you have 2 and more categories then this solution will always work.</p>\n"
}
] |
2015/06/18
|
[
"https://wordpress.stackexchange.com/questions/191856",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63278/"
] |
As per my requirement I need to show a page say `firstpage.php` for user who visit my site for `first time` else should show home page say `homepage.php`
I created both this pages as `page-templates`
For this so far I have managed to set using cookies using below code
```
if (!isset($_COOKIE['visited'])) { // no cookie, so probably the first time here
setcookie ('visited', 'yes', time() + 3600); // set visited cookie
header("Location: index.php");
exit(); // always use exit after redirect to prevent further loading of the page
}
else{
header("Location: index.php/first-page/");
}
```
When I use above code it is not being redirected to required URL and resulting an error.
>
> The page isn't redirecting properly
>
>
>
|
You can do that with `single_template` filter. First you will need to check if a post belongs to a top level category. So here is the function.
```
// custom single template for specific category
function wpse_custom_category_single_template( $single_template ) {
global $post;
// get all categories of current post
$categories = get_the_category( $post->ID );
$top_categories = array();
// get top level categories
foreach( $categories as $cat ) {
if ( $cat->parent != 0 ) {
$top_categories[] = $cat->parent;
} else {
$top_categories[] = $cat->term_id;
}
}
// check if specific category exists in array
if ( in_array( '8', $top_categories ) ) {
if ( file_exists( get_template_directory() . '/single-custom.php' ) ) return get_template_directory() . '/single-custom.php';
}
return $single_template;
}
add_filter( 'single_template', 'wpse_custom_category_single_template' );
```
In similar situation usually people check for parent category with `$categories[0]->category_parent;`, which is right but only works if you have assigned one category to each post. If you have 2 and more categories then this solution will always work.
|
191,864 |
<p>I am looking for a script to select 1 random post per day in Wordpress.
I found the code below, but this keeps gathering a new post every time I refresh the page:</p>
<pre><code> <?php
function force_random_day_seed($orderby) {
$seed = floor( time() / DAY_IN_SECONDS );
$orderby=str_replace('RAND()', "RAND({$seed})", $orderby);
return $orderby;
}
add_filter('posts_orderby', 'force_random_day_seed');
$args = array('numberposts' => 1, 'orderby' => 'rand', 'post_type' => 'listing');
$totd = get_posts($args);
remove_filter('posts_orderby', 'force_random_day_seed');
foreach( $totd as $post ) : ?>
<?php the_title(); ?>
<?php the_content(); ?>
<?php endforeach; ?>
</code></pre>
<p>Any ideas?</p>
|
[
{
"answer_id": 191868,
"author": "Domain",
"author_id": 26523,
"author_profile": "https://wordpress.stackexchange.com/users/26523",
"pm_score": 0,
"selected": false,
"text": "<p>Try to use following code:-</p>\n\n<pre><code> <?php\n function force_random_day_seed($orderby) {\n $seed = floor( time() / DAY_IN_SECONDS );\n $orderby=str_replace('RAND()', \"RAND({$seed})\", $orderby);\n return $orderby;\n }\n add_filter('posts_orderby', 'force_random_day_seed');\n$temp_value = get_option(current_time('Y-m-d'));\nif($temp_value == '' ){\n $args = array('numberposts' => 1, 'orderby' => 'rand', 'post_type' => 'listing');\n $totd = get_posts($args);\nforeach($totd as $k=>$v){\nupdate_option(current_time('Y-m-d'),$v->ID);\n}\n}else{\n$totd = get_posts($temp_value);\n}\n remove_filter('posts_orderby', 'force_random_day_seed');\n foreach( $totd as $post ) : ?> \n <?php the_title(); ?>\n <?php the_content(); ?>\n <?php endforeach; ?>\n</code></pre>\n"
},
{
"answer_id": 191869,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>Note that the <code>posts_orderby</code> filter is not available for <code>get_posts()</code> where <code>suppress_filters</code> is <code>true</code> by default.</p>\n\n<p>You can use <code>WP_Query</code> instead:</p>\n\n<pre><code>$args = [ \n 'posts_per_page' => 1, \n 'orderby' => 'rand', \n 'post_type' => 'listing', \n 'ignore_sticky_posts' => true,\n];\n\nadd_filter( 'posts_orderby', 'force_random_day_seed' );\n$q = new WP_Query( $args );\nremove_filter( 'posts_orderby', 'force_random_day_seed' );\n\nif( $q->have_posts() )\n{\n while( $q->have_posts() )\n {\n $q->the_post();\n the_title();\n }\n wp_reset_postdata();\n}\nelse\n{\n _e( 'Sorry no posts found!' );\n}\n</code></pre>\n\n<p>It's also possible to skip your <code>posts_orderby</code> filter callback and just use <a href=\"https://codex.wordpress.org/Transients_API\" rel=\"nofollow\">transients</a> to store the results for 24 hours.</p>\n"
}
] |
2015/06/18
|
[
"https://wordpress.stackexchange.com/questions/191864",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/32810/"
] |
I am looking for a script to select 1 random post per day in Wordpress.
I found the code below, but this keeps gathering a new post every time I refresh the page:
```
<?php
function force_random_day_seed($orderby) {
$seed = floor( time() / DAY_IN_SECONDS );
$orderby=str_replace('RAND()', "RAND({$seed})", $orderby);
return $orderby;
}
add_filter('posts_orderby', 'force_random_day_seed');
$args = array('numberposts' => 1, 'orderby' => 'rand', 'post_type' => 'listing');
$totd = get_posts($args);
remove_filter('posts_orderby', 'force_random_day_seed');
foreach( $totd as $post ) : ?>
<?php the_title(); ?>
<?php the_content(); ?>
<?php endforeach; ?>
```
Any ideas?
|
Note that the `posts_orderby` filter is not available for `get_posts()` where `suppress_filters` is `true` by default.
You can use `WP_Query` instead:
```
$args = [
'posts_per_page' => 1,
'orderby' => 'rand',
'post_type' => 'listing',
'ignore_sticky_posts' => true,
];
add_filter( 'posts_orderby', 'force_random_day_seed' );
$q = new WP_Query( $args );
remove_filter( 'posts_orderby', 'force_random_day_seed' );
if( $q->have_posts() )
{
while( $q->have_posts() )
{
$q->the_post();
the_title();
}
wp_reset_postdata();
}
else
{
_e( 'Sorry no posts found!' );
}
```
It's also possible to skip your `posts_orderby` filter callback and just use [transients](https://codex.wordpress.org/Transients_API) to store the results for 24 hours.
|
191,877 |
<p><strong>UPDATE</strong>: </p>
<p>The hook is working with "classic" Wordpress filter (like <code>post__in</code>), so it's probably a Posts2Posts issue. I'm still looking for suggestions if someone has any idea.</p>
<p><strong>ORIGINAL POST</strong></p>
<p>I'm trying to get all posts displayed by issue number in archive pages. Issues are a custom post type (linked with post2post, which is why I use <code>parse_query</code> instead of <code>pre_get_post</code>)</p>
<pre><code><?php
function categories_by_issue ($query) {
if (! $query->is_category() || ! $query->is_main_query()) return;
$query->set( 'connected_type', 'issue_to_posts');
$query->set( 'connected_items', 71); // 71 needs to be dynamic
$query->set( 'nopaging', true);
}
add_action('parse_query', 'categories_by_issue');
?>
</code></pre>
<p>This action hook <strong>works fine</strong>! Problem is: I need to get the issue ID with another query. (ID and issue number are of course different, my '#3' issue has '71' ID)</p>
<p>I tried to add a <code>WP_Query</code> in my hook, which basically break the whole thing. I can get my issue number, but the main query finally shows all posts.</p>
<pre><code><?php
function categories_by_issue ($query) {
if (! $query->is_category() || ! $query->is_main_query()) return;
$issues = new WP_Query ( /* ... */);
$issue_id = $issues->get_posts()[0]->ID;
var_dump($issue_id); // -> 71 : My ID is correct
$query->set( 'connected_type', 'issue_to_posts');
$query->set( 'connected_items', $issue_id);
$query->set( 'nopaging', true);
}
add_action('parse_query', 'categories_by_issue');
?>
</code></pre>
<p>Is there a way I could request some information in my hook, ideally without involving direct SQL request?</p>
|
[
{
"answer_id": 191883,
"author": "Mayeenul Islam",
"author_id": 22728,
"author_profile": "https://wordpress.stackexchange.com/users/22728",
"pm_score": 0,
"selected": false,
"text": "<p>I din't try this. But what about making a function for fetching the <code>issue_id</code>? And remember, <code>wp_reset_postdata()</code> for a <code>WP_Query()</code> is important.</p>\n\n<pre><code>function get_the_issue_id() {\n $issues = new WP_Query( /* .... */ );\n $issue_id = $issues->get_posts()[0]->ID;\n wp_reset_postdata(); //it's important\n return (int) $issue_id; \n}\n</code></pre>\n\n<p>Now do the <code>parse_query</code> thing:</p>\n\n<pre><code>function categories_by_issue ($query) { \n if (! $query->is_category() || ! $query->is_main_query()) return;\n\n $query->set( 'connected_type', 'issue_to_posts');\n $query->set( 'connected_items', get_the_issue_id() ); //using the function\n $query->set( 'nopaging', true); \n} \nadd_action('parse_query', 'categories_by_issue');\n</code></pre>\n"
},
{
"answer_id": 191936,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 1,
"selected": false,
"text": "<p>You are invoking an infinite loop, because you are calling <code>WP_Query</code> inside <code>WP_Query</code>, which is where the hook resides, so you are hooking it into <code>parse_query</code> over and over again. To avoid it, put the following at the beginning of your callback function:</p>\n\n<pre><code>// avoid infinite loop\nremove_action( 'parse_query', __FUNCTION__ ); \n</code></pre>\n\n<p><br>\nAdditional note, it might just be a lesser technicality, but in my mind the right hook to use would be <code>pre_get_posts</code>.</p>\n"
},
{
"answer_id": 192113,
"author": "Jérémie",
"author_id": 38465,
"author_profile": "https://wordpress.stackexchange.com/users/38465",
"pm_score": 2,
"selected": true,
"text": "<p>I couldn't solve this issue but found a workaround : I get my issue ID on parse_request hook \nand use it in parse_query (I created a class with an $issue_id var, but global variable should be fine too). </p>\n\n<p>Still don't know why you can't use WP_Query directly in parse_query, but I opened ticket on Posts2Posts github : <a href=\"https://github.com/scribu/wp-posts-to-posts/issues/483\" rel=\"nofollow\">https://github.com/scribu/wp-posts-to-posts/issues/483</a></p>\n"
}
] |
2015/06/18
|
[
"https://wordpress.stackexchange.com/questions/191877",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/38465/"
] |
**UPDATE**:
The hook is working with "classic" Wordpress filter (like `post__in`), so it's probably a Posts2Posts issue. I'm still looking for suggestions if someone has any idea.
**ORIGINAL POST**
I'm trying to get all posts displayed by issue number in archive pages. Issues are a custom post type (linked with post2post, which is why I use `parse_query` instead of `pre_get_post`)
```
<?php
function categories_by_issue ($query) {
if (! $query->is_category() || ! $query->is_main_query()) return;
$query->set( 'connected_type', 'issue_to_posts');
$query->set( 'connected_items', 71); // 71 needs to be dynamic
$query->set( 'nopaging', true);
}
add_action('parse_query', 'categories_by_issue');
?>
```
This action hook **works fine**! Problem is: I need to get the issue ID with another query. (ID and issue number are of course different, my '#3' issue has '71' ID)
I tried to add a `WP_Query` in my hook, which basically break the whole thing. I can get my issue number, but the main query finally shows all posts.
```
<?php
function categories_by_issue ($query) {
if (! $query->is_category() || ! $query->is_main_query()) return;
$issues = new WP_Query ( /* ... */);
$issue_id = $issues->get_posts()[0]->ID;
var_dump($issue_id); // -> 71 : My ID is correct
$query->set( 'connected_type', 'issue_to_posts');
$query->set( 'connected_items', $issue_id);
$query->set( 'nopaging', true);
}
add_action('parse_query', 'categories_by_issue');
?>
```
Is there a way I could request some information in my hook, ideally without involving direct SQL request?
|
I couldn't solve this issue but found a workaround : I get my issue ID on parse\_request hook
and use it in parse\_query (I created a class with an $issue\_id var, but global variable should be fine too).
Still don't know why you can't use WP\_Query directly in parse\_query, but I opened ticket on Posts2Posts github : <https://github.com/scribu/wp-posts-to-posts/issues/483>
|
191,891 |
<p><strong>Plugin Class File:</strong></p>
<pre><code>function __construct()
{
add_shortcode('user_registration_form', array($this, 'shortcode'));
}
public function hook(){
add_action( 'wp_ajax_get_product_serial_callback', 'get_product_serial_callback' );
add_action( 'wp_ajax_nopriv_get_product_serial_callback', 'get_product_serial_callback' );
}
public function product_serial_ajax() { ?>
<script type="text/javascript">
jQuery(document).ready(function(){
alert('Hello World!');
jQuery.ajax({
type: 'GET',
url: "<?php echo admin_url('admin-ajax.php'); ?>",
//url: ajaxurl,
dataType : "JSON",
data : {action: "get_product_serial_callback"},
//cache: false,
success: function(data){
alert('Eureka')';
}
});
});
</script><?php
}
function csv_to_array($filename='', $delimiter=',')
{
//if(!file_exists($filename) || !is_readable($filename))
//return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1024, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
function get_product_serial_callback(){
$upload_dir = wp_upload_dir();
$csvFile = $upload_dir['baseurl'].'/Eragon-Serial.csv';
$csv = $this->csv_to_array($csvFile); //read csv
foreach ($csv as $serialnum){
$serial_num_array[] = $serialnum['product_serial'];
}
$json_array = json_encode($serial_num_array);
echo $json_array;
die();
}
function shortcode()
{
$this->product_serial_ajax();//fetch product serial number
}
</code></pre>
<p>However, when encountered <code>ajaxurl</code> is not defined, I changed it <code>ajaxurl</code> which forms in below URL </p>
<pre><code>http://example.com/wp-admin/admin-ajax.php?action=get_product_serial_callback
</code></pre>
<p><a href="https://stackoverflow.com/questions/17710728/how-to-load-ajax-in-wordpress">This</a> too did not helped.</p>
<p>How can I call <code>get_product_serial_callback</code> function in order to fetch the <code>JSON</code> values and set those values in <code>function(data)</code> ?</p>
|
[
{
"answer_id": 191894,
"author": "Domain",
"author_id": 26523,
"author_profile": "https://wordpress.stackexchange.com/users/26523",
"pm_score": 1,
"selected": false,
"text": "<p>Put below code in _construct() function and change action name to get_product_serial_callback :-</p>\n\n<pre><code>add_action( 'wp_ajax_get_product_serial_callback', array($this,'get_product_serial_callback') );\nadd_action( 'wp_ajax_nopriv_get_product_serial_callback', array($this,'get_product_serial_callback' ));\n</code></pre>\n"
},
{
"answer_id": 191905,
"author": "Slimshadddyyy",
"author_id": 66252,
"author_profile": "https://wordpress.stackexchange.com/users/66252",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Plugin Class File:</strong></p>\n\n<pre><code>function __construct()\n {\n\n\n add_shortcode('user_registration_form', array($this, 'shortcode'));\n wp_register_script('product-serial', plugins_url('bootstrap/js/product-serial.js', __FILE__),array('jquery')); //custom jquery for product serial\n wp_enqueue_script( 'product-serial' ); //custom jquery for product serial\n\n $this->hook();\n }\n\n public function hook()\n {\n add_action('wp_ajax_get_product_serial', array( $this,'get_product_serial'));\n add_action('wp_ajax_nopriv_get_product_serial',array( $this,'get_product_serial') );\n }\n\n public function product_serial_ajax(){ ?>\n\n <script type=\"text/javascript\">load_product();</script>\n\n <?php\n }\n\n\n\n //convert csv data into array\n function csv_to_array($filename='', $delimiter=',')\n {\n //if(!file_exists($filename) || !is_readable($filename))\n //return FALSE;\n\n $header = NULL;\n $data = array();\n if (($handle = fopen($filename, 'r')) !== FALSE)\n {\n while (($row = fgetcsv($handle, 1024, $delimiter)) !== FALSE)\n {\n if(!$header)\n $header = $row;\n else\n $data[] = array_combine($header, $row);\n }\n fclose($handle);\n }\n return $data;\n }\n\n\n //get product serial number\n function get_product_serial(){\n\n\n $upload_dir = wp_upload_dir();\n $csvFile = $upload_dir['baseurl'].'/Eragon-Serial.csv';\n $csv = $this->csv_to_array($csvFile); //read csv\n\n foreach ($csv as $serialnum){\n $serial_num_array[] = $serialnum['product_serial'];\n }\n\n $json_array = json_encode($serial_num_array);\n echo $json_array;\n die();\n }\n\n function shortcode()\n {\n $this->product_serial_ajax(); //fetch product serial number\n }\n</code></pre>\n\n<p><strong>Seperate JS file</strong></p>\n\n<pre><code> function load_product(){\n jQuery.ajax({\n type: \"GET\", \n url: ajaxurl,\n dataType : \"JSON\",\n data : {action: \"get_product_serial\"},\n //cache: false, \n success: function(data){\n alert('Eureka');\n }\n });\n }\n</code></pre>\n\n<p><strong>P.S: putting the following in the header.php of my theme worked for me</strong></p>\n\n<pre><code><script type=\"text/javascript\">\n var ajaxurl = \"<?php echo admin_url('admin-ajax.php'); ?>\";\n </script>\n</code></pre>\n"
}
] |
2015/06/18
|
[
"https://wordpress.stackexchange.com/questions/191891",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/66252/"
] |
**Plugin Class File:**
```
function __construct()
{
add_shortcode('user_registration_form', array($this, 'shortcode'));
}
public function hook(){
add_action( 'wp_ajax_get_product_serial_callback', 'get_product_serial_callback' );
add_action( 'wp_ajax_nopriv_get_product_serial_callback', 'get_product_serial_callback' );
}
public function product_serial_ajax() { ?>
<script type="text/javascript">
jQuery(document).ready(function(){
alert('Hello World!');
jQuery.ajax({
type: 'GET',
url: "<?php echo admin_url('admin-ajax.php'); ?>",
//url: ajaxurl,
dataType : "JSON",
data : {action: "get_product_serial_callback"},
//cache: false,
success: function(data){
alert('Eureka')';
}
});
});
</script><?php
}
function csv_to_array($filename='', $delimiter=',')
{
//if(!file_exists($filename) || !is_readable($filename))
//return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1024, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
function get_product_serial_callback(){
$upload_dir = wp_upload_dir();
$csvFile = $upload_dir['baseurl'].'/Eragon-Serial.csv';
$csv = $this->csv_to_array($csvFile); //read csv
foreach ($csv as $serialnum){
$serial_num_array[] = $serialnum['product_serial'];
}
$json_array = json_encode($serial_num_array);
echo $json_array;
die();
}
function shortcode()
{
$this->product_serial_ajax();//fetch product serial number
}
```
However, when encountered `ajaxurl` is not defined, I changed it `ajaxurl` which forms in below URL
```
http://example.com/wp-admin/admin-ajax.php?action=get_product_serial_callback
```
[This](https://stackoverflow.com/questions/17710728/how-to-load-ajax-in-wordpress) too did not helped.
How can I call `get_product_serial_callback` function in order to fetch the `JSON` values and set those values in `function(data)` ?
|
Put below code in \_construct() function and change action name to get\_product\_serial\_callback :-
```
add_action( 'wp_ajax_get_product_serial_callback', array($this,'get_product_serial_callback') );
add_action( 'wp_ajax_nopriv_get_product_serial_callback', array($this,'get_product_serial_callback' ));
```
|
191,896 |
<p>I am running into a headache trying to get some url rewriting working on a wordpress website, running Centos 6 for operating system.</p>
<p>This is what I am trying to achieve.</p>
<p><strong>Current URL = <a href="http://www.downer.co.uk/property-details/?propertyidtag=508362_166879S" rel="nofollow">http://www.downer.co.uk/property-details/?propertyidtag=508362_166879S</a></strong></p>
<p>I would like this to be re-written to </p>
<p><strong><a href="http://www.downer.co.uk/property-details/508362_166879S/" rel="nofollow">http://www.downer.co.uk/property-details/508362_166879S/</a></strong></p>
<p>I must of tried every tuturial online with absolutely no success.
Please help me!!</p>
|
[
{
"answer_id": 191894,
"author": "Domain",
"author_id": 26523,
"author_profile": "https://wordpress.stackexchange.com/users/26523",
"pm_score": 1,
"selected": false,
"text": "<p>Put below code in _construct() function and change action name to get_product_serial_callback :-</p>\n\n<pre><code>add_action( 'wp_ajax_get_product_serial_callback', array($this,'get_product_serial_callback') );\nadd_action( 'wp_ajax_nopriv_get_product_serial_callback', array($this,'get_product_serial_callback' ));\n</code></pre>\n"
},
{
"answer_id": 191905,
"author": "Slimshadddyyy",
"author_id": 66252,
"author_profile": "https://wordpress.stackexchange.com/users/66252",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Plugin Class File:</strong></p>\n\n<pre><code>function __construct()\n {\n\n\n add_shortcode('user_registration_form', array($this, 'shortcode'));\n wp_register_script('product-serial', plugins_url('bootstrap/js/product-serial.js', __FILE__),array('jquery')); //custom jquery for product serial\n wp_enqueue_script( 'product-serial' ); //custom jquery for product serial\n\n $this->hook();\n }\n\n public function hook()\n {\n add_action('wp_ajax_get_product_serial', array( $this,'get_product_serial'));\n add_action('wp_ajax_nopriv_get_product_serial',array( $this,'get_product_serial') );\n }\n\n public function product_serial_ajax(){ ?>\n\n <script type=\"text/javascript\">load_product();</script>\n\n <?php\n }\n\n\n\n //convert csv data into array\n function csv_to_array($filename='', $delimiter=',')\n {\n //if(!file_exists($filename) || !is_readable($filename))\n //return FALSE;\n\n $header = NULL;\n $data = array();\n if (($handle = fopen($filename, 'r')) !== FALSE)\n {\n while (($row = fgetcsv($handle, 1024, $delimiter)) !== FALSE)\n {\n if(!$header)\n $header = $row;\n else\n $data[] = array_combine($header, $row);\n }\n fclose($handle);\n }\n return $data;\n }\n\n\n //get product serial number\n function get_product_serial(){\n\n\n $upload_dir = wp_upload_dir();\n $csvFile = $upload_dir['baseurl'].'/Eragon-Serial.csv';\n $csv = $this->csv_to_array($csvFile); //read csv\n\n foreach ($csv as $serialnum){\n $serial_num_array[] = $serialnum['product_serial'];\n }\n\n $json_array = json_encode($serial_num_array);\n echo $json_array;\n die();\n }\n\n function shortcode()\n {\n $this->product_serial_ajax(); //fetch product serial number\n }\n</code></pre>\n\n<p><strong>Seperate JS file</strong></p>\n\n<pre><code> function load_product(){\n jQuery.ajax({\n type: \"GET\", \n url: ajaxurl,\n dataType : \"JSON\",\n data : {action: \"get_product_serial\"},\n //cache: false, \n success: function(data){\n alert('Eureka');\n }\n });\n }\n</code></pre>\n\n<p><strong>P.S: putting the following in the header.php of my theme worked for me</strong></p>\n\n<pre><code><script type=\"text/javascript\">\n var ajaxurl = \"<?php echo admin_url('admin-ajax.php'); ?>\";\n </script>\n</code></pre>\n"
}
] |
2015/06/18
|
[
"https://wordpress.stackexchange.com/questions/191896",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74877/"
] |
I am running into a headache trying to get some url rewriting working on a wordpress website, running Centos 6 for operating system.
This is what I am trying to achieve.
**Current URL = <http://www.downer.co.uk/property-details/?propertyidtag=508362_166879S>**
I would like this to be re-written to
**<http://www.downer.co.uk/property-details/508362_166879S/>**
I must of tried every tuturial online with absolutely no success.
Please help me!!
|
Put below code in \_construct() function and change action name to get\_product\_serial\_callback :-
```
add_action( 'wp_ajax_get_product_serial_callback', array($this,'get_product_serial_callback') );
add_action( 'wp_ajax_nopriv_get_product_serial_callback', array($this,'get_product_serial_callback' ));
```
|
191,923 |
<h2>Summary</h2>
<p>Because of a bug in WP Core, sending <a href="https://en.wikipedia.org/wiki/MIME">multipart</a> emails (html/text) with <a href="https://codex.wordpress.org/Function_Reference/wp_mail">wp_mail()</a> (to reduce chance of emails ending up in spam folders) will <em>ironically</em> result with your domain being blocked by Hotmail (and other Microsoft emails). </p>
<p>This is a complex problem that I'll aim to break down in great detail in an attempt to help someone find a workable solution which may eventually be implemented in core. </p>
<p><strong>It's going to be a rewarding read. Let's begin...</strong></p>
<h2>The bug</h2>
<p>The most common advice to avoid having your newsletter emails ending up in spam folders is to send multipart messages.</p>
<p>Multi-part (mime) refers to sending both an HTML and TEXT part of an email message in a single email. When a client receives a multipart message, it accepts the HTML version if it can render HTML, otherwise it presents the plain text version. </p>
<p>This is proven to work. When sending to gmail, all our emails landed in spam folders until we changed the messages to multipart when they came through to main inbox. Great stuff. </p>
<p>Now, when sending multipart messages via wp_mail(), it outputs the Content Type (multipart/*) twice, once with boundary (if customly set) and once without. This behaviour results with the email being displayed as a raw message and not multipart on some emails, including <strong>all</strong> Microsoft (Hotmail, Outlook, etc...)</p>
<p>Microsoft will flag this message as junk, and the few messages that comes through will be flagged manually by the recipient. <em>Unfortunately</em>, Microsoft emails addresses are widely used. 40% of our subscribers use it. </p>
<p>This is confirmed by Microsoft via an email exchange we had recently.</p>
<p>The flagging of the messages will result with the domain being completely <strong>blocked</strong>. This means that message will not be sent to spam folder, <strong>they will not even be delivered</strong> to the recipient at all. </p>
<p>We have had our main domain blocked 3 times so far. </p>
<p>Because this is a bug in the WP core, <strong>every</strong> domain that sends multipart messages are being blocked. The problem is that most webmasters do not know why. I have confirmed this when doing my research and seeing other users discussing this on forums etc. It requires delving into the raw code and having a good knowledge of how these type of email messages work, which we are going on to next...</p>
<h2>Let's break it down into code</h2>
<p>Create a hotmail/outlook account. Then, run the following code:</p>
<pre><code>// Set $to to an hotmail.com or outlook.com email
$to = "[email protected]";
$subject = 'wp_mail testing multipart';
$message = '------=_Part_18243133_1346573420.1408991447668
Content-Type: text/plain; charset=UTF-8
Hello world! This is plain text...
------=_Part_18243133_1346573420.1408991447668
Content-Type: text/html; charset=UTF-8
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<p>Hello World! This is HTML...</p>
</body>
</html>
------=_Part_18243133_1346573420.1408991447668--';
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From: Foo <[email protected]>\r\n";
$headers .= 'Content-Type: multipart/alternative;boundary="----=_Part_18243133_1346573420.1408991447668"';
// send email
wp_mail( $to, $subject, $message, $headers );
</code></pre>
<p>And if you want to change the <a href="http://codex.wordpress.org/Plugin_API/Filter_Reference/wp_mail_content_type">default content type</a>, use: </p>
<pre><code>add_filter( 'wp_mail_content_type', 'set_content_type' );
function set_content_type( $content_type ) {
return 'multipart/alternative';
}
</code></pre>
<p>This will send a multipart message. </p>
<p>So if you check the full raw source of the message, you'll notice that the content type is added twice, once without boundary: </p>
<pre><code>MIME-Version: 1.0
Content-Type: multipart/alternative;
boundary="====f230673f9d7c359a81ffebccb88e5d61=="
MIME-Version: 1.0
Content-Type: multipart/alternative; charset=
</code></pre>
<p>That's the issue. </p>
<p>The source of the problem lies in <code>pluggable.php</code> - if we look somewhere here: </p>
<pre><code>// Set Content-Type and charset
// If we don't have a content-type from the input headers
if ( !isset( $content_type ) )
$content_type = 'text/plain';
/**
* Filter the wp_mail() content type.
*
* @since 2.3.0
*
* @param string $content_type Default wp_mail() content type.
*/
$content_type = apply_filters( 'wp_mail_content_type', $content_type );
$phpmailer->ContentType = $content_type;
// Set whether it's plaintext, depending on $content_type
if ( 'text/html' == $content_type )
$phpmailer->IsHTML( true );
// If we don't have a charset from the input headers
if ( !isset( $charset ) )
$charset = get_bloginfo( 'charset' );
// Set the content-type and charset
/**
* Filter the default wp_mail() charset.
*
* @since 2.3.0
*
* @param string $charset Default email charset.
*/
$phpmailer->CharSet = apply_filters( 'wp_mail_charset', $charset );
// Set custom headers
if ( !empty( $headers ) ) {
foreach( (array) $headers as $name => $content ) {
$phpmailer->AddCustomHeader( sprintf( '%1$s: %2$s', $name, $content ) );
}
if ( false !== stripos( $content_type, 'multipart' ) && ! empty($boundary) )
$phpmailer->AddCustomHeader( sprintf( "Content-Type: %s;\n\t boundary=\"%s\"", $content_type, $boundary ) );
}
if ( !empty( $attachments ) ) {
foreach ( $attachments as $attachment ) {
try {
$phpmailer->AddAttachment($attachment);
} catch ( phpmailerException $e ) {
continue;
}
}
}
</code></pre>
<h2>Potential solutions</h2>
<p>So you are wondering, <strong>why have you not reported this at <a href="https://core.trac.wordpress.org/">trac</a>?</strong> I <a href="https://core.trac.wordpress.org/ticket/31653">already have</a>. To my great surprise, a <a href="https://core.trac.wordpress.org/ticket/15448">different ticket</a> was created 5 years ago outlining the same problem. </p>
<p>Let's face it, it's been a half decade. In internet years, that is more like 30. The issue has clearly been abandoned and basically will never be fixed (...unless if we resolve it here).</p>
<p>I found a great <a href="https://wordpress.org/support/topic/using-wp_mail-with-php-generated-attachments">thread here</a> offering a solution, but while his solution works, it breaks emails that do not have custom <code>$headers</code> set.</p>
<p>That's where we crash every time. Either the multipart version work fine, and normal unset <code>$headers</code> messages don't, or vise verse. </p>
<p>The solution we came up with was: </p>
<pre><code>if ( false !== stripos( $content_type, 'multipart' ) && ! empty($boundary) ) {
$phpmailer->ContentType = $content_type . "; boundary=" . $boundary;
}
else {
$content_type = apply_filters( 'wp_mail_content_type', $content_type );
$phpmailer->ContentType = $content_type;
// Set whether it's plaintext, depending on $content_type
if ( 'text/html' == $content_type )
$phpmailer->IsHTML( true );
// If we don't have a charset from the input headers
if ( !isset( $charset ) )
$charset = get_bloginfo( 'charset' );
}
// Set the content-type and charset
/**
* Filter the default wp_mail() charset.
*
* @since 2.3.0
*
* @param string $charset Default email charset.
*/
$phpmailer->CharSet = apply_filters( 'wp_mail_charset', $charset );
// Set custom headers
if ( !empty( $headers ) ) {
foreach( (array) $headers as $name => $content ) {
$phpmailer->AddCustomHeader( sprintf( '%1$s: %2$s', $name, $content ) );
}
}
</code></pre>
<p>Yes, I know, editing core files are taboo, sit back down... this was a desperate fix and a poor attempt to provide a fix for core. </p>
<p>The problem with our fix is that default emails like new registrations, comment, password reset etc will be delivered as blank messages. So we have a working wp_mail() script that will send multipart messages but nothing else. </p>
<h2>What to do</h2>
<p>The aim here is to find a way to send both normal (plain text) and multipart messages <strong>using the core wp_mail() function</strong> (not a custom sendmail function). </p>
<p>When attempting to solve this, the main problem you will encounter is the amount of time that you'll spend on sending dummy messages, checking if they're received and basically opening a box of aspirin and cursing at Microsoft because you are used to their IE issues while the gremlin here is unfortunately WordPress. </p>
<h2>Update</h2>
<p>The solution posted by @bonger allows <code>$message</code> to be an array containing content-type keyed alternates. I have confirmed that it works in all scenarios.</p>
<p>We will allow this question to remain open until bounty runs out to raise awareness about the problem, <strong>maybe to a level where it will be fixed in core.</strong> Feel free to post an alternative solution where <code>$message</code> can be a string. </p>
|
[
{
"answer_id": 191974,
"author": "bonger",
"author_id": 57034,
"author_profile": "https://wordpress.stackexchange.com/users/57034",
"pm_score": 5,
"selected": true,
"text": "<p>The following version of <code>wp_mail()</code> is with the patch applied of @rmccue/@MattyRob in the ticket <a href=\"https://core.trac.wordpress.org/ticket/15448\" rel=\"noreferrer\">https://core.trac.wordpress.org/ticket/15448</a>, refreshed for 4.2.2, which allows <code>$message</code> to be an array containing content-type keyed alternates:</p>\n\n<pre><code>/**\n * Send mail, similar to PHP's mail\n *\n * A true return value does not automatically mean that the user received the\n * email successfully. It just only means that the method used was able to\n * process the request without any errors.\n *\n * Using the two 'wp_mail_from' and 'wp_mail_from_name' hooks allow from\n * creating a from address like 'Name <[email protected]>' when both are set. If\n * just 'wp_mail_from' is set, then just the email address will be used with no\n * name.\n *\n * The default content type is 'text/plain' which does not allow using HTML.\n * However, you can set the content type of the email by using the\n * 'wp_mail_content_type' filter.\n *\n * If $message is an array, the key of each is used to add as an attachment\n * with the value used as the body. The 'text/plain' element is used as the\n * text version of the body, with the 'text/html' element used as the HTML\n * version of the body. All other types are added as attachments.\n *\n * The default charset is based on the charset used on the blog. The charset can\n * be set using the 'wp_mail_charset' filter.\n *\n * @since 1.2.1\n *\n * @uses PHPMailer\n *\n * @param string|array $to Array or comma-separated list of email addresses to send message.\n * @param string $subject Email subject\n * @param string|array $message Message contents\n * @param string|array $headers Optional. Additional headers.\n * @param string|array $attachments Optional. Files to attach.\n * @return bool Whether the email contents were sent successfully.\n */\nfunction wp_mail( $to, $subject, $message, $headers = '', $attachments = array() ) {\n // Compact the input, apply the filters, and extract them back out\n\n /**\n * Filter the wp_mail() arguments.\n *\n * @since 2.2.0\n *\n * @param array $args A compacted array of wp_mail() arguments, including the \"to\" email,\n * subject, message, headers, and attachments values.\n */\n $atts = apply_filters( 'wp_mail', compact( 'to', 'subject', 'message', 'headers', 'attachments' ) );\n\n if ( isset( $atts['to'] ) ) {\n $to = $atts['to'];\n }\n\n if ( isset( $atts['subject'] ) ) {\n $subject = $atts['subject'];\n }\n\n if ( isset( $atts['message'] ) ) {\n $message = $atts['message'];\n }\n\n if ( isset( $atts['headers'] ) ) {\n $headers = $atts['headers'];\n }\n\n if ( isset( $atts['attachments'] ) ) {\n $attachments = $atts['attachments'];\n }\n\n if ( ! is_array( $attachments ) ) {\n $attachments = explode( \"\\n\", str_replace( \"\\r\\n\", \"\\n\", $attachments ) );\n }\n global $phpmailer;\n\n // (Re)create it, if it's gone missing\n if ( ! ( $phpmailer instanceof PHPMailer ) ) {\n require_once ABSPATH . WPINC . '/class-phpmailer.php';\n require_once ABSPATH . WPINC . '/class-smtp.php';\n $phpmailer = new PHPMailer( true );\n }\n\n // Headers\n if ( empty( $headers ) ) {\n $headers = array();\n } else {\n if ( !is_array( $headers ) ) {\n // Explode the headers out, so this function can take both\n // string headers and an array of headers.\n $tempheaders = explode( \"\\n\", str_replace( \"\\r\\n\", \"\\n\", $headers ) );\n } else {\n $tempheaders = $headers;\n }\n $headers = array();\n $cc = array();\n $bcc = array();\n\n // If it's actually got contents\n if ( !empty( $tempheaders ) ) {\n // Iterate through the raw headers\n foreach ( (array) $tempheaders as $header ) {\n if ( strpos($header, ':') === false ) {\n if ( false !== stripos( $header, 'boundary=' ) ) {\n $parts = preg_split('/boundary=/i', trim( $header ) );\n $boundary = trim( str_replace( array( \"'\", '\"' ), '', $parts[1] ) );\n }\n continue;\n }\n // Explode them out\n list( $name, $content ) = explode( ':', trim( $header ), 2 );\n\n // Cleanup crew\n $name = trim( $name );\n $content = trim( $content );\n\n switch ( strtolower( $name ) ) {\n // Mainly for legacy -- process a From: header if it's there\n case 'from':\n $bracket_pos = strpos( $content, '<' );\n if ( $bracket_pos !== false ) {\n // Text before the bracketed email is the \"From\" name.\n if ( $bracket_pos > 0 ) {\n $from_name = substr( $content, 0, $bracket_pos - 1 );\n $from_name = str_replace( '\"', '', $from_name );\n $from_name = trim( $from_name );\n }\n\n $from_email = substr( $content, $bracket_pos + 1 );\n $from_email = str_replace( '>', '', $from_email );\n $from_email = trim( $from_email );\n\n // Avoid setting an empty $from_email.\n } elseif ( '' !== trim( $content ) ) {\n $from_email = trim( $content );\n }\n break;\n case 'content-type':\n if ( is_array($message) ) {\n // Multipart email, ignore the content-type header\n break;\n }\n if ( strpos( $content, ';' ) !== false ) {\n list( $type, $charset_content ) = explode( ';', $content );\n $content_type = trim( $type );\n if ( false !== stripos( $charset_content, 'charset=' ) ) {\n $charset = trim( str_replace( array( 'charset=', '\"' ), '', $charset_content ) );\n } elseif ( false !== stripos( $charset_content, 'boundary=' ) ) {\n $boundary = trim( str_replace( array( 'BOUNDARY=', 'boundary=', '\"' ), '', $charset_content ) );\n $charset = '';\n }\n\n // Avoid setting an empty $content_type.\n } elseif ( '' !== trim( $content ) ) {\n $content_type = trim( $content );\n }\n break;\n case 'cc':\n $cc = array_merge( (array) $cc, explode( ',', $content ) );\n break;\n case 'bcc':\n $bcc = array_merge( (array) $bcc, explode( ',', $content ) );\n break;\n default:\n // Add it to our grand headers array\n $headers[trim( $name )] = trim( $content );\n break;\n }\n }\n }\n }\n\n // Empty out the values that may be set\n $phpmailer->ClearAllRecipients();\n $phpmailer->ClearAttachments();\n $phpmailer->ClearCustomHeaders();\n $phpmailer->ClearReplyTos();\n\n $phpmailer->Body= '';\n $phpmailer->AltBody= '';\n\n // From email and name\n // If we don't have a name from the input headers\n if ( !isset( $from_name ) )\n $from_name = 'WordPress';\n\n /* If we don't have an email from the input headers default to wordpress@$sitename\n * Some hosts will block outgoing mail from this address if it doesn't exist but\n * there's no easy alternative. Defaulting to admin_email might appear to be another\n * option but some hosts may refuse to relay mail from an unknown domain. See\n * https://core.trac.wordpress.org/ticket/5007.\n */\n\n if ( !isset( $from_email ) ) {\n // Get the site domain and get rid of www.\n $sitename = strtolower( $_SERVER['SERVER_NAME'] );\n if ( substr( $sitename, 0, 4 ) == 'www.' ) {\n $sitename = substr( $sitename, 4 );\n }\n\n $from_email = 'wordpress@' . $sitename;\n }\n\n /**\n * Filter the email address to send from.\n *\n * @since 2.2.0\n *\n * @param string $from_email Email address to send from.\n */\n $phpmailer->From = apply_filters( 'wp_mail_from', $from_email );\n\n /**\n * Filter the name to associate with the \"from\" email address.\n *\n * @since 2.3.0\n *\n * @param string $from_name Name associated with the \"from\" email address.\n */\n $phpmailer->FromName = apply_filters( 'wp_mail_from_name', $from_name );\n\n // Set destination addresses\n if ( !is_array( $to ) )\n $to = explode( ',', $to );\n\n foreach ( (array) $to as $recipient ) {\n try {\n // Break $recipient into name and address parts if in the format \"Foo <[email protected]>\"\n $recipient_name = '';\n if( preg_match( '/(.*)<(.+)>/', $recipient, $matches ) ) {\n if ( count( $matches ) == 3 ) {\n $recipient_name = $matches[1];\n $recipient = $matches[2];\n }\n }\n $phpmailer->AddAddress( $recipient, $recipient_name);\n } catch ( phpmailerException $e ) {\n continue;\n }\n }\n\n // If we don't have a charset from the input headers\n if ( !isset( $charset ) )\n $charset = get_bloginfo( 'charset' );\n\n // Set the content-type and charset\n\n /**\n * Filter the default wp_mail() charset.\n *\n * @since 2.3.0\n *\n * @param string $charset Default email charset.\n */\n $phpmailer->CharSet = apply_filters( 'wp_mail_charset', $charset );\n\n // Set mail's subject and body\n $phpmailer->Subject = $subject;\n\n if ( is_string($message) ) {\n $phpmailer->Body = $message;\n\n // Set Content-Type and charset\n // If we don't have a content-type from the input headers\n if ( !isset( $content_type ) )\n $content_type = 'text/plain';\n\n /**\n * Filter the wp_mail() content type.\n *\n * @since 2.3.0\n *\n * @param string $content_type Default wp_mail() content type.\n */\n $content_type = apply_filters( 'wp_mail_content_type', $content_type );\n\n $phpmailer->ContentType = $content_type;\n\n // Set whether it's plaintext, depending on $content_type\n if ( 'text/html' == $content_type )\n $phpmailer->IsHTML( true );\n\n // For backwards compatibility, new multipart emails should use\n // the array style $message. This never really worked well anyway\n if ( false !== stripos( $content_type, 'multipart' ) && ! empty($boundary) )\n $phpmailer->AddCustomHeader( sprintf( \"Content-Type: %s;\\n\\t boundary=\\\"%s\\\"\", $content_type, $boundary ) );\n }\n elseif ( is_array($message) ) {\n foreach ($message as $type => $bodies) {\n foreach ((array) $bodies as $body) {\n if ($type === 'text/html') {\n $phpmailer->Body = $body;\n }\n elseif ($type === 'text/plain') {\n $phpmailer->AltBody = $body;\n }\n else {\n $phpmailer->AddAttachment($body, '', 'base64', $type);\n }\n }\n }\n }\n\n // Add any CC and BCC recipients\n if ( !empty( $cc ) ) {\n foreach ( (array) $cc as $recipient ) {\n try {\n // Break $recipient into name and address parts if in the format \"Foo <[email protected]>\"\n $recipient_name = '';\n if( preg_match( '/(.*)<(.+)>/', $recipient, $matches ) ) {\n if ( count( $matches ) == 3 ) {\n $recipient_name = $matches[1];\n $recipient = $matches[2];\n }\n }\n $phpmailer->AddCc( $recipient, $recipient_name );\n } catch ( phpmailerException $e ) {\n continue;\n }\n }\n }\n\n if ( !empty( $bcc ) ) {\n foreach ( (array) $bcc as $recipient) {\n try {\n // Break $recipient into name and address parts if in the format \"Foo <[email protected]>\"\n $recipient_name = '';\n if( preg_match( '/(.*)<(.+)>/', $recipient, $matches ) ) {\n if ( count( $matches ) == 3 ) {\n $recipient_name = $matches[1];\n $recipient = $matches[2];\n }\n }\n $phpmailer->AddBcc( $recipient, $recipient_name );\n } catch ( phpmailerException $e ) {\n continue;\n }\n }\n }\n\n // Set to use PHP's mail()\n $phpmailer->IsMail();\n\n // Set custom headers\n if ( !empty( $headers ) ) {\n foreach ( (array) $headers as $name => $content ) {\n $phpmailer->AddCustomHeader( sprintf( '%1$s: %2$s', $name, $content ) );\n }\n }\n\n if ( !empty( $attachments ) ) {\n foreach ( $attachments as $attachment ) {\n try {\n $phpmailer->AddAttachment($attachment);\n } catch ( phpmailerException $e ) {\n continue;\n }\n }\n }\n\n /**\n * Fires after PHPMailer is initialized.\n *\n * @since 2.2.0\n *\n * @param PHPMailer &$phpmailer The PHPMailer instance, passed by reference.\n */\n do_action_ref_array( 'phpmailer_init', array( &$phpmailer ) );\n\n // Send!\n try {\n return $phpmailer->Send();\n } catch ( phpmailerException $e ) {\n return false;\n }\n}\n</code></pre>\n\n<p>So if you put that in your eg \"wp-content/mu-plugins/functions.php\" file then it will override the WP version. It has a nice usage without any messing around with headers, eg:</p>\n\n<pre><code>// Set $to to an hotmail.com or outlook.com email\n$to = \"[email protected]\";\n\n$subject = 'wp_mail testing multipart';\n\n$message['text/plain'] = 'Hello world! This is plain text...';\n$message['text/html'] = '<html>\n<head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n</head>\n<body>\n\n<p>Hello World! This is HTML...</p> \n\n</body>\n</html>';\n\nadd_filter( 'wp_mail_from', $from_func = function ( $from_email ) { return '[email protected]'; } );\nadd_filter( 'wp_mail_from_name', $from_name_func = function ( $from_name ) { return 'Foo'; } );\n\n// send email\nwp_mail( $to, $subject, $message );\n\nremove_filter( 'wp_mail_from', $from_func );\nremove_filter( 'wp_mail_from_name', $from_name_func );\n</code></pre>\n\n<p>Please note I haven't tested this with actual emails...</p>\n"
},
{
"answer_id": 194131,
"author": "chifliiiii",
"author_id": 4130,
"author_profile": "https://wordpress.stackexchange.com/users/4130",
"pm_score": 2,
"selected": false,
"text": "<p>I just <a href=\"http://wordpress.org/plugins/email-templates/\" rel=\"nofollow noreferrer\">released a plugin</a> to let users use html templates on WordPress and I'm playing right now on the <a href=\"http://github.com/timersys/wordpress-email-templates\" rel=\"nofollow noreferrer\">dev version</a> to add a simple text fallback. I did the following and in my tests I only see one boundary added and emails are arriving fine to Hotmail.</p>\n\n<pre><code>add_action( 'phpmailer_init', array($this->mailer, 'send_email' ) );\n\n/**\n* Modify php mailer body with final email\n*\n* @since 1.0.0\n* @param object $phpmailer\n*/\nfunction send_email( $phpmailer ) {\n\n $message = $this->add_template( apply_filters( 'mailtpl/email_content', $phpmailer->Body ) );\n $phpmailer->AltBody = $this->replace_placeholders( strip_tags($phpmailer->Body) );\n $phpmailer->Body = $this->replace_placeholders( $message );\n}\n</code></pre>\n\n<p>So basically what I do in here is modify the phpmailer object , load the message inside an HTML template and set it to the Body property. Also I took the original message and set the AltBody property.</p>\n"
},
{
"answer_id": 227702,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 3,
"selected": false,
"text": "<p><strong>TLDR</strong>, the simple solution is:</p>\n<pre><code>add_action('phpmailer_init','wp_mail_set_text_body');\nfunction wp_mail_set_text_body($phpmailer) {\n if (empty($phpmailer->AltBody)) {$phpmailer->AltBody = wp_strip_all_tags($phpmailer->Body);}\n}\n</code></pre>\n<p>Then you don't need to set the headers explicitly at all, the header boundaries are set correctly for you.</p>\n<p>Read on to for a detailed explanation as to why...</p>\n<p>This is not really a WordPress bug at all, it is a <code>phpmailer</code> one in not allowing for custom headers... if you look at <code>class-phpmailer.php</code>:</p>\n<pre><code>public function getMailMIME()\n{\n $result = '';\n $ismultipart = true;\n switch ($this->message_type) {\n case 'inline':\n $result .= $this->headerLine('Content-Type', 'multipart/related;');\n $result .= $this->textLine("\\tboundary=\\"" . $this->boundary[1] . '"');\n break;\n case 'attach':\n case 'inline_attach':\n case 'alt_attach':\n case 'alt_inline_attach':\n $result .= $this->headerLine('Content-Type', 'multipart/mixed;');\n $result .= $this->textLine("\\tboundary=\\"" . $this->boundary[1] . '"');\n break;\n case 'alt':\n case 'alt_inline':\n $result .= $this->headerLine('Content-Type', 'multipart/alternative;');\n $result .= $this->textLine("\\tboundary=\\"" . $this->boundary[1] . '"');\n break;\n default:\n // Catches case 'plain': and case '':\n $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet);\n $ismultipart = false;\n break;\n }\n</code></pre>\n<p>You can see the offending default case is what is outputting the extra header line with charset and no boundary. Setting the content type by filter does not solve this by itself only because the <code>alt</code> case here is set on <code>message_type</code> by checking <code>AltBody</code> is not empty rather than the content type.</p>\n<pre><code>protected function setMessageType()\n{\n $type = array();\n if ($this->alternativeExists()) {\n $type[] = 'alt';\n }\n if ($this->inlineImageExists()) {\n $type[] = 'inline';\n }\n if ($this->attachmentExists()) {\n $type[] = 'attach';\n }\n $this->message_type = implode('_', $type);\n if ($this->message_type == '') {\n $this->message_type = 'plain';\n }\n}\n\npublic function alternativeExists()\n{\n return !empty($this->AltBody);\n}\n</code></pre>\n<p>In the end what this means is as soon as you attach a file or inline image, or set the <code>AltBody</code>, the offending bug should be bypassed. It also means there is no need to explicitly set the content type because as soon as there is an <code>AltBody</code> it is set to <code>multipart/alternative</code> by <code>phpmailer</code>.</p>\n<p>So the simple answer is:</p>\n<pre><code>add_action('phpmailer_init','wp_mail_set_text_body');\nfunction wp_mail_set_text_body($phpmailer) {\n if (empty($phpmailer->AltBody)) {$phpmailer->AltBody = wp_strip_all_tags($phpmailer->Body);}\n}\n</code></pre>\n<p>Then you don't need to set the headers explicitly, you can simply do:</p>\n<pre><code> $message ='<html>\n <head>\n <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />\n </head>\n <body>\n <p>Hello World! This is HTML...</p> \n </body>\n </html>';\n\n wp_mail($to,$subject,$message);\n</code></pre>\n<p>Unforunately many of the functions and properties in the <code>phpmailer</code> class are protected, if not for that a valid alternative would be to simply check and override the <code>MIMEHeaders</code> property via the <code>phpmailer_init</code> hook before sending.</p>\n"
},
{
"answer_id": 242277,
"author": "Frugan",
"author_id": 99214,
"author_profile": "https://wordpress.stackexchange.com/users/99214",
"pm_score": 2,
"selected": false,
"text": "<p>My simply solution is to use html2text <a href=\"https://github.com/soundasleep/html2text\" rel=\"nofollow noreferrer\">https://github.com/soundasleep/html2text</a> in this way:</p>\n<pre><code>add_action( 'phpmailer_init', 'phpmailer_init' );\n\n//http://wordpress.stackexchange.com/a/191974\n//http://stackoverflow.com/a/2564472\nfunction phpmailer_init( $phpmailer )\n{\n if( $phpmailer->ContentType == 'text/html' ) {\n $phpmailer->AltBody = Html2Text\\Html2Text::convert( $phpmailer->Body );\n }\n}\n</code></pre>\n<p>Here <a href=\"https://gist.github.com/frugan-it/6c4d22cd856456480bd77b988b5c9e80\" rel=\"nofollow noreferrer\">https://gist.github.com/frugan-it/6c4d22cd856456480bd77b988b5c9e80</a> also a gist about.</p>\n"
},
{
"answer_id": 253956,
"author": "Olly",
"author_id": 111758,
"author_profile": "https://wordpress.stackexchange.com/users/111758",
"pm_score": 2,
"selected": false,
"text": "<p>This might not be an exact answer to the initial post here, but it's an alternative to some of the solutions here provided regarding setting an alt body</p>\n\n<p>Essentially, I needed to (wanted to) set a distinct altbody (i.e plain text) additionally to the HTML part instead of relying on some conversion/striptags and whatnot.</p>\n\n<p>So I came up with this which seems to work just fine:</p>\n\n<pre><code>/* setting the message parts for wp_mail()*/\n$markup = array();\n$markup['html'] = '<html>some html</html>';\n$markup['plaintext'] = 'some plaintext';\n/* message we are sending */ \n$message = maybe_serialize($markup);\n\n\n/* setting alt body distinctly */\nadd_action('phpmailer_init', array($this, 'set_alt_mail_body'));\n\nfunction set_alt_mail_body($phpmailer){\n if( $phpmailer->ContentType == 'text/html' ) {\n $body_parts = maybe_unserialize($phpmailer->Body);\n\n if(!empty($body_parts['html'])){\n $phpmailer->MsgHTML($body_parts['html']);\n }\n\n if(!empty($body_parts['plaintext'])){\n $phpmailer->AltBody = $body_parts['plaintext'];\n }\n } \n}\n</code></pre>\n"
},
{
"answer_id": 314470,
"author": "Joshua Reyes",
"author_id": 150797,
"author_profile": "https://wordpress.stackexchange.com/users/150797",
"pm_score": 1,
"selected": false,
"text": "<p>If you do not want to create any code conflict in the WordPress core, I think the alternative or simplest solution is to add action to <code>phpmailer_init</code> that will do before the actual sending of mail in the <code>wp_mail()</code> function. To simplify my explanation see the below code example:</p>\n\n<pre><code><?php \n\n$to = '';\n$subject = '';\n$from = '';\n$body = 'The text html content, <html>...';\n\n$headers = \"FROM: {$from}\";\n\nadd_action( 'phpmailer_init', function ( $phpmailer ) {\n $phpmailer->AltBody = 'The text plain content of your original text html content.';\n} );\n\nwp_mail($to, $subject, $body, $headers);\n</code></pre>\n\n<p>If you add content in the PHPMailer class <code>AltBody</code> property then the default content type will automatically set to <code>multipart/alternative</code>.</p>\n"
},
{
"answer_id": 316829,
"author": "Tanuki",
"author_id": 37903,
"author_profile": "https://wordpress.stackexchange.com/users/37903",
"pm_score": 2,
"selected": false,
"text": "<p>For anyone that's using the <code>phpmailer_init</code> hook to add their own 'AltBody':</p>\n\n<p>The alternative text body is <strong>reused</strong> for different consecutive mails being sent, unless you clear it manually! WordPress doesn't clear it in <code>wp_mail()</code> because it doesn't expect this property to be used.</p>\n\n<p>This results in recipients potentially receiving mails not meant for them. Luckily most people using HTML-enabled mail clients won’t see the text version, but it’s still basically a security problem.</p>\n\n<p>Luckily there's an easy fix. This includes the altbody replacement bit; note that you do need Html2Text PHP library:</p>\n\n<pre><code>add_filter( 'wp_mail', 'wpse191923_force_phpmailer_reinit_for_multiple_mails', -1 );\nfunction wpse191923_force_phpmailer_reinit_for_multiple_mails( $wp_mail_atts ) {\n global $phpmailer;\n\n if ( $phpmailer instanceof PHPMailer && $phpmailer->alternativeExists() ) {\n // AltBody property is set, so WordPress must already have used this\n // $phpmailer object just now to send mail, so let's\n // clear the AltBody property\n $phpmailer->AltBody = '';\n }\n\n // Return untouched atts\n return $wp_mail_atts;\n}\n\nadd_action( 'phpmailer_init', 'wpse191923_phpmailer_init_altbody', 1000, 1 );\nfunction wpse191923_phpmailer_init_altbody( $phpmailer ) {\n if ( ( $phpmailer->ContentType == 'text/html' ) && empty( $phpmailer->AltBody ) ) {\n if ( ! class_exists( 'Html2Text\\Html2Text' ) ) {\n require_once( 'Html2Text.php' );\n }\n if ( ! class_exists( 'Html2Text\\Html2TextException' ) ) {\n require_once( 'Html2TextException.php' );\n }\n $phpmailer->AltBody = Html2Text\\Html2Text::convert( $phpmailer->Body );\n }\n}\n</code></pre>\n\n<p>Here's also a gist for a WP plugin I modified to fix this problem: <a href=\"https://gist.github.com/youri--/c4618740b7c50c549314eaebc9f78661\" rel=\"nofollow noreferrer\">https://gist.github.com/youri--/c4618740b7c50c549314eaebc9f78661</a></p>\n\n<p><em>Unfortunately I can't comment on the other solutions using the aforementioned hook, to warn them of this, as I don't have enough rep yet to comment.</em></p>\n"
},
{
"answer_id": 359044,
"author": "Paul Schreiber",
"author_id": 8591,
"author_profile": "https://wordpress.stackexchange.com/users/8591",
"pm_score": 2,
"selected": false,
"text": "<p>This version of <code>wp_mail()</code> is based on @bonger's code. It has these changes:</p>\n\n<ul>\n<li>Code styles fixes (via PHPCS)</li>\n<li>Handle cases where $message is either an array or a string (ensures compatibility with WP 5.x)</li>\n<li>Throw an exception instead of returning false</li>\n<li>Short array syntax</li>\n</ul>\n\n<pre class=\"lang-php prettyprint-override\"><code><?php\n/**\n * Adapted from https://wordpress.stackexchange.com/a/191974/8591\n *\n * Send mail, similar to PHP's mail\n *\n * A true return value does not automatically mean that the user received the\n * email successfully. It just only means that the method used was able to\n * process the request without any errors.\n *\n * Using the two 'wp_mail_from' and 'wp_mail_from_name' hooks allow from\n * creating a from address like 'Name <[email protected]>' when both are set. If\n * just 'wp_mail_from' is set, then just the email address will be used with no\n * name.\n *\n * The default content type is 'text/plain' which does not allow using HTML.\n * However, you can set the content type of the email by using the\n * 'wp_mail_content_type' filter.\n *\n * If $message is an array, the key of each is used to add as an attachment\n * with the value used as the body. The 'text/plain' element is used as the\n * text version of the body, with the 'text/html' element used as the HTML\n * version of the body. All other types are added as attachments.\n *\n * The default charset is based on the charset used on the blog. The charset can\n * be set using the 'wp_mail_charset' filter.\n *\n * @since 1.2.1\n *\n * @uses PHPMailer\n *\n * @param string|array $to Array or comma-separated list of email addresses to send message.\n * @param string $subject Email subject\n * @param string|array $message Message contents\n * @param string|array $headers Optional. Additional headers.\n * @param string|array $attachments Optional. Files to attach.\n * @return bool Whether the email contents were sent successfully.\n */\npublic static function wp_mail( $to, $subject, $message, $headers = '', $attachments = [] ) {\n // Compact the input, apply the filters, and extract them back out\n\n /**\n * Filter the wp_mail() arguments.\n *\n * @since 2.2.0\n *\n * @param array $args A compacted array of wp_mail() arguments, including the \"to\" email,\n * subject, message, headers, and attachments values.\n */\n $atts = apply_filters( 'wp_mail', compact( 'to', 'subject', 'headers', 'attachments' ) );\n\n // Since $message is an array, and will wp_staticize_emoji_for_email() expects strings, walk over it one item at a time\n if ( ! is_array( $message ) ) {\n $message = [ $message ];\n }\n foreach ( $message as $message_part ) {\n $message_part = apply_filters( 'wp_mail', $message_part );\n }\n $atts['message'] = $message;\n\n if ( isset( $atts['to'] ) ) {\n $to = $atts['to'];\n }\n\n if ( isset( $atts['subject'] ) ) {\n $subject = $atts['subject'];\n }\n\n if ( isset( $atts['message'] ) ) {\n $message = $atts['message'];\n }\n\n if ( isset( $atts['headers'] ) ) {\n $headers = $atts['headers'];\n }\n\n if ( isset( $atts['attachments'] ) ) {\n $attachments = $atts['attachments'];\n }\n\n if ( ! is_array( $attachments ) ) {\n $attachments = explode( \"\\n\", str_replace( \"\\r\\n\", \"\\n\", $attachments ) );\n }\n global $phpmailer;\n\n // (Re)create it, if it's gone missing\n if ( ! ( $phpmailer instanceof PHPMailer ) ) {\n require_once ABSPATH . WPINC . '/class-phpmailer.php';\n require_once ABSPATH . WPINC . '/class-smtp.php';\n $phpmailer = new PHPMailer( true ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited\n }\n\n // Headers\n if ( empty( $headers ) ) {\n $headers = [];\n } else {\n if ( ! is_array( $headers ) ) {\n // Explode the headers out, so this function can take both\n // string headers and an array of headers.\n $tempheaders = explode( \"\\n\", str_replace( \"\\r\\n\", \"\\n\", $headers ) );\n } else {\n $tempheaders = $headers;\n }\n $headers = [];\n $cc = [];\n $bcc = [];\n\n // If it's actually got contents\n if ( ! empty( $tempheaders ) ) {\n // Iterate through the raw headers\n foreach ( (array) $tempheaders as $header ) {\n if ( strpos( $header, ':' ) === false ) {\n if ( false !== stripos( $header, 'boundary=' ) ) {\n $parts = preg_split( '/boundary=/i', trim( $header ) );\n $boundary = trim( str_replace( [ \"'\", '\"' ], '', $parts[1] ) );\n }\n continue;\n }\n // Explode them out\n list( $name, $content ) = explode( ':', trim( $header ), 2 );\n\n // Cleanup crew\n $name = trim( $name );\n $content = trim( $content );\n\n switch ( strtolower( $name ) ) {\n // Mainly for legacy -- process a From: header if it's there\n case 'from':\n $bracket_pos = strpos( $content, '<' );\n if ( false !== $bracket_pos ) {\n // Text before the bracketed email is the \"From\" name.\n if ( $bracket_pos > 0 ) {\n $from_name = substr( $content, 0, $bracket_pos - 1 );\n $from_name = str_replace( '\"', '', $from_name );\n $from_name = trim( $from_name );\n }\n\n $from_email = substr( $content, $bracket_pos + 1 );\n $from_email = str_replace( '>', '', $from_email );\n $from_email = trim( $from_email );\n\n // Avoid setting an empty $from_email.\n } elseif ( '' !== trim( $content ) ) {\n $from_email = trim( $content );\n }\n break;\n case 'content-type':\n if ( is_array( $message ) ) {\n // Multipart email, ignore the content-type header\n break;\n }\n if ( strpos( $content, ';' ) !== false ) {\n list( $type, $charset_content ) = explode( ';', $content );\n $content_type = trim( $type );\n if ( false !== stripos( $charset_content, 'charset=' ) ) {\n $charset = trim( str_replace( [ 'charset=', '\"' ], '', $charset_content ) );\n } elseif ( false !== stripos( $charset_content, 'boundary=' ) ) {\n $boundary = trim( str_replace( [ 'BOUNDARY=', 'boundary=', '\"' ], '', $charset_content ) );\n $charset = '';\n }\n\n // Avoid setting an empty $content_type.\n } elseif ( '' !== trim( $content ) ) {\n $content_type = trim( $content );\n }\n break;\n case 'cc':\n $cc = array_merge( (array) $cc, explode( ',', $content ) );\n break;\n case 'bcc':\n $bcc = array_merge( (array) $bcc, explode( ',', $content ) );\n break;\n default:\n // Add it to our grand headers array\n $headers[ trim( $name ) ] = trim( $content );\n break;\n }\n }\n }\n }\n\n // Empty out the values that may be set\n $phpmailer->ClearAllRecipients();\n $phpmailer->ClearAttachments();\n $phpmailer->ClearCustomHeaders();\n $phpmailer->ClearReplyTos();\n\n $phpmailer->Body = ''; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase\n $phpmailer->AltBody = ''; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase\n\n // From email and name\n // If we don't have a name from the input headers\n if ( ! isset( $from_name ) ) {\n $from_name = 'WordPress';\n }\n\n /* If we don't have an email from the input headers default to wordpress@$sitename\n * Some hosts will block outgoing mail from this address if it doesn't exist but\n * there's no easy alternative. Defaulting to admin_email might appear to be another\n * option but some hosts may refuse to relay mail from an unknown domain. See\n * https://core.trac.wordpress.org/ticket/5007.\n */\n\n if ( ! isset( $from_email ) ) {\n // Get the site domain and get rid of www.\n $sitename = isset( $_SERVER['SERVER_NAME'] ) ? strtolower( sanitize_text_field( wp_unslash( $_SERVER['SERVER_NAME'] ) ) ) : ''; // phpcs:ignore WordPress.VIP.SuperGlobalInputUsage.AccessDetected\n if ( substr( $sitename, 0, 4 ) === 'www.' ) {\n $sitename = substr( $sitename, 4 );\n }\n\n $from_email = 'wordpress@' . $sitename;\n }\n\n /**\n * Filter the email address to send from.\n *\n * @since 2.2.0\n *\n * @param string $from_email Email address to send from.\n */\n $phpmailer->From = apply_filters( 'wp_mail_from', $from_email ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase\n\n /**\n * Filter the name to associate with the \"from\" email address.\n *\n * @since 2.3.0\n *\n * @param string $from_name Name associated with the \"from\" email address.\n */\n $phpmailer->FromName = apply_filters( 'wp_mail_from_name', $from_name ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase\n\n // Set destination addresses\n if ( ! is_array( $to ) ) {\n $to = explode( ',', $to );\n }\n\n foreach ( (array) $to as $recipient ) {\n try {\n // Break $recipient into name and address parts if in the format \"Foo <[email protected]>\"\n $recipient_name = '';\n if ( preg_match( '/(.*)<(.+)>/', $recipient, $matches ) ) {\n if ( count( $matches ) === 3 ) {\n $recipient_name = $matches[1];\n $recipient = $matches[2];\n }\n }\n $phpmailer->AddAddress( $recipient, $recipient_name );\n } catch ( phpmailerException $e ) {\n continue;\n }\n }\n\n // If we don't have a charset from the input headers\n if ( ! isset( $charset ) ) {\n $charset = get_bloginfo( 'charset' );\n }\n\n // Set the content-type and charset\n\n /**\n * Filter the default wp_mail() charset.\n *\n * @since 2.3.0\n *\n * @param string $charset Default email charset.\n */\n $phpmailer->CharSet = apply_filters( 'wp_mail_charset', $charset ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase\n\n // Set mail's subject and body\n $phpmailer->Subject = $subject; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase\n\n if ( is_string( $message ) ) {\n $phpmailer->Body = $message; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase\n\n // Set Content-Type and charset\n // If we don't have a content-type from the input headers\n if ( ! isset( $content_type ) ) {\n $content_type = 'text/plain';\n }\n\n /**\n * Filter the wp_mail() content type.\n *\n * @since 2.3.0\n *\n * @param string $content_type Default wp_mail() content type.\n */\n $content_type = apply_filters( 'wp_mail_content_type', $content_type );\n\n $phpmailer->ContentType = $content_type; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase\n\n // Set whether it's plaintext, depending on $content_type\n if ( 'text/html' === $content_type ) {\n $phpmailer->IsHTML( true );\n }\n\n // For backwards compatibility, new multipart emails should use\n // the array style $message. This never really worked well anyway\n if ( false !== stripos( $content_type, 'multipart' ) && ! empty( $boundary ) ) {\n $phpmailer->AddCustomHeader( sprintf( \"Content-Type: %s;\\n\\t boundary=\\\"%s\\\"\", $content_type, $boundary ) );\n }\n } elseif ( is_array( $message ) ) {\n foreach ( $message as $type => $bodies ) {\n foreach ( (array) $bodies as $body ) {\n if ( 'text/html' === $type ) {\n $phpmailer->Body = $body; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase\n } elseif ( 'text/plain' === $type ) {\n $phpmailer->AltBody = $body; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase\n } else {\n $phpmailer->AddAttachment( $body, '', 'base64', $type );\n }\n }\n }\n }\n\n // Add any CC and BCC recipients\n if ( ! empty( $cc ) ) {\n foreach ( (array) $cc as $recipient ) {\n try {\n // Break $recipient into name and address parts if in the format \"Foo <[email protected]>\"\n $recipient_name = '';\n if ( preg_match( '/(.*)<(.+)>/', $recipient, $matches ) ) {\n if ( count( $matches ) === 3 ) {\n $recipient_name = $matches[1];\n $recipient = $matches[2];\n }\n }\n $phpmailer->AddCc( $recipient, $recipient_name );\n } catch ( phpmailerException $e ) {\n continue;\n }\n }\n }\n\n if ( ! empty( $bcc ) ) {\n foreach ( (array) $bcc as $recipient ) {\n try {\n // Break $recipient into name and address parts if in the format \"Foo <[email protected]>\"\n $recipient_name = '';\n if ( preg_match( '/(.*)<(.+)>/', $recipient, $matches ) ) {\n if ( count( $matches ) === 3 ) {\n $recipient_name = $matches[1];\n $recipient = $matches[2];\n }\n }\n $phpmailer->AddBcc( $recipient, $recipient_name );\n } catch ( phpmailerException $e ) {\n continue;\n }\n }\n }\n\n // Set to use PHP's mail()\n $phpmailer->IsMail();\n\n // Set custom headers\n if ( ! empty( $headers ) ) {\n foreach ( (array) $headers as $name => $content ) {\n $phpmailer->AddCustomHeader( sprintf( '%1$s: %2$s', $name, $content ) );\n }\n }\n\n if ( ! empty( $attachments ) ) {\n foreach ( $attachments as $attachment ) {\n try {\n $phpmailer->AddAttachment( $attachment );\n } catch ( phpmailerException $e ) {\n continue;\n }\n }\n }\n\n /**\n * Fires after PHPMailer is initialized.\n *\n * @since 2.2.0\n *\n * @param PHPMailer &$phpmailer The PHPMailer instance, passed by reference.\n */\n do_action_ref_array( 'phpmailer_init', [ &$phpmailer ] );\n\n // Send!\n try {\n return $phpmailer->Send();\n } catch ( phpmailerException $e ) {\n return new WP_Error( 'email-error', $e->getMessage() );\n }\n}\n</code></pre>\n"
},
{
"answer_id": 380141,
"author": "TheAddonDepot",
"author_id": 199213,
"author_profile": "https://wordpress.stackexchange.com/users/199213",
"pm_score": 0,
"selected": false,
"text": "<p>Took a close look at the implementation for <strong><code>wp_mail($to, $subject, $message, $headers, $attachments)</code></strong> in <a href=\"https://core.svn.wordpress.org/tags/5.1/wp-includes/pluggable.php\" rel=\"nofollow noreferrer\"><strong><code>pluggable.php</code></strong></a> and found a solution that does not require patching the core.</p>\n<p>The <strong><code>wp_mail()</code></strong> function checks the <strong><code>$headers</code></strong> argument for a specific collection of standard header types, namely <code>from</code>, <code>content-type</code>, <code>cc</code>, <code>bcc</code> and <code>reply-to</code>.</p>\n<p>All other types are designated as custom headers and processed separately. But here's the thing, when a custom header is defined, as in your case where you set the <code>MIME-Version</code> header, the following block of code gets executed (inside <strong><code>wp_mail()</code></strong>):</p>\n<pre class=\"lang-php prettyprint-override\"><code>// Set custom headers\nif ( ! empty( $headers ) ) {\n foreach ( (array) $headers as $name => $content ) {\n $phpmailer->addCustomHeader( sprintf( '%1$s: %2$s', $name, $content ) );\n }\n\n if ( false !== stripos( $content_type, 'multipart' ) && ! empty( $boundary ) ) {\n $phpmailer->addCustomHeader( sprintf( "Content-Type: %s;\\n\\t boundary=\\"%s\\"", $content_type, $boundary ) );\n }\n}\n</code></pre>\n<p>That nested <strong><code>if</code></strong> statement in the above snippet is the culprit. Basically, another <code>Content-Type</code> header is added as a custom header under the following conditions:</p>\n<ol>\n<li>Custom header was defined (you defined <code>MIME-Version</code> in the scenario described in your post).</li>\n<li>Mime-type of <code>Content-Type</code> header contains the string <code>multipart</code>.</li>\n<li>A multi-part boundary was set.</li>\n</ol>\n<p>Quickest fix in your case is to remove the <code>MIME-Version</code> header. Most user agents automatically add that header anyways so removing it shouldn't be an issue.</p>\n<p>But what if you want to add custom headers <strong>without</strong> generating a duplicate <code>Content-Type</code> header?</p>\n<p><strong>SOLUTION:</strong>\nDO NOT explicitly set the <code>Content-Type</code> header in the <code>$headers</code> array when adding custom headers, do the following instead :</p>\n<pre class=\"lang-php prettyprint-override\"><code>$headers = 'boundary="----=_Part_18243133_1346573420.1408991447668"\\r\\n';\n$headers .= "MIME-Version: 1.0\\r\\n";\n$headers .= "From: Foo <[email protected]>\\r\\n";\n\nfunction set_content_type( $content_type ) {\n return 'multipart/alternative';\n}\n\nfunction set_charset( $char_set ) {\n return 'utf-8';\n}\n\nadd_filter( 'wp_mail_content_type', 'set_content_type' );\nadd_filter( 'wp_mail_charset', 'set_charset' );\n</code></pre>\n<p>The first line in the snippet above may appear baffling, but the <strong><code>wp_mail()</code></strong> function will internally set its <strong><code>$boundary</code></strong> variable as long as a boundary definition appears on its own line without being prefixed by <strong><code>Content-Type:</code></strong>. Then you can follow up with filter hooks to set the <code>content-type</code> and <code>charset</code> respectively. This way you satisfy the conditions to execute the code block for setting custom headers without explicitly adding <code>Content-Type: [mime-type]; [boundary];</code>.</p>\n<p>No need to touch the core <strong><code>wp_mail()</code></strong> implementation, buggy though it may be.</p>\n"
}
] |
2015/06/18
|
[
"https://wordpress.stackexchange.com/questions/191923",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/24875/"
] |
Summary
-------
Because of a bug in WP Core, sending [multipart](https://en.wikipedia.org/wiki/MIME) emails (html/text) with [wp\_mail()](https://codex.wordpress.org/Function_Reference/wp_mail) (to reduce chance of emails ending up in spam folders) will *ironically* result with your domain being blocked by Hotmail (and other Microsoft emails).
This is a complex problem that I'll aim to break down in great detail in an attempt to help someone find a workable solution which may eventually be implemented in core.
**It's going to be a rewarding read. Let's begin...**
The bug
-------
The most common advice to avoid having your newsletter emails ending up in spam folders is to send multipart messages.
Multi-part (mime) refers to sending both an HTML and TEXT part of an email message in a single email. When a client receives a multipart message, it accepts the HTML version if it can render HTML, otherwise it presents the plain text version.
This is proven to work. When sending to gmail, all our emails landed in spam folders until we changed the messages to multipart when they came through to main inbox. Great stuff.
Now, when sending multipart messages via wp\_mail(), it outputs the Content Type (multipart/\*) twice, once with boundary (if customly set) and once without. This behaviour results with the email being displayed as a raw message and not multipart on some emails, including **all** Microsoft (Hotmail, Outlook, etc...)
Microsoft will flag this message as junk, and the few messages that comes through will be flagged manually by the recipient. *Unfortunately*, Microsoft emails addresses are widely used. 40% of our subscribers use it.
This is confirmed by Microsoft via an email exchange we had recently.
The flagging of the messages will result with the domain being completely **blocked**. This means that message will not be sent to spam folder, **they will not even be delivered** to the recipient at all.
We have had our main domain blocked 3 times so far.
Because this is a bug in the WP core, **every** domain that sends multipart messages are being blocked. The problem is that most webmasters do not know why. I have confirmed this when doing my research and seeing other users discussing this on forums etc. It requires delving into the raw code and having a good knowledge of how these type of email messages work, which we are going on to next...
Let's break it down into code
-----------------------------
Create a hotmail/outlook account. Then, run the following code:
```
// Set $to to an hotmail.com or outlook.com email
$to = "[email protected]";
$subject = 'wp_mail testing multipart';
$message = '------=_Part_18243133_1346573420.1408991447668
Content-Type: text/plain; charset=UTF-8
Hello world! This is plain text...
------=_Part_18243133_1346573420.1408991447668
Content-Type: text/html; charset=UTF-8
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<p>Hello World! This is HTML...</p>
</body>
</html>
------=_Part_18243133_1346573420.1408991447668--';
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From: Foo <[email protected]>\r\n";
$headers .= 'Content-Type: multipart/alternative;boundary="----=_Part_18243133_1346573420.1408991447668"';
// send email
wp_mail( $to, $subject, $message, $headers );
```
And if you want to change the [default content type](http://codex.wordpress.org/Plugin_API/Filter_Reference/wp_mail_content_type), use:
```
add_filter( 'wp_mail_content_type', 'set_content_type' );
function set_content_type( $content_type ) {
return 'multipart/alternative';
}
```
This will send a multipart message.
So if you check the full raw source of the message, you'll notice that the content type is added twice, once without boundary:
```
MIME-Version: 1.0
Content-Type: multipart/alternative;
boundary="====f230673f9d7c359a81ffebccb88e5d61=="
MIME-Version: 1.0
Content-Type: multipart/alternative; charset=
```
That's the issue.
The source of the problem lies in `pluggable.php` - if we look somewhere here:
```
// Set Content-Type and charset
// If we don't have a content-type from the input headers
if ( !isset( $content_type ) )
$content_type = 'text/plain';
/**
* Filter the wp_mail() content type.
*
* @since 2.3.0
*
* @param string $content_type Default wp_mail() content type.
*/
$content_type = apply_filters( 'wp_mail_content_type', $content_type );
$phpmailer->ContentType = $content_type;
// Set whether it's plaintext, depending on $content_type
if ( 'text/html' == $content_type )
$phpmailer->IsHTML( true );
// If we don't have a charset from the input headers
if ( !isset( $charset ) )
$charset = get_bloginfo( 'charset' );
// Set the content-type and charset
/**
* Filter the default wp_mail() charset.
*
* @since 2.3.0
*
* @param string $charset Default email charset.
*/
$phpmailer->CharSet = apply_filters( 'wp_mail_charset', $charset );
// Set custom headers
if ( !empty( $headers ) ) {
foreach( (array) $headers as $name => $content ) {
$phpmailer->AddCustomHeader( sprintf( '%1$s: %2$s', $name, $content ) );
}
if ( false !== stripos( $content_type, 'multipart' ) && ! empty($boundary) )
$phpmailer->AddCustomHeader( sprintf( "Content-Type: %s;\n\t boundary=\"%s\"", $content_type, $boundary ) );
}
if ( !empty( $attachments ) ) {
foreach ( $attachments as $attachment ) {
try {
$phpmailer->AddAttachment($attachment);
} catch ( phpmailerException $e ) {
continue;
}
}
}
```
Potential solutions
-------------------
So you are wondering, **why have you not reported this at [trac](https://core.trac.wordpress.org/)?** I [already have](https://core.trac.wordpress.org/ticket/31653). To my great surprise, a [different ticket](https://core.trac.wordpress.org/ticket/15448) was created 5 years ago outlining the same problem.
Let's face it, it's been a half decade. In internet years, that is more like 30. The issue has clearly been abandoned and basically will never be fixed (...unless if we resolve it here).
I found a great [thread here](https://wordpress.org/support/topic/using-wp_mail-with-php-generated-attachments) offering a solution, but while his solution works, it breaks emails that do not have custom `$headers` set.
That's where we crash every time. Either the multipart version work fine, and normal unset `$headers` messages don't, or vise verse.
The solution we came up with was:
```
if ( false !== stripos( $content_type, 'multipart' ) && ! empty($boundary) ) {
$phpmailer->ContentType = $content_type . "; boundary=" . $boundary;
}
else {
$content_type = apply_filters( 'wp_mail_content_type', $content_type );
$phpmailer->ContentType = $content_type;
// Set whether it's plaintext, depending on $content_type
if ( 'text/html' == $content_type )
$phpmailer->IsHTML( true );
// If we don't have a charset from the input headers
if ( !isset( $charset ) )
$charset = get_bloginfo( 'charset' );
}
// Set the content-type and charset
/**
* Filter the default wp_mail() charset.
*
* @since 2.3.0
*
* @param string $charset Default email charset.
*/
$phpmailer->CharSet = apply_filters( 'wp_mail_charset', $charset );
// Set custom headers
if ( !empty( $headers ) ) {
foreach( (array) $headers as $name => $content ) {
$phpmailer->AddCustomHeader( sprintf( '%1$s: %2$s', $name, $content ) );
}
}
```
Yes, I know, editing core files are taboo, sit back down... this was a desperate fix and a poor attempt to provide a fix for core.
The problem with our fix is that default emails like new registrations, comment, password reset etc will be delivered as blank messages. So we have a working wp\_mail() script that will send multipart messages but nothing else.
What to do
----------
The aim here is to find a way to send both normal (plain text) and multipart messages **using the core wp\_mail() function** (not a custom sendmail function).
When attempting to solve this, the main problem you will encounter is the amount of time that you'll spend on sending dummy messages, checking if they're received and basically opening a box of aspirin and cursing at Microsoft because you are used to their IE issues while the gremlin here is unfortunately WordPress.
Update
------
The solution posted by @bonger allows `$message` to be an array containing content-type keyed alternates. I have confirmed that it works in all scenarios.
We will allow this question to remain open until bounty runs out to raise awareness about the problem, **maybe to a level where it will be fixed in core.** Feel free to post an alternative solution where `$message` can be a string.
|
The following version of `wp_mail()` is with the patch applied of @rmccue/@MattyRob in the ticket <https://core.trac.wordpress.org/ticket/15448>, refreshed for 4.2.2, which allows `$message` to be an array containing content-type keyed alternates:
```
/**
* Send mail, similar to PHP's mail
*
* A true return value does not automatically mean that the user received the
* email successfully. It just only means that the method used was able to
* process the request without any errors.
*
* Using the two 'wp_mail_from' and 'wp_mail_from_name' hooks allow from
* creating a from address like 'Name <[email protected]>' when both are set. If
* just 'wp_mail_from' is set, then just the email address will be used with no
* name.
*
* The default content type is 'text/plain' which does not allow using HTML.
* However, you can set the content type of the email by using the
* 'wp_mail_content_type' filter.
*
* If $message is an array, the key of each is used to add as an attachment
* with the value used as the body. The 'text/plain' element is used as the
* text version of the body, with the 'text/html' element used as the HTML
* version of the body. All other types are added as attachments.
*
* The default charset is based on the charset used on the blog. The charset can
* be set using the 'wp_mail_charset' filter.
*
* @since 1.2.1
*
* @uses PHPMailer
*
* @param string|array $to Array or comma-separated list of email addresses to send message.
* @param string $subject Email subject
* @param string|array $message Message contents
* @param string|array $headers Optional. Additional headers.
* @param string|array $attachments Optional. Files to attach.
* @return bool Whether the email contents were sent successfully.
*/
function wp_mail( $to, $subject, $message, $headers = '', $attachments = array() ) {
// Compact the input, apply the filters, and extract them back out
/**
* Filter the wp_mail() arguments.
*
* @since 2.2.0
*
* @param array $args A compacted array of wp_mail() arguments, including the "to" email,
* subject, message, headers, and attachments values.
*/
$atts = apply_filters( 'wp_mail', compact( 'to', 'subject', 'message', 'headers', 'attachments' ) );
if ( isset( $atts['to'] ) ) {
$to = $atts['to'];
}
if ( isset( $atts['subject'] ) ) {
$subject = $atts['subject'];
}
if ( isset( $atts['message'] ) ) {
$message = $atts['message'];
}
if ( isset( $atts['headers'] ) ) {
$headers = $atts['headers'];
}
if ( isset( $atts['attachments'] ) ) {
$attachments = $atts['attachments'];
}
if ( ! is_array( $attachments ) ) {
$attachments = explode( "\n", str_replace( "\r\n", "\n", $attachments ) );
}
global $phpmailer;
// (Re)create it, if it's gone missing
if ( ! ( $phpmailer instanceof PHPMailer ) ) {
require_once ABSPATH . WPINC . '/class-phpmailer.php';
require_once ABSPATH . WPINC . '/class-smtp.php';
$phpmailer = new PHPMailer( true );
}
// Headers
if ( empty( $headers ) ) {
$headers = array();
} else {
if ( !is_array( $headers ) ) {
// Explode the headers out, so this function can take both
// string headers and an array of headers.
$tempheaders = explode( "\n", str_replace( "\r\n", "\n", $headers ) );
} else {
$tempheaders = $headers;
}
$headers = array();
$cc = array();
$bcc = array();
// If it's actually got contents
if ( !empty( $tempheaders ) ) {
// Iterate through the raw headers
foreach ( (array) $tempheaders as $header ) {
if ( strpos($header, ':') === false ) {
if ( false !== stripos( $header, 'boundary=' ) ) {
$parts = preg_split('/boundary=/i', trim( $header ) );
$boundary = trim( str_replace( array( "'", '"' ), '', $parts[1] ) );
}
continue;
}
// Explode them out
list( $name, $content ) = explode( ':', trim( $header ), 2 );
// Cleanup crew
$name = trim( $name );
$content = trim( $content );
switch ( strtolower( $name ) ) {
// Mainly for legacy -- process a From: header if it's there
case 'from':
$bracket_pos = strpos( $content, '<' );
if ( $bracket_pos !== false ) {
// Text before the bracketed email is the "From" name.
if ( $bracket_pos > 0 ) {
$from_name = substr( $content, 0, $bracket_pos - 1 );
$from_name = str_replace( '"', '', $from_name );
$from_name = trim( $from_name );
}
$from_email = substr( $content, $bracket_pos + 1 );
$from_email = str_replace( '>', '', $from_email );
$from_email = trim( $from_email );
// Avoid setting an empty $from_email.
} elseif ( '' !== trim( $content ) ) {
$from_email = trim( $content );
}
break;
case 'content-type':
if ( is_array($message) ) {
// Multipart email, ignore the content-type header
break;
}
if ( strpos( $content, ';' ) !== false ) {
list( $type, $charset_content ) = explode( ';', $content );
$content_type = trim( $type );
if ( false !== stripos( $charset_content, 'charset=' ) ) {
$charset = trim( str_replace( array( 'charset=', '"' ), '', $charset_content ) );
} elseif ( false !== stripos( $charset_content, 'boundary=' ) ) {
$boundary = trim( str_replace( array( 'BOUNDARY=', 'boundary=', '"' ), '', $charset_content ) );
$charset = '';
}
// Avoid setting an empty $content_type.
} elseif ( '' !== trim( $content ) ) {
$content_type = trim( $content );
}
break;
case 'cc':
$cc = array_merge( (array) $cc, explode( ',', $content ) );
break;
case 'bcc':
$bcc = array_merge( (array) $bcc, explode( ',', $content ) );
break;
default:
// Add it to our grand headers array
$headers[trim( $name )] = trim( $content );
break;
}
}
}
}
// Empty out the values that may be set
$phpmailer->ClearAllRecipients();
$phpmailer->ClearAttachments();
$phpmailer->ClearCustomHeaders();
$phpmailer->ClearReplyTos();
$phpmailer->Body= '';
$phpmailer->AltBody= '';
// From email and name
// If we don't have a name from the input headers
if ( !isset( $from_name ) )
$from_name = 'WordPress';
/* If we don't have an email from the input headers default to wordpress@$sitename
* Some hosts will block outgoing mail from this address if it doesn't exist but
* there's no easy alternative. Defaulting to admin_email might appear to be another
* option but some hosts may refuse to relay mail from an unknown domain. See
* https://core.trac.wordpress.org/ticket/5007.
*/
if ( !isset( $from_email ) ) {
// Get the site domain and get rid of www.
$sitename = strtolower( $_SERVER['SERVER_NAME'] );
if ( substr( $sitename, 0, 4 ) == 'www.' ) {
$sitename = substr( $sitename, 4 );
}
$from_email = 'wordpress@' . $sitename;
}
/**
* Filter the email address to send from.
*
* @since 2.2.0
*
* @param string $from_email Email address to send from.
*/
$phpmailer->From = apply_filters( 'wp_mail_from', $from_email );
/**
* Filter the name to associate with the "from" email address.
*
* @since 2.3.0
*
* @param string $from_name Name associated with the "from" email address.
*/
$phpmailer->FromName = apply_filters( 'wp_mail_from_name', $from_name );
// Set destination addresses
if ( !is_array( $to ) )
$to = explode( ',', $to );
foreach ( (array) $to as $recipient ) {
try {
// Break $recipient into name and address parts if in the format "Foo <[email protected]>"
$recipient_name = '';
if( preg_match( '/(.*)<(.+)>/', $recipient, $matches ) ) {
if ( count( $matches ) == 3 ) {
$recipient_name = $matches[1];
$recipient = $matches[2];
}
}
$phpmailer->AddAddress( $recipient, $recipient_name);
} catch ( phpmailerException $e ) {
continue;
}
}
// If we don't have a charset from the input headers
if ( !isset( $charset ) )
$charset = get_bloginfo( 'charset' );
// Set the content-type and charset
/**
* Filter the default wp_mail() charset.
*
* @since 2.3.0
*
* @param string $charset Default email charset.
*/
$phpmailer->CharSet = apply_filters( 'wp_mail_charset', $charset );
// Set mail's subject and body
$phpmailer->Subject = $subject;
if ( is_string($message) ) {
$phpmailer->Body = $message;
// Set Content-Type and charset
// If we don't have a content-type from the input headers
if ( !isset( $content_type ) )
$content_type = 'text/plain';
/**
* Filter the wp_mail() content type.
*
* @since 2.3.0
*
* @param string $content_type Default wp_mail() content type.
*/
$content_type = apply_filters( 'wp_mail_content_type', $content_type );
$phpmailer->ContentType = $content_type;
// Set whether it's plaintext, depending on $content_type
if ( 'text/html' == $content_type )
$phpmailer->IsHTML( true );
// For backwards compatibility, new multipart emails should use
// the array style $message. This never really worked well anyway
if ( false !== stripos( $content_type, 'multipart' ) && ! empty($boundary) )
$phpmailer->AddCustomHeader( sprintf( "Content-Type: %s;\n\t boundary=\"%s\"", $content_type, $boundary ) );
}
elseif ( is_array($message) ) {
foreach ($message as $type => $bodies) {
foreach ((array) $bodies as $body) {
if ($type === 'text/html') {
$phpmailer->Body = $body;
}
elseif ($type === 'text/plain') {
$phpmailer->AltBody = $body;
}
else {
$phpmailer->AddAttachment($body, '', 'base64', $type);
}
}
}
}
// Add any CC and BCC recipients
if ( !empty( $cc ) ) {
foreach ( (array) $cc as $recipient ) {
try {
// Break $recipient into name and address parts if in the format "Foo <[email protected]>"
$recipient_name = '';
if( preg_match( '/(.*)<(.+)>/', $recipient, $matches ) ) {
if ( count( $matches ) == 3 ) {
$recipient_name = $matches[1];
$recipient = $matches[2];
}
}
$phpmailer->AddCc( $recipient, $recipient_name );
} catch ( phpmailerException $e ) {
continue;
}
}
}
if ( !empty( $bcc ) ) {
foreach ( (array) $bcc as $recipient) {
try {
// Break $recipient into name and address parts if in the format "Foo <[email protected]>"
$recipient_name = '';
if( preg_match( '/(.*)<(.+)>/', $recipient, $matches ) ) {
if ( count( $matches ) == 3 ) {
$recipient_name = $matches[1];
$recipient = $matches[2];
}
}
$phpmailer->AddBcc( $recipient, $recipient_name );
} catch ( phpmailerException $e ) {
continue;
}
}
}
// Set to use PHP's mail()
$phpmailer->IsMail();
// Set custom headers
if ( !empty( $headers ) ) {
foreach ( (array) $headers as $name => $content ) {
$phpmailer->AddCustomHeader( sprintf( '%1$s: %2$s', $name, $content ) );
}
}
if ( !empty( $attachments ) ) {
foreach ( $attachments as $attachment ) {
try {
$phpmailer->AddAttachment($attachment);
} catch ( phpmailerException $e ) {
continue;
}
}
}
/**
* Fires after PHPMailer is initialized.
*
* @since 2.2.0
*
* @param PHPMailer &$phpmailer The PHPMailer instance, passed by reference.
*/
do_action_ref_array( 'phpmailer_init', array( &$phpmailer ) );
// Send!
try {
return $phpmailer->Send();
} catch ( phpmailerException $e ) {
return false;
}
}
```
So if you put that in your eg "wp-content/mu-plugins/functions.php" file then it will override the WP version. It has a nice usage without any messing around with headers, eg:
```
// Set $to to an hotmail.com or outlook.com email
$to = "[email protected]";
$subject = 'wp_mail testing multipart';
$message['text/plain'] = 'Hello world! This is plain text...';
$message['text/html'] = '<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<p>Hello World! This is HTML...</p>
</body>
</html>';
add_filter( 'wp_mail_from', $from_func = function ( $from_email ) { return '[email protected]'; } );
add_filter( 'wp_mail_from_name', $from_name_func = function ( $from_name ) { return 'Foo'; } );
// send email
wp_mail( $to, $subject, $message );
remove_filter( 'wp_mail_from', $from_func );
remove_filter( 'wp_mail_from_name', $from_name_func );
```
Please note I haven't tested this with actual emails...
|
191,924 |
<p>I create a new page with post name is 'my-page'. I also have 2 custom query strings. So, the URL will be like:</p>
<p><a href="http://domain.com/my-page/?qst1=aaa&qst2=bbb" rel="nofollow">http://domain.com/my-page/?qst1=aaa&qst2=bbb</a></p>
<p>I want the URL like:</p>
<p><a href="http://domain.com/aaa/bbb" rel="nofollow">http://domain.com/aaa/bbb</a></p>
<p>How I can do it? How I can tell WP it is a valid URL, because WP will point to 404 page (aaa page not found).</p>
|
[
{
"answer_id": 191925,
"author": "KingCodeFish",
"author_id": 74125,
"author_profile": "https://wordpress.stackexchange.com/users/74125",
"pm_score": 1,
"selected": false,
"text": "<p>In your .htaccess you should be able to do something like what is shown by Chris Coyier on CSS Tricks.</p>\n\n<p>Link to example by Chris Coyier: <a href=\"https://css-tricks.com/snippets/htaccess/subdirectories-redirect-query-string/\" rel=\"nofollow\">https://css-tricks.com/snippets/htaccess/subdirectories-redirect-query-string/</a></p>\n\n<p>Since you don't have .php in your URL, WordPress has most likely already created RewriteEngine rules for you to not need .php. But the result should still work fine.</p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>Another example of this is shown with pretty much the same exact scenario as you.\nIt's on Apache's Wiki website: <a href=\"https://wiki.apache.org/httpd/RewriteQueryString\" rel=\"nofollow\">https://wiki.apache.org/httpd/RewriteQueryString</a>\nThe example shown to do this in your .htaccess is something like this:</p>\n\n<pre><code>RewriteCond %{QUERY_STRING} ^(\\w+)=(\\w+)$\nRewriteRule ^/path /path/%1/%2?\n</code></pre>\n"
},
{
"answer_id": 259781,
"author": "ferdouswp",
"author_id": 114362,
"author_profile": "https://wordpress.stackexchange.com/users/114362",
"pm_score": 0,
"selected": false,
"text": "<p>You can use permalink setting Custom Structure /%category%/%postname%/.</p>\n\n<p>or You can use <a href=\"https://wordpress.org/plugins/simple-301-redirects/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/simple-301-redirects/</a> plugin.</p>\n"
},
{
"answer_id": 267306,
"author": "rheeantz",
"author_id": 119810,
"author_profile": "https://wordpress.stackexchange.com/users/119810",
"pm_score": 1,
"selected": false,
"text": "<p>You can add add_rewrite_rule function in your website. For your case you can try this following code </p>\n\n<pre><code>add_action( 'init', 'wpse12065_init' );\nfunction wpse12065_init() { \nadd_rewrite_rule(\n 'my-page(/([^/]+))?(/([^/]+))?/?',\n 'index.php?pagename=my-page&qst1=$matches[2]&qst2=$matches[4]',\n 'top' \n);\n</code></pre>\n\n<p>Then save your permalink. </p>\n\n<p>In my-page Page ( you need to create custom page template ) you can catch that query vars with this code </p>\n\n<pre><code>if (isset($wp_query->query_vars['qst1']) && !empty($wp_query->query_vars['qst1']) ) {\n$qst1 = $wp_query->query_vars['qst1'];\n}\nelse {\n//do something else \n}\n//do the same step for qst2\n</code></pre>\n\n<p>Hope it helps</p>\n"
}
] |
2015/06/18
|
[
"https://wordpress.stackexchange.com/questions/191924",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/28101/"
] |
I create a new page with post name is 'my-page'. I also have 2 custom query strings. So, the URL will be like:
<http://domain.com/my-page/?qst1=aaa&qst2=bbb>
I want the URL like:
<http://domain.com/aaa/bbb>
How I can do it? How I can tell WP it is a valid URL, because WP will point to 404 page (aaa page not found).
|
In your .htaccess you should be able to do something like what is shown by Chris Coyier on CSS Tricks.
Link to example by Chris Coyier: <https://css-tricks.com/snippets/htaccess/subdirectories-redirect-query-string/>
Since you don't have .php in your URL, WordPress has most likely already created RewriteEngine rules for you to not need .php. But the result should still work fine.
**EDIT:**
Another example of this is shown with pretty much the same exact scenario as you.
It's on Apache's Wiki website: <https://wiki.apache.org/httpd/RewriteQueryString>
The example shown to do this in your .htaccess is something like this:
```
RewriteCond %{QUERY_STRING} ^(\w+)=(\w+)$
RewriteRule ^/path /path/%1/%2?
```
|
191,933 |
<p>I am looking for a method to get the registered metaboxes for a specific post type (or post ID) when on a separate, unrelated post type. I am working on making a custom "editing" post type for a specific client need and want the ability to load the metaboxes without having them be registered to that 'editable' type.</p>
<p><strong>Clarification:</strong></p>
<p>What I am trying to accomplish is the actual display of the metaboxes from another post type. So if my "events" post type has a metabox with date, time, and location, I would want to show those same boxes on a separate post type without actually registering the metabox again.</p>
|
[
{
"answer_id": 191942,
"author": "Mickey",
"author_id": 74899,
"author_profile": "https://wordpress.stackexchange.com/users/74899",
"pm_score": 0,
"selected": false,
"text": "<p>Create an additional metabox (checkbox, I'm thinking) that provides the option to create an 'edit' post type from this post. For the sake of this code, we'll call it 'transfer_data'.</p>\n\n<p>Change the value of $post_type to the post type of the original post that we will be retrieving the data from.</p>\n\n<p>I've added the functionality to save the original post ID intoback a meta value for the 'edit' post type. In order to save the 'edit' metaboxes to the original post, you should be able to use that value and this function ( with <code>update_post_meta()</code> instead, of course) to reverse engineer another function to hook into.</p>\n\n<pre><code>function create_edit_page($data){\n $post_type = 'the_post_type_to_work_with';\n // Grab this post's ID\n $orig_id = $_POST['post_ID'];\n // Grab the value of the 'transfer_data' field\n $is_transfer_val = get_post_meta( $orig_id, 'transfer_data');\n if($data['post_type'] == $post_type && $is_transfer_val == TRUE && \n isset($data['guid']) && strlen($data['guid'])>0 ){\n\n $post_id = wp_insert_post(\n array(\n 'comment_status' => 'closed',\n 'ping_status' => 'closed',\n 'post_author' => $data['post_author'],\n 'post_name' => $slug,\n 'post_content' => $data['post_content'],\n 'post_title' => $data['post_title'],\n 'post_status' => 'publish',\n // The custom post type 'editing'\n 'post_type' => 'editing'\n )\n );\n\n // create the meta fields\n $all_meta_boxes = get_post_meta( $orig_id );\n if(isset( $all_meta_boxes ) && is_array( $all_meta_boxes )){\n foreach($all_meta_boxes as $metakey => $metavalue){\n add_post_meta($post_id, $metakey, $metavalue);\n }\n }\n // add a meta field that points to original post (for editing purposes, etc.)\n add_post_meta($post_id, 'original_post_id', $orig_id);\n\n // If you want to redirect the user after saving use the filter below\n // add_filter('redirect_post_location', 'my_post_redirect_filter', '99');\n\n return $data;\n }\n return $data;\n}\nadd_action( 'wp_insert_post', 'create_edit_page', '99' );\n// Or, call BEFORE updating the database with below action\n//add_action( 'wp_insert_post_data', 'create_edit_page', '99' );\n</code></pre>\n"
},
{
"answer_id": 191951,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 0,
"selected": false,
"text": "<p>I will make no claim this is reliable, but this is about how far I got:</p>\n\n<pre><code>add_action( 'add_meta_boxes', function () {\n global $wp_meta_boxes;\n\n foreach ( $wp_meta_boxes['steal-from'] as $context => $priorities ) {\n\n foreach ( $priorities as $priority => $boxes ) {\n\n if ( ! isset( $wp_meta_boxes['metabox-stealer'][ $context ] ) ) {\n $wp_meta_boxes['metabox-stealer'][ $context ] = [ ];\n }\n\n if ( ! isset( $wp_meta_boxes['metabox-stealer'][ $context ][ $priority ] ) ) {\n $wp_meta_boxes['metabox-stealer'][ $context ][ $priority ] = [ ];\n }\n\n $wp_meta_boxes['metabox-stealer'][ $context ][ $priority ] = array_merge(\n $wp_meta_boxes['metabox-stealer'][ $context ][ $priority ],\n $boxes\n );\n }\n }\n}, 11 );\n</code></pre>\n\n<p>Where <code>steal-from</code> and <code>metabox-stealer</code> are post types to operate on.</p>\n"
},
{
"answer_id": 191956,
"author": "Dan Cameron",
"author_id": 8286,
"author_profile": "https://wordpress.stackexchange.com/users/8286",
"pm_score": 0,
"selected": false,
"text": "<p>This will insert the metaboxes manually in close enough locations to where the meta boxes should go. The problem is that they'll be inserted before the standard mboxes for that post type.</p>\n\n<p>I'm sure you could hack with it more if necessary but this at least gets the basics of what you need.</p>\n\n<pre><code>function monkey_advanced_meta_boxes() {\n $post = get_post( 2457 );\n do_meta_boxes( 'post_type_to_take_mboxes_from', 'normal', $post );\n do_meta_boxes( 'post_type_to_take_mboxes_from', 'advanced', $post );\n}\nadd_action( 'edit_form_advanced', 'monkey_advanced_meta_boxes' );\n\nfunction monkey_sidebar_meta_boxes() {\n $post = get_post( 2457 );\n do_meta_boxes( 'post_type_to_take_mboxes_from', 'side', $post );\n}\nadd_action( 'submitpost_box', 'monkey_sidebar_meta_boxes' );\n</code></pre>\n\n<p>Of course you will need to check the screen->id and make sure you're adding the mboxes to the correct screen. This also won't register meta boxes the same so things like removing them from screen options won't work.</p>\n\n<hr>\n\n<p>UPDATE: After thinking about this a bit it looks like this isn't as easy as I've described above. I'm assuming you'll want to have the meta boxes save the meta which you may have to do manually if the original save action is checking the post_type (which it should) and then there's the issue of the meta box not being compatible.</p>\n\n<p>I figure there's gotta be a way around this like I originally mentioned with modifying the global variable. </p>\n"
},
{
"answer_id": 191963,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 3,
"selected": true,
"text": "<h2>Wrong Assumptions</h2>\n\n<p><strong>@Rarst</strong> or <strong>@Dan-Cameron</strong> answers may work, but assume that when you are viewing a post type editing page, the metaboxes for the other post type are all registered.</p>\n\n<p>There are different case in which that won't happen:</p>\n\n<ul>\n<li>If metaboxes are registered using <a href=\"https://developer.wordpress.org/reference/hooks/add_meta_boxes_post_type/\" rel=\"nofollow noreferrer\"><code>\"add_meta_boxes_{$post_type}\"</code></a> hook, instead of the more common, generic <code>\"add_meta_boxes\"</code> they won't be available in the admin page for the <em>stealer</em> post type</li>\n<li>Even the generic post hook <a href=\"https://developer.wordpress.org/reference/hooks/add_meta_boxes/\" rel=\"nofollow noreferrer\"><code>\"add_meta_boxes\"</code></a> pass to hooking callbacks the current post type and the current post object as arguments. It means that registering callbacks may use those arguments in some <code>if</code> conditions, so is possible that we are in same situation of previous point</li>\n</ul>\n\n<p>In short, unless you have control on how the metaboxes for some post type <em>A</em> are registered, you can't be sure they will be able in post editing page for some post type <em>B</em>.</p>\n\n<p>In case you have that control, then <a href=\"https://wordpress.stackexchange.com/a/191951/35541\">@Rarst answer</a> would do the trick.</p>\n\n<p>In case you have not that control, the only way would be a bit tricky.</p>\n\n<p>IMO your only chance, in that case, is to send an HTTP request (AJAX or via WP HTTP API) to the post edit page of the CPT you want to steal the boxes from. You have to add some request variable that will make the page return the boxes array (probaly serialized or JSON-enconded).</p>\n\n<p>After that, you can merge the boxes returned with the boxes for current post, and you are done.</p>\n\n<p>The point is that such code</p>\n\n<ul>\n<li>is slow (because additional request)</li>\n<li>is not trivial</li>\n</ul>\n\n<p>So, if you have control on which are all the boxes registered for post a certain post type, is much simpler and faster just register those boxes again for the <em>stealer</em> post type.</p>\n\n<p>If you can't be sure which are all the boxes for that post type, then the additional HTTP request is your only chance.</p>\n\n<p>I'll post here a class, that implements that workflow (<a href=\"https://gist.github.com/Giuseppe-Mazzapica/e45bb38565e221876958\" rel=\"nofollow noreferrer\">here</a> as Gist for better readability):</p>\n\n<pre><code>class MetaboxStealer\n{\n private static $stealing;\n\n private $post_type;\n private $boxes = [];\n\n /**\n * When the request contain special variable, this function will make it\n * return a serialized version of $wp_meta_boxes array and die.\n */\n public static function init()\n {\n add_filter('post_updated_messages', function ($messages) {\n if (MetaboxStealer::stealing()) {\n ob_start();\n return [];\n }\n return $messages;\n });\n\n add_action('do_meta_boxes', function () {\n if (MetaboxStealer::stealing()) {\n ob_end_clean();\n global $wp_meta_boxes;\n echo serialize($wp_meta_boxes);\n die();\n }\n });\n }\n\n /**\n * Checks that the request contain a special variable that will make request\n * return a serialized version of $wp_meta_boxes array and die.\n *\n * @return bool\n */\n public static function stealing()\n {\n if (is_null(self::$stealing)) {\n $screen = function_exists('get_current_screen') ? get_current_screen() : null;\n $stealing = filter_input(INPUT_GET, 'stealing-boxes', FILTER_SANITIZE_STRING);\n self::$stealing =\n $screen instanceof \\WP_Screen\n && $stealing\n && wp_verify_nonce($stealing, $screen->post_type);\n }\n return self::$stealing;\n }\n\n /**\n * @param string $post_type Current post type\n */\n public function __construct($post_type)\n {\n $this->post_type = $post_type;\n }\n\n /**\n * Send a HTTP request to post edit page of a given CPT setting a special\n * variable that will make that page return serialized $wp_meta_boxes array.\n * After that, so obtained boxes are merged with the boxes for current post type.\n *\n * @param string $cpt CPT to steal metaboxes from\n */\n public function steal($cpt)\n {\n $vars = [\n 'post_type' => $cpt,\n 'stealing-boxes' => wp_create_nonce($cpt),\n ];\n $url = add_query_arg($vars, admin_url('/post-new.php'));\n $cookies = [];\n foreach ($_COOKIE as $name => $value) {\n if ('PHPSESSID' !== strtoupper($name)) {\n $cookies[] = new \\WP_Http_Cookie([\n 'name' => $name,\n 'value' => $value,\n ]);\n }\n }\n $response = wp_remote_get($url, ['cookies' => $cookies]);\n if (! is_wp_error($response)) {\n $body = wp_remote_retrieve_body($response);\n if (is_serialized($body)) {\n $boxes = unserialize($body);\n $this->boxes = isset($boxes[$cpt]) ? $boxes[$cpt] : [];\n empty($this->boxes) or $this->merge();\n }\n }\n }\n\n /**\n * Merge metaboxes for current post type with boxes obtained with \n * a HTTP request to another CPT post edit page.\n */\n private function merge()\n {\n global $wp_meta_boxes;\n isset($wp_meta_boxes[$this->post_type]) or $wp_meta_boxes[$this->post_type] = [];\n foreach ($this->boxes as $context => $priorities) {\n foreach ($priorities as $priority => $boxes) {\n if (! isset($wp_meta_boxes[$this->post_type][$context])) {\n $wp_meta_boxes[$this->post_type][$context] = [];\n }\n if (! isset($wp_meta_boxes[$this->post_type][$context][$priority])) {\n $wp_meta_boxes[$this->post_type][$context][$priority] = [];\n }\n $wp_meta_boxes[$this->post_type][$context][$priority] = array_merge(\n $wp_meta_boxes[$this->post_type][$context][$priority],\n $boxes\n );\n }\n }\n }\n}\n</code></pre>\n\n<p>Notes: </p>\n\n<ul>\n<li>the method <code>merge()</code> is highly derived from Rarst answer</li>\n<li>I've used WP HTTP API to send additional request to keep all in one place, but an AJAX implementation would be nicer</li>\n</ul>\n\n<h2>How To Use</h2>\n\n<p>Pretty simple.</p>\n\n<pre><code>// init the class\nadd_action('admin_init', ['MetaboxStealer', 'init']);\n\n// use the class to merge boxes for current CPT with boxes for another CPT\nadd_action('edit_form_after_editor', function ($post) {\n $stealer_cpt = 'stealer-cpt';\n $steal_from = 'events';\n if ($post->post_type === $stealer_cpt) {\n $stealer = new MetaboxStealer($post->post_type);\n $stealer->steal($steal_from);\n // note that you can steal from different CPTs\n // $stealer->steal($another_steal_from);\n }\n});\n</code></pre>\n\n<h2>The Saving Issue</h2>\n\n<p>No matter how do you manage to show boxes from one CPT in the post edit page of another CPT, is possible that the saving routine checks the post type before saving post meta in it.</p>\n\n<p>In that case, metaboxes from the other CPT, even if showed, will not be saved and you'll probably need to write another saving routine, if you have no access on the original \none.</p>\n"
}
] |
2015/06/18
|
[
"https://wordpress.stackexchange.com/questions/191933",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/403/"
] |
I am looking for a method to get the registered metaboxes for a specific post type (or post ID) when on a separate, unrelated post type. I am working on making a custom "editing" post type for a specific client need and want the ability to load the metaboxes without having them be registered to that 'editable' type.
**Clarification:**
What I am trying to accomplish is the actual display of the metaboxes from another post type. So if my "events" post type has a metabox with date, time, and location, I would want to show those same boxes on a separate post type without actually registering the metabox again.
|
Wrong Assumptions
-----------------
**@Rarst** or **@Dan-Cameron** answers may work, but assume that when you are viewing a post type editing page, the metaboxes for the other post type are all registered.
There are different case in which that won't happen:
* If metaboxes are registered using [`"add_meta_boxes_{$post_type}"`](https://developer.wordpress.org/reference/hooks/add_meta_boxes_post_type/) hook, instead of the more common, generic `"add_meta_boxes"` they won't be available in the admin page for the *stealer* post type
* Even the generic post hook [`"add_meta_boxes"`](https://developer.wordpress.org/reference/hooks/add_meta_boxes/) pass to hooking callbacks the current post type and the current post object as arguments. It means that registering callbacks may use those arguments in some `if` conditions, so is possible that we are in same situation of previous point
In short, unless you have control on how the metaboxes for some post type *A* are registered, you can't be sure they will be able in post editing page for some post type *B*.
In case you have that control, then [@Rarst answer](https://wordpress.stackexchange.com/a/191951/35541) would do the trick.
In case you have not that control, the only way would be a bit tricky.
IMO your only chance, in that case, is to send an HTTP request (AJAX or via WP HTTP API) to the post edit page of the CPT you want to steal the boxes from. You have to add some request variable that will make the page return the boxes array (probaly serialized or JSON-enconded).
After that, you can merge the boxes returned with the boxes for current post, and you are done.
The point is that such code
* is slow (because additional request)
* is not trivial
So, if you have control on which are all the boxes registered for post a certain post type, is much simpler and faster just register those boxes again for the *stealer* post type.
If you can't be sure which are all the boxes for that post type, then the additional HTTP request is your only chance.
I'll post here a class, that implements that workflow ([here](https://gist.github.com/Giuseppe-Mazzapica/e45bb38565e221876958) as Gist for better readability):
```
class MetaboxStealer
{
private static $stealing;
private $post_type;
private $boxes = [];
/**
* When the request contain special variable, this function will make it
* return a serialized version of $wp_meta_boxes array and die.
*/
public static function init()
{
add_filter('post_updated_messages', function ($messages) {
if (MetaboxStealer::stealing()) {
ob_start();
return [];
}
return $messages;
});
add_action('do_meta_boxes', function () {
if (MetaboxStealer::stealing()) {
ob_end_clean();
global $wp_meta_boxes;
echo serialize($wp_meta_boxes);
die();
}
});
}
/**
* Checks that the request contain a special variable that will make request
* return a serialized version of $wp_meta_boxes array and die.
*
* @return bool
*/
public static function stealing()
{
if (is_null(self::$stealing)) {
$screen = function_exists('get_current_screen') ? get_current_screen() : null;
$stealing = filter_input(INPUT_GET, 'stealing-boxes', FILTER_SANITIZE_STRING);
self::$stealing =
$screen instanceof \WP_Screen
&& $stealing
&& wp_verify_nonce($stealing, $screen->post_type);
}
return self::$stealing;
}
/**
* @param string $post_type Current post type
*/
public function __construct($post_type)
{
$this->post_type = $post_type;
}
/**
* Send a HTTP request to post edit page of a given CPT setting a special
* variable that will make that page return serialized $wp_meta_boxes array.
* After that, so obtained boxes are merged with the boxes for current post type.
*
* @param string $cpt CPT to steal metaboxes from
*/
public function steal($cpt)
{
$vars = [
'post_type' => $cpt,
'stealing-boxes' => wp_create_nonce($cpt),
];
$url = add_query_arg($vars, admin_url('/post-new.php'));
$cookies = [];
foreach ($_COOKIE as $name => $value) {
if ('PHPSESSID' !== strtoupper($name)) {
$cookies[] = new \WP_Http_Cookie([
'name' => $name,
'value' => $value,
]);
}
}
$response = wp_remote_get($url, ['cookies' => $cookies]);
if (! is_wp_error($response)) {
$body = wp_remote_retrieve_body($response);
if (is_serialized($body)) {
$boxes = unserialize($body);
$this->boxes = isset($boxes[$cpt]) ? $boxes[$cpt] : [];
empty($this->boxes) or $this->merge();
}
}
}
/**
* Merge metaboxes for current post type with boxes obtained with
* a HTTP request to another CPT post edit page.
*/
private function merge()
{
global $wp_meta_boxes;
isset($wp_meta_boxes[$this->post_type]) or $wp_meta_boxes[$this->post_type] = [];
foreach ($this->boxes as $context => $priorities) {
foreach ($priorities as $priority => $boxes) {
if (! isset($wp_meta_boxes[$this->post_type][$context])) {
$wp_meta_boxes[$this->post_type][$context] = [];
}
if (! isset($wp_meta_boxes[$this->post_type][$context][$priority])) {
$wp_meta_boxes[$this->post_type][$context][$priority] = [];
}
$wp_meta_boxes[$this->post_type][$context][$priority] = array_merge(
$wp_meta_boxes[$this->post_type][$context][$priority],
$boxes
);
}
}
}
}
```
Notes:
* the method `merge()` is highly derived from Rarst answer
* I've used WP HTTP API to send additional request to keep all in one place, but an AJAX implementation would be nicer
How To Use
----------
Pretty simple.
```
// init the class
add_action('admin_init', ['MetaboxStealer', 'init']);
// use the class to merge boxes for current CPT with boxes for another CPT
add_action('edit_form_after_editor', function ($post) {
$stealer_cpt = 'stealer-cpt';
$steal_from = 'events';
if ($post->post_type === $stealer_cpt) {
$stealer = new MetaboxStealer($post->post_type);
$stealer->steal($steal_from);
// note that you can steal from different CPTs
// $stealer->steal($another_steal_from);
}
});
```
The Saving Issue
----------------
No matter how do you manage to show boxes from one CPT in the post edit page of another CPT, is possible that the saving routine checks the post type before saving post meta in it.
In that case, metaboxes from the other CPT, even if showed, will not be saved and you'll probably need to write another saving routine, if you have no access on the original
one.
|
191,938 |
<p><strong>UPDATED QUESTION to be CLEARER</strong></p>
<p>Here's my situation:</p>
<ul>
<li><p>Wordpress top navigation has several menu items that jump to an array of posts within a specific category. For example, if you click "necklaces" you will find yourself in the necklaces section. You can click "next" or "previous" buttons and advance to the next necklace post.</p></li>
<li><p>At the top of the page, there is an H2 tag which displays the title by getting its category name:</p>
<pre><code><?php
$category = get_the_category();
echo $category[0]->cat_name;
?>
</code></pre></li>
<li><p>The problem is that all these posts are listed under MULTIPLE categories. The above code only gets the first category. If one post is listed under the categories of "necklaces" as well as "pendants" then it's going to display the wrong title in one of these categories.</p></li>
</ul>
<p>So, I need to have the title display the correct category according to the actual category the user is in at the moment. Currently, when you click "next" or "previous", the title will randomly change depending on which category is listed as first for that particular post.</p>
<p>There are dozens of categories. They all share the single.php template. I am trying to change the title on the single.php template page NOT category.php</p>
|
[
{
"answer_id": 191939,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 0,
"selected": false,
"text": "<p>What's the simplest way to spit out a single category as a title in an H2 tag for a post with multiple categories? </p>\n\n<pre><code>$c = get_the_category();\nif (!empty($c[0])) {\n echo $c[0]->name;\n}\n</code></pre>\n\n<p>I have no idea how or why sessions would come into that.</p>\n"
},
{
"answer_id": 192018,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>In order for this to work, you will need to know from where the single post was refered from and if the referrer is a valid one. Secondly, we need to adjust pagination between single posts in order for us to pass our referrer between single posts. </p>\n\n<p>The problem with referrers is, they are set and controlled by user side. Referrers can be disabled or blocked (like users accessing a site behind a proxy). Just for interest sake, here is very interesting answer to the question <em>In what cases will http referrer be empty</em> taken from <a href=\"https://stackoverflow.com/a/6880668/1908141\">this post on SO</a></p>\n\n<p>It will/may be empty when the enduser</p>\n\n<ul>\n<li>entered the site URL in browser address bar itself.</li>\n<li>visited the site by a browser-maintained bookmark.</li>\n<li>visited the site as first page in the window/tab.</li>\n<li>switched from a https URL to a http URL.</li>\n<li>switched from a https URL to a different https URL.</li>\n<li>has security software installed (antivirus/firewall/etc) which strips the referrer from all requests.</li>\n<li>is behind a proxy which strips the referrer from all requests.</li>\n<li>visited the site programmatically (like, <a href=\"http://php.net/manual/en/ref.curl.php\" rel=\"nofollow noreferrer\">curl</a>) without setting the referrer header (searchbots!).</li>\n</ul>\n\n<p>You would want to read the other answers there as well for extra insight</p>\n\n<p>I sat with similar issue and was looking for a more reliable way to set and pass referrers, and this led to <a href=\"https://wordpress.stackexchange.com/q/170007/31545\">this question</a> and a wonderful <a href=\"https://wordpress.stackexchange.com/a/170016/31545\">answer by @gmazzap</a></p>\n\n<p>So your solution would be based on something similar. We will be adding a special parameter to our URL which will serve as referrer (<em>I have made the assumption that your posts are from the build in post type <code>post</code> and taxonomy <code>category</code></em>)</p>\n\n<ul>\n<li><p>Identify our category pages and add a referrer to the post links via the <code>post_link</code> filter. This referrer will hold the category id. You can use the category name, but this can become quite messy in your URL. The choice is all up you.</p>\n\n<pre><code>add_filter('post_link', function( $permalink ) // Change to post_type_link for custom post type posts\n{\n if ( is_category() // Change to is_tax() for custom taxonomy pages\n && ( $cat = get_queried_object() ) \n ) {\n $permalink = esc_url( add_query_arg( array( 'ref' => $cat->term_id ), $permalink ) );\n }\n return $permalink;\n});\n</code></pre>\n\n<p>This will give you a URL like the following on your single post page if you click on a post link on the category page</p>\n\n<pre><code>http://example.com/wordpress/post-name?ref=1\n</code></pre></li>\n<li><p>We must have a way to read and use that info from the URL in order to make it useful. For this, we must add a the query arg <code>ref</code> so Wordpress can read it</p>\n\n<pre><code>add_filter( 'query_vars', function ( $vars ) \n{\n $vars[] = 'ref';\n return $vars;\n});\n</code></pre></li>\n<li><p>All you need to do now, is to check if the single post was a referred post, get the value from the URL and use that info to display the correct category name (<strong><em>NOTE:</strong> This piece of code goes into your <code>single.php</code></em>)</p>\n\n<pre><code>$referrer = filter_input( INPUT_GET, 'ref', FILTER_VALIDATE_INT ); // This validate and checks if our referrer \"ref\" is set\nif ( $referrer ) {\n $category = get_category( $referrer );\n echo '<h2>' . $category->name . '</h2>';\n}\n</code></pre></li>\n</ul>\n\n<p>The above is just a rough draft of what you can do to accomplish this, it just gives you a foundation to work from. You can tweak and modify it as needed.</p>\n\n<p>On your single pages, you will also need to get your referrer and pass that to your next and previous post links in order to maintain this feature between posts. I have written an answer for pagination based on this, it is quite bulky though and can use some clean up. There are some parts that I have handled here now, and there are also parts that you will most probably never need which you can just remove. You can work through it and modify and adjust it as needed. </p>\n\n<p>I am busy rewritting the complete pagination function ( using better and cleaner php functionality ) with some extra features, the classes are done, it is just the final pieces putting everything into functional functions that is giving me a nightmare, and to be honest, I haven't got back to working on the project for quite some time now as I really don't have much time at night. When it will be completed is still a mystery. But the idea and code from what I have given in that specific answer should do the trick for you. You can check out my answer and referrer pagination function <a href=\"https://wordpress.stackexchange.com/a/173041/31545\">here</a></p>\n\n<h2>EDIT</h2>\n\n<p>I have quickly written a small plugin which covers the referrer and new pagination links to carry the referrer across multiple single posts. This pagination links will also page between single posts from the referrer</p>\n\n<p>What this means is, if a single post was clicked from <code>category B</code>, and this post has three categories, <code>category A</code>, <code>category B</code> and <code>category C</code>, the next and previous adjacent post will be from <code>category B</code>. If you go to either post, the adjacent post from that clicked single post will also be from <code>category B</code> etc</p>\n\n<p>I have commented the code so you should be able to follow it better and also adjust and modify it as needed. Just copy and paste this code in a plugin file and activate it. Alternatively, copy the code (without the plugin header of course) and paste it as is into your <code>functions.php</code> (<strong><em>NOTE:</strong> This only works for the build in taxonomy <code>category</code> and the build in post type <code>post</code>. You should modify it accordingly to your needs according to post type and custom taxonomy</em>)</p>\n\n<pre><code><?php\n/*\n * Plugin Name: Category referred posts\n * URI: https://wordpress.stackexchange.com/a/192018/31545\n * Description: Add referrer links to single posts and pagination if single posts was referred from a category page\n * Version: 1.0\n * Author: Pieter Goosen\n */\n\n/*\n * Add our custom query vars so Wordpress can read it\n */\nadd_filter( 'query_vars', function ( $vars ) \n{\n $vars[] = 'ref';\n return $vars;\n});\n\n/* \n * Add our referrer to single post links if we are on a category page\n */\nadd_filter('post_link', function( $permalink ) // Change to post_type_link for custom post type posts\n{\n if ( is_category() // Change to is_tax() for custom taxonomy pages\n && ( $cat = get_queried_object() ) \n ) {\n $permalink = esc_url( add_query_arg( ['ref' => $cat->term_id], $permalink ) );\n }\n return $permalink;\n});\n\n/*\n * Create our custom adjacent post link \n */\nfunction get_referred_adjacent_post( $args = [] ) \n{\n //First check if we are on a single post, else return false\n if ( !is_single() )\n return false;\n\n //Defaults arguments set for the function. \n $defaults = [\n 'previous' => true,\n 'anchor_text' => '%anchor',\n 'post_link_text' => '%text',\n 'span_text_prev' => __( 'Older post: ' ),\n 'span_text_next' => __( 'Newer post: ' ),\n ]; \n\n $combined_args = wp_parse_args( $args, $defaults );\n\n /**\n * Get the currently displayed single post. For this use \n * get_queried_object() as this is more safe than the global $post\n *\n * The $post global is very easily changed by any poorly written custom query\n * or function, and is there for not reliable\n *\n * @see Post below on WPSE for explanation\n * @link https://wordpress.stackexchange.com/q/167706/31545\n */ \n $current_post = get_queried_object();\n $current_post_date = $current_post->post_date;\n $current_post_type = $current_post->post_type;\n\n //Set the important parameters to either get the next post or previous post\n $previous = $combined_args['previous'];\n $order = ( $previous ) ? 'DESC' : 'ASC';\n $op = ( $previous ) ? 'before' : 'after';\n\n // Check if we have a referrer, if so, we need to set this to get the next post in this specific referrer category\n $cat_id = filter_input( INPUT_GET, 'ref', FILTER_VALIDATE_INT );\n\n if ( $cat_id )\n $custom_args = ['cat' => $cat_id];\n\n /**\n * Set the default arguments to merge with the referrer arguments\n *\n * Uses date_query (introduced Wordpress 3.7) to calculate the appropriate adjacent post\n * @see http://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters\n */ \n $query_args = [\n 'post_type' => $current_post_type,\n 'posts_per_page' => 1,\n 'order' => $order,\n 'no_found_rows' => true,\n 'suppress_filters' => true,\n 'date_query' => [\n [\n $op => $current_post_date,\n 'inclusive' => false\n ]\n ]\n ];\n\n $query_args = ( isset( $custom_args ) ) ? wp_parse_args( $custom_args, $query_args ) : $query_args;\n\n $q = new WP_Query( $query_args );\n\n //If there are no post found, bail early\n if( !$q->have_posts() === 0 )\n return false;\n\n //If there are posts, continue\n $adjacent_post = $q->posts[0];\n\n //Build the permalinks for the adjacent post\n $permalink = get_permalink( $adjacent_post->ID );\n\n // Return the correct permalink, we should add our referrer to the link now if this post was referred\n $link = ( $cat_id ) ? add_query_arg( ['ref' => $cat_id], $permalink ) : $permalink;\n\n // Set up out link text to display\n $span_text = ( $combined_args['previous'] ) ? $combined_args['span_text_prev'] : $combined_args['span_text_next'];\n $span = '<span class=\"meta-nav\">' . $span_text . '</span>';\n\n // Create our anchor and post title text. By default. The post title is used\n $anchor_text = ( $combined_args['anchor_text'] == '%anchor' ) ? $adjacent_post->post_title : $combined_args['anchor_text'];\n $post_title = ( $combined_args['post_link_text'] == '%text' ) ? $adjacent_post->post_title : $combined_args['post_link_text'];\n\n //Create the link with title name and anchor text\n $adjacent_post_link = $span . '<a href=\"' . $link . '\" title=\"' . $anchor_text . '\">' . $post_title . '</a>';\n\n return $adjacent_post_link;\n}\n\n// Create the next post link - Return the post link\nfunction get_next_adjacent_post_link( $anchor_text = '%anchor', $post_link_text = '%text', $span_text_next = 'Newer post: ' )\n{\n $args = [\n 'previous' => false,\n 'anchor_text' => $anchor_text,\n 'post_link_text' => $post_link_text,\n 'span_text_next' => $span_text_next,\n ];\n return get_referred_adjacent_post( $args );\n}\n\n// Create the previous post link - Return the post link\nfunction get_previos_adjacent_post_link( $anchor_text = '%anchor', $post_link_text = '%text', $span_text_prev = 'Older post: ' )\n{\n $args = [\n 'previous' => true,\n 'anchor_text' => $anchor_text,\n 'post_link_text' => $post_link_text,\n 'span_text_prev' => $span_text_prev,\n ];\n return get_referred_adjacent_post( $args );\n}\n\n// Create the next post link - Echo post link\nfunction next_adjacent_post_link( $anchor_text = '%anchor', $post_link_text = '%text', $span_text_next = 'Newer post: ' )\n{\n echo get_next_adjacent_post_link( $anchor_text, $post_link_text, $span_text_next );\n}\n\n// Create the previous post link - Echo post link\nfunction previos_adjacent_post_link( $anchor_text = '%anchor', $post_link_text = '%text', $span_text_prev = 'Older post: ' )\n{\n echo get_previos_adjacent_post_link( $anchor_text, $post_link_text, $span_text_prev );\n}\n</code></pre>\n\n<p>You should now add the following in your single.php:</p>\n\n<ul>\n<li><p>To display your custom text</p>\n\n<pre><code>$referrer = filter_input( INPUT_GET, 'ref', FILTER_VALIDATE_INT ); // This validate and checks if our referrer \"ref\" is set\nif ( $referrer ) {\n $category = get_category( $referrer );\n echo '<h2>' . $category->name . '</h2>';\n}\n</code></pre></li>\n<li><p>To display your post links</p>\n\n<pre><code>if ( function_exists( 'next_adjacent_post_link' ) )\n next_adjacent_post_link();\nif ( function_exists( 'previos_adjacent_post_link' ) )\n previos_adjacent_post_link();\n</code></pre>\n\n<p>Just add your relevant mark up to your links. Also check the accepted arguments to customize the text the links display.</p></li>\n</ul>\n\n<p>This should lay the foundation to set you on your way. You should be able to customize this to suit your exact needs</p>\n"
},
{
"answer_id": 277362,
"author": "YuriGoul",
"author_id": 126121,
"author_profile": "https://wordpress.stackexchange.com/users/126121",
"pm_score": 0,
"selected": false,
"text": "<p>I have been looking for like two days before I found this, why this is not standard behavior in WP is beyond me. The only thing I did find were plugins that were no longer working and code that did not take into account that there are hierarchical categories and that there could be multiple tags and categories attached to a post.</p>\n\n<p>FYI: I expanded the code van Pieter Goosen to also include the tags. I also corrected something the showing of next and previous links at the end of the line to posts that were not there. And I decided to separate the normal next-prev-post stuff from the next-pref stuff from this code in single.php. The thing that I did not get to work was using menu_order as sorting - since I have a custom post order - ah well.</p>\n\n<p>This is now in my functions.php:</p>\n\n<pre><code>/*\n * Add our custom query vars so Wordpress can read it\n */\nadd_filter( 'query_vars', function ( $vars )\n{\n array_push($vars, \"ref\", \"thetype\");\n return $vars;\n});\n\n/*\n * Add our referrer to single post links if we are on a category page\n */\nadd_filter('post_link', function( $permalink ) // Change to post_type_link for custom post type posts\n{\n if ( is_category() // Change to is_tax() for custom taxonomy pages\n && ( $cat = get_queried_object() )\n ) {\n $permalink = esc_url( add_query_arg( ['ref' => $cat->term_id], $permalink ) );\n $permalink = esc_url( add_query_arg( ['thetype' => 'category'], $permalink ) );\n }\n\n if ( is_tag() // Change to is_tax() for custom taxonomy pages\n && ( $cat = get_queried_object() )\n ) {\n $permalink = esc_url( add_query_arg( ['ref' => $cat->term_id], $permalink ) );\n $permalink = esc_url( add_query_arg( ['thetype' => 'tag'], $permalink ) );\n }\n\n return $permalink;\n\n});\n\n/*\n * Create our custom adjacent post link\n */\nfunction get_referred_adjacent_post( $args = [] )\n{\n //First check if we are on a single post, else return false\n if ( !is_single() )\n return false;\n\n //Defaults arguments set for the function.\n $defaults = [\n 'previous' => true,\n 'anchor_text' => '%anchor',\n 'post_link_text' => '%text',\n 'span_text_prev' => __( 'Older post: ' ),\n 'span_text_next' => __( 'Newer post: ' ),\n ];\n\n $combined_args = wp_parse_args( $args, $defaults );\n\n /**\n * Get the currently displayed single post. For this use\n * get_queried_object() as this is more safe than the global $post\n *\n * The $post global is very easily changed by any poorly written custom query\n * or function, and is there for not reliable\n *\n * @see Post below on WPSE for explanation\n * @link https://wordpress.stackexchange.com/q/167706/31545\n */\n $current_post = get_queried_object();\n $current_post_date = $current_post->post_date;\n $current_post_type = $current_post->post_type;\n $current_post_ID = $current_post->ID;\n\n\n //Set the important parameters to either get the next post or previous post\n $previous = $combined_args['previous'];\n $order = ( $previous ) ? 'DESC' : 'ASC';\n $op = ( $previous ) ? 'before' : 'after';\n $css_class = $combined_args['css_class'];\n\n // Check if we have a referrer, if so, we need to set this to get the next post in this specific referrer category\n $mytype = filter_input( INPUT_GET, 'thetype');\n if ($mytype == 'category')\n {\n $cat_id = filter_input( INPUT_GET, 'ref', FILTER_VALIDATE_INT );\n if ( $cat_id )\n $custom_args = ['cat' => $cat_id];\n\n }\n else\n {\n $cat_id = filter_input( INPUT_GET, 'ref', FILTER_VALIDATE_INT );\n if ( $cat_id )\n $custom_args = ['tag_id' => $cat_id];\n\n }\n\n\n /**\n * Set the default arguments to merge with the referrer arguments\n *\n * Uses date_query (introduced Wordpress 3.7) to calculate the appropriate adjacent post\n * @see http://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters\n */\n $query_args = [\n 'post_type' => $current_post_type,\n 'posts_per_page' => 1,\n 'order' => $order,\n 'no_found_rows' => true,\n 'suppress_filters' => true,\n 'date_query' => [\n [\n $op => $current_post_date,\n 'inclusive' => false\n ]\n ]\n ];\n\n $query_args = ( isset( $custom_args ) ) ? wp_parse_args( $custom_args, $query_args ) : $query_args;\n\n $q = new WP_Query( $query_args );\n\n //If there are no post found, bail early\n if( !$q->have_posts() === 0 )\n return false;\n\n //If there are posts, continue\n $adjacent_post = $q->posts[0];\n\n if( empty($adjacent_post->ID) ) return false;\n\n //Build the permalinks for the adjacent post\n $permalink = get_permalink( $adjacent_post->ID );\n\n // Return the correct permalink, we should add our referrer to the link now if this post was referred\n $link = ( $cat_id ) ? add_query_arg( ['ref' => $cat_id, 'thetype' => $mytype], $permalink ) : $permalink;\n\n\n // Set up out link text to display\n$span_text = ( $combined_args['previous'] ) ? $combined_args['span_text_prev'] : $combined_args['span_text_next'];\n$span = '<span class=\"meta-nav\">' . $span_text . '</span>';\n\n// Create our anchor and post title text. By default. The post title is used\n$anchor_text = ( $combined_args['anchor_text'] == '%anchor' ) ? $adjacent_post->post_title : $combined_args['anchor_text'];\n$post_title = ( $combined_args['post_link_text'] == '%text' ) ? $adjacent_post->post_title : $combined_args['post_link_text'];\n\n//Create the link with title name and anchor text\n$adjacent_post_link = $span . '<a href=\"' . $link . '\" class=\"' . $css_class . '\" title=\"' . $anchor_text . '\">' . $post_title . '</a>';\n return $adjacent_post_link;\n}\n\n// Create the next post link - Return the post link\nfunction get_next_adjacent_post_link( $anchor_text = '%anchor', $post_link_text = '%text', $span_text_next = 'Newer post: ' )\n{\n $args = [\n 'previous' => false,\n 'anchor_text' => $anchor_text,\n 'post_link_text' => $post_link_text,\n 'span_text_next' => $span_text_next,\n 'css_class' => \"post-nav-next\",\n ];\n return get_referred_adjacent_post( $args );\n}\n\n// Create the previous post link - Return the post link\nfunction get_previos_adjacent_post_link( $anchor_text = '%anchor', $post_link_text = '%text', $span_text_prev = 'Older post: ' )\n{\n $args = [\n 'previous' => true,\n 'anchor_text' => $anchor_text,\n 'post_link_text' => $post_link_text,\n 'span_text_prev' => $span_text_prev,\n 'css_class' => \"post-nav-prev\",\n ];\n return get_referred_adjacent_post( $args );\n}\n\n// Create the next post link - Echo post link\nfunction next_adjacent_post_link( $anchor_text = '%anchor', $post_link_text = '%text', $span_text_next = 'Next post ' )\n{\n echo get_next_adjacent_post_link( $anchor_text, $post_link_text, $span_text_next );\n}\n\n// Create the previous post link - Echo post link\nfunction previos_adjacent_post_link( $anchor_text = '%anchor', $post_link_text = '%text', $span_text_prev = 'Previous post ' )\n{\n echo get_previos_adjacent_post_link( $anchor_text, $post_link_text, $span_text_prev );\n}\n</code></pre>\n\n<p>From the single.php:</p>\n\n<pre><code><?php $referrer = filter_input( INPUT_GET, 'ref', FILTER_VALIDATE_INT );?>\n<!-- // checks if our referrer \"ref\" is set -->\n<?php if ( $referrer ): ?>\n\n if ( function_exists( 'next_adjacent_post_link' ) )\n next_adjacent_post_link();\n if ( function_exists( 'previos_adjacent_post_link' ) )\n previos_adjacent_post_link();\n\n<?php else: ?> <!--else referer -->\n\n <!--normal prev next links here -->\n\n<?php endif; ?> <!-- end if refferer -->\n</code></pre>\n"
}
] |
2015/06/18
|
[
"https://wordpress.stackexchange.com/questions/191938",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74898/"
] |
**UPDATED QUESTION to be CLEARER**
Here's my situation:
* Wordpress top navigation has several menu items that jump to an array of posts within a specific category. For example, if you click "necklaces" you will find yourself in the necklaces section. You can click "next" or "previous" buttons and advance to the next necklace post.
* At the top of the page, there is an H2 tag which displays the title by getting its category name:
```
<?php
$category = get_the_category();
echo $category[0]->cat_name;
?>
```
* The problem is that all these posts are listed under MULTIPLE categories. The above code only gets the first category. If one post is listed under the categories of "necklaces" as well as "pendants" then it's going to display the wrong title in one of these categories.
So, I need to have the title display the correct category according to the actual category the user is in at the moment. Currently, when you click "next" or "previous", the title will randomly change depending on which category is listed as first for that particular post.
There are dozens of categories. They all share the single.php template. I am trying to change the title on the single.php template page NOT category.php
|
In order for this to work, you will need to know from where the single post was refered from and if the referrer is a valid one. Secondly, we need to adjust pagination between single posts in order for us to pass our referrer between single posts.
The problem with referrers is, they are set and controlled by user side. Referrers can be disabled or blocked (like users accessing a site behind a proxy). Just for interest sake, here is very interesting answer to the question *In what cases will http referrer be empty* taken from [this post on SO](https://stackoverflow.com/a/6880668/1908141)
It will/may be empty when the enduser
* entered the site URL in browser address bar itself.
* visited the site by a browser-maintained bookmark.
* visited the site as first page in the window/tab.
* switched from a https URL to a http URL.
* switched from a https URL to a different https URL.
* has security software installed (antivirus/firewall/etc) which strips the referrer from all requests.
* is behind a proxy which strips the referrer from all requests.
* visited the site programmatically (like, [curl](http://php.net/manual/en/ref.curl.php)) without setting the referrer header (searchbots!).
You would want to read the other answers there as well for extra insight
I sat with similar issue and was looking for a more reliable way to set and pass referrers, and this led to [this question](https://wordpress.stackexchange.com/q/170007/31545) and a wonderful [answer by @gmazzap](https://wordpress.stackexchange.com/a/170016/31545)
So your solution would be based on something similar. We will be adding a special parameter to our URL which will serve as referrer (*I have made the assumption that your posts are from the build in post type `post` and taxonomy `category`*)
* Identify our category pages and add a referrer to the post links via the `post_link` filter. This referrer will hold the category id. You can use the category name, but this can become quite messy in your URL. The choice is all up you.
```
add_filter('post_link', function( $permalink ) // Change to post_type_link for custom post type posts
{
if ( is_category() // Change to is_tax() for custom taxonomy pages
&& ( $cat = get_queried_object() )
) {
$permalink = esc_url( add_query_arg( array( 'ref' => $cat->term_id ), $permalink ) );
}
return $permalink;
});
```
This will give you a URL like the following on your single post page if you click on a post link on the category page
```
http://example.com/wordpress/post-name?ref=1
```
* We must have a way to read and use that info from the URL in order to make it useful. For this, we must add a the query arg `ref` so Wordpress can read it
```
add_filter( 'query_vars', function ( $vars )
{
$vars[] = 'ref';
return $vars;
});
```
* All you need to do now, is to check if the single post was a referred post, get the value from the URL and use that info to display the correct category name (***NOTE:*** This piece of code goes into your `single.php`)
```
$referrer = filter_input( INPUT_GET, 'ref', FILTER_VALIDATE_INT ); // This validate and checks if our referrer "ref" is set
if ( $referrer ) {
$category = get_category( $referrer );
echo '<h2>' . $category->name . '</h2>';
}
```
The above is just a rough draft of what you can do to accomplish this, it just gives you a foundation to work from. You can tweak and modify it as needed.
On your single pages, you will also need to get your referrer and pass that to your next and previous post links in order to maintain this feature between posts. I have written an answer for pagination based on this, it is quite bulky though and can use some clean up. There are some parts that I have handled here now, and there are also parts that you will most probably never need which you can just remove. You can work through it and modify and adjust it as needed.
I am busy rewritting the complete pagination function ( using better and cleaner php functionality ) with some extra features, the classes are done, it is just the final pieces putting everything into functional functions that is giving me a nightmare, and to be honest, I haven't got back to working on the project for quite some time now as I really don't have much time at night. When it will be completed is still a mystery. But the idea and code from what I have given in that specific answer should do the trick for you. You can check out my answer and referrer pagination function [here](https://wordpress.stackexchange.com/a/173041/31545)
EDIT
----
I have quickly written a small plugin which covers the referrer and new pagination links to carry the referrer across multiple single posts. This pagination links will also page between single posts from the referrer
What this means is, if a single post was clicked from `category B`, and this post has three categories, `category A`, `category B` and `category C`, the next and previous adjacent post will be from `category B`. If you go to either post, the adjacent post from that clicked single post will also be from `category B` etc
I have commented the code so you should be able to follow it better and also adjust and modify it as needed. Just copy and paste this code in a plugin file and activate it. Alternatively, copy the code (without the plugin header of course) and paste it as is into your `functions.php` (***NOTE:*** This only works for the build in taxonomy `category` and the build in post type `post`. You should modify it accordingly to your needs according to post type and custom taxonomy)
```
<?php
/*
* Plugin Name: Category referred posts
* URI: https://wordpress.stackexchange.com/a/192018/31545
* Description: Add referrer links to single posts and pagination if single posts was referred from a category page
* Version: 1.0
* Author: Pieter Goosen
*/
/*
* Add our custom query vars so Wordpress can read it
*/
add_filter( 'query_vars', function ( $vars )
{
$vars[] = 'ref';
return $vars;
});
/*
* Add our referrer to single post links if we are on a category page
*/
add_filter('post_link', function( $permalink ) // Change to post_type_link for custom post type posts
{
if ( is_category() // Change to is_tax() for custom taxonomy pages
&& ( $cat = get_queried_object() )
) {
$permalink = esc_url( add_query_arg( ['ref' => $cat->term_id], $permalink ) );
}
return $permalink;
});
/*
* Create our custom adjacent post link
*/
function get_referred_adjacent_post( $args = [] )
{
//First check if we are on a single post, else return false
if ( !is_single() )
return false;
//Defaults arguments set for the function.
$defaults = [
'previous' => true,
'anchor_text' => '%anchor',
'post_link_text' => '%text',
'span_text_prev' => __( 'Older post: ' ),
'span_text_next' => __( 'Newer post: ' ),
];
$combined_args = wp_parse_args( $args, $defaults );
/**
* Get the currently displayed single post. For this use
* get_queried_object() as this is more safe than the global $post
*
* The $post global is very easily changed by any poorly written custom query
* or function, and is there for not reliable
*
* @see Post below on WPSE for explanation
* @link https://wordpress.stackexchange.com/q/167706/31545
*/
$current_post = get_queried_object();
$current_post_date = $current_post->post_date;
$current_post_type = $current_post->post_type;
//Set the important parameters to either get the next post or previous post
$previous = $combined_args['previous'];
$order = ( $previous ) ? 'DESC' : 'ASC';
$op = ( $previous ) ? 'before' : 'after';
// Check if we have a referrer, if so, we need to set this to get the next post in this specific referrer category
$cat_id = filter_input( INPUT_GET, 'ref', FILTER_VALIDATE_INT );
if ( $cat_id )
$custom_args = ['cat' => $cat_id];
/**
* Set the default arguments to merge with the referrer arguments
*
* Uses date_query (introduced Wordpress 3.7) to calculate the appropriate adjacent post
* @see http://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters
*/
$query_args = [
'post_type' => $current_post_type,
'posts_per_page' => 1,
'order' => $order,
'no_found_rows' => true,
'suppress_filters' => true,
'date_query' => [
[
$op => $current_post_date,
'inclusive' => false
]
]
];
$query_args = ( isset( $custom_args ) ) ? wp_parse_args( $custom_args, $query_args ) : $query_args;
$q = new WP_Query( $query_args );
//If there are no post found, bail early
if( !$q->have_posts() === 0 )
return false;
//If there are posts, continue
$adjacent_post = $q->posts[0];
//Build the permalinks for the adjacent post
$permalink = get_permalink( $adjacent_post->ID );
// Return the correct permalink, we should add our referrer to the link now if this post was referred
$link = ( $cat_id ) ? add_query_arg( ['ref' => $cat_id], $permalink ) : $permalink;
// Set up out link text to display
$span_text = ( $combined_args['previous'] ) ? $combined_args['span_text_prev'] : $combined_args['span_text_next'];
$span = '<span class="meta-nav">' . $span_text . '</span>';
// Create our anchor and post title text. By default. The post title is used
$anchor_text = ( $combined_args['anchor_text'] == '%anchor' ) ? $adjacent_post->post_title : $combined_args['anchor_text'];
$post_title = ( $combined_args['post_link_text'] == '%text' ) ? $adjacent_post->post_title : $combined_args['post_link_text'];
//Create the link with title name and anchor text
$adjacent_post_link = $span . '<a href="' . $link . '" title="' . $anchor_text . '">' . $post_title . '</a>';
return $adjacent_post_link;
}
// Create the next post link - Return the post link
function get_next_adjacent_post_link( $anchor_text = '%anchor', $post_link_text = '%text', $span_text_next = 'Newer post: ' )
{
$args = [
'previous' => false,
'anchor_text' => $anchor_text,
'post_link_text' => $post_link_text,
'span_text_next' => $span_text_next,
];
return get_referred_adjacent_post( $args );
}
// Create the previous post link - Return the post link
function get_previos_adjacent_post_link( $anchor_text = '%anchor', $post_link_text = '%text', $span_text_prev = 'Older post: ' )
{
$args = [
'previous' => true,
'anchor_text' => $anchor_text,
'post_link_text' => $post_link_text,
'span_text_prev' => $span_text_prev,
];
return get_referred_adjacent_post( $args );
}
// Create the next post link - Echo post link
function next_adjacent_post_link( $anchor_text = '%anchor', $post_link_text = '%text', $span_text_next = 'Newer post: ' )
{
echo get_next_adjacent_post_link( $anchor_text, $post_link_text, $span_text_next );
}
// Create the previous post link - Echo post link
function previos_adjacent_post_link( $anchor_text = '%anchor', $post_link_text = '%text', $span_text_prev = 'Older post: ' )
{
echo get_previos_adjacent_post_link( $anchor_text, $post_link_text, $span_text_prev );
}
```
You should now add the following in your single.php:
* To display your custom text
```
$referrer = filter_input( INPUT_GET, 'ref', FILTER_VALIDATE_INT ); // This validate and checks if our referrer "ref" is set
if ( $referrer ) {
$category = get_category( $referrer );
echo '<h2>' . $category->name . '</h2>';
}
```
* To display your post links
```
if ( function_exists( 'next_adjacent_post_link' ) )
next_adjacent_post_link();
if ( function_exists( 'previos_adjacent_post_link' ) )
previos_adjacent_post_link();
```
Just add your relevant mark up to your links. Also check the accepted arguments to customize the text the links display.
This should lay the foundation to set you on your way. You should be able to customize this to suit your exact needs
|
191,947 |
<p>I've been developing a website on wordpress for some time now and came across some issues but until now I could figure it out, not today... Yesterday I've worked some more on the website and today when I came back to do some more work the pages on my site that are part of my navigation menu didn't load properly (minus the home page that is static and a news page that is the index page), they were loading the index.php page. Also with my posts in the news(index) page the load the index page instead of the post content. The URLs appear correct, but the loaded page is the index one. This doesn´t happen with the other pages I have that are not in the navigation menu and also with some custom post types, everything works fine there. The strange thing is that it happened from nothing, maybe is a quick fix... or not, I'm not an expert.</p>
<p>Thank you in advance and if you could help me I would aprecciate it!</p>
|
[
{
"answer_id": 191939,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 0,
"selected": false,
"text": "<p>What's the simplest way to spit out a single category as a title in an H2 tag for a post with multiple categories? </p>\n\n<pre><code>$c = get_the_category();\nif (!empty($c[0])) {\n echo $c[0]->name;\n}\n</code></pre>\n\n<p>I have no idea how or why sessions would come into that.</p>\n"
},
{
"answer_id": 192018,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>In order for this to work, you will need to know from where the single post was refered from and if the referrer is a valid one. Secondly, we need to adjust pagination between single posts in order for us to pass our referrer between single posts. </p>\n\n<p>The problem with referrers is, they are set and controlled by user side. Referrers can be disabled or blocked (like users accessing a site behind a proxy). Just for interest sake, here is very interesting answer to the question <em>In what cases will http referrer be empty</em> taken from <a href=\"https://stackoverflow.com/a/6880668/1908141\">this post on SO</a></p>\n\n<p>It will/may be empty when the enduser</p>\n\n<ul>\n<li>entered the site URL in browser address bar itself.</li>\n<li>visited the site by a browser-maintained bookmark.</li>\n<li>visited the site as first page in the window/tab.</li>\n<li>switched from a https URL to a http URL.</li>\n<li>switched from a https URL to a different https URL.</li>\n<li>has security software installed (antivirus/firewall/etc) which strips the referrer from all requests.</li>\n<li>is behind a proxy which strips the referrer from all requests.</li>\n<li>visited the site programmatically (like, <a href=\"http://php.net/manual/en/ref.curl.php\" rel=\"nofollow noreferrer\">curl</a>) without setting the referrer header (searchbots!).</li>\n</ul>\n\n<p>You would want to read the other answers there as well for extra insight</p>\n\n<p>I sat with similar issue and was looking for a more reliable way to set and pass referrers, and this led to <a href=\"https://wordpress.stackexchange.com/q/170007/31545\">this question</a> and a wonderful <a href=\"https://wordpress.stackexchange.com/a/170016/31545\">answer by @gmazzap</a></p>\n\n<p>So your solution would be based on something similar. We will be adding a special parameter to our URL which will serve as referrer (<em>I have made the assumption that your posts are from the build in post type <code>post</code> and taxonomy <code>category</code></em>)</p>\n\n<ul>\n<li><p>Identify our category pages and add a referrer to the post links via the <code>post_link</code> filter. This referrer will hold the category id. You can use the category name, but this can become quite messy in your URL. The choice is all up you.</p>\n\n<pre><code>add_filter('post_link', function( $permalink ) // Change to post_type_link for custom post type posts\n{\n if ( is_category() // Change to is_tax() for custom taxonomy pages\n && ( $cat = get_queried_object() ) \n ) {\n $permalink = esc_url( add_query_arg( array( 'ref' => $cat->term_id ), $permalink ) );\n }\n return $permalink;\n});\n</code></pre>\n\n<p>This will give you a URL like the following on your single post page if you click on a post link on the category page</p>\n\n<pre><code>http://example.com/wordpress/post-name?ref=1\n</code></pre></li>\n<li><p>We must have a way to read and use that info from the URL in order to make it useful. For this, we must add a the query arg <code>ref</code> so Wordpress can read it</p>\n\n<pre><code>add_filter( 'query_vars', function ( $vars ) \n{\n $vars[] = 'ref';\n return $vars;\n});\n</code></pre></li>\n<li><p>All you need to do now, is to check if the single post was a referred post, get the value from the URL and use that info to display the correct category name (<strong><em>NOTE:</strong> This piece of code goes into your <code>single.php</code></em>)</p>\n\n<pre><code>$referrer = filter_input( INPUT_GET, 'ref', FILTER_VALIDATE_INT ); // This validate and checks if our referrer \"ref\" is set\nif ( $referrer ) {\n $category = get_category( $referrer );\n echo '<h2>' . $category->name . '</h2>';\n}\n</code></pre></li>\n</ul>\n\n<p>The above is just a rough draft of what you can do to accomplish this, it just gives you a foundation to work from. You can tweak and modify it as needed.</p>\n\n<p>On your single pages, you will also need to get your referrer and pass that to your next and previous post links in order to maintain this feature between posts. I have written an answer for pagination based on this, it is quite bulky though and can use some clean up. There are some parts that I have handled here now, and there are also parts that you will most probably never need which you can just remove. You can work through it and modify and adjust it as needed. </p>\n\n<p>I am busy rewritting the complete pagination function ( using better and cleaner php functionality ) with some extra features, the classes are done, it is just the final pieces putting everything into functional functions that is giving me a nightmare, and to be honest, I haven't got back to working on the project for quite some time now as I really don't have much time at night. When it will be completed is still a mystery. But the idea and code from what I have given in that specific answer should do the trick for you. You can check out my answer and referrer pagination function <a href=\"https://wordpress.stackexchange.com/a/173041/31545\">here</a></p>\n\n<h2>EDIT</h2>\n\n<p>I have quickly written a small plugin which covers the referrer and new pagination links to carry the referrer across multiple single posts. This pagination links will also page between single posts from the referrer</p>\n\n<p>What this means is, if a single post was clicked from <code>category B</code>, and this post has three categories, <code>category A</code>, <code>category B</code> and <code>category C</code>, the next and previous adjacent post will be from <code>category B</code>. If you go to either post, the adjacent post from that clicked single post will also be from <code>category B</code> etc</p>\n\n<p>I have commented the code so you should be able to follow it better and also adjust and modify it as needed. Just copy and paste this code in a plugin file and activate it. Alternatively, copy the code (without the plugin header of course) and paste it as is into your <code>functions.php</code> (<strong><em>NOTE:</strong> This only works for the build in taxonomy <code>category</code> and the build in post type <code>post</code>. You should modify it accordingly to your needs according to post type and custom taxonomy</em>)</p>\n\n<pre><code><?php\n/*\n * Plugin Name: Category referred posts\n * URI: https://wordpress.stackexchange.com/a/192018/31545\n * Description: Add referrer links to single posts and pagination if single posts was referred from a category page\n * Version: 1.0\n * Author: Pieter Goosen\n */\n\n/*\n * Add our custom query vars so Wordpress can read it\n */\nadd_filter( 'query_vars', function ( $vars ) \n{\n $vars[] = 'ref';\n return $vars;\n});\n\n/* \n * Add our referrer to single post links if we are on a category page\n */\nadd_filter('post_link', function( $permalink ) // Change to post_type_link for custom post type posts\n{\n if ( is_category() // Change to is_tax() for custom taxonomy pages\n && ( $cat = get_queried_object() ) \n ) {\n $permalink = esc_url( add_query_arg( ['ref' => $cat->term_id], $permalink ) );\n }\n return $permalink;\n});\n\n/*\n * Create our custom adjacent post link \n */\nfunction get_referred_adjacent_post( $args = [] ) \n{\n //First check if we are on a single post, else return false\n if ( !is_single() )\n return false;\n\n //Defaults arguments set for the function. \n $defaults = [\n 'previous' => true,\n 'anchor_text' => '%anchor',\n 'post_link_text' => '%text',\n 'span_text_prev' => __( 'Older post: ' ),\n 'span_text_next' => __( 'Newer post: ' ),\n ]; \n\n $combined_args = wp_parse_args( $args, $defaults );\n\n /**\n * Get the currently displayed single post. For this use \n * get_queried_object() as this is more safe than the global $post\n *\n * The $post global is very easily changed by any poorly written custom query\n * or function, and is there for not reliable\n *\n * @see Post below on WPSE for explanation\n * @link https://wordpress.stackexchange.com/q/167706/31545\n */ \n $current_post = get_queried_object();\n $current_post_date = $current_post->post_date;\n $current_post_type = $current_post->post_type;\n\n //Set the important parameters to either get the next post or previous post\n $previous = $combined_args['previous'];\n $order = ( $previous ) ? 'DESC' : 'ASC';\n $op = ( $previous ) ? 'before' : 'after';\n\n // Check if we have a referrer, if so, we need to set this to get the next post in this specific referrer category\n $cat_id = filter_input( INPUT_GET, 'ref', FILTER_VALIDATE_INT );\n\n if ( $cat_id )\n $custom_args = ['cat' => $cat_id];\n\n /**\n * Set the default arguments to merge with the referrer arguments\n *\n * Uses date_query (introduced Wordpress 3.7) to calculate the appropriate adjacent post\n * @see http://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters\n */ \n $query_args = [\n 'post_type' => $current_post_type,\n 'posts_per_page' => 1,\n 'order' => $order,\n 'no_found_rows' => true,\n 'suppress_filters' => true,\n 'date_query' => [\n [\n $op => $current_post_date,\n 'inclusive' => false\n ]\n ]\n ];\n\n $query_args = ( isset( $custom_args ) ) ? wp_parse_args( $custom_args, $query_args ) : $query_args;\n\n $q = new WP_Query( $query_args );\n\n //If there are no post found, bail early\n if( !$q->have_posts() === 0 )\n return false;\n\n //If there are posts, continue\n $adjacent_post = $q->posts[0];\n\n //Build the permalinks for the adjacent post\n $permalink = get_permalink( $adjacent_post->ID );\n\n // Return the correct permalink, we should add our referrer to the link now if this post was referred\n $link = ( $cat_id ) ? add_query_arg( ['ref' => $cat_id], $permalink ) : $permalink;\n\n // Set up out link text to display\n $span_text = ( $combined_args['previous'] ) ? $combined_args['span_text_prev'] : $combined_args['span_text_next'];\n $span = '<span class=\"meta-nav\">' . $span_text . '</span>';\n\n // Create our anchor and post title text. By default. The post title is used\n $anchor_text = ( $combined_args['anchor_text'] == '%anchor' ) ? $adjacent_post->post_title : $combined_args['anchor_text'];\n $post_title = ( $combined_args['post_link_text'] == '%text' ) ? $adjacent_post->post_title : $combined_args['post_link_text'];\n\n //Create the link with title name and anchor text\n $adjacent_post_link = $span . '<a href=\"' . $link . '\" title=\"' . $anchor_text . '\">' . $post_title . '</a>';\n\n return $adjacent_post_link;\n}\n\n// Create the next post link - Return the post link\nfunction get_next_adjacent_post_link( $anchor_text = '%anchor', $post_link_text = '%text', $span_text_next = 'Newer post: ' )\n{\n $args = [\n 'previous' => false,\n 'anchor_text' => $anchor_text,\n 'post_link_text' => $post_link_text,\n 'span_text_next' => $span_text_next,\n ];\n return get_referred_adjacent_post( $args );\n}\n\n// Create the previous post link - Return the post link\nfunction get_previos_adjacent_post_link( $anchor_text = '%anchor', $post_link_text = '%text', $span_text_prev = 'Older post: ' )\n{\n $args = [\n 'previous' => true,\n 'anchor_text' => $anchor_text,\n 'post_link_text' => $post_link_text,\n 'span_text_prev' => $span_text_prev,\n ];\n return get_referred_adjacent_post( $args );\n}\n\n// Create the next post link - Echo post link\nfunction next_adjacent_post_link( $anchor_text = '%anchor', $post_link_text = '%text', $span_text_next = 'Newer post: ' )\n{\n echo get_next_adjacent_post_link( $anchor_text, $post_link_text, $span_text_next );\n}\n\n// Create the previous post link - Echo post link\nfunction previos_adjacent_post_link( $anchor_text = '%anchor', $post_link_text = '%text', $span_text_prev = 'Older post: ' )\n{\n echo get_previos_adjacent_post_link( $anchor_text, $post_link_text, $span_text_prev );\n}\n</code></pre>\n\n<p>You should now add the following in your single.php:</p>\n\n<ul>\n<li><p>To display your custom text</p>\n\n<pre><code>$referrer = filter_input( INPUT_GET, 'ref', FILTER_VALIDATE_INT ); // This validate and checks if our referrer \"ref\" is set\nif ( $referrer ) {\n $category = get_category( $referrer );\n echo '<h2>' . $category->name . '</h2>';\n}\n</code></pre></li>\n<li><p>To display your post links</p>\n\n<pre><code>if ( function_exists( 'next_adjacent_post_link' ) )\n next_adjacent_post_link();\nif ( function_exists( 'previos_adjacent_post_link' ) )\n previos_adjacent_post_link();\n</code></pre>\n\n<p>Just add your relevant mark up to your links. Also check the accepted arguments to customize the text the links display.</p></li>\n</ul>\n\n<p>This should lay the foundation to set you on your way. You should be able to customize this to suit your exact needs</p>\n"
},
{
"answer_id": 277362,
"author": "YuriGoul",
"author_id": 126121,
"author_profile": "https://wordpress.stackexchange.com/users/126121",
"pm_score": 0,
"selected": false,
"text": "<p>I have been looking for like two days before I found this, why this is not standard behavior in WP is beyond me. The only thing I did find were plugins that were no longer working and code that did not take into account that there are hierarchical categories and that there could be multiple tags and categories attached to a post.</p>\n\n<p>FYI: I expanded the code van Pieter Goosen to also include the tags. I also corrected something the showing of next and previous links at the end of the line to posts that were not there. And I decided to separate the normal next-prev-post stuff from the next-pref stuff from this code in single.php. The thing that I did not get to work was using menu_order as sorting - since I have a custom post order - ah well.</p>\n\n<p>This is now in my functions.php:</p>\n\n<pre><code>/*\n * Add our custom query vars so Wordpress can read it\n */\nadd_filter( 'query_vars', function ( $vars )\n{\n array_push($vars, \"ref\", \"thetype\");\n return $vars;\n});\n\n/*\n * Add our referrer to single post links if we are on a category page\n */\nadd_filter('post_link', function( $permalink ) // Change to post_type_link for custom post type posts\n{\n if ( is_category() // Change to is_tax() for custom taxonomy pages\n && ( $cat = get_queried_object() )\n ) {\n $permalink = esc_url( add_query_arg( ['ref' => $cat->term_id], $permalink ) );\n $permalink = esc_url( add_query_arg( ['thetype' => 'category'], $permalink ) );\n }\n\n if ( is_tag() // Change to is_tax() for custom taxonomy pages\n && ( $cat = get_queried_object() )\n ) {\n $permalink = esc_url( add_query_arg( ['ref' => $cat->term_id], $permalink ) );\n $permalink = esc_url( add_query_arg( ['thetype' => 'tag'], $permalink ) );\n }\n\n return $permalink;\n\n});\n\n/*\n * Create our custom adjacent post link\n */\nfunction get_referred_adjacent_post( $args = [] )\n{\n //First check if we are on a single post, else return false\n if ( !is_single() )\n return false;\n\n //Defaults arguments set for the function.\n $defaults = [\n 'previous' => true,\n 'anchor_text' => '%anchor',\n 'post_link_text' => '%text',\n 'span_text_prev' => __( 'Older post: ' ),\n 'span_text_next' => __( 'Newer post: ' ),\n ];\n\n $combined_args = wp_parse_args( $args, $defaults );\n\n /**\n * Get the currently displayed single post. For this use\n * get_queried_object() as this is more safe than the global $post\n *\n * The $post global is very easily changed by any poorly written custom query\n * or function, and is there for not reliable\n *\n * @see Post below on WPSE for explanation\n * @link https://wordpress.stackexchange.com/q/167706/31545\n */\n $current_post = get_queried_object();\n $current_post_date = $current_post->post_date;\n $current_post_type = $current_post->post_type;\n $current_post_ID = $current_post->ID;\n\n\n //Set the important parameters to either get the next post or previous post\n $previous = $combined_args['previous'];\n $order = ( $previous ) ? 'DESC' : 'ASC';\n $op = ( $previous ) ? 'before' : 'after';\n $css_class = $combined_args['css_class'];\n\n // Check if we have a referrer, if so, we need to set this to get the next post in this specific referrer category\n $mytype = filter_input( INPUT_GET, 'thetype');\n if ($mytype == 'category')\n {\n $cat_id = filter_input( INPUT_GET, 'ref', FILTER_VALIDATE_INT );\n if ( $cat_id )\n $custom_args = ['cat' => $cat_id];\n\n }\n else\n {\n $cat_id = filter_input( INPUT_GET, 'ref', FILTER_VALIDATE_INT );\n if ( $cat_id )\n $custom_args = ['tag_id' => $cat_id];\n\n }\n\n\n /**\n * Set the default arguments to merge with the referrer arguments\n *\n * Uses date_query (introduced Wordpress 3.7) to calculate the appropriate adjacent post\n * @see http://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters\n */\n $query_args = [\n 'post_type' => $current_post_type,\n 'posts_per_page' => 1,\n 'order' => $order,\n 'no_found_rows' => true,\n 'suppress_filters' => true,\n 'date_query' => [\n [\n $op => $current_post_date,\n 'inclusive' => false\n ]\n ]\n ];\n\n $query_args = ( isset( $custom_args ) ) ? wp_parse_args( $custom_args, $query_args ) : $query_args;\n\n $q = new WP_Query( $query_args );\n\n //If there are no post found, bail early\n if( !$q->have_posts() === 0 )\n return false;\n\n //If there are posts, continue\n $adjacent_post = $q->posts[0];\n\n if( empty($adjacent_post->ID) ) return false;\n\n //Build the permalinks for the adjacent post\n $permalink = get_permalink( $adjacent_post->ID );\n\n // Return the correct permalink, we should add our referrer to the link now if this post was referred\n $link = ( $cat_id ) ? add_query_arg( ['ref' => $cat_id, 'thetype' => $mytype], $permalink ) : $permalink;\n\n\n // Set up out link text to display\n$span_text = ( $combined_args['previous'] ) ? $combined_args['span_text_prev'] : $combined_args['span_text_next'];\n$span = '<span class=\"meta-nav\">' . $span_text . '</span>';\n\n// Create our anchor and post title text. By default. The post title is used\n$anchor_text = ( $combined_args['anchor_text'] == '%anchor' ) ? $adjacent_post->post_title : $combined_args['anchor_text'];\n$post_title = ( $combined_args['post_link_text'] == '%text' ) ? $adjacent_post->post_title : $combined_args['post_link_text'];\n\n//Create the link with title name and anchor text\n$adjacent_post_link = $span . '<a href=\"' . $link . '\" class=\"' . $css_class . '\" title=\"' . $anchor_text . '\">' . $post_title . '</a>';\n return $adjacent_post_link;\n}\n\n// Create the next post link - Return the post link\nfunction get_next_adjacent_post_link( $anchor_text = '%anchor', $post_link_text = '%text', $span_text_next = 'Newer post: ' )\n{\n $args = [\n 'previous' => false,\n 'anchor_text' => $anchor_text,\n 'post_link_text' => $post_link_text,\n 'span_text_next' => $span_text_next,\n 'css_class' => \"post-nav-next\",\n ];\n return get_referred_adjacent_post( $args );\n}\n\n// Create the previous post link - Return the post link\nfunction get_previos_adjacent_post_link( $anchor_text = '%anchor', $post_link_text = '%text', $span_text_prev = 'Older post: ' )\n{\n $args = [\n 'previous' => true,\n 'anchor_text' => $anchor_text,\n 'post_link_text' => $post_link_text,\n 'span_text_prev' => $span_text_prev,\n 'css_class' => \"post-nav-prev\",\n ];\n return get_referred_adjacent_post( $args );\n}\n\n// Create the next post link - Echo post link\nfunction next_adjacent_post_link( $anchor_text = '%anchor', $post_link_text = '%text', $span_text_next = 'Next post ' )\n{\n echo get_next_adjacent_post_link( $anchor_text, $post_link_text, $span_text_next );\n}\n\n// Create the previous post link - Echo post link\nfunction previos_adjacent_post_link( $anchor_text = '%anchor', $post_link_text = '%text', $span_text_prev = 'Previous post ' )\n{\n echo get_previos_adjacent_post_link( $anchor_text, $post_link_text, $span_text_prev );\n}\n</code></pre>\n\n<p>From the single.php:</p>\n\n<pre><code><?php $referrer = filter_input( INPUT_GET, 'ref', FILTER_VALIDATE_INT );?>\n<!-- // checks if our referrer \"ref\" is set -->\n<?php if ( $referrer ): ?>\n\n if ( function_exists( 'next_adjacent_post_link' ) )\n next_adjacent_post_link();\n if ( function_exists( 'previos_adjacent_post_link' ) )\n previos_adjacent_post_link();\n\n<?php else: ?> <!--else referer -->\n\n <!--normal prev next links here -->\n\n<?php endif; ?> <!-- end if refferer -->\n</code></pre>\n"
}
] |
2015/06/18
|
[
"https://wordpress.stackexchange.com/questions/191947",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74904/"
] |
I've been developing a website on wordpress for some time now and came across some issues but until now I could figure it out, not today... Yesterday I've worked some more on the website and today when I came back to do some more work the pages on my site that are part of my navigation menu didn't load properly (minus the home page that is static and a news page that is the index page), they were loading the index.php page. Also with my posts in the news(index) page the load the index page instead of the post content. The URLs appear correct, but the loaded page is the index one. This doesn´t happen with the other pages I have that are not in the navigation menu and also with some custom post types, everything works fine there. The strange thing is that it happened from nothing, maybe is a quick fix... or not, I'm not an expert.
Thank you in advance and if you could help me I would aprecciate it!
|
In order for this to work, you will need to know from where the single post was refered from and if the referrer is a valid one. Secondly, we need to adjust pagination between single posts in order for us to pass our referrer between single posts.
The problem with referrers is, they are set and controlled by user side. Referrers can be disabled or blocked (like users accessing a site behind a proxy). Just for interest sake, here is very interesting answer to the question *In what cases will http referrer be empty* taken from [this post on SO](https://stackoverflow.com/a/6880668/1908141)
It will/may be empty when the enduser
* entered the site URL in browser address bar itself.
* visited the site by a browser-maintained bookmark.
* visited the site as first page in the window/tab.
* switched from a https URL to a http URL.
* switched from a https URL to a different https URL.
* has security software installed (antivirus/firewall/etc) which strips the referrer from all requests.
* is behind a proxy which strips the referrer from all requests.
* visited the site programmatically (like, [curl](http://php.net/manual/en/ref.curl.php)) without setting the referrer header (searchbots!).
You would want to read the other answers there as well for extra insight
I sat with similar issue and was looking for a more reliable way to set and pass referrers, and this led to [this question](https://wordpress.stackexchange.com/q/170007/31545) and a wonderful [answer by @gmazzap](https://wordpress.stackexchange.com/a/170016/31545)
So your solution would be based on something similar. We will be adding a special parameter to our URL which will serve as referrer (*I have made the assumption that your posts are from the build in post type `post` and taxonomy `category`*)
* Identify our category pages and add a referrer to the post links via the `post_link` filter. This referrer will hold the category id. You can use the category name, but this can become quite messy in your URL. The choice is all up you.
```
add_filter('post_link', function( $permalink ) // Change to post_type_link for custom post type posts
{
if ( is_category() // Change to is_tax() for custom taxonomy pages
&& ( $cat = get_queried_object() )
) {
$permalink = esc_url( add_query_arg( array( 'ref' => $cat->term_id ), $permalink ) );
}
return $permalink;
});
```
This will give you a URL like the following on your single post page if you click on a post link on the category page
```
http://example.com/wordpress/post-name?ref=1
```
* We must have a way to read and use that info from the URL in order to make it useful. For this, we must add a the query arg `ref` so Wordpress can read it
```
add_filter( 'query_vars', function ( $vars )
{
$vars[] = 'ref';
return $vars;
});
```
* All you need to do now, is to check if the single post was a referred post, get the value from the URL and use that info to display the correct category name (***NOTE:*** This piece of code goes into your `single.php`)
```
$referrer = filter_input( INPUT_GET, 'ref', FILTER_VALIDATE_INT ); // This validate and checks if our referrer "ref" is set
if ( $referrer ) {
$category = get_category( $referrer );
echo '<h2>' . $category->name . '</h2>';
}
```
The above is just a rough draft of what you can do to accomplish this, it just gives you a foundation to work from. You can tweak and modify it as needed.
On your single pages, you will also need to get your referrer and pass that to your next and previous post links in order to maintain this feature between posts. I have written an answer for pagination based on this, it is quite bulky though and can use some clean up. There are some parts that I have handled here now, and there are also parts that you will most probably never need which you can just remove. You can work through it and modify and adjust it as needed.
I am busy rewritting the complete pagination function ( using better and cleaner php functionality ) with some extra features, the classes are done, it is just the final pieces putting everything into functional functions that is giving me a nightmare, and to be honest, I haven't got back to working on the project for quite some time now as I really don't have much time at night. When it will be completed is still a mystery. But the idea and code from what I have given in that specific answer should do the trick for you. You can check out my answer and referrer pagination function [here](https://wordpress.stackexchange.com/a/173041/31545)
EDIT
----
I have quickly written a small plugin which covers the referrer and new pagination links to carry the referrer across multiple single posts. This pagination links will also page between single posts from the referrer
What this means is, if a single post was clicked from `category B`, and this post has three categories, `category A`, `category B` and `category C`, the next and previous adjacent post will be from `category B`. If you go to either post, the adjacent post from that clicked single post will also be from `category B` etc
I have commented the code so you should be able to follow it better and also adjust and modify it as needed. Just copy and paste this code in a plugin file and activate it. Alternatively, copy the code (without the plugin header of course) and paste it as is into your `functions.php` (***NOTE:*** This only works for the build in taxonomy `category` and the build in post type `post`. You should modify it accordingly to your needs according to post type and custom taxonomy)
```
<?php
/*
* Plugin Name: Category referred posts
* URI: https://wordpress.stackexchange.com/a/192018/31545
* Description: Add referrer links to single posts and pagination if single posts was referred from a category page
* Version: 1.0
* Author: Pieter Goosen
*/
/*
* Add our custom query vars so Wordpress can read it
*/
add_filter( 'query_vars', function ( $vars )
{
$vars[] = 'ref';
return $vars;
});
/*
* Add our referrer to single post links if we are on a category page
*/
add_filter('post_link', function( $permalink ) // Change to post_type_link for custom post type posts
{
if ( is_category() // Change to is_tax() for custom taxonomy pages
&& ( $cat = get_queried_object() )
) {
$permalink = esc_url( add_query_arg( ['ref' => $cat->term_id], $permalink ) );
}
return $permalink;
});
/*
* Create our custom adjacent post link
*/
function get_referred_adjacent_post( $args = [] )
{
//First check if we are on a single post, else return false
if ( !is_single() )
return false;
//Defaults arguments set for the function.
$defaults = [
'previous' => true,
'anchor_text' => '%anchor',
'post_link_text' => '%text',
'span_text_prev' => __( 'Older post: ' ),
'span_text_next' => __( 'Newer post: ' ),
];
$combined_args = wp_parse_args( $args, $defaults );
/**
* Get the currently displayed single post. For this use
* get_queried_object() as this is more safe than the global $post
*
* The $post global is very easily changed by any poorly written custom query
* or function, and is there for not reliable
*
* @see Post below on WPSE for explanation
* @link https://wordpress.stackexchange.com/q/167706/31545
*/
$current_post = get_queried_object();
$current_post_date = $current_post->post_date;
$current_post_type = $current_post->post_type;
//Set the important parameters to either get the next post or previous post
$previous = $combined_args['previous'];
$order = ( $previous ) ? 'DESC' : 'ASC';
$op = ( $previous ) ? 'before' : 'after';
// Check if we have a referrer, if so, we need to set this to get the next post in this specific referrer category
$cat_id = filter_input( INPUT_GET, 'ref', FILTER_VALIDATE_INT );
if ( $cat_id )
$custom_args = ['cat' => $cat_id];
/**
* Set the default arguments to merge with the referrer arguments
*
* Uses date_query (introduced Wordpress 3.7) to calculate the appropriate adjacent post
* @see http://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters
*/
$query_args = [
'post_type' => $current_post_type,
'posts_per_page' => 1,
'order' => $order,
'no_found_rows' => true,
'suppress_filters' => true,
'date_query' => [
[
$op => $current_post_date,
'inclusive' => false
]
]
];
$query_args = ( isset( $custom_args ) ) ? wp_parse_args( $custom_args, $query_args ) : $query_args;
$q = new WP_Query( $query_args );
//If there are no post found, bail early
if( !$q->have_posts() === 0 )
return false;
//If there are posts, continue
$adjacent_post = $q->posts[0];
//Build the permalinks for the adjacent post
$permalink = get_permalink( $adjacent_post->ID );
// Return the correct permalink, we should add our referrer to the link now if this post was referred
$link = ( $cat_id ) ? add_query_arg( ['ref' => $cat_id], $permalink ) : $permalink;
// Set up out link text to display
$span_text = ( $combined_args['previous'] ) ? $combined_args['span_text_prev'] : $combined_args['span_text_next'];
$span = '<span class="meta-nav">' . $span_text . '</span>';
// Create our anchor and post title text. By default. The post title is used
$anchor_text = ( $combined_args['anchor_text'] == '%anchor' ) ? $adjacent_post->post_title : $combined_args['anchor_text'];
$post_title = ( $combined_args['post_link_text'] == '%text' ) ? $adjacent_post->post_title : $combined_args['post_link_text'];
//Create the link with title name and anchor text
$adjacent_post_link = $span . '<a href="' . $link . '" title="' . $anchor_text . '">' . $post_title . '</a>';
return $adjacent_post_link;
}
// Create the next post link - Return the post link
function get_next_adjacent_post_link( $anchor_text = '%anchor', $post_link_text = '%text', $span_text_next = 'Newer post: ' )
{
$args = [
'previous' => false,
'anchor_text' => $anchor_text,
'post_link_text' => $post_link_text,
'span_text_next' => $span_text_next,
];
return get_referred_adjacent_post( $args );
}
// Create the previous post link - Return the post link
function get_previos_adjacent_post_link( $anchor_text = '%anchor', $post_link_text = '%text', $span_text_prev = 'Older post: ' )
{
$args = [
'previous' => true,
'anchor_text' => $anchor_text,
'post_link_text' => $post_link_text,
'span_text_prev' => $span_text_prev,
];
return get_referred_adjacent_post( $args );
}
// Create the next post link - Echo post link
function next_adjacent_post_link( $anchor_text = '%anchor', $post_link_text = '%text', $span_text_next = 'Newer post: ' )
{
echo get_next_adjacent_post_link( $anchor_text, $post_link_text, $span_text_next );
}
// Create the previous post link - Echo post link
function previos_adjacent_post_link( $anchor_text = '%anchor', $post_link_text = '%text', $span_text_prev = 'Older post: ' )
{
echo get_previos_adjacent_post_link( $anchor_text, $post_link_text, $span_text_prev );
}
```
You should now add the following in your single.php:
* To display your custom text
```
$referrer = filter_input( INPUT_GET, 'ref', FILTER_VALIDATE_INT ); // This validate and checks if our referrer "ref" is set
if ( $referrer ) {
$category = get_category( $referrer );
echo '<h2>' . $category->name . '</h2>';
}
```
* To display your post links
```
if ( function_exists( 'next_adjacent_post_link' ) )
next_adjacent_post_link();
if ( function_exists( 'previos_adjacent_post_link' ) )
previos_adjacent_post_link();
```
Just add your relevant mark up to your links. Also check the accepted arguments to customize the text the links display.
This should lay the foundation to set you on your way. You should be able to customize this to suit your exact needs
|
191,964 |
<p>Let's say I've the following file in my parent theme folder: <code>'theme-folder/inc/custom.php'</code></p>
<p>Then I created a child theme.</p>
<p>How can I check if that file exists in the child theme, then fetch it, otherwise fetch it from the parent theme?</p>
<p><code>get_template_directory()</code> always fetches the file from the parent theme.</p>
<p>While <code>get_stylesheet_directory()</code> requires the file to exists in the child theme.</p>
|
[
{
"answer_id": 191968,
"author": "Mathew Tinsley",
"author_id": 69793,
"author_profile": "https://wordpress.stackexchange.com/users/69793",
"pm_score": 3,
"selected": true,
"text": "<p><a href=\"https://codex.wordpress.org/Function_Reference/locate_template\" rel=\"nofollow\"><code>locate_template</code></a> will attempt to find the specified file in the child theme, and fall back to the parent theme if it does not exist:</p>\n\n<pre><code>locate_template('inc/custom.php', true);\n</code></pre>\n\n<p>Setting the second parameter to <code>true</code> causes it to require the file instead of just determining the path.</p>\n\n<p>As the name suggests, <code>locate_template</code> is meant for loading template files. It has some additional overhead that you most likely don't need for loading libraries. A stripped down version would be:</p>\n\n<pre><code>function load_theme_file($path) {\n if ( file_exists( STYLESHEETPATH . '/' . $path )) {\n include( STYLESHEETPATH . '/' . $path );\n } else {\n require( TEMPLATEPATH . '/' . $path );\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>load_theme_file('inc/custom.php');\n</code></pre>\n\n<hr>\n\n<p>Edit: I just wanted to provide a quick note about potential issues with this overall approach.</p>\n\n<p>Letting a child theme override files works well for templates, but for libraries there is more room for error. If a child theme needs to modify a single function, you would have to copy that entire file, overriding every function in that file in the process.</p>\n\n<p>If the parent theme is updated and changes have been made to any of the functions in the overwritten file it can cause problems. You can mitigate this issue by breaking up your libraries into smaller chunks, but that can make your code base harder to maintain.</p>\n\n<p>A better solution, in my opinion, is to use an object oriented approach. Allow a child theme to <em>extend</em> classes you define and then use the child theme's class. In the implementing classes the child theme would only have to define methods it needs to overwrite. In the parent theme you could specify which methods should not be overwritten by making them <code>final</code>.</p>\n\n<p>You can also mitigate the need for child themes to replace entire files by using filters and actions generously.</p>\n"
},
{
"answer_id": 191969,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://codex.wordpress.org/Function_Reference/get_template_part\" rel=\"nofollow\"><code>get_template_part()</code></a> would do that, if I understand your question.</p>\n\n<pre><code>get_template_part('inc/custom');\n</code></pre>\n\n<p>It is sort of built to do exactly that, if I am reading you right:</p>\n\n<blockquote>\n <p>Makes it easy for a theme to reuse sections of code and an easy way\n for child themes to replace sections of their parent theme.</p>\n</blockquote>\n"
}
] |
2015/06/19
|
[
"https://wordpress.stackexchange.com/questions/191964",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37529/"
] |
Let's say I've the following file in my parent theme folder: `'theme-folder/inc/custom.php'`
Then I created a child theme.
How can I check if that file exists in the child theme, then fetch it, otherwise fetch it from the parent theme?
`get_template_directory()` always fetches the file from the parent theme.
While `get_stylesheet_directory()` requires the file to exists in the child theme.
|
[`locate_template`](https://codex.wordpress.org/Function_Reference/locate_template) will attempt to find the specified file in the child theme, and fall back to the parent theme if it does not exist:
```
locate_template('inc/custom.php', true);
```
Setting the second parameter to `true` causes it to require the file instead of just determining the path.
As the name suggests, `locate_template` is meant for loading template files. It has some additional overhead that you most likely don't need for loading libraries. A stripped down version would be:
```
function load_theme_file($path) {
if ( file_exists( STYLESHEETPATH . '/' . $path )) {
include( STYLESHEETPATH . '/' . $path );
} else {
require( TEMPLATEPATH . '/' . $path );
}
}
```
Usage:
```
load_theme_file('inc/custom.php');
```
---
Edit: I just wanted to provide a quick note about potential issues with this overall approach.
Letting a child theme override files works well for templates, but for libraries there is more room for error. If a child theme needs to modify a single function, you would have to copy that entire file, overriding every function in that file in the process.
If the parent theme is updated and changes have been made to any of the functions in the overwritten file it can cause problems. You can mitigate this issue by breaking up your libraries into smaller chunks, but that can make your code base harder to maintain.
A better solution, in my opinion, is to use an object oriented approach. Allow a child theme to *extend* classes you define and then use the child theme's class. In the implementing classes the child theme would only have to define methods it needs to overwrite. In the parent theme you could specify which methods should not be overwritten by making them `final`.
You can also mitigate the need for child themes to replace entire files by using filters and actions generously.
|
191,988 |
<p>How can I add post content in meta description via <code>Title & Metas</code>?</p>
<p>I have seen excerpt variable <code>%%excerpt%%</code> but it will give only excerpt but I want whole content in meta description.</p>
<p>Can any one help me for this because I can not found variable for content?</p>
<p>Thankns</p>
|
[
{
"answer_id": 191989,
"author": "Karun",
"author_id": 63470,
"author_profile": "https://wordpress.stackexchange.com/users/63470",
"pm_score": 3,
"selected": true,
"text": "<p>Here is a safe and Yoast preferred method</p>\n\n<pre><code>add_action('wp_head','add_custom_meta_description_box');\n\nfunction retrieve_var1_replacement( $var1 ) {\n global $post;\n return strip_tags($post->post_content);\n}\nfunction register_my_plugin_extra_replacements() {\n wpseo_register_var_replacement( '%%mycustomdesc%%', 'retrieve_var1_replacement', 'advanced', 'this is a help text for myvar1' );\n}\nadd_action( 'wpseo_register_extra_replacements', 'register_my_plugin_extra_replacements' );\n</code></pre>\n\n<p>You can now replace your %%excerpt%% with %%mycustomdesc%%</p>\n"
},
{
"answer_id": 191991,
"author": "James Barrett",
"author_id": 74733,
"author_profile": "https://wordpress.stackexchange.com/users/74733",
"pm_score": 2,
"selected": false,
"text": "<p>In Yoast SEO there is no variable available for the content. The 2 variables that are available are %%excerpt%% and %%excerpt_only%%. The difference between these 2 is:</p>\n\n<blockquote>\n <p>%%excerpt%% - Replaced with the post/page excerpt (or auto-generated if\n it does not exist)</p>\n \n <p>%%excerpt_only%% - Replaced with the post/page excerpt (without\n auto-generation)</p>\n</blockquote>\n\n<p>For a full list of available variables you can click on the \"Help\" tab (top right) when viewing the \"Title and Metas\" page of the Yoast SEO plugin.</p>\n\n<p>If using %%excerpt_only%% and adding your post content in your post excerpt is not going to work for you then you could write your own function to hook into the <code>wpseo_metadesc</code> filter.</p>\n\n<pre><code>function custom_seo_description( $seo_desc ) {\n $seo_desc = \"This is a custom description\";\n return $seo_desc;\n}\n\nadd_filter( 'wpseo_metadesc', 'custom_seo_description', 10, 1 );\n</code></pre>\n\n<p>I've not tested this code but something along theser lines should work. More info on the Yoast SEO API can be found here: <a href=\"https://yoast.com/wordpress/plugins/seo/api/\" rel=\"nofollow\">https://yoast.com/wordpress/plugins/seo/api/</a></p>\n"
}
] |
2015/06/19
|
[
"https://wordpress.stackexchange.com/questions/191988",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/38491/"
] |
How can I add post content in meta description via `Title & Metas`?
I have seen excerpt variable `%%excerpt%%` but it will give only excerpt but I want whole content in meta description.
Can any one help me for this because I can not found variable for content?
Thankns
|
Here is a safe and Yoast preferred method
```
add_action('wp_head','add_custom_meta_description_box');
function retrieve_var1_replacement( $var1 ) {
global $post;
return strip_tags($post->post_content);
}
function register_my_plugin_extra_replacements() {
wpseo_register_var_replacement( '%%mycustomdesc%%', 'retrieve_var1_replacement', 'advanced', 'this is a help text for myvar1' );
}
add_action( 'wpseo_register_extra_replacements', 'register_my_plugin_extra_replacements' );
```
You can now replace your %%excerpt%% with %%mycustomdesc%%
|
192,044 |
<p>I'm trying to make a login form, but select query isn't working. Is there another syntax in WordPress and in which way is password hashed?
My code is:</p>
<pre><code>if ( isset( $_POST['submit'] ) ) {
if ( !$_POST['username'] ) {
echo "You did not complete all of the required fields";
} else {
$username=$_POST['username'];
$password=$_POST['password'];
$query = $wpdb->get_row( "SELECT * FROM $wpdb->wp_users
WHERE user_login='@admin' && user_pass = 'some_pass'" );
if ( $query != null ) {
echo "Login success";
return true;
} else {
echo "incorrect pass or user";
return false;
}
}
}
?>
<form action="" method="post"/>
<input type="text" name="username" placeholder="Username"/>
<input type="text" name="password" placeholder="Password"/><br>
<input type="submit" name="submit" value="Submit">
</form>
</code></pre>
|
[
{
"answer_id": 191989,
"author": "Karun",
"author_id": 63470,
"author_profile": "https://wordpress.stackexchange.com/users/63470",
"pm_score": 3,
"selected": true,
"text": "<p>Here is a safe and Yoast preferred method</p>\n\n<pre><code>add_action('wp_head','add_custom_meta_description_box');\n\nfunction retrieve_var1_replacement( $var1 ) {\n global $post;\n return strip_tags($post->post_content);\n}\nfunction register_my_plugin_extra_replacements() {\n wpseo_register_var_replacement( '%%mycustomdesc%%', 'retrieve_var1_replacement', 'advanced', 'this is a help text for myvar1' );\n}\nadd_action( 'wpseo_register_extra_replacements', 'register_my_plugin_extra_replacements' );\n</code></pre>\n\n<p>You can now replace your %%excerpt%% with %%mycustomdesc%%</p>\n"
},
{
"answer_id": 191991,
"author": "James Barrett",
"author_id": 74733,
"author_profile": "https://wordpress.stackexchange.com/users/74733",
"pm_score": 2,
"selected": false,
"text": "<p>In Yoast SEO there is no variable available for the content. The 2 variables that are available are %%excerpt%% and %%excerpt_only%%. The difference between these 2 is:</p>\n\n<blockquote>\n <p>%%excerpt%% - Replaced with the post/page excerpt (or auto-generated if\n it does not exist)</p>\n \n <p>%%excerpt_only%% - Replaced with the post/page excerpt (without\n auto-generation)</p>\n</blockquote>\n\n<p>For a full list of available variables you can click on the \"Help\" tab (top right) when viewing the \"Title and Metas\" page of the Yoast SEO plugin.</p>\n\n<p>If using %%excerpt_only%% and adding your post content in your post excerpt is not going to work for you then you could write your own function to hook into the <code>wpseo_metadesc</code> filter.</p>\n\n<pre><code>function custom_seo_description( $seo_desc ) {\n $seo_desc = \"This is a custom description\";\n return $seo_desc;\n}\n\nadd_filter( 'wpseo_metadesc', 'custom_seo_description', 10, 1 );\n</code></pre>\n\n<p>I've not tested this code but something along theser lines should work. More info on the Yoast SEO API can be found here: <a href=\"https://yoast.com/wordpress/plugins/seo/api/\" rel=\"nofollow\">https://yoast.com/wordpress/plugins/seo/api/</a></p>\n"
}
] |
2015/06/19
|
[
"https://wordpress.stackexchange.com/questions/192044",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74943/"
] |
I'm trying to make a login form, but select query isn't working. Is there another syntax in WordPress and in which way is password hashed?
My code is:
```
if ( isset( $_POST['submit'] ) ) {
if ( !$_POST['username'] ) {
echo "You did not complete all of the required fields";
} else {
$username=$_POST['username'];
$password=$_POST['password'];
$query = $wpdb->get_row( "SELECT * FROM $wpdb->wp_users
WHERE user_login='@admin' && user_pass = 'some_pass'" );
if ( $query != null ) {
echo "Login success";
return true;
} else {
echo "incorrect pass or user";
return false;
}
}
}
?>
<form action="" method="post"/>
<input type="text" name="username" placeholder="Username"/>
<input type="text" name="password" placeholder="Password"/><br>
<input type="submit" name="submit" value="Submit">
</form>
```
|
Here is a safe and Yoast preferred method
```
add_action('wp_head','add_custom_meta_description_box');
function retrieve_var1_replacement( $var1 ) {
global $post;
return strip_tags($post->post_content);
}
function register_my_plugin_extra_replacements() {
wpseo_register_var_replacement( '%%mycustomdesc%%', 'retrieve_var1_replacement', 'advanced', 'this is a help text for myvar1' );
}
add_action( 'wpseo_register_extra_replacements', 'register_my_plugin_extra_replacements' );
```
You can now replace your %%excerpt%% with %%mycustomdesc%%
|
192,049 |
<p>I'd like to avoid hard coding my plugin's version at multiple places. To realize this the function <a href="https://developer.wordpress.org/reference/functions/get_plugin_data/" rel="nofollow"><code>get_plugin_data()</code></a> comes in handy. But here the fun comes to an unpleasant stop. Checking for a plugin update to execute related housekeeping for example should be done early (e.g. <code>plugins_loaded</code>) but unfortunately <a href="https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-admin/includes/plugin.php#L72" rel="nofollow">wp-admin/includes/plugin.php</a> is not loaded before <code>admin_init</code> is fired.</p>
<p>Using a later hook is not possible here. This might be a solution for <a href="https://wordpress.org/support/topic/get_plugin_data-is-undefined-function" rel="nofollow">some plugins</a> but it doesn't work for me, as my plugin hooks into the login process and needs to do its on update processing before that...</p>
<p>My question is: is it save to <code>require( ABSPATH . 'wp-admin/includes/plugin.php')</code>
earlier in my plugin? The file contains some function definitions and adds a filter. That's it.</p>
<p>I tried it. At first glance it works and I cannot see any implications but maybe you are aware of some? I'd be happy about any hint, positive or negative. Thank you!</p>
|
[
{
"answer_id": 192063,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>At first glance it works and I cannot see any implications but maybe\n you are aware of some?</p>\n</blockquote>\n\n<p>You say that you are not getting errors, which I would have expected but <a href=\"https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-admin/includes/admin.php#L39\" rel=\"nofollow\">it looks as though WordPress uses <code>require_once()</code></a> so you are probably safe:</p>\n\n<pre><code>39 /** WordPress Plugin Administration API */\n40 require_once(ABSPATH . 'wp-admin/includes/plugin.php');\n</code></pre>\n\n<p>This kind of hack tends to indicate that you are doing something wrong though.</p>\n"
},
{
"answer_id": 331737,
"author": "Dima Stefantsov",
"author_id": 76002,
"author_profile": "https://wordpress.stackexchange.com/users/76002",
"pm_score": 1,
"selected": false,
"text": "<p><strong>No, don't require plugin.php.</strong></p>\n\n<p>To avoid a tiny bit of bad code you are about to introduce a lot of really bad code. Who knows what can go wrong if you include plugin.php.\nAnd who knows what could go wrong in the years to come. WordPress core developers are not expecting users to include core files earlier in init process.</p>\n\n<p>So instead of doing it in really dangerous and unexpected way, just do something like <code>define('MY_PLUGIN_VERSION', 2);</code> right below your plugin Version header. This is way safer and better.</p>\n"
}
] |
2015/06/19
|
[
"https://wordpress.stackexchange.com/questions/192049",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/50373/"
] |
I'd like to avoid hard coding my plugin's version at multiple places. To realize this the function [`get_plugin_data()`](https://developer.wordpress.org/reference/functions/get_plugin_data/) comes in handy. But here the fun comes to an unpleasant stop. Checking for a plugin update to execute related housekeeping for example should be done early (e.g. `plugins_loaded`) but unfortunately [wp-admin/includes/plugin.php](https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-admin/includes/plugin.php#L72) is not loaded before `admin_init` is fired.
Using a later hook is not possible here. This might be a solution for [some plugins](https://wordpress.org/support/topic/get_plugin_data-is-undefined-function) but it doesn't work for me, as my plugin hooks into the login process and needs to do its on update processing before that...
My question is: is it save to `require( ABSPATH . 'wp-admin/includes/plugin.php')`
earlier in my plugin? The file contains some function definitions and adds a filter. That's it.
I tried it. At first glance it works and I cannot see any implications but maybe you are aware of some? I'd be happy about any hint, positive or negative. Thank you!
|
>
> At first glance it works and I cannot see any implications but maybe
> you are aware of some?
>
>
>
You say that you are not getting errors, which I would have expected but [it looks as though WordPress uses `require_once()`](https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-admin/includes/admin.php#L39) so you are probably safe:
```
39 /** WordPress Plugin Administration API */
40 require_once(ABSPATH . 'wp-admin/includes/plugin.php');
```
This kind of hack tends to indicate that you are doing something wrong though.
|
192,051 |
<p>I'm trying to hide a large amount of categories from my category widget. I've tried a few plugins but none of them seem to want to let me use the dropdown option. I looked into the widget_categories_args hook and that seems to be what I want but I can't get it to work. </p>
<p>Anyways here's my code</p>
<pre><code>function widget_categories_args_filter( $cat_args ) {
$exclude_arr = array( 57,61,63,56,55,62,52,53,54,67,65 );
if( isset( $cat_args['exclude'] ) && !empty( $cat_args['exclude'] ) )
$exclude_arr = array_unique( array_merge( explode( ',', $cat_args['exclude'] ), $exclude_arr ) );
$cat_args['exclude'] = implode( ',', $exclude_arr );
return $cat_args;
}
add_filter( 'widget_categories_args', 'widget_categories_args_filter', 10, 1 );
</code></pre>
<p>I Took that from here: <a href="https://codex.wordpress.org/Plugin_API/Filter_Reference/widget_categories_args" rel="noreferrer">https://codex.wordpress.org/Plugin_API/Filter_Reference/widget_categories_args</a></p>
<p>I'm putting this in my theme's functions.php. That shouldn't matter even though the function is set for plugins, right?</p>
|
[
{
"answer_id": 253170,
"author": "Kevin",
"author_id": 76841,
"author_profile": "https://wordpress.stackexchange.com/users/76841",
"pm_score": 4,
"selected": false,
"text": "<p>I know this post is pretty old, but because I came across the same issue and this post came up higher than one with a solution, I figured I'd add this, which worked for me.</p>\n\n<p>Source: <a href=\"http://coffeecupweb.com/how-to-exclude-or-hide-categories-from-category-widget-in-wordpress-sidebar/\" rel=\"noreferrer\">http://coffeecupweb.com/how-to-exclude-or-hide-categories-from-category-widget-in-wordpress-sidebar/</a></p>\n\n<pre><code>//Hide categories from WordPress category widget\nfunction exclude_widget_categories($args){\n $exclude = \"1,4,8,57,80\";\n $args[\"exclude\"] = $exclude;\n return $args;\n}\nadd_filter(\"widget_categories_args\",\"exclude_widget_categories\");\n</code></pre>\n"
},
{
"answer_id": 308034,
"author": "jgangso",
"author_id": 104184,
"author_profile": "https://wordpress.stackexchange.com/users/104184",
"pm_score": 2,
"selected": false,
"text": "<h2>Hide the uncatecogrized / default category in WooCommerce:</h2>\n\n<p>I guess I'm not the only one who came to this page in search for a way to hide <em>the default / uncategorized category</em> introduced in WooCommerce 3.3.</p>\n\n<p>If you're one of them, instead of hard-coding the category ID which may be different in different environments / installations, you can use the following snippet, modified from <a href=\"https://mikejolley.com/2018/02/07/woocommerce-3-3-hide-uncategorized-category-from-the-shop-page-on-the-frontend/\" rel=\"nofollow noreferrer\">the snippet by Mike Jolley</a> to hide it from the Woocommerce Product Categories widget:</p>\n\n<pre><code><?php // Do not include this if already open!\n\n/**\n * Code goes in theme functions.php.\n *\n * If you use dropdown instead of hierachical view, \n * hook to the following filter instead: \n * `woocommerce_product_categories_widget_dropdown_args`\n */\nadd_filter( 'woocommerce_product_categories_widget_args', 'custom_woocommerce_product_categories_widget_args' );\n\nfunction custom_woocommerce_product_categories_widget_args( $args ) {\n $args['exclude'] = get_option( 'default_product_cat' );\n return $args;\n}\n</code></pre>\n"
},
{
"answer_id": 314532,
"author": "jaripp",
"author_id": 66502,
"author_profile": "https://wordpress.stackexchange.com/users/66502",
"pm_score": 2,
"selected": false,
"text": "<p>This works: <a href=\"https://gist.github.com/peltopiri/76e7d1143e33b424633114103cfae5ec\" rel=\"nofollow noreferrer\">https://gist.github.com/peltopiri/76e7d1143e33b424633114103cfae5ec</a></p>\n\n<pre><code><?php\nfunction exclude_woocommerce_widget_product_categories($widget_args) {\n //Insert excluded category ids here\n $excludes = array(12,33);\n $includes = explode(\",\",$widget_args['include']);\n\n $includes = array_filter($includes, function($value) use ($excludes) {\n return !in_array($value, $excludes);\n });\n $widget_args[\"include\"] = implode(\",\", $includes);\n return $widget_args;\n}\nadd_filter( 'woocommerce_product_categories_widget_dropdown_args', 'exclude_woocommerce_widget_product_categories');\nadd_filter( 'woocommerce_product_categories_widget_args', 'exclude_woocommerce_widget_product_categories');\n</code></pre>\n"
},
{
"answer_id": 329997,
"author": "kpatrickos",
"author_id": 162072,
"author_profile": "https://wordpress.stackexchange.com/users/162072",
"pm_score": 0,
"selected": false,
"text": "<p>After several searches and tests, hiding post categories for list items and drop-down is done separately since they're called by different filter ids.</p>\n\n<p>For list category items use </p>\n\n<pre><code>add_filter(\"widget_categories_args\",\"YOUR_CUSTOM_FUNCTION\");\n</code></pre>\n\n<p>For drop-down category items use </p>\n\n<pre><code>add_filter(\"widget_categories_dropdown_args\",\"YOUR_CUSTOM_FUNCTION\");\n</code></pre>\n\n<p>Reference: <a href=\"https://basicwp.com/exclude-categories-from-category-widgets-in-wordpress/\" rel=\"nofollow noreferrer\">https://basicwp.com/exclude-categories-from-category-widgets-in-wordpress/</a></p>\n"
},
{
"answer_id": 355294,
"author": "Brent Baccala",
"author_id": 107416,
"author_profile": "https://wordpress.stackexchange.com/users/107416",
"pm_score": 1,
"selected": false,
"text": "<p>I was able to hide a single category using CSS:</p>\n\n<pre><code>li.cat-item-1 {\n display: none;\n}\n</code></pre>\n\n<p>I put this CSS snippet in my theme's \"Additional CSS\".</p>\n\n<p>Category 1 is \"Uncategorized\", which is the one I wanted to hide.</p>\n"
}
] |
2015/06/19
|
[
"https://wordpress.stackexchange.com/questions/192051",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/55351/"
] |
I'm trying to hide a large amount of categories from my category widget. I've tried a few plugins but none of them seem to want to let me use the dropdown option. I looked into the widget\_categories\_args hook and that seems to be what I want but I can't get it to work.
Anyways here's my code
```
function widget_categories_args_filter( $cat_args ) {
$exclude_arr = array( 57,61,63,56,55,62,52,53,54,67,65 );
if( isset( $cat_args['exclude'] ) && !empty( $cat_args['exclude'] ) )
$exclude_arr = array_unique( array_merge( explode( ',', $cat_args['exclude'] ), $exclude_arr ) );
$cat_args['exclude'] = implode( ',', $exclude_arr );
return $cat_args;
}
add_filter( 'widget_categories_args', 'widget_categories_args_filter', 10, 1 );
```
I Took that from here: <https://codex.wordpress.org/Plugin_API/Filter_Reference/widget_categories_args>
I'm putting this in my theme's functions.php. That shouldn't matter even though the function is set for plugins, right?
|
I know this post is pretty old, but because I came across the same issue and this post came up higher than one with a solution, I figured I'd add this, which worked for me.
Source: <http://coffeecupweb.com/how-to-exclude-or-hide-categories-from-category-widget-in-wordpress-sidebar/>
```
//Hide categories from WordPress category widget
function exclude_widget_categories($args){
$exclude = "1,4,8,57,80";
$args["exclude"] = $exclude;
return $args;
}
add_filter("widget_categories_args","exclude_widget_categories");
```
|
192,053 |
<p>I have my post image thumbnails set with: </p>
<pre><code> add_theme_support('post-thumbnails');
set_post_thumbnail_size(1280, 436, true);
add_image_size('general-thumb', 600, 339, true);
</code></pre>
<p>They are resized into two columns with the following css:</p>
<pre><code> max-width: 100%;
height: auto;
</code></pre>
<p>The columns they are displayed in are about 348px wide.</p>
<p>The issue is that when I upload an image that is less than the dimensions 600x339 in either height or width, they show up incorrectly on the page.</p>
<p>I think the reason for this is that 600x339 is the starting 'box' within which an image is cropped. It's then resized to fill the width of the column while retaining the aspect ratio of the original image size. </p>
<p>What are some ways I can fix this with wordpress' functions or css hacks?</p>
<p>What I think needs to happen so that the images can resize dynamically is have every uploaded image automatically cropped to the correct aspect ratio without resizing it. But this needs to start with the original image's width and height, not the predefined box dimensions. </p>
<p>Thanks!</p>
|
[
{
"answer_id": 192363,
"author": "theHands",
"author_id": 74366,
"author_profile": "https://wordpress.stackexchange.com/users/74366",
"pm_score": 2,
"selected": true,
"text": "<p>It sounds like your problem occurs before the image is cropped/ resized and displayed in the page - the original image is too small.</p>\n\n<p>You can require minimum dimensions for uploaded images, see: <a href=\"https://wordpress.stackexchange.com/questions/28359/how-to-require-a-minimum-image-dimension-for-uploading\">How to Require a Minimum Image Dimension for Uploading?</a></p>\n\n<p>Then, to resize the uploaded image without cropping it, define the image size with a 'soft crop' using 'false' in the third parameter:</p>\n\n<pre><code>add_image_size('general-thumb', 600, 339, false);\n</code></pre>\n\n<p>Finally, using the image as a background image for an element may be an alternative way of getting the sizing right.</p>\n\n<p>You can position the element within your layout with whatever height, width, minimum height etc is required and use the CSS <code>background-size</code> to fill/ position the image within the element.</p>\n\n<p>For example:</p>\n\n<pre><code>background-size: contain;\n</code></pre>\n\n<p>Will ensure the image is as large as possible without hiding any part of it.</p>\n\n<p>See: <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/background-size\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/CSS/background-size</a></p>\n"
},
{
"answer_id": 192576,
"author": "Stanislau Ladutska",
"author_id": 24891,
"author_profile": "https://wordpress.stackexchange.com/users/24891",
"pm_score": 0,
"selected": false,
"text": "<p>It's because wordpress do not use upscale for thumbnails by default.</p>\n\n<p>You could use this plugin to solve this problem: <a href=\"https://wordpress.org/plugins/thumbnail-upscale/\" rel=\"nofollow\">https://wordpress.org/plugins/thumbnail-upscale/</a></p>\n\n<p>It will affect only new uploaded images. To regenerate your old images use this plugin: <a href=\"https://wordpress.org/plugins/regenerate-thumbnails/\" rel=\"nofollow\">https://wordpress.org/plugins/regenerate-thumbnails/</a></p>\n"
},
{
"answer_id": 192681,
"author": "Nia Skywalk",
"author_id": 74433,
"author_profile": "https://wordpress.stackexchange.com/users/74433",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>The issue is that when I upload an image that is less than the dimensions 600x339 in either height or width, they show up incorrectly on the page.</p>\n</blockquote>\n\n<p>I did not understand this statement as you wrote it, but when I started researching I found what you meant, so I am writing this answer to document this for others who do not understand your meaning, or how WP processes images.</p>\n\n<p>When you are uploading images to WordPress, they are automatically processed and several sizes are cropped or resized depending on settings. </p>\n\n<p>A developer can declare her custom sizes using the code that was used in this question.</p>\n\n<pre><code>add_theme_support('post-thumbnails');\nset_post_thumbnail_size(1280, 436, true); \nadd_image_size('general-thumb', 600, 339, true);\n</code></pre>\n\n<p>for <code>set_post_thumbnail()</code> The first variable is Width, the second Height, and the third indicates cropping type: Hard(true) or Soft(false)</p>\n\n<p>for <code>add_image_size()</code> The first string is the name you want to call the image, followed by width, height, and cropping.</p>\n\n<p><strong>Hard cropping</strong> reduces the dimension proportionately to the requested number, then cuts off everything else to match the odd dimension.\n<em>For example: if you upload a 800x600 photo you want cropped to 600x200, WP will reduce 800w proportionately down to 600w, then crop the remaining 450h down to 200h. I believe it centers the image and takes it evenly from top and bottom.</em></p>\n\n<p><strong>Soft cropping</strong> reduces the whole image proportionately, maintaining the whole image. <em>For example: That 800x600 image you uploaded would soft crop down to smallest maximum dimension 200h, leaving the width proportionately 267w.</em></p>\n\n<p>In this case, I believe the OP definitely wants to <strong>Hard Crop</strong>, as indicated in the code.</p>\n\n<p>The issue that is being encountered is that WP will not scale up an image to match the proportions. If you want that 600w x 200h image, but upload 550w x 300h, it will crop the 300h down to 200h, but leave the 550w. Most of the documentation I have run across makes this very clear. The 'fix' I know most people use is to scale the image in a desktop program before uploading it if it absolutely cannot be gotten at a larger scale already.</p>\n\n<p>OP is looking for a solution that will allow WP to scale up the image to the requested dimensions. This solution can be found here: <a href=\"https://wordpress.stackexchange.com/questions/173318/how-to-scale-up-image-into-thumbnail-without-distorting-it\">How to scale up image into thumbnail without distorting it?</a> </p>\n\n<p>Axlmedia (the source quoted) also adds this warning about the solution:</p>\n\n<blockquote>\n <p>The slight downside (not much to worry about with the server space we have today) is that if you for example upload a 16×16 favicon to your media library, it will be cropped and upscaled to all larger thumbnail sizes available. So, some more images will be created.</p>\n</blockquote>\n\n<p>As for older images, WordPress does not go back and revert your older thumbnails. These settings would only work on everything new from point of install onward. Once your solution is set, you can find a plugin or two that will go back in and rescale every image to the new settings. I do not know if it will work with the added upscale function. The two plugins suggested by user Stanislau Ladutska may offer a quicker overall solution.</p>\n"
},
{
"answer_id": 192692,
"author": "Vee",
"author_id": 44979,
"author_profile": "https://wordpress.stackexchange.com/users/44979",
"pm_score": 0,
"selected": false,
"text": "<p>Having a solution:</p>\n\n<p>First register thumbnail size in function.php</p>\n\n<pre><code>add_image_size( 'cp-thumb', 600, 339, true ); // (cropped) Generate thumbnail while uploading image.\n</code></pre>\n\n<p>Then call it in post loop in following way:</p>\n\n<pre><code><div class=\"outer-div\">\n <div class=\"inner-div\">\n <?php get_the_post_thumbnail( $thumbnail->ID, 'cp-thumb' ); ?>\n </div>\n</div>\n</code></pre>\n\n<p>Set the inner div as table-cell, align center vertically and horizontally. In this case if the image size is smaller than requirement. Positioning or layout will not disturbed. </p>\n\n<p>Give it a try.</p>\n\n<p>Thanks\nVee</p>\n"
},
{
"answer_id": 192707,
"author": "Karun",
"author_id": 63470,
"author_profile": "https://wordpress.stackexchange.com/users/63470",
"pm_score": 1,
"selected": false,
"text": "<p>You can try to crop the image in places you want manually using the <code>WP_Image_Editor</code> class. Here is a simple example</p>\n\n<pre><code>$image = 'http://karunshakya.com.np/wp-content/themes/twentyeleven/images/headers/lanterns.jpg';\n$img_size = getimagesize($image);\n$img_process = wp_get_image_editor( $image ); // Return an implementation that extends <tt>WP_Image_Editor</tt>\n\nif ( ! is_wp_error( $img_process ) ) {\n //$img_process->resize( 1920, 661, array( 'left', 'top' ) );\n $img_process->crop( 0, 0, $img_size[0], $img_size[1], 600, 339 );\n $img_process->save( $image );\n $img_process->set_quality( 100 );\n}\n</code></pre>\n"
}
] |
2015/06/19
|
[
"https://wordpress.stackexchange.com/questions/192053",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/35549/"
] |
I have my post image thumbnails set with:
```
add_theme_support('post-thumbnails');
set_post_thumbnail_size(1280, 436, true);
add_image_size('general-thumb', 600, 339, true);
```
They are resized into two columns with the following css:
```
max-width: 100%;
height: auto;
```
The columns they are displayed in are about 348px wide.
The issue is that when I upload an image that is less than the dimensions 600x339 in either height or width, they show up incorrectly on the page.
I think the reason for this is that 600x339 is the starting 'box' within which an image is cropped. It's then resized to fill the width of the column while retaining the aspect ratio of the original image size.
What are some ways I can fix this with wordpress' functions or css hacks?
What I think needs to happen so that the images can resize dynamically is have every uploaded image automatically cropped to the correct aspect ratio without resizing it. But this needs to start with the original image's width and height, not the predefined box dimensions.
Thanks!
|
It sounds like your problem occurs before the image is cropped/ resized and displayed in the page - the original image is too small.
You can require minimum dimensions for uploaded images, see: [How to Require a Minimum Image Dimension for Uploading?](https://wordpress.stackexchange.com/questions/28359/how-to-require-a-minimum-image-dimension-for-uploading)
Then, to resize the uploaded image without cropping it, define the image size with a 'soft crop' using 'false' in the third parameter:
```
add_image_size('general-thumb', 600, 339, false);
```
Finally, using the image as a background image for an element may be an alternative way of getting the sizing right.
You can position the element within your layout with whatever height, width, minimum height etc is required and use the CSS `background-size` to fill/ position the image within the element.
For example:
```
background-size: contain;
```
Will ensure the image is as large as possible without hiding any part of it.
See: <https://developer.mozilla.org/en-US/docs/Web/CSS/background-size>
|
192,061 |
<p>I converted an old site, which used to run on a CMS called Smarty, to WordPress and am trying to make the look and feel of the site look like a proper music lyrics site.</p>
<p>There don't seem to be themes dedicated to this type of content. I have tried <a href="http://www.2035themes.com/muusico/" rel="nofollow">this</a> theme, and while it looks to be just the right thing for the task, there is no ability to make it work with existing posts. It doesn't recognize my existing posts as lyrics, so basically nothing is functional. So I could enter existing posts into this theme one by one or run a complex database query to convert them, but neither is probably a good idea.</p>
<p>I did create a test new lyric with this theme, and these "lyrics" pages are, in fact, posts, but the URL appended to WordPress dashboard's URL is /wp-admin/post-new.php?post_type=lyrics. What does post_type=lyrics mean? I don't want to create a custom database that will not be readable by other themes if this one is discontinued and stops being compatible with future WordPres updates.</p>
<p>Should I find a theme that uses more standard nomenclature? Or is WordPress not a good engine for this task?</p>
|
[
{
"answer_id": 192062,
"author": "Stephen Bailey",
"author_id": 74953,
"author_profile": "https://wordpress.stackexchange.com/users/74953",
"pm_score": 1,
"selected": false,
"text": "<p>The theme is using a custom post type, in this case, \"lyrics\". Converting the old posts over to it should be as simple as writing a single query to update the old posts to the new post type.</p>\n\n<p>The query will be something like:</p>\n\n<pre><code>UPDATE `wp_posts` SET post_type = \"lyrics\" WHERE post_type = \"post\";\n</code></pre>\n\n<p>Just as an added precaution, run this one first to ensure that all the posts you think should be converted will be affected and check the results:</p>\n\n<pre><code>SELECT * FROM wp_posts WHERE post_type = \"post\";\n</code></pre>\n"
},
{
"answer_id": 192071,
"author": "sakibmoon",
"author_id": 23214,
"author_profile": "https://wordpress.stackexchange.com/users/23214",
"pm_score": 0,
"selected": false,
"text": "<p>The theme is using custom post type and you are right to worry about using it. If you start using this theme, you are doomed in the sense that you can't change it later without breaking the site.</p>\n\n<p>My personal opinion on theme is that it should only work on the visual aspect and leave the functionality part to the plugin. But so many themes break this rule and it is frustrating. Once you start using it, you are married to it for life. If you want to divorce, there are so much Alimony you have to pay that you will hardly think about it. In my opinion, it should be like a date rather than a marriage in the first place.</p>\n\n<p>So, what's the best option for you?</p>\n\n<p>First question, Do you really need custom post type? It depends on which functionality you want to incorporate. It's the question that you have to answer yourself. Personally, I believe it gives a lot of choice and I would've used it just for the fact that it separates my lyrics from post.</p>\n\n<p>IMO for you the best option is to create a plugin that creates the custom post types for lyrics. Now the functionality is in the plugin and you can switch theme any time you want as long as the plugin is activated. You should give only a basic template in your plugin so that everything works without giving much visual consideration as it won't match with your theme anyway. Now in your theme, you need to create a template to display the custom post type properly. Every time you change a plugin, you will need to create a template so that it matches that theme style.</p>\n\n<p>It means that you will still need to modify a little bit when you change theme to match everything perfectly, but even without it your site will work without failing to display the content. If coded properly, it might give nice view even without a template. And lastly modifying theme default template isn't going to take much time.</p>\n"
},
{
"answer_id": 263737,
"author": "goodguy289",
"author_id": 117740,
"author_profile": "https://wordpress.stackexchange.com/users/117740",
"pm_score": 1,
"selected": false,
"text": "<p>Some new lyrics website scripts, theme are available out there. They are made with Wordpress, it is way easier to manage because it seems that everybody knows how to use Wordpress. </p>\n\n<p>Melyric | Song Lyrics Wordpress Theme\n<a href=\"https://www.lyricsphpscript.com/\" rel=\"nofollow noreferrer\">https://www.lyricsphpscript.com/</a></p>\n\n<p>Muusico - Song Lyrics WordPress Theme \n<a href=\"https://themeforest.net/item/muusico-song-lyrics-wordpress-theme/10964140?ref=PixWeber\" rel=\"nofollow noreferrer\">https://themeforest.net/item/muusico-song-lyrics-wordpress-theme/10964140?ref=PixWeber</a></p>\n\n<p>Cheers</p>\n"
}
] |
2015/06/20
|
[
"https://wordpress.stackexchange.com/questions/192061",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89348/"
] |
I converted an old site, which used to run on a CMS called Smarty, to WordPress and am trying to make the look and feel of the site look like a proper music lyrics site.
There don't seem to be themes dedicated to this type of content. I have tried [this](http://www.2035themes.com/muusico/) theme, and while it looks to be just the right thing for the task, there is no ability to make it work with existing posts. It doesn't recognize my existing posts as lyrics, so basically nothing is functional. So I could enter existing posts into this theme one by one or run a complex database query to convert them, but neither is probably a good idea.
I did create a test new lyric with this theme, and these "lyrics" pages are, in fact, posts, but the URL appended to WordPress dashboard's URL is /wp-admin/post-new.php?post\_type=lyrics. What does post\_type=lyrics mean? I don't want to create a custom database that will not be readable by other themes if this one is discontinued and stops being compatible with future WordPres updates.
Should I find a theme that uses more standard nomenclature? Or is WordPress not a good engine for this task?
|
The theme is using a custom post type, in this case, "lyrics". Converting the old posts over to it should be as simple as writing a single query to update the old posts to the new post type.
The query will be something like:
```
UPDATE `wp_posts` SET post_type = "lyrics" WHERE post_type = "post";
```
Just as an added precaution, run this one first to ensure that all the posts you think should be converted will be affected and check the results:
```
SELECT * FROM wp_posts WHERE post_type = "post";
```
|
192,078 |
<p>I am trying to delete records from my custom table but it does not delete anything.</p>
<p>Here is my code:</p>
<pre><code><?php
global $wpdb;
$retrieve_data = $wpdb->get_results( "SELECT * FROM wp_paypal" );
// some code to display here...
?>
<form method="post" enctype="multipart/form-data">
<td><input type="submit" name="delete" value="Delete" /></td>
</form>
<?php
$myid= $retrieved_data->id;
if (isset($_POST['delete'])) {
//global $wpdb;
$wpdb->query(
'DELETE FROM $wpdb->paypal
WHERE id = "'.$myid.'"
'
);
}
}
</code></pre>
|
[
{
"answer_id": 192103,
"author": "Domain",
"author_id": 26523,
"author_profile": "https://wordpress.stackexchange.com/users/26523",
"pm_score": 3,
"selected": false,
"text": "<p>Try to use <code>$wpdb->prefix</code> insted of <code>$wpdb</code> in Delete query.</p>\n\n<p>Example:</p>\n\n<pre><code> $wpdb->query(\n 'DELETE FROM '.$wpdb->prefix.'paypal\n WHERE id = \"'.$myid.'\"'\n);\n</code></pre>\n"
},
{
"answer_id": 320667,
"author": "Maxime",
"author_id": 13876,
"author_profile": "https://wordpress.stackexchange.com/users/13876",
"pm_score": 1,
"selected": false,
"text": "<p>I know I'm late... but the main issue in your question is that you are using single quotes (') in your statement:</p>\n\n<pre><code>$wpdb->query(\n 'DELETE FROM $wpdb->paypal\n WHERE id = \"'.$myid.'\"\n '\n);\n</code></pre>\n\n<p>This means that <code>$wpdb->paypal</code> is not producing the result you are expecting. First, you assume this displays the \"paypal\" table name. But it doesn't.</p>\n\n<p>If <code>$myid</code> has a value of <code>4</code>, your PHP code will produce this SQL statement :</p>\n\n<pre><code>DELETE FROM $wpdb->paypal WHERE id = 4\n</code></pre>\n\n<p>... instead of being:</p>\n\n<pre><code>DELETE FROM wp_paypal WHERE id = 4\n</code></pre>\n\n<p>To fix the issue, you must:</p>\n\n<ol>\n<li>Change your single quotes to double quotes. (<a href=\"https://stackoverflow.com/a/3446286/771496\">Read why</a>)</li>\n<li>Add the table prefix in front of the table name.</li>\n</ol>\n\n<p>Like this:</p>\n\n<pre><code>$table_name = $wpdb->prefix . 'paypal';\n$wpdb->query( \"DELETE FROM {$table_name} WHERE id = '{$myid}'\" );\n</code></pre>\n\n<p>Also, make sure <a href=\"https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data\" rel=\"nofollow noreferrer\">you sanitize</a> the <code>$myid</code> variable because if I submit the value <code>0 OR 1=1</code>, this will produce this SQL statement:</p>\n\n<pre><code>DELETE FROM wp_paypal WHERE id = 0 OR 1=1\n</code></pre>\n\n<p>... and will delete every row in the table</p>\n"
}
] |
2015/06/20
|
[
"https://wordpress.stackexchange.com/questions/192078",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74198/"
] |
I am trying to delete records from my custom table but it does not delete anything.
Here is my code:
```
<?php
global $wpdb;
$retrieve_data = $wpdb->get_results( "SELECT * FROM wp_paypal" );
// some code to display here...
?>
<form method="post" enctype="multipart/form-data">
<td><input type="submit" name="delete" value="Delete" /></td>
</form>
<?php
$myid= $retrieved_data->id;
if (isset($_POST['delete'])) {
//global $wpdb;
$wpdb->query(
'DELETE FROM $wpdb->paypal
WHERE id = "'.$myid.'"
'
);
}
}
```
|
Try to use `$wpdb->prefix` insted of `$wpdb` in Delete query.
Example:
```
$wpdb->query(
'DELETE FROM '.$wpdb->prefix.'paypal
WHERE id = "'.$myid.'"'
);
```
|
192,096 |
<p>I'm having hard times with showing only posts which have featured images using the loop. My PHP level is basic and any help will be really useful. </p>
<p>So basically this is my original code :</p>
<pre><code>if( have_posts() ) {
while( have_posts() ) {
the_post();
get_template_part( 'inc/template-parts/content', $post_layout );
// and some other stuff
}
}
</code></pre>
<p>I tried the advice from this thread - <a href="https://wordpress.stackexchange.com/questions/45909/how-do-i-check-if-a-post-has-a-post-thumbnail-in-wp-query">How do I check if a post has a post thumbnail in <code>WP_Query</code>?</a>
But without any success. When I implement the code all posts disappear from the front page.</p>
<p>This is the code I tried: </p>
<pre><code>$query = new WP_Query( $thumbs );
$thumbs = array(
'meta_query' => array( 'key' => '_thumbnail_id' )
);
if( $query->have_posts() ) {
while( $query->have_posts() ) {
$query->the_post();
get_template_part( 'inc/template-parts/content', $post_layout );
}
}
</code></pre>
<p>Any advice will be appreciated!
Regards</p>
|
[
{
"answer_id": 192099,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 4,
"selected": true,
"text": "<p>You need to define your arguments <strong>before</strong> you pass them to <code>WP_Query</code>, not after. Also, your <code>meta_query</code> should be an array of an array, not just an array</p>\n\n<p>This</p>\n\n<pre><code> $query = new WP_Query($thumbs);\n $thumbs = array(\n 'meta_query' => array('key' => '_thumbnail_id') \n );\n</code></pre>\n\n<p>should look like this</p>\n\n<pre><code> $thumbs = array(\n 'meta_query' => array( \n array(\n 'key' => '_thumbnail_id'\n ) \n )\n );\n\n $query = new WP_Query($thumbs);\n</code></pre>\n\n<h2>EDIT</h2>\n\n<p>Just a few extra notes</p>\n\n<ul>\n<li><p>Make sure to reset postdata after a custom query. Just add <code>wp_reset_postdata();</code> before you close your <code>if</code> statement and just after closing your <code>while</code> statement</p></li>\n<li><p>I believe that a custom query might not be necessary here. If I read your question correctly, you can simply use <code>pre_get_posts</code> to alter the main query. You shouldn't use a custom query just because you want to alter the main query </p></li>\n</ul>\n"
},
{
"answer_id": 357271,
"author": "Yaakov Aglamaz",
"author_id": 154659,
"author_profile": "https://wordpress.stackexchange.com/users/154659",
"pm_score": 0,
"selected": false,
"text": "<p>Another approch for woocommerce products:</p>\n\n<pre><code>add_filter('woocommerce_product_query_meta_query', 'products_with_thumbs', 10);\n</code></pre>\n\n<p><code>function products_with_thumbs()\n{\n return array(\n 'relation' => 'OR',\n array('key' => '_thumbnail_id',\n 'compare' => '>',\n 'value' => '0')\n );\n}</code></p>\n"
}
] |
2015/06/20
|
[
"https://wordpress.stackexchange.com/questions/192096",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74969/"
] |
I'm having hard times with showing only posts which have featured images using the loop. My PHP level is basic and any help will be really useful.
So basically this is my original code :
```
if( have_posts() ) {
while( have_posts() ) {
the_post();
get_template_part( 'inc/template-parts/content', $post_layout );
// and some other stuff
}
}
```
I tried the advice from this thread - [How do I check if a post has a post thumbnail in `WP_Query`?](https://wordpress.stackexchange.com/questions/45909/how-do-i-check-if-a-post-has-a-post-thumbnail-in-wp-query)
But without any success. When I implement the code all posts disappear from the front page.
This is the code I tried:
```
$query = new WP_Query( $thumbs );
$thumbs = array(
'meta_query' => array( 'key' => '_thumbnail_id' )
);
if( $query->have_posts() ) {
while( $query->have_posts() ) {
$query->the_post();
get_template_part( 'inc/template-parts/content', $post_layout );
}
}
```
Any advice will be appreciated!
Regards
|
You need to define your arguments **before** you pass them to `WP_Query`, not after. Also, your `meta_query` should be an array of an array, not just an array
This
```
$query = new WP_Query($thumbs);
$thumbs = array(
'meta_query' => array('key' => '_thumbnail_id')
);
```
should look like this
```
$thumbs = array(
'meta_query' => array(
array(
'key' => '_thumbnail_id'
)
)
);
$query = new WP_Query($thumbs);
```
EDIT
----
Just a few extra notes
* Make sure to reset postdata after a custom query. Just add `wp_reset_postdata();` before you close your `if` statement and just after closing your `while` statement
* I believe that a custom query might not be necessary here. If I read your question correctly, you can simply use `pre_get_posts` to alter the main query. You shouldn't use a custom query just because you want to alter the main query
|
192,133 |
<p>I am creating a multi website for an organization and I want to do is reduce the step upon account activation so when the user register for a sub site.</p>
<p>When they select a custom theme, a default content, default plugin, default menu will automatically be configured or in other words, sample content and settings will automatically be configured on the selected theme
Similar to importing an XML, only want it upon user signup on multisite</p>
|
[
{
"answer_id": 192099,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 4,
"selected": true,
"text": "<p>You need to define your arguments <strong>before</strong> you pass them to <code>WP_Query</code>, not after. Also, your <code>meta_query</code> should be an array of an array, not just an array</p>\n\n<p>This</p>\n\n<pre><code> $query = new WP_Query($thumbs);\n $thumbs = array(\n 'meta_query' => array('key' => '_thumbnail_id') \n );\n</code></pre>\n\n<p>should look like this</p>\n\n<pre><code> $thumbs = array(\n 'meta_query' => array( \n array(\n 'key' => '_thumbnail_id'\n ) \n )\n );\n\n $query = new WP_Query($thumbs);\n</code></pre>\n\n<h2>EDIT</h2>\n\n<p>Just a few extra notes</p>\n\n<ul>\n<li><p>Make sure to reset postdata after a custom query. Just add <code>wp_reset_postdata();</code> before you close your <code>if</code> statement and just after closing your <code>while</code> statement</p></li>\n<li><p>I believe that a custom query might not be necessary here. If I read your question correctly, you can simply use <code>pre_get_posts</code> to alter the main query. You shouldn't use a custom query just because you want to alter the main query </p></li>\n</ul>\n"
},
{
"answer_id": 357271,
"author": "Yaakov Aglamaz",
"author_id": 154659,
"author_profile": "https://wordpress.stackexchange.com/users/154659",
"pm_score": 0,
"selected": false,
"text": "<p>Another approch for woocommerce products:</p>\n\n<pre><code>add_filter('woocommerce_product_query_meta_query', 'products_with_thumbs', 10);\n</code></pre>\n\n<p><code>function products_with_thumbs()\n{\n return array(\n 'relation' => 'OR',\n array('key' => '_thumbnail_id',\n 'compare' => '>',\n 'value' => '0')\n );\n}</code></p>\n"
}
] |
2015/06/20
|
[
"https://wordpress.stackexchange.com/questions/192133",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/44422/"
] |
I am creating a multi website for an organization and I want to do is reduce the step upon account activation so when the user register for a sub site.
When they select a custom theme, a default content, default plugin, default menu will automatically be configured or in other words, sample content and settings will automatically be configured on the selected theme
Similar to importing an XML, only want it upon user signup on multisite
|
You need to define your arguments **before** you pass them to `WP_Query`, not after. Also, your `meta_query` should be an array of an array, not just an array
This
```
$query = new WP_Query($thumbs);
$thumbs = array(
'meta_query' => array('key' => '_thumbnail_id')
);
```
should look like this
```
$thumbs = array(
'meta_query' => array(
array(
'key' => '_thumbnail_id'
)
)
);
$query = new WP_Query($thumbs);
```
EDIT
----
Just a few extra notes
* Make sure to reset postdata after a custom query. Just add `wp_reset_postdata();` before you close your `if` statement and just after closing your `while` statement
* I believe that a custom query might not be necessary here. If I read your question correctly, you can simply use `pre_get_posts` to alter the main query. You shouldn't use a custom query just because you want to alter the main query
|
192,159 |
<p>Does someone know a solution for this?</p>
<p>I want to remove (<strong>not unregister</strong>) all widgets from a sidebar with a function.</p>
|
[
{
"answer_id": 192161,
"author": "James Barrett",
"author_id": 74733,
"author_profile": "https://wordpress.stackexchange.com/users/74733",
"pm_score": 4,
"selected": true,
"text": "<p>You could add this function to your functions.php file.</p>\n\n<pre><code>add_filter( 'sidebars_widgets', 'disable_all_widgets' );\n\nfunction disable_all_widgets( $sidebars_widgets ) {\n\n $sidebars_widgets = array( false );\n\n return $sidebars_widgets;\n}\n</code></pre>\n\n<p>You could also use the <a href=\"http://codex.wordpress.org/Conditional_Tags\" rel=\"noreferrer\">Wordpress conditional tags</a> to disable widgets only on certain pages. For example; this would only disable widgets on the home page.</p>\n\n<pre><code>add_filter( 'sidebars_widgets', 'disable_all_widgets' );\n\nfunction disable_all_widgets( $sidebars_widgets ) {\n\n if ( is_home() )\n $sidebars_widgets = array( false );\n\n return $sidebars_widgets;\n}\n</code></pre>\n"
},
{
"answer_id": 305262,
"author": "James Revillini",
"author_id": 133859,
"author_profile": "https://wordpress.stackexchange.com/users/133859",
"pm_score": 2,
"selected": false,
"text": "<p>There is a quick way to accomplish this via jQuery and the developer console. First, navigate to Appearance Widgets and open the developer console (I use Chrome so I just hit CTRL+SHIFT+J on the keyboard to open it). <strong>This action cannot be undone, so be careful and make a database backup first.</strong></p>\n\n<pre><code>$('.button-link.button-link-delete.widget-control-remove').click();\n</code></pre>\n\n<p>What this is doing is using a CSS selector to get a list of all 'Delete' buttons/links on the page and simulating a click on it.</p>\n\n<p>This leaves your sidebars registered, but it empties all widgets that are added. </p>\n\n<p>I used it today because a theme I installed pre-populated all the sidebars with tons of widgets that were causing the site to load slowly even though they were only used on certain pages.</p>\n\n<p>Note: for some reason, this will appear to remove even the widget templates on the left. It is not. Just refresh the Widget management page and they will all be there, available to add to the sidebars.</p>\n"
}
] |
2015/06/21
|
[
"https://wordpress.stackexchange.com/questions/192159",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/33235/"
] |
Does someone know a solution for this?
I want to remove (**not unregister**) all widgets from a sidebar with a function.
|
You could add this function to your functions.php file.
```
add_filter( 'sidebars_widgets', 'disable_all_widgets' );
function disable_all_widgets( $sidebars_widgets ) {
$sidebars_widgets = array( false );
return $sidebars_widgets;
}
```
You could also use the [Wordpress conditional tags](http://codex.wordpress.org/Conditional_Tags) to disable widgets only on certain pages. For example; this would only disable widgets on the home page.
```
add_filter( 'sidebars_widgets', 'disable_all_widgets' );
function disable_all_widgets( $sidebars_widgets ) {
if ( is_home() )
$sidebars_widgets = array( false );
return $sidebars_widgets;
}
```
|
192,193 |
<p>For example I have an image that's very long but want to show a cropped version of that but when people click my blog post from the homepage they see the longer version.</p>
<p>I tried doing using the plugin "Custom CSS Manager" with the code:</p>
<pre><code>.home .post-4262 .entry p:first-of-type {
max-height: 375px;
overflow: hidden;
}
</code></pre>
<p>Which works but I can't figure out a way to crop my image to the specific 600X375 that I want. Like for some pictures I don't want it to start from the top but close to the top if that makes sense. That code is good but won't let me do that from what I understand.</p>
<p>Or do I need to take a simpler approach? If anyone knows how to make my homepage blog image shorter that I can control the 600X375 crop but the post page has the full image please share. I have been trying to figure this out for the last two days but with no avail. Thanks for any help. </p>
|
[
{
"answer_id": 192161,
"author": "James Barrett",
"author_id": 74733,
"author_profile": "https://wordpress.stackexchange.com/users/74733",
"pm_score": 4,
"selected": true,
"text": "<p>You could add this function to your functions.php file.</p>\n\n<pre><code>add_filter( 'sidebars_widgets', 'disable_all_widgets' );\n\nfunction disable_all_widgets( $sidebars_widgets ) {\n\n $sidebars_widgets = array( false );\n\n return $sidebars_widgets;\n}\n</code></pre>\n\n<p>You could also use the <a href=\"http://codex.wordpress.org/Conditional_Tags\" rel=\"noreferrer\">Wordpress conditional tags</a> to disable widgets only on certain pages. For example; this would only disable widgets on the home page.</p>\n\n<pre><code>add_filter( 'sidebars_widgets', 'disable_all_widgets' );\n\nfunction disable_all_widgets( $sidebars_widgets ) {\n\n if ( is_home() )\n $sidebars_widgets = array( false );\n\n return $sidebars_widgets;\n}\n</code></pre>\n"
},
{
"answer_id": 305262,
"author": "James Revillini",
"author_id": 133859,
"author_profile": "https://wordpress.stackexchange.com/users/133859",
"pm_score": 2,
"selected": false,
"text": "<p>There is a quick way to accomplish this via jQuery and the developer console. First, navigate to Appearance Widgets and open the developer console (I use Chrome so I just hit CTRL+SHIFT+J on the keyboard to open it). <strong>This action cannot be undone, so be careful and make a database backup first.</strong></p>\n\n<pre><code>$('.button-link.button-link-delete.widget-control-remove').click();\n</code></pre>\n\n<p>What this is doing is using a CSS selector to get a list of all 'Delete' buttons/links on the page and simulating a click on it.</p>\n\n<p>This leaves your sidebars registered, but it empties all widgets that are added. </p>\n\n<p>I used it today because a theme I installed pre-populated all the sidebars with tons of widgets that were causing the site to load slowly even though they were only used on certain pages.</p>\n\n<p>Note: for some reason, this will appear to remove even the widget templates on the left. It is not. Just refresh the Widget management page and they will all be there, available to add to the sidebars.</p>\n"
}
] |
2015/06/21
|
[
"https://wordpress.stackexchange.com/questions/192193",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75022/"
] |
For example I have an image that's very long but want to show a cropped version of that but when people click my blog post from the homepage they see the longer version.
I tried doing using the plugin "Custom CSS Manager" with the code:
```
.home .post-4262 .entry p:first-of-type {
max-height: 375px;
overflow: hidden;
}
```
Which works but I can't figure out a way to crop my image to the specific 600X375 that I want. Like for some pictures I don't want it to start from the top but close to the top if that makes sense. That code is good but won't let me do that from what I understand.
Or do I need to take a simpler approach? If anyone knows how to make my homepage blog image shorter that I can control the 600X375 crop but the post page has the full image please share. I have been trying to figure this out for the last two days but with no avail. Thanks for any help.
|
You could add this function to your functions.php file.
```
add_filter( 'sidebars_widgets', 'disable_all_widgets' );
function disable_all_widgets( $sidebars_widgets ) {
$sidebars_widgets = array( false );
return $sidebars_widgets;
}
```
You could also use the [Wordpress conditional tags](http://codex.wordpress.org/Conditional_Tags) to disable widgets only on certain pages. For example; this would only disable widgets on the home page.
```
add_filter( 'sidebars_widgets', 'disable_all_widgets' );
function disable_all_widgets( $sidebars_widgets ) {
if ( is_home() )
$sidebars_widgets = array( false );
return $sidebars_widgets;
}
```
|
192,202 |
<p>i'm really getting crazy about this. after hours of trials, i can't get out of this.</p>
<p>I'm trying to pass a php variable value to an enqueued jquery script but i can't. </p>
<p>here is my code.</p>
<p>php : </p>
<pre><code>function itinerary_enqueuescripts(){
wp_enqueue_script('itenqueue', JSONURL.'/js/loadjson.js', array('jquery'));
wp_localize_script( 'itenqueue', 'itajax', array( 'ajaxurl' => "hithere" ) );
}
add_action('wp_enqueue_scripts', 'itinerary_enqueuescripts');
</code></pre>
<p>in my loadjson.js file i have a simple </p>
<pre><code>var _latitude = 43.309;
var _longitude = 8.499;
var jsonPath = itajax.ajaxurl; //and should transform, in this example, in hithere
</code></pre>
<p>But when the script is enqueued, the var jsonPath as the value of itajax.ajaxurl :)</p>
<p>The scripts gets enqueued correctly, in this example i make a simple variable declaration (just to let out problems.. e.g. the script gets enqueued too early).</p>
<p>Funny thing (and perhaps here's the clue, this is quite a copy/paste from another plugin of mine, for a function that points to admin-ajax.php for front end posting. It's the same syntax, with different variable names of course, but in this case it doesn't work).</p>
<p>Thanks for any clue. (i tried quite anything, registering-localizing-enqueueing, enqueueing in wp_footer at the very last.. even changing double qoutes to single quotes :) Now i suppose i really must miss something.</p>
|
[
{
"answer_id": 192161,
"author": "James Barrett",
"author_id": 74733,
"author_profile": "https://wordpress.stackexchange.com/users/74733",
"pm_score": 4,
"selected": true,
"text": "<p>You could add this function to your functions.php file.</p>\n\n<pre><code>add_filter( 'sidebars_widgets', 'disable_all_widgets' );\n\nfunction disable_all_widgets( $sidebars_widgets ) {\n\n $sidebars_widgets = array( false );\n\n return $sidebars_widgets;\n}\n</code></pre>\n\n<p>You could also use the <a href=\"http://codex.wordpress.org/Conditional_Tags\" rel=\"noreferrer\">Wordpress conditional tags</a> to disable widgets only on certain pages. For example; this would only disable widgets on the home page.</p>\n\n<pre><code>add_filter( 'sidebars_widgets', 'disable_all_widgets' );\n\nfunction disable_all_widgets( $sidebars_widgets ) {\n\n if ( is_home() )\n $sidebars_widgets = array( false );\n\n return $sidebars_widgets;\n}\n</code></pre>\n"
},
{
"answer_id": 305262,
"author": "James Revillini",
"author_id": 133859,
"author_profile": "https://wordpress.stackexchange.com/users/133859",
"pm_score": 2,
"selected": false,
"text": "<p>There is a quick way to accomplish this via jQuery and the developer console. First, navigate to Appearance Widgets and open the developer console (I use Chrome so I just hit CTRL+SHIFT+J on the keyboard to open it). <strong>This action cannot be undone, so be careful and make a database backup first.</strong></p>\n\n<pre><code>$('.button-link.button-link-delete.widget-control-remove').click();\n</code></pre>\n\n<p>What this is doing is using a CSS selector to get a list of all 'Delete' buttons/links on the page and simulating a click on it.</p>\n\n<p>This leaves your sidebars registered, but it empties all widgets that are added. </p>\n\n<p>I used it today because a theme I installed pre-populated all the sidebars with tons of widgets that were causing the site to load slowly even though they were only used on certain pages.</p>\n\n<p>Note: for some reason, this will appear to remove even the widget templates on the left. It is not. Just refresh the Widget management page and they will all be there, available to add to the sidebars.</p>\n"
}
] |
2015/06/22
|
[
"https://wordpress.stackexchange.com/questions/192202",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/51568/"
] |
i'm really getting crazy about this. after hours of trials, i can't get out of this.
I'm trying to pass a php variable value to an enqueued jquery script but i can't.
here is my code.
php :
```
function itinerary_enqueuescripts(){
wp_enqueue_script('itenqueue', JSONURL.'/js/loadjson.js', array('jquery'));
wp_localize_script( 'itenqueue', 'itajax', array( 'ajaxurl' => "hithere" ) );
}
add_action('wp_enqueue_scripts', 'itinerary_enqueuescripts');
```
in my loadjson.js file i have a simple
```
var _latitude = 43.309;
var _longitude = 8.499;
var jsonPath = itajax.ajaxurl; //and should transform, in this example, in hithere
```
But when the script is enqueued, the var jsonPath as the value of itajax.ajaxurl :)
The scripts gets enqueued correctly, in this example i make a simple variable declaration (just to let out problems.. e.g. the script gets enqueued too early).
Funny thing (and perhaps here's the clue, this is quite a copy/paste from another plugin of mine, for a function that points to admin-ajax.php for front end posting. It's the same syntax, with different variable names of course, but in this case it doesn't work).
Thanks for any clue. (i tried quite anything, registering-localizing-enqueueing, enqueueing in wp\_footer at the very last.. even changing double qoutes to single quotes :) Now i suppose i really must miss something.
|
You could add this function to your functions.php file.
```
add_filter( 'sidebars_widgets', 'disable_all_widgets' );
function disable_all_widgets( $sidebars_widgets ) {
$sidebars_widgets = array( false );
return $sidebars_widgets;
}
```
You could also use the [Wordpress conditional tags](http://codex.wordpress.org/Conditional_Tags) to disable widgets only on certain pages. For example; this would only disable widgets on the home page.
```
add_filter( 'sidebars_widgets', 'disable_all_widgets' );
function disable_all_widgets( $sidebars_widgets ) {
if ( is_home() )
$sidebars_widgets = array( false );
return $sidebars_widgets;
}
```
|
192,243 |
<p>Is there any experience using widget logic, I want to display a widget on single custom post type with specific taxonomy. Tried using </p>
<pre><code>is_tax(taxonomy_name) || is_single() && in_term(term_name).
</code></pre>
|
[
{
"answer_id": 192247,
"author": "Anand",
"author_id": 73187,
"author_profile": "https://wordpress.stackexchange.com/users/73187",
"pm_score": -1,
"selected": false,
"text": "<p>Please try below code:</p>\n\n<pre><code>if(has_tag( array( 'sharp', 'mild', 'extreme' ) ) && get_post_type()==\"custom-post-type\"){\n}\n</code></pre>\n\n<p>The array value should be the term name which is stored in taxonomy.</p>\n\n<p>You can directly pass the array in <code>has_tag()</code> function</p>\n"
},
{
"answer_id": 192256,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 2,
"selected": true,
"text": "<p>Before I start, I must say that your terminology is quite confusing and plain wrong. You should take your time and read through <a href=\"https://wordpress.stackexchange.com/a/158223/31545\">my answer</a> to this question: <a href=\"https://wordpress.stackexchange.com/questions/158206/is-there-a-difference-between-taxonomies-and-categories/158223#158223\">Is There a Difference Between Taxonomies and Categories?</a></p>\n\n<p>As I stated before, there is no <code>in_term()</code> function to check if a post has a specific term. There is however a <a href=\"https://codex.wordpress.org/Function_Reference/has_term\" rel=\"nofollow noreferrer\"><code>has_term()</code></a> function which accepts the term as first parameter and the taxonomy name as second parameter. So your condition should look like this: (<em>if this is for a specific post type outside the loop</em>)</p>\n\n<pre><code>global $post;\nif ( $post->post_type == 'my_post_type' // checks the post type of the post\n && is_single() // Checks if this is a single post\n && has_term( 'term-name or id or slug', 'my_taxonomy', $post->ID ) // Check if post has specific term\n) {\n // Do something if our condition is true\n}\n</code></pre>\n"
}
] |
2015/06/22
|
[
"https://wordpress.stackexchange.com/questions/192243",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/62707/"
] |
Is there any experience using widget logic, I want to display a widget on single custom post type with specific taxonomy. Tried using
```
is_tax(taxonomy_name) || is_single() && in_term(term_name).
```
|
Before I start, I must say that your terminology is quite confusing and plain wrong. You should take your time and read through [my answer](https://wordpress.stackexchange.com/a/158223/31545) to this question: [Is There a Difference Between Taxonomies and Categories?](https://wordpress.stackexchange.com/questions/158206/is-there-a-difference-between-taxonomies-and-categories/158223#158223)
As I stated before, there is no `in_term()` function to check if a post has a specific term. There is however a [`has_term()`](https://codex.wordpress.org/Function_Reference/has_term) function which accepts the term as first parameter and the taxonomy name as second parameter. So your condition should look like this: (*if this is for a specific post type outside the loop*)
```
global $post;
if ( $post->post_type == 'my_post_type' // checks the post type of the post
&& is_single() // Checks if this is a single post
&& has_term( 'term-name or id or slug', 'my_taxonomy', $post->ID ) // Check if post has specific term
) {
// Do something if our condition is true
}
```
|
192,245 |
<p>I have this custom query:</p>
<pre><code>query_posts(
array (
'orderby' => 'rr_recommends_count',
'meta_key' => 'rr_recommends_count',
'order' => 'DESC',
)
);
</code></pre>
<p>Which orders the posts like this:</p>
<p>9, 8, 7, 6, 5, 4, 3, 2, <strong>11, 10,</strong> 1 etc.</p>
<p>I see that the problem is that the meta_value field has a type of <strong>longtext</strong>.</p>
<p>How can I fix the sort without changing the meta_value field type?</p>
|
[
{
"answer_id": 192248,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>First of all, never ever use <code>query_posts</code>. It breaks the main function and all plugins and functions relying on the main query object. For custom queries, use <code>WP_Query</code> or <code>get_posts</code> if aren't looking to paginate the query</p>\n\n<p>As for the following line</p>\n\n<pre><code>'orderby' => 'rr_recommends_count',\n</code></pre>\n\n<p>I can tell you that <code>rr_recommends_count</code> is an invalid value to the <code>orderby</code> parameter. Suspect that this is actually the key name, and the values are all numerical in that key, so you would use the <code>meta_value_num</code> value to the <code>orderby</code> parameter which is a valid value</p>\n\n<pre><code>'orderby' => 'meta_value_num',\n</code></pre>\n\n<p>Please see <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters\" rel=\"nofollow\">Order and Orderby Parameters in <code>WP_Query</code></a></p>\n"
},
{
"answer_id": 192250,
"author": "Anand",
"author_id": 73187,
"author_profile": "https://wordpress.stackexchange.com/users/73187",
"pm_score": 0,
"selected": false,
"text": "<p>please try this:</p>\n\n<pre><code>$args = array(\n 'orderby' => 'meta_value_num',\n 'meta_key' => 'rr_recommends_count',\n 'order' => 'DESC');\n$query = new WP_Query( $args );\n</code></pre>\n"
}
] |
2015/06/22
|
[
"https://wordpress.stackexchange.com/questions/192245",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25239/"
] |
I have this custom query:
```
query_posts(
array (
'orderby' => 'rr_recommends_count',
'meta_key' => 'rr_recommends_count',
'order' => 'DESC',
)
);
```
Which orders the posts like this:
9, 8, 7, 6, 5, 4, 3, 2, **11, 10,** 1 etc.
I see that the problem is that the meta\_value field has a type of **longtext**.
How can I fix the sort without changing the meta\_value field type?
|
First of all, never ever use `query_posts`. It breaks the main function and all plugins and functions relying on the main query object. For custom queries, use `WP_Query` or `get_posts` if aren't looking to paginate the query
As for the following line
```
'orderby' => 'rr_recommends_count',
```
I can tell you that `rr_recommends_count` is an invalid value to the `orderby` parameter. Suspect that this is actually the key name, and the values are all numerical in that key, so you would use the `meta_value_num` value to the `orderby` parameter which is a valid value
```
'orderby' => 'meta_value_num',
```
Please see [Order and Orderby Parameters in `WP_Query`](https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters)
|
192,258 |
<p>I have to execute custom PHP code after new post is saved with all it's meta data.</p>
<p>My question is how to achieve that? Tried with <strong>save_post</strong> action, but it executes before meta records are saved, so I cannot use it in this case.</p>
<p>So, how can I run my custom function after post with all related data is saved in database?</p>
<p><strong>UPDATED:</strong> I tried to achieve with next code in functions.php file:</p>
<pre><code>add_action( 'save_post', 'wpse41912_save_post' );
function wpse41912_save_post() {
// get info about latest added post
$args = array( 'numberposts' => '1', 'post_type' => 'post' );
$recent_posts = wp_get_recent_posts( $args );
$myFunc_latest_id = $recent_posts[0]['ID']; // id of the latest post
$myFunc_post_details = get_post($myFunc_latest_id);
print_r($myFunc_post_details);
// how to execute php code when all post meta is added?
}
</code></pre>
<p>Thank you in advance!</p>
|
[
{
"answer_id": 192323,
"author": "Frank P. Walentynowicz",
"author_id": 32851,
"author_profile": "https://wordpress.stackexchange.com/users/32851",
"pm_score": 3,
"selected": false,
"text": "<p>For <strong>NEW</strong> post type 'post' use <code>draft_to_publish</code> action hook:</p>\n\n<pre><code>function fpw_post_info( $post ) {\n if ( 'post' == $post->post_type ) {\n // echo '<pre>'; print_r( $post ); echo '<br />';\n // $meta = get_post_meta( $post->ID ); print_r( $meta ); echo '</pre>'; die();\n // your custom code goes here...\n }\n}\nadd_action( 'draft_to_publish', 'fpw_post_info', 10, 1 );\n</code></pre>\n\n<p>In your callback function <code>$post</code> is your post as <code>WP_post</code> object. You'll get post's meta calling <code>get_post_meta</code> function.</p>\n\n<p>For <strong>NEW</strong> or <strong>UPDATED</strong> post type 'post' use <code>publish_post</code> action hook:</p>\n\n<pre><code>function fpw_post_info( $id, $post ) {\n // echo '<pre>'; print_r( $post ); echo '<br />';\n // $meta = get_post_meta( $post->ID ); print_r( $meta ); echo '</pre>'; die();\n // your custom code goes here...\n}\nadd_action( 'publish_post', 'fpw_post_info', 10, 2 );\n</code></pre>\n\n<p>In this case the callback function takes two parameters!</p>\n"
},
{
"answer_id": 215273,
"author": "user2455079",
"author_id": 75633,
"author_profile": "https://wordpress.stackexchange.com/users/75633",
"pm_score": 3,
"selected": false,
"text": "<p>Quite stupid solution, but works:</p>\n\n<pre><code>function afterPostUpdated($meta_id, $post_id, $meta_key='', $meta_value=''){\n if($meta_key=='_edit_lock') {\n if($_GET['message']==1) {\n //\n Your code here\n // \n }\n }\n}\nadd_action('updated_post_meta', 'afterPostUpdated', 10, 4);\n</code></pre>\n"
},
{
"answer_id": 367758,
"author": "BonisTech",
"author_id": 162672,
"author_profile": "https://wordpress.stackexchange.com/users/162672",
"pm_score": 1,
"selected": false,
"text": "<p>You might use this:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function myFunction($post_id, $post, $update ) {\n // your code here\n}\n\nadd_action('save_post', 'myFunction');\n</code></pre>\n\n<p><code>$update</code> is a boolean and return false if this is a new post. If it's an update it returns true.</p>\n\n<p>Here is the documentation: <a href=\"https://developer.wordpress.org/reference/hooks/save_post/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/save_post/</a></p>\n"
},
{
"answer_id": 402431,
"author": "Dave Hilditch",
"author_id": 19869,
"author_profile": "https://wordpress.stackexchange.com/users/19869",
"pm_score": 0,
"selected": false,
"text": "<p>The correct and simpler answer is to use the <code>wp_insert_post</code> action.</p>\n<p><a href=\"https://developer.wordpress.org/reference/hooks/wp_insert_post/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/wp_insert_post/</a></p>\n<blockquote>\n<p>An important distinction of wp_insert_post action is that it is fired\nafter update_post_meta has been called.</p>\n</blockquote>\n<p>There are 3 parameters available - the $update flag tells you if this is a new or updated post.</p>\n<pre><code>add_action('wp_insert_post', 'run_after_post_updated', 10, 3); \nfunction run_after_post_updated($post_ID, $post = null, $update = true) {\n //even though the docs say 3 parameters, it seems sometimes only the postid is passed - so you need defaults on the other 2 parameters\n $meta = get_post_meta( $post_ID ); \n // ...\n}\n</code></pre>\n"
}
] |
2015/06/22
|
[
"https://wordpress.stackexchange.com/questions/192258",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/44050/"
] |
I have to execute custom PHP code after new post is saved with all it's meta data.
My question is how to achieve that? Tried with **save\_post** action, but it executes before meta records are saved, so I cannot use it in this case.
So, how can I run my custom function after post with all related data is saved in database?
**UPDATED:** I tried to achieve with next code in functions.php file:
```
add_action( 'save_post', 'wpse41912_save_post' );
function wpse41912_save_post() {
// get info about latest added post
$args = array( 'numberposts' => '1', 'post_type' => 'post' );
$recent_posts = wp_get_recent_posts( $args );
$myFunc_latest_id = $recent_posts[0]['ID']; // id of the latest post
$myFunc_post_details = get_post($myFunc_latest_id);
print_r($myFunc_post_details);
// how to execute php code when all post meta is added?
}
```
Thank you in advance!
|
For **NEW** post type 'post' use `draft_to_publish` action hook:
```
function fpw_post_info( $post ) {
if ( 'post' == $post->post_type ) {
// echo '<pre>'; print_r( $post ); echo '<br />';
// $meta = get_post_meta( $post->ID ); print_r( $meta ); echo '</pre>'; die();
// your custom code goes here...
}
}
add_action( 'draft_to_publish', 'fpw_post_info', 10, 1 );
```
In your callback function `$post` is your post as `WP_post` object. You'll get post's meta calling `get_post_meta` function.
For **NEW** or **UPDATED** post type 'post' use `publish_post` action hook:
```
function fpw_post_info( $id, $post ) {
// echo '<pre>'; print_r( $post ); echo '<br />';
// $meta = get_post_meta( $post->ID ); print_r( $meta ); echo '</pre>'; die();
// your custom code goes here...
}
add_action( 'publish_post', 'fpw_post_info', 10, 2 );
```
In this case the callback function takes two parameters!
|
192,275 |
<p>I'm experiencing an odd situation while running an UPDATE with <code>$wpdb->query()</code>.</p>
<p>Given the <code>users</code> table, with columns <code>user_id</code> (Primary Key) and <code>status</code>, and the user 3 existing and with status 0, I run the following query:</p>
<pre>
update users
set status = 8
where user_id = 3
</pre>
<p>On my machine, running the query with <code>$wpdb->query</code>, I get the result of 1: 1 row affected.</p>
<p>On another machine I run the query with the PHP code and always get 0 rows: before running the query I checked the status and it was 0, and if I run it with another tool (e.g. command line mysql client), it says me that is 1 affected row.</p>
<p>The query method of wpdb returns the number of affected rows in case of update (<a href="https://codex.wordpress.org/Class_Reference/wpdb#Running_General_Queries" rel="nofollow">https://codex.wordpress.org/Class_Reference/wpdb#Running_General_Queries</a>).</p>
<p>My machine and the remote one have got the same PHP version (5.4.40), same mysql server version, and same wordpress version (4.2.2). About the mysql PHP extensions, in local I've installed mysql, mysqli and mysqlnd: on the other machine I've got mysql and mysqli.</p>
<p>Is there someone with some clues about the possible reason? Thank you.</p>
<p><strong>Edit 1</strong></p>
<p>I tried to run the query also with <a href="https://codex.wordpress.org/Class_Reference/wpdb#UPDATE_rows" rel="nofollow">the <code>update</code> method</a>, but the result is always 0 rows affected. I start thinking that I found an incoherency in the $wpdb abstraction layer.</p>
|
[
{
"answer_id": 192284,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 1,
"selected": false,
"text": "<p><code>wpdb</code> <a href=\"https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/wp-db.php#L1686\" rel=\"nofollow\">uses PHP's <code>mysqli_affected_rows()</code> or <code>mysql_affected_rows()</code></a>, which can be disabled <a href=\"http://php.net/manual/en/ini.core.php#ini.disable-functions\" rel=\"nofollow\">via an argument in <code>php.ini</code></a>. I am guessing that that is what has happened. Check the <code>disabled_functions</code> line in your <code>php.ini</code> file and remove the references to those function.</p>\n\n<p>Of the top of my head, I am not sure if extensions like Suhosin mess with that function but that is certainly possible.</p>\n"
},
{
"answer_id": 257711,
"author": "Harm",
"author_id": 114058,
"author_profile": "https://wordpress.stackexchange.com/users/114058",
"pm_score": 0,
"selected": false,
"text": "<p>I hope may answer is still useful.\nI have had the same problem with 3 servers and a bit of php script in a WP page to read/write to the WP db. One server worked perfectly, the other two would always return 0 on wpdb->update. Truly indicating no changes were made to the db, although inspecting the db showed the changes were indeed made. As it turned out, the affected pages were run twice due to a AJAX interference caused by Yoast SEO. The resulting html only showed the latest result however. Turning Yoast SEO off solved the problem and as it turned out the not affected server had Yoast SEO turned off to start with. In my case is was Yoast, but any AJAX interaction can cause the problem you so thoroughly described.</p>\n"
}
] |
2015/06/22
|
[
"https://wordpress.stackexchange.com/questions/192275",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/69734/"
] |
I'm experiencing an odd situation while running an UPDATE with `$wpdb->query()`.
Given the `users` table, with columns `user_id` (Primary Key) and `status`, and the user 3 existing and with status 0, I run the following query:
```
update users
set status = 8
where user_id = 3
```
On my machine, running the query with `$wpdb->query`, I get the result of 1: 1 row affected.
On another machine I run the query with the PHP code and always get 0 rows: before running the query I checked the status and it was 0, and if I run it with another tool (e.g. command line mysql client), it says me that is 1 affected row.
The query method of wpdb returns the number of affected rows in case of update (<https://codex.wordpress.org/Class_Reference/wpdb#Running_General_Queries>).
My machine and the remote one have got the same PHP version (5.4.40), same mysql server version, and same wordpress version (4.2.2). About the mysql PHP extensions, in local I've installed mysql, mysqli and mysqlnd: on the other machine I've got mysql and mysqli.
Is there someone with some clues about the possible reason? Thank you.
**Edit 1**
I tried to run the query also with [the `update` method](https://codex.wordpress.org/Class_Reference/wpdb#UPDATE_rows), but the result is always 0 rows affected. I start thinking that I found an incoherency in the $wpdb abstraction layer.
|
`wpdb` [uses PHP's `mysqli_affected_rows()` or `mysql_affected_rows()`](https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/wp-db.php#L1686), which can be disabled [via an argument in `php.ini`](http://php.net/manual/en/ini.core.php#ini.disable-functions). I am guessing that that is what has happened. Check the `disabled_functions` line in your `php.ini` file and remove the references to those function.
Of the top of my head, I am not sure if extensions like Suhosin mess with that function but that is certainly possible.
|
192,340 |
<p>Hi i would like to add a custom text in order confirmation email template . Currently i am not using woo commerce tax option, But i would like to mention my product has 25 % including vat in email template . That custom text need to show only in order confirmation email template near Order total : Total: 348.00 DKK ( Including tax 25% ) .</p>
|
[
{
"answer_id": 192351,
"author": "Anam Shah",
"author_id": 75030,
"author_profile": "https://wordpress.stackexchange.com/users/75030",
"pm_score": 0,
"selected": false,
"text": "<p>Go to your child theme folder.</p>\n\n<p>Find woccomerce > emails</p>\n\n<p>from here you can edit your email template.</p>\n\n<p>Refer <a href=\"http://docs.woothemes.com/document/template-structure/\" rel=\"nofollow\">this link</a> this will might be helpful</p>\n"
},
{
"answer_id": 293860,
"author": "Abhay Yadav",
"author_id": 136553,
"author_profile": "https://wordpress.stackexchange.com/users/136553",
"pm_score": 1,
"selected": false,
"text": "<p>You can add custom text or html using this action.</p>\n\n<pre><code>add_action( 'woocommerce_email_after_order_table', 'add_order_email_instructions', 10, 2 );\n\n function add_order_email_instructions( $order, $sent_to_admin ) {\n if ( ! $sent_to_admin ) {\n echo 'Custom HTml OR Custom Text';\n }\n}\n</code></pre>\n"
}
] |
2015/06/23
|
[
"https://wordpress.stackexchange.com/questions/192340",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74812/"
] |
Hi i would like to add a custom text in order confirmation email template . Currently i am not using woo commerce tax option, But i would like to mention my product has 25 % including vat in email template . That custom text need to show only in order confirmation email template near Order total : Total: 348.00 DKK ( Including tax 25% ) .
|
You can add custom text or html using this action.
```
add_action( 'woocommerce_email_after_order_table', 'add_order_email_instructions', 10, 2 );
function add_order_email_instructions( $order, $sent_to_admin ) {
if ( ! $sent_to_admin ) {
echo 'Custom HTml OR Custom Text';
}
}
```
|
192,341 |
<p>I want to add javascript to page footer if the shortcode is used into the page content.</p>
<pre><code>add_shortcode('show-popup', 'show_aip_popup');
function show_aip_popup($args){
// HTML Comes here for popup
}
</code></pre>
|
[
{
"answer_id": 192345,
"author": "Mitul",
"author_id": 74728,
"author_profile": "https://wordpress.stackexchange.com/users/74728",
"pm_score": 1,
"selected": false,
"text": "<p>Thank you for your help </p>\n\n<p>I have do some googling and finally i got the ans i have added just 1 line of code into the shortcode function and i got the ans.</p>\n\n<p>I have added bellow line into the shortcode function .</p>\n\n<pre><code>wp_enqueue_script( 'parent-stylesheet', '[js URL]' . $postId, false );\n</code></pre>\n"
},
{
"answer_id": 192346,
"author": "Anam Shah",
"author_id": 75030,
"author_profile": "https://wordpress.stackexchange.com/users/75030",
"pm_score": -1,
"selected": true,
"text": "<p>Please try this one</p>\n\n<pre><code>function show_aip_popup($args){\n wp_enqueue_script( 'parent-stylesheet', 'javascript file', false );\n //your code for show shortcode data\n}\n</code></pre>\n"
}
] |
2015/06/23
|
[
"https://wordpress.stackexchange.com/questions/192341",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74728/"
] |
I want to add javascript to page footer if the shortcode is used into the page content.
```
add_shortcode('show-popup', 'show_aip_popup');
function show_aip_popup($args){
// HTML Comes here for popup
}
```
|
Please try this one
```
function show_aip_popup($args){
wp_enqueue_script( 'parent-stylesheet', 'javascript file', false );
//your code for show shortcode data
}
```
|
192,344 |
<p>I am using "front-end-only-users" plugin for user registration and log in system. Now how i check that my front end user is log in or not through coding i use 'is_user_logged_in()' but it checking the admin panel user.</p>
|
[
{
"answer_id": 192347,
"author": "Anam Shah",
"author_id": 75030,
"author_profile": "https://wordpress.stackexchange.com/users/75030",
"pm_score": 1,
"selected": false,
"text": "<p>Hope this will helful to you</p>\n\n<pre><code>global $current_user; // Use global\nget_currentuserinfo(); // Make sure global is set, if not set it.\nif ( user_can( $current_user, \"subscriber\" ) ) \n echo 'User is a Subscriber';\nelse\n echo 'User is not a Subscriber';\n</code></pre>\n"
},
{
"answer_id": 192348,
"author": "Mitul",
"author_id": 74728,
"author_profile": "https://wordpress.stackexchange.com/users/74728",
"pm_score": 1,
"selected": false,
"text": "<p>The CheckLoginCookie() function will help you to get the current login username </p>\n\n<p>you can get the username by using bellow code</p>\n\n<pre><code>$UserCookie = CheckLoginCookie();\n$username = $UserCookie['Username'];\nif($username){\n // User Login\n}else{\n // User Not login\n}\n</code></pre>\n"
},
{
"answer_id": 192353,
"author": "Anand",
"author_id": 73187,
"author_profile": "https://wordpress.stackexchange.com/users/73187",
"pm_score": 2,
"selected": false,
"text": "<p>write this code in front page to check user is login or not:</p>\n\n<pre><code> if ( is_user_logged_in() ) { ... } \n</code></pre>\n"
}
] |
2015/06/23
|
[
"https://wordpress.stackexchange.com/questions/192344",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74808/"
] |
I am using "front-end-only-users" plugin for user registration and log in system. Now how i check that my front end user is log in or not through coding i use 'is\_user\_logged\_in()' but it checking the admin panel user.
|
write this code in front page to check user is login or not:
```
if ( is_user_logged_in() ) { ... }
```
|
192,349 |
<p>I have five categories for a custom post type, additionally I have installed a plugin to enable upload image to each category detail, actually I can get show list of categories with details. I need to show a list like the follow structure:</p>
<p>Image Category<br />
Category Name One<br />
This is the category description for category one</p>
<p>Image Category<br />
Category Name two<br />
This is the category description for category one</p>
<p>This is my acual code:</p>
<pre><code>$customPostTaxonomies = get_object_taxonomies('products');
if(count($customPostTaxonomies) > 0)
{
foreach($customPostTaxonomies as $tax)
{
$args = array(
'orderby' => 'name',
'show_count' => 0,
'pad_counts' => 0,
'hierarchical' => 1,
'taxonomy' => $tax,
'title_li' => '',
'hide_empty' => 0
);
wp_list_categories( $args );
}
}
</code></pre>
<p>With this code I only archive print list of categories in bullet but without any detail.</p>
|
[
{
"answer_id": 192347,
"author": "Anam Shah",
"author_id": 75030,
"author_profile": "https://wordpress.stackexchange.com/users/75030",
"pm_score": 1,
"selected": false,
"text": "<p>Hope this will helful to you</p>\n\n<pre><code>global $current_user; // Use global\nget_currentuserinfo(); // Make sure global is set, if not set it.\nif ( user_can( $current_user, \"subscriber\" ) ) \n echo 'User is a Subscriber';\nelse\n echo 'User is not a Subscriber';\n</code></pre>\n"
},
{
"answer_id": 192348,
"author": "Mitul",
"author_id": 74728,
"author_profile": "https://wordpress.stackexchange.com/users/74728",
"pm_score": 1,
"selected": false,
"text": "<p>The CheckLoginCookie() function will help you to get the current login username </p>\n\n<p>you can get the username by using bellow code</p>\n\n<pre><code>$UserCookie = CheckLoginCookie();\n$username = $UserCookie['Username'];\nif($username){\n // User Login\n}else{\n // User Not login\n}\n</code></pre>\n"
},
{
"answer_id": 192353,
"author": "Anand",
"author_id": 73187,
"author_profile": "https://wordpress.stackexchange.com/users/73187",
"pm_score": 2,
"selected": false,
"text": "<p>write this code in front page to check user is login or not:</p>\n\n<pre><code> if ( is_user_logged_in() ) { ... } \n</code></pre>\n"
}
] |
2015/06/23
|
[
"https://wordpress.stackexchange.com/questions/192349",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75093/"
] |
I have five categories for a custom post type, additionally I have installed a plugin to enable upload image to each category detail, actually I can get show list of categories with details. I need to show a list like the follow structure:
Image Category
Category Name One
This is the category description for category one
Image Category
Category Name two
This is the category description for category one
This is my acual code:
```
$customPostTaxonomies = get_object_taxonomies('products');
if(count($customPostTaxonomies) > 0)
{
foreach($customPostTaxonomies as $tax)
{
$args = array(
'orderby' => 'name',
'show_count' => 0,
'pad_counts' => 0,
'hierarchical' => 1,
'taxonomy' => $tax,
'title_li' => '',
'hide_empty' => 0
);
wp_list_categories( $args );
}
}
```
With this code I only archive print list of categories in bullet but without any detail.
|
write this code in front page to check user is login or not:
```
if ( is_user_logged_in() ) { ... }
```
|
192,360 |
<p>I have a custom post type named <code>project</code> which has</p>
<pre><code>'capability_type' => 'post'
</code></pre>
<p>while registering using <code>register_post_type</code>.</p>
<p>In my theme files and also <code>functions.php</code> file, I have situations where I should check if the project to be edited is authored by the user or not.</p>
<p>So I use this:</p>
<pre><code>if ( !current_user_can( 'edit_post', $porject_id ) ) return;
</code></pre>
<p>where <code>$project_id</code> is post id of the project to be edited.</p>
<p>For example I have a page template named <code>single_project.php</code> where I can show single posts in project post type to users and I want these people can see each project single page:</p>
<ol>
<li>administrators</li>
<li>editors</li>
<li>the contributor (post author)</li>
</ol>
<p>but using the above code, It is ok with administrators and editors, while not for the contributor himself!</p>
<p>When I use:</p>
<pre class="lang-php prettyprint-override"><code>var_dump( current_user_can( 'edit_post', $project_id ) );
</code></pre>
<p>with the contributor logged-in account, it returns <code>false</code>, while this:</p>
<pre class="lang-php prettyprint-override"><code>var_dump( current_user_can( 'edit_posts' ) ); // (with trailing 's')
</code></pre>
<p>returns <code>true</code> (but for every post, not just does for him).</p>
<p>Any help with this?</p>
|
[
{
"answer_id": 193106,
"author": "Peyman Mohamadpour",
"author_id": 75020,
"author_profile": "https://wordpress.stackexchange.com/users/75020",
"pm_score": 3,
"selected": true,
"text": "<p>using <code>map_meta_cap</code> I added <code>edit_post</code> per post cap to user</p>\n\n<pre><code>function my_map_meta_cap( $caps, $cap, $user_id, $args ){\n if ( 'edit_post' == $cap ) {\n $post = get_post( $args[0] );\n $post_type = get_post_type_object( $post->post_type );\n $caps = array();\n if ( $user_id == $post->post_author )\n $caps[] = $post_type->cap->edit_posts;\n else\n $caps[] = $post_type->cap->edit_others_posts;\n }\n return $caps;\n}\nadd_filter( 'map_meta_cap', 'my_map_meta_cap', 10, 4 );\n</code></pre>\n"
},
{
"answer_id": 382390,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>This is a very late answer, but the accepted answer is incorrect, and I've seen other users referring to it, so I'm submitting the correct answer.</p>\n<p>The reason the Contributor user was seeing <code>false</code> for <code>edit_post</code> is that Contributors cannot edit posts that have already been published. Only roles with <code>edit_published_posts</code> can do that.</p>\n<p>In the original question, the author says:</p>\n<blockquote>\n<p>I have situations where I should check if the project to be edited is authored by the user or not.</p>\n</blockquote>\n<p>That is <em>not</em> the same as whether or not a user can edit a post, which is what their code is actually checking. If you want to check whether the author of a post is a particular user, then that's what should be compared:</p>\n<pre><code>if ( get_current_user_id() === get_post_field( 'post_author', $project_id ) ) {\n // etc.\n}\n</code></pre>\n"
}
] |
2015/06/23
|
[
"https://wordpress.stackexchange.com/questions/192360",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75020/"
] |
I have a custom post type named `project` which has
```
'capability_type' => 'post'
```
while registering using `register_post_type`.
In my theme files and also `functions.php` file, I have situations where I should check if the project to be edited is authored by the user or not.
So I use this:
```
if ( !current_user_can( 'edit_post', $porject_id ) ) return;
```
where `$project_id` is post id of the project to be edited.
For example I have a page template named `single_project.php` where I can show single posts in project post type to users and I want these people can see each project single page:
1. administrators
2. editors
3. the contributor (post author)
but using the above code, It is ok with administrators and editors, while not for the contributor himself!
When I use:
```php
var_dump( current_user_can( 'edit_post', $project_id ) );
```
with the contributor logged-in account, it returns `false`, while this:
```php
var_dump( current_user_can( 'edit_posts' ) ); // (with trailing 's')
```
returns `true` (but for every post, not just does for him).
Any help with this?
|
using `map_meta_cap` I added `edit_post` per post cap to user
```
function my_map_meta_cap( $caps, $cap, $user_id, $args ){
if ( 'edit_post' == $cap ) {
$post = get_post( $args[0] );
$post_type = get_post_type_object( $post->post_type );
$caps = array();
if ( $user_id == $post->post_author )
$caps[] = $post_type->cap->edit_posts;
else
$caps[] = $post_type->cap->edit_others_posts;
}
return $caps;
}
add_filter( 'map_meta_cap', 'my_map_meta_cap', 10, 4 );
```
|
192,412 |
<p>I have two custom fields:</p>
<ul>
<li><code>meta_key1</code> is boolean (<code>0</code> or <code>1</code>). </li>
<li><code>meta_key2</code> is a date value - <code>20150623</code> for example.</li>
</ul>
<p>Not all <code>meta_key2</code> fields have an explicit value. It looks like their being treated as an empty string <code>''</code>. </p>
<p>I'd like to find all posts that have a <code>meta_key2</code> (date) value that is greater than today or have a <code>meta_key1</code> value that is true.</p>
<p>This is the order I'd like them to display.</p>
<blockquote>
<ol>
<li><code>key2.meta_value >= today ASC</code></li>
<li><code>key1.meta_value = TRUE ordered by date ASC</code> (those with dates given first).</li>
</ol>
</blockquote>
<p>Part of the issue is that fields with an empty date parameter appear to be treated as <code>0</code> and thus come first in <code>ASC</code> order. I've attempted to use <code>COALESCE</code> to account for this and have had some success but I'm hung up on one part. I can't get the posts that <code>key1.meta_value = FALSE</code> and <code>key2.meta_value is >= today</code> to display in <code>ASC</code> order.</p>
<p>Here's my query:</p>
<pre><code>$meta_key1 = 'prog_ongoing';
$meta_key2 = 'prog_date_start';
$start_date = date('Ymd');
$postids = $wpdb->get_col( $wpdb->prepare(
"
SELECT DISTINCT key1.post_id
FROM $wpdb->postmeta key1
INNER JOIN $wpdb->postmeta key2
ON key2.post_id = key1.post_id
AND key2.meta_key = %s
WHERE key1.meta_key = %s
AND key1.meta_value is TRUE
OR key2.meta_value >= %d
ORDER BY COALESCE(NULLIF(key1.meta_value, 0), 0) DESC, COALESCE(NULLIF(key2.meta_value, ''), $start_date) ASC, key2.meta_value ASC
",
$meta_key2,
$meta_key1,
$start_date
) );
</code></pre>
<p>I'm not sure my <code>COALESCE</code> statement on <code>key1.meta_value</code> is doing anything. Thanks for any insight on this.</p>
|
[
{
"answer_id": 192417,
"author": "passatgt",
"author_id": 8038,
"author_profile": "https://wordpress.stackexchange.com/users/8038",
"pm_score": 0,
"selected": false,
"text": "<p>Why not use <code>WP_Query()</code>? Lot simpler this way:</p>\n\n<pre><code> <?php\n $args = array(\n 'posts_per_page' => -1,\n 'meta_query' => array(\n 'relation' => 'OR',\n array(\n 'key' => 'prog_ongoing',\n 'value' => 1\n ),\n array(\n 'relation' => 'AND',\n array(\n 'key' => 'prog_date_start',\n 'value' => date('Ymd'),\n 'type' => 'numeric',\n 'compare' => '<='\n ),\n array(\n 'key' => 'prog_date_start',\n 'value' => 1,\n 'type' => 'numeric',\n 'compare' => '>'\n )\n )\n ),\n 'orderby' => 'meta_value_num date',\n 'order' => 'ASC',\n 'meta_key' => 'prog_date_start'\n );\n\n $programs = new WP_Query($args);\n ?>\n <?php while($programs->have_posts()): $programs->the_post(); ?>\n <h1><?php the_title(); ?></h1>\n <?php endwhile; ?>\n</code></pre>\n"
},
{
"answer_id": 192456,
"author": "Manny Fleurmond",
"author_id": 2234,
"author_profile": "https://wordpress.stackexchange.com/users/2234",
"pm_score": 2,
"selected": false,
"text": "<p>First pass for a solution. It uses the new meta sorting that was introduced in 4.2: </p>\n\n<pre><code> <?php\n $args = array(\n 'posts_per_page' => -1,\n 'meta_query' => array(\n 'relation' => 'OR',\n 'ongoing' => array(\n 'key' => 'prog_ongoing',\n 'value' => 1\n ),\n 'start_date' => array(\n array(\n 'key' => 'prog_date_start',\n 'value' => date('Ymd'),\n 'type' => 'numeric',\n 'compare' => '>='\n )\n )\n ),\n 'orderby' => 'start_date ongoing',\n 'order' => 'ASC',\n );\n\n $programs = new WP_Query($args);\n ?>\n <?php while($programs->have_posts()): $programs->the_post(); ?>\n <h1><?php the_title(); ?></h1>\n <?php endwhile; ?>\n</code></pre>\n\n<p>I think I got the logic right, but let me know if otherwise</p>\n\n<h2>EDIT</h2>\n\n<p>You can check out the new syntax to sort by multiple custom fields in Wordpress 4.2 in the following make</p>\n\n<ul>\n<li><a href=\"https://make.wordpress.org/core/2015/03/30/query-improvements-in-wp-4-2-orderby-and-meta_query/\" rel=\"nofollow\">Query improvements in WP 4.2 orderby and meta query</a></li>\n</ul>\n"
},
{
"answer_id": 192512,
"author": "bonger",
"author_id": 57034,
"author_profile": "https://wordpress.stackexchange.com/users/57034",
"pm_score": 3,
"selected": true,
"text": "<p>One problem with the query is that the self-join with the ambiguous <code>WHERE</code> gives you a crossed dataset (which is masked by the <code>DISTINCT</code>), so it would be simpler to use <code>wp_post</code> as a base to attach the joins that precisely match the keys, eg</p>\n\n<pre><code> SELECT p.ID, key1.meta_value as prog_ongoing, key2.meta_value as prog_date_start\n FROM $wpdb->posts p\n INNER JOIN $wpdb->postmeta key1\n ON key1.post_id = p.ID\n AND key1.meta_key = %s\n INNER JOIN $wpdb->postmeta key2\n ON key2.post_id = p.ID\n AND key2.meta_key = %s\n</code></pre>\n\n<p>which gives a linear dataset. Then you could add (or not) the <code>WHERE</code> clause to restrict the data:</p>\n\n<pre><code> WHERE key1.meta_value IS TRUE OR key2.meta_value >= %d\n</code></pre>\n\n<p>and for the <code>ORDER BY</code> use a <code>CASE</code> statement single field sort:</p>\n\n<pre><code> ORDER BY CASE\n WHEN key2.meta_value >= %d THEN CONCAT('A', key2.meta_value)\n WHEN key1.meta_value AND key2.meta_value THEN CONCAT('B', key2.meta_value)\n WHEN key1.meta_value THEN 'C'\n ELSE 'D'\n END ASC\n</code></pre>\n\n<p>or something similar, the above needing the <code>prepare</code> args to be:</p>\n\n<pre><code> $meta_key1,\n $meta_key2,\n $start_date, $start_date\n</code></pre>\n\n<p>You could use the <code>posts_orderby</code> filter to do something similar using <code>WP_Query</code> (although it uses a method that produces crossed datasets, requiring it to have to use a <code>GROUP BY</code>, which can complicate things). For instance</p>\n\n<pre><code>$args = array(\n 'posts_per_page' => -1,\n 'post_type' => 'cpt_program',\n 'meta_query' => array(\n 'ongoing' => array(\n 'key' => 'prog_ongoing',\n ),\n 'start_date' => array(\n 'key' => 'prog_date_start',\n )\n ),\n);\n\nadd_filter( 'posts_orderby', $func = function ( $orderby, $query ) {\n $start_date = date('Ymd');\n global $wpdb;\n $orderby = $wpdb->prepare(\n \"\n CASE\n WHEN mt1.meta_value >= %d THEN CONCAT('A', mt1.meta_value)\n WHEN {$wpdb->postmeta}.meta_value AND mt1.meta_value THEN CONCAT('B', mt1.meta_value)\n WHEN {$wpdb->postmeta}.meta_value THEN 'C'\n ELSE 'D'\n END ASC\n \"\n , $start_date\n );\n return $orderby;\n}, 10, 2 );\n$query = new WP_Query( $args );\nremove_filter( 'posts_orderby', $func, 10, 2 );\n</code></pre>\n"
}
] |
2015/06/23
|
[
"https://wordpress.stackexchange.com/questions/192412",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/65669/"
] |
I have two custom fields:
* `meta_key1` is boolean (`0` or `1`).
* `meta_key2` is a date value - `20150623` for example.
Not all `meta_key2` fields have an explicit value. It looks like their being treated as an empty string `''`.
I'd like to find all posts that have a `meta_key2` (date) value that is greater than today or have a `meta_key1` value that is true.
This is the order I'd like them to display.
>
> 1. `key2.meta_value >= today ASC`
> 2. `key1.meta_value = TRUE ordered by date ASC` (those with dates given first).
>
>
>
Part of the issue is that fields with an empty date parameter appear to be treated as `0` and thus come first in `ASC` order. I've attempted to use `COALESCE` to account for this and have had some success but I'm hung up on one part. I can't get the posts that `key1.meta_value = FALSE` and `key2.meta_value is >= today` to display in `ASC` order.
Here's my query:
```
$meta_key1 = 'prog_ongoing';
$meta_key2 = 'prog_date_start';
$start_date = date('Ymd');
$postids = $wpdb->get_col( $wpdb->prepare(
"
SELECT DISTINCT key1.post_id
FROM $wpdb->postmeta key1
INNER JOIN $wpdb->postmeta key2
ON key2.post_id = key1.post_id
AND key2.meta_key = %s
WHERE key1.meta_key = %s
AND key1.meta_value is TRUE
OR key2.meta_value >= %d
ORDER BY COALESCE(NULLIF(key1.meta_value, 0), 0) DESC, COALESCE(NULLIF(key2.meta_value, ''), $start_date) ASC, key2.meta_value ASC
",
$meta_key2,
$meta_key1,
$start_date
) );
```
I'm not sure my `COALESCE` statement on `key1.meta_value` is doing anything. Thanks for any insight on this.
|
One problem with the query is that the self-join with the ambiguous `WHERE` gives you a crossed dataset (which is masked by the `DISTINCT`), so it would be simpler to use `wp_post` as a base to attach the joins that precisely match the keys, eg
```
SELECT p.ID, key1.meta_value as prog_ongoing, key2.meta_value as prog_date_start
FROM $wpdb->posts p
INNER JOIN $wpdb->postmeta key1
ON key1.post_id = p.ID
AND key1.meta_key = %s
INNER JOIN $wpdb->postmeta key2
ON key2.post_id = p.ID
AND key2.meta_key = %s
```
which gives a linear dataset. Then you could add (or not) the `WHERE` clause to restrict the data:
```
WHERE key1.meta_value IS TRUE OR key2.meta_value >= %d
```
and for the `ORDER BY` use a `CASE` statement single field sort:
```
ORDER BY CASE
WHEN key2.meta_value >= %d THEN CONCAT('A', key2.meta_value)
WHEN key1.meta_value AND key2.meta_value THEN CONCAT('B', key2.meta_value)
WHEN key1.meta_value THEN 'C'
ELSE 'D'
END ASC
```
or something similar, the above needing the `prepare` args to be:
```
$meta_key1,
$meta_key2,
$start_date, $start_date
```
You could use the `posts_orderby` filter to do something similar using `WP_Query` (although it uses a method that produces crossed datasets, requiring it to have to use a `GROUP BY`, which can complicate things). For instance
```
$args = array(
'posts_per_page' => -1,
'post_type' => 'cpt_program',
'meta_query' => array(
'ongoing' => array(
'key' => 'prog_ongoing',
),
'start_date' => array(
'key' => 'prog_date_start',
)
),
);
add_filter( 'posts_orderby', $func = function ( $orderby, $query ) {
$start_date = date('Ymd');
global $wpdb;
$orderby = $wpdb->prepare(
"
CASE
WHEN mt1.meta_value >= %d THEN CONCAT('A', mt1.meta_value)
WHEN {$wpdb->postmeta}.meta_value AND mt1.meta_value THEN CONCAT('B', mt1.meta_value)
WHEN {$wpdb->postmeta}.meta_value THEN 'C'
ELSE 'D'
END ASC
"
, $start_date
);
return $orderby;
}, 10, 2 );
$query = new WP_Query( $args );
remove_filter( 'posts_orderby', $func, 10, 2 );
```
|
192,414 |
<pre>
$sidebars = array(
is_active_sidebar( 'footer-4' ),
is_active_sidebar( 'footer-3' ),
is_active_sidebar( 'footer-2' ),
is_active_sidebar( 'footer-1' ),
);
$col = 0;
foreach ( $sidebars as $sidebar ) {
if ( $sidebar ) {
$col++;
}
}
echo 'col-'.$col.'';
</pre>
<p>What i am trying to accomplish is have the correct number of WordPress active sidebars outputted. So that they can be styled with css example: if 3 sidebars are active you get col-3 if (1) if you col-1.</p>
<p>The code above works. My concern is can it be improved, is this the right way to do it ? Or can increments be used for example: $i = 0; $i++; instead of an array.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 192415,
"author": "passatgt",
"author_id": 8038,
"author_profile": "https://wordpress.stackexchange.com/users/8038",
"pm_score": 1,
"selected": false,
"text": "<p>Use the <code>array_filter()</code> function, which will remove every array element that has false as the value. Then you can count the array length. So your example would look like this: </p>\n\n<pre><code>$sidebars = array(\n is_active_sidebar( 'footer-4' ),\n is_active_sidebar( 'footer-3' ),\n is_active_sidebar( 'footer-2' ),\n is_active_sidebar( 'footer-1' ),\n);\n\n$active_sidebars = array_filter($sidebars);\n\necho 'col-'.count($active_sidebars);\n</code></pre>\n"
},
{
"answer_id": 192416,
"author": "James Barrett",
"author_id": 74733,
"author_profile": "https://wordpress.stackexchange.com/users/74733",
"pm_score": 0,
"selected": false,
"text": "<p>From the Wordpress Codex: is_active_sidebar()</p>\n\n<blockquote>\n <p>This Conditional Tag checks if a given sidebar is active (in use).\n This is a boolean function, meaning it returns either TRUE or FALSE.</p>\n \n <p>Any sidebar that contains widgets will return TRUE, whereas any\n sidebar that does not contain any widgets will return FALSE.</p>\n</blockquote>\n\n<p>So you should be able to do something like this:</p>\n\n<pre><code>$col = 0;\n\nif( is_active_sidebar( 'footer-4' ) ) $col++;\nif( is_active_sidebar( 'footer-3' ) ) $col++;\nif( is_active_sidebar( 'footer-2' ) ) $col++;\nif( is_active_sidebar( 'footer-1' ) ) $col++;\n\necho 'col-'.$col;\n</code></pre>\n\n<p>Or maybe even:</p>\n\n<pre><code>$col = 0;\n\nfor ($i = 1; $i <= 4; $i++) {\n if( is_active_sidebar( 'footer-'.$i ) ) $col++;\n}\n\necho 'col-'.$col;\n</code></pre>\n\n<p><strong>NOTE:</strong> I've not had time to test either of these methods.</p>\n"
}
] |
2015/06/23
|
[
"https://wordpress.stackexchange.com/questions/192414",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70695/"
] |
```
$sidebars = array(
is_active_sidebar( 'footer-4' ),
is_active_sidebar( 'footer-3' ),
is_active_sidebar( 'footer-2' ),
is_active_sidebar( 'footer-1' ),
);
$col = 0;
foreach ( $sidebars as $sidebar ) {
if ( $sidebar ) {
$col++;
}
}
echo 'col-'.$col.'';
```
What i am trying to accomplish is have the correct number of WordPress active sidebars outputted. So that they can be styled with css example: if 3 sidebars are active you get col-3 if (1) if you col-1.
The code above works. My concern is can it be improved, is this the right way to do it ? Or can increments be used for example: $i = 0; $i++; instead of an array.
Thanks.
|
Use the `array_filter()` function, which will remove every array element that has false as the value. Then you can count the array length. So your example would look like this:
```
$sidebars = array(
is_active_sidebar( 'footer-4' ),
is_active_sidebar( 'footer-3' ),
is_active_sidebar( 'footer-2' ),
is_active_sidebar( 'footer-1' ),
);
$active_sidebars = array_filter($sidebars);
echo 'col-'.count($active_sidebars);
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.