qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
sequence | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
360,410 | <p>If I try to upgrade to PHP 7 or up (from 5.6), I have one site that is throwing a PHP error. </p>
<p>I have tried uninstalling all plugins and activating the Twenty Twenty theme before changing PHP version. No dice.</p>
<p>Is there a setting in the database or core that would be effecting this? I also tried a default .htaccess file.</p>
<p>EDIT: WP debug.log says:</p>
<pre><code>[10-Mar-2020 23:35:45 UTC] PHP Fatal error: Allowed memory size of 2097152 bytes exhausted (tried to allocate 32768 bytes) in /path/public_html/wp-includes/formatting.php on line 1600
[10-Mar-2020 23:35:45 UTC] PHP Fatal error: Allowed memory size of 2097152 bytes exhausted (tried to allocate 32768 bytes) in /path/public_html/wp-includes/version.php on line 1
</code></pre>
<p>But this seems unrelated, right? The site is having i/o issues as well.</p>
| [
{
"answer_id": 360414,
"author": "ngearing",
"author_id": 50184,
"author_profile": "https://wordpress.stackexchange.com/users/50184",
"pm_score": 2,
"selected": true,
"text": "<p>Gutenberg blocks are not stored in the Wordpress files in a readable or debuggable format. Instead, they have their own separate git repos.</p>\n\n<p>Here is the source for the Latest Posts Block:\n<a href=\"https://github.com/WordPress/gutenberg/tree/master/packages/block-library/src/latest-posts\" rel=\"nofollow noreferrer\">https://github.com/WordPress/gutenberg/tree/master/packages/block-library/src/latest-posts</a></p>\n"
},
{
"answer_id": 360936,
"author": "Trisha",
"author_id": 56458,
"author_profile": "https://wordpress.stackexchange.com/users/56458",
"pm_score": 0,
"selected": false,
"text": "<p>Something you might try, I found this solution years ago and it's worked well - it does more than just allow overriding the number of words limitation, it also allows for some basic styles so that if your excerpt contains bolded words those will show in the excerpt. </p>\n\n<pre><code>// Improves the look of the excerpt, more words, allows bolding\n\nfunction improved_trim_excerpt($text) {\n$raw_excerpt = $text;\n\n$excerpt_more = '&hellip;<a class=\"more-link\" href=\"'. esc_url( get_permalink() ) . '\" title=\"' . esc_html__( 'Continue reading', 'wp-answers' ) . ' &lsquo;' . get_the_title() . '&rsquo;\">' . wp_kses( __( 'Continue reading <span class=\"meta-nav\">&rarr;</span>', 'wp-answers' ), array( 'span' => array( \n 'class' => array() ) ) ) . '</a>'; \n\nif ( '' == $text ) {\n $text = get_the_content('');\n $text = strip_shortcodes( $text );\n $text = apply_filters('the_content', $text);\n $text = str_replace('\\]\\]\\>', ']]&gt;', $text);\n $text = strip_tags($text, '<b><strong><del><em>');\n $excerpt_length = apply_filters('excerpt_length', 55);//change 55 to whatever word limit you want\n $newexcerpt_more = apply_filters('excerpt_more', ' ' . $excerpt_more);\n $words = preg_split(\"/[\\n\\r\\t ]+/\", $text, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY);\n if ( count($words) > $excerpt_length ) {\n array_pop($words);\n $text = implode(' ', $words);\n $text = $text . $newexcerpt_more;\n $text = force_balance_tags( $text );\n } else {\n $text = implode(' ', $words);\n $text = force_balance_tags( $text );\n }\n}\nreturn $text;\n}\nremove_filter('get_the_excerpt', 'wp_trim_excerpt');\nadd_filter('get_the_excerpt', 'improved_trim_excerpt');\n</code></pre>\n\n<p>This would go in your (hopefully child) theme's functions.php file or a custom plugin file.....</p>\n"
}
] | 2020/03/10 | [
"https://wordpress.stackexchange.com/questions/360410",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/117675/"
] | If I try to upgrade to PHP 7 or up (from 5.6), I have one site that is throwing a PHP error.
I have tried uninstalling all plugins and activating the Twenty Twenty theme before changing PHP version. No dice.
Is there a setting in the database or core that would be effecting this? I also tried a default .htaccess file.
EDIT: WP debug.log says:
```
[10-Mar-2020 23:35:45 UTC] PHP Fatal error: Allowed memory size of 2097152 bytes exhausted (tried to allocate 32768 bytes) in /path/public_html/wp-includes/formatting.php on line 1600
[10-Mar-2020 23:35:45 UTC] PHP Fatal error: Allowed memory size of 2097152 bytes exhausted (tried to allocate 32768 bytes) in /path/public_html/wp-includes/version.php on line 1
```
But this seems unrelated, right? The site is having i/o issues as well. | Gutenberg blocks are not stored in the Wordpress files in a readable or debuggable format. Instead, they have their own separate git repos.
Here is the source for the Latest Posts Block:
<https://github.com/WordPress/gutenberg/tree/master/packages/block-library/src/latest-posts> |
360,428 | <p>I understand that the <code>auth_redirect()</code> checks if a user is logged in, if not it redirects them to the login page then come back to the previous page on success. I need that functionality on my website and I have that.</p>
<p>For example, I wanted one of the pages to access only by logged in users, if they tried to access the page then they need to login first then on success come back to that page. I have the following code on my <code>function.php</code>.</p>
<pre><code>if ( is_page('user_only') && ! is_user_logged_in() ) {
auth_redirect();
}
</code></pre>
<p>The problem is I have a custom login/registration page and instead of the default WordPress login page, I want the <code>auth_redirect();</code> to use my custom login/registration page. </p>
<p>The <code>auth_redirect();</code> is using the <code>wp-login.php</code> and I want to use my custom page <code>account/index.php</code>.
Can this be done? I know about <code>wp_redirect( url, );</code> but I don't need that since its purpose is for redirection only and not for authentication.</p>
| [
{
"answer_id": 360414,
"author": "ngearing",
"author_id": 50184,
"author_profile": "https://wordpress.stackexchange.com/users/50184",
"pm_score": 2,
"selected": true,
"text": "<p>Gutenberg blocks are not stored in the Wordpress files in a readable or debuggable format. Instead, they have their own separate git repos.</p>\n\n<p>Here is the source for the Latest Posts Block:\n<a href=\"https://github.com/WordPress/gutenberg/tree/master/packages/block-library/src/latest-posts\" rel=\"nofollow noreferrer\">https://github.com/WordPress/gutenberg/tree/master/packages/block-library/src/latest-posts</a></p>\n"
},
{
"answer_id": 360936,
"author": "Trisha",
"author_id": 56458,
"author_profile": "https://wordpress.stackexchange.com/users/56458",
"pm_score": 0,
"selected": false,
"text": "<p>Something you might try, I found this solution years ago and it's worked well - it does more than just allow overriding the number of words limitation, it also allows for some basic styles so that if your excerpt contains bolded words those will show in the excerpt. </p>\n\n<pre><code>// Improves the look of the excerpt, more words, allows bolding\n\nfunction improved_trim_excerpt($text) {\n$raw_excerpt = $text;\n\n$excerpt_more = '&hellip;<a class=\"more-link\" href=\"'. esc_url( get_permalink() ) . '\" title=\"' . esc_html__( 'Continue reading', 'wp-answers' ) . ' &lsquo;' . get_the_title() . '&rsquo;\">' . wp_kses( __( 'Continue reading <span class=\"meta-nav\">&rarr;</span>', 'wp-answers' ), array( 'span' => array( \n 'class' => array() ) ) ) . '</a>'; \n\nif ( '' == $text ) {\n $text = get_the_content('');\n $text = strip_shortcodes( $text );\n $text = apply_filters('the_content', $text);\n $text = str_replace('\\]\\]\\>', ']]&gt;', $text);\n $text = strip_tags($text, '<b><strong><del><em>');\n $excerpt_length = apply_filters('excerpt_length', 55);//change 55 to whatever word limit you want\n $newexcerpt_more = apply_filters('excerpt_more', ' ' . $excerpt_more);\n $words = preg_split(\"/[\\n\\r\\t ]+/\", $text, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY);\n if ( count($words) > $excerpt_length ) {\n array_pop($words);\n $text = implode(' ', $words);\n $text = $text . $newexcerpt_more;\n $text = force_balance_tags( $text );\n } else {\n $text = implode(' ', $words);\n $text = force_balance_tags( $text );\n }\n}\nreturn $text;\n}\nremove_filter('get_the_excerpt', 'wp_trim_excerpt');\nadd_filter('get_the_excerpt', 'improved_trim_excerpt');\n</code></pre>\n\n<p>This would go in your (hopefully child) theme's functions.php file or a custom plugin file.....</p>\n"
}
] | 2020/03/11 | [
"https://wordpress.stackexchange.com/questions/360428",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/192520/"
] | I understand that the `auth_redirect()` checks if a user is logged in, if not it redirects them to the login page then come back to the previous page on success. I need that functionality on my website and I have that.
For example, I wanted one of the pages to access only by logged in users, if they tried to access the page then they need to login first then on success come back to that page. I have the following code on my `function.php`.
```
if ( is_page('user_only') && ! is_user_logged_in() ) {
auth_redirect();
}
```
The problem is I have a custom login/registration page and instead of the default WordPress login page, I want the `auth_redirect();` to use my custom login/registration page.
The `auth_redirect();` is using the `wp-login.php` and I want to use my custom page `account/index.php`.
Can this be done? I know about `wp_redirect( url, );` but I don't need that since its purpose is for redirection only and not for authentication. | Gutenberg blocks are not stored in the Wordpress files in a readable or debuggable format. Instead, they have their own separate git repos.
Here is the source for the Latest Posts Block:
<https://github.com/WordPress/gutenberg/tree/master/packages/block-library/src/latest-posts> |
360,431 | <p>I am working on custom development in wordpress, my problem is the following every time I create a new template.</p>
<p><b>Code</b></p>
<pre><code> /* Template Name: Citas Rolex*/
get_header();
echo "<h1>loren ipsum</h1>";
get_footer();
</code></pre>
<p>It gives me the following error in the user view</p>
<p><strong>In browser</strong></p>
<blockquote>
<p>Internal Server Error<br>
The server encountered an internal error or misconfiguration and was unable to complete your request.<br>
Please contact the server administrator to inform of the time the error occurred and of anything you might have done that may have caused the error.</p>
<p>More information about this error may be available in the server error log.</p>
</blockquote>
<p>I miss that when I comment on <code>get_header ()</code> the view works perfectly for me</p>
<pre><code>/* Template Name: Citas Rolex*/
//get_header();
echo "<h1>loren ipsum</h1>";
get_footer();
?>
</code></pre>
| [
{
"answer_id": 360414,
"author": "ngearing",
"author_id": 50184,
"author_profile": "https://wordpress.stackexchange.com/users/50184",
"pm_score": 2,
"selected": true,
"text": "<p>Gutenberg blocks are not stored in the Wordpress files in a readable or debuggable format. Instead, they have their own separate git repos.</p>\n\n<p>Here is the source for the Latest Posts Block:\n<a href=\"https://github.com/WordPress/gutenberg/tree/master/packages/block-library/src/latest-posts\" rel=\"nofollow noreferrer\">https://github.com/WordPress/gutenberg/tree/master/packages/block-library/src/latest-posts</a></p>\n"
},
{
"answer_id": 360936,
"author": "Trisha",
"author_id": 56458,
"author_profile": "https://wordpress.stackexchange.com/users/56458",
"pm_score": 0,
"selected": false,
"text": "<p>Something you might try, I found this solution years ago and it's worked well - it does more than just allow overriding the number of words limitation, it also allows for some basic styles so that if your excerpt contains bolded words those will show in the excerpt. </p>\n\n<pre><code>// Improves the look of the excerpt, more words, allows bolding\n\nfunction improved_trim_excerpt($text) {\n$raw_excerpt = $text;\n\n$excerpt_more = '&hellip;<a class=\"more-link\" href=\"'. esc_url( get_permalink() ) . '\" title=\"' . esc_html__( 'Continue reading', 'wp-answers' ) . ' &lsquo;' . get_the_title() . '&rsquo;\">' . wp_kses( __( 'Continue reading <span class=\"meta-nav\">&rarr;</span>', 'wp-answers' ), array( 'span' => array( \n 'class' => array() ) ) ) . '</a>'; \n\nif ( '' == $text ) {\n $text = get_the_content('');\n $text = strip_shortcodes( $text );\n $text = apply_filters('the_content', $text);\n $text = str_replace('\\]\\]\\>', ']]&gt;', $text);\n $text = strip_tags($text, '<b><strong><del><em>');\n $excerpt_length = apply_filters('excerpt_length', 55);//change 55 to whatever word limit you want\n $newexcerpt_more = apply_filters('excerpt_more', ' ' . $excerpt_more);\n $words = preg_split(\"/[\\n\\r\\t ]+/\", $text, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY);\n if ( count($words) > $excerpt_length ) {\n array_pop($words);\n $text = implode(' ', $words);\n $text = $text . $newexcerpt_more;\n $text = force_balance_tags( $text );\n } else {\n $text = implode(' ', $words);\n $text = force_balance_tags( $text );\n }\n}\nreturn $text;\n}\nremove_filter('get_the_excerpt', 'wp_trim_excerpt');\nadd_filter('get_the_excerpt', 'improved_trim_excerpt');\n</code></pre>\n\n<p>This would go in your (hopefully child) theme's functions.php file or a custom plugin file.....</p>\n"
}
] | 2020/03/11 | [
"https://wordpress.stackexchange.com/questions/360431",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/182606/"
] | I am working on custom development in wordpress, my problem is the following every time I create a new template.
**Code**
```
/* Template Name: Citas Rolex*/
get_header();
echo "<h1>loren ipsum</h1>";
get_footer();
```
It gives me the following error in the user view
**In browser**
>
> Internal Server Error
>
> The server encountered an internal error or misconfiguration and was unable to complete your request.
>
> Please contact the server administrator to inform of the time the error occurred and of anything you might have done that may have caused the error.
>
>
> More information about this error may be available in the server error log.
>
>
>
I miss that when I comment on `get_header ()` the view works perfectly for me
```
/* Template Name: Citas Rolex*/
//get_header();
echo "<h1>loren ipsum</h1>";
get_footer();
?>
``` | Gutenberg blocks are not stored in the Wordpress files in a readable or debuggable format. Instead, they have their own separate git repos.
Here is the source for the Latest Posts Block:
<https://github.com/WordPress/gutenberg/tree/master/packages/block-library/src/latest-posts> |
360,441 | <p>I need to dublicate all existing routes with several language codes:</p>
<pre><code>/2020/03/11/Hello-world
/en/2020/03/11/Hello-world
/de/2020/03/11/Hello-world
/Hello-world-page
/en/Hello-world-page
/de/Hello-world-page
/...
/en/...
/de/...
</code></pre>
<p>Then I need to pre-handle all routes to check prefix exists and get as slug, then let related handlers do thier jobs.. I searched it many many times but never lucky to solve..</p>
<p>How to accomplish that? Thank you!</p>
| [
{
"answer_id": 360414,
"author": "ngearing",
"author_id": 50184,
"author_profile": "https://wordpress.stackexchange.com/users/50184",
"pm_score": 2,
"selected": true,
"text": "<p>Gutenberg blocks are not stored in the Wordpress files in a readable or debuggable format. Instead, they have their own separate git repos.</p>\n\n<p>Here is the source for the Latest Posts Block:\n<a href=\"https://github.com/WordPress/gutenberg/tree/master/packages/block-library/src/latest-posts\" rel=\"nofollow noreferrer\">https://github.com/WordPress/gutenberg/tree/master/packages/block-library/src/latest-posts</a></p>\n"
},
{
"answer_id": 360936,
"author": "Trisha",
"author_id": 56458,
"author_profile": "https://wordpress.stackexchange.com/users/56458",
"pm_score": 0,
"selected": false,
"text": "<p>Something you might try, I found this solution years ago and it's worked well - it does more than just allow overriding the number of words limitation, it also allows for some basic styles so that if your excerpt contains bolded words those will show in the excerpt. </p>\n\n<pre><code>// Improves the look of the excerpt, more words, allows bolding\n\nfunction improved_trim_excerpt($text) {\n$raw_excerpt = $text;\n\n$excerpt_more = '&hellip;<a class=\"more-link\" href=\"'. esc_url( get_permalink() ) . '\" title=\"' . esc_html__( 'Continue reading', 'wp-answers' ) . ' &lsquo;' . get_the_title() . '&rsquo;\">' . wp_kses( __( 'Continue reading <span class=\"meta-nav\">&rarr;</span>', 'wp-answers' ), array( 'span' => array( \n 'class' => array() ) ) ) . '</a>'; \n\nif ( '' == $text ) {\n $text = get_the_content('');\n $text = strip_shortcodes( $text );\n $text = apply_filters('the_content', $text);\n $text = str_replace('\\]\\]\\>', ']]&gt;', $text);\n $text = strip_tags($text, '<b><strong><del><em>');\n $excerpt_length = apply_filters('excerpt_length', 55);//change 55 to whatever word limit you want\n $newexcerpt_more = apply_filters('excerpt_more', ' ' . $excerpt_more);\n $words = preg_split(\"/[\\n\\r\\t ]+/\", $text, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY);\n if ( count($words) > $excerpt_length ) {\n array_pop($words);\n $text = implode(' ', $words);\n $text = $text . $newexcerpt_more;\n $text = force_balance_tags( $text );\n } else {\n $text = implode(' ', $words);\n $text = force_balance_tags( $text );\n }\n}\nreturn $text;\n}\nremove_filter('get_the_excerpt', 'wp_trim_excerpt');\nadd_filter('get_the_excerpt', 'improved_trim_excerpt');\n</code></pre>\n\n<p>This would go in your (hopefully child) theme's functions.php file or a custom plugin file.....</p>\n"
}
] | 2020/03/11 | [
"https://wordpress.stackexchange.com/questions/360441",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/26048/"
] | I need to dublicate all existing routes with several language codes:
```
/2020/03/11/Hello-world
/en/2020/03/11/Hello-world
/de/2020/03/11/Hello-world
/Hello-world-page
/en/Hello-world-page
/de/Hello-world-page
/...
/en/...
/de/...
```
Then I need to pre-handle all routes to check prefix exists and get as slug, then let related handlers do thier jobs.. I searched it many many times but never lucky to solve..
How to accomplish that? Thank you! | Gutenberg blocks are not stored in the Wordpress files in a readable or debuggable format. Instead, they have their own separate git repos.
Here is the source for the Latest Posts Block:
<https://github.com/WordPress/gutenberg/tree/master/packages/block-library/src/latest-posts> |
360,452 | <p>In my blog index page I do not want to show posts which has empty content but only title (<a href="https://wordpress.stackexchange.com/questions/37686/how-does-filter-the-posts-work">How does filter the_posts work?</a>) . I am looking at 'the_post' hook which seems to fire inside the loop . So , I thought if the action hook is fired inside the loop I could check the post content on 'the_post' hook and if it is null continue with the loop . I tried the below :</p>
<pre><code>add_action('the_post' , 'rb_test_the_post');
function rb_test_the_post($post){
if (($post->post_content) == '') {
continue;
}
}
</code></pre>
<p>This gives me an error in Wordpress ( "The site is experiencing technical difficulties " and also in my editor as it doesnt see any while or if statement for the continue statement.) . I am not able to understand why the continue statement doesnt work even though the hook is fired inside the loop .Could some one please explain? </p>
<p>Also , how would one achieve this (using a plugin and not the theme as I want the empty posts not to show even when I change theme) ? </p>
| [
{
"answer_id": 360414,
"author": "ngearing",
"author_id": 50184,
"author_profile": "https://wordpress.stackexchange.com/users/50184",
"pm_score": 2,
"selected": true,
"text": "<p>Gutenberg blocks are not stored in the Wordpress files in a readable or debuggable format. Instead, they have their own separate git repos.</p>\n\n<p>Here is the source for the Latest Posts Block:\n<a href=\"https://github.com/WordPress/gutenberg/tree/master/packages/block-library/src/latest-posts\" rel=\"nofollow noreferrer\">https://github.com/WordPress/gutenberg/tree/master/packages/block-library/src/latest-posts</a></p>\n"
},
{
"answer_id": 360936,
"author": "Trisha",
"author_id": 56458,
"author_profile": "https://wordpress.stackexchange.com/users/56458",
"pm_score": 0,
"selected": false,
"text": "<p>Something you might try, I found this solution years ago and it's worked well - it does more than just allow overriding the number of words limitation, it also allows for some basic styles so that if your excerpt contains bolded words those will show in the excerpt. </p>\n\n<pre><code>// Improves the look of the excerpt, more words, allows bolding\n\nfunction improved_trim_excerpt($text) {\n$raw_excerpt = $text;\n\n$excerpt_more = '&hellip;<a class=\"more-link\" href=\"'. esc_url( get_permalink() ) . '\" title=\"' . esc_html__( 'Continue reading', 'wp-answers' ) . ' &lsquo;' . get_the_title() . '&rsquo;\">' . wp_kses( __( 'Continue reading <span class=\"meta-nav\">&rarr;</span>', 'wp-answers' ), array( 'span' => array( \n 'class' => array() ) ) ) . '</a>'; \n\nif ( '' == $text ) {\n $text = get_the_content('');\n $text = strip_shortcodes( $text );\n $text = apply_filters('the_content', $text);\n $text = str_replace('\\]\\]\\>', ']]&gt;', $text);\n $text = strip_tags($text, '<b><strong><del><em>');\n $excerpt_length = apply_filters('excerpt_length', 55);//change 55 to whatever word limit you want\n $newexcerpt_more = apply_filters('excerpt_more', ' ' . $excerpt_more);\n $words = preg_split(\"/[\\n\\r\\t ]+/\", $text, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY);\n if ( count($words) > $excerpt_length ) {\n array_pop($words);\n $text = implode(' ', $words);\n $text = $text . $newexcerpt_more;\n $text = force_balance_tags( $text );\n } else {\n $text = implode(' ', $words);\n $text = force_balance_tags( $text );\n }\n}\nreturn $text;\n}\nremove_filter('get_the_excerpt', 'wp_trim_excerpt');\nadd_filter('get_the_excerpt', 'improved_trim_excerpt');\n</code></pre>\n\n<p>This would go in your (hopefully child) theme's functions.php file or a custom plugin file.....</p>\n"
}
] | 2020/03/11 | [
"https://wordpress.stackexchange.com/questions/360452",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/170935/"
] | In my blog index page I do not want to show posts which has empty content but only title ([How does filter the\_posts work?](https://wordpress.stackexchange.com/questions/37686/how-does-filter-the-posts-work)) . I am looking at 'the\_post' hook which seems to fire inside the loop . So , I thought if the action hook is fired inside the loop I could check the post content on 'the\_post' hook and if it is null continue with the loop . I tried the below :
```
add_action('the_post' , 'rb_test_the_post');
function rb_test_the_post($post){
if (($post->post_content) == '') {
continue;
}
}
```
This gives me an error in Wordpress ( "The site is experiencing technical difficulties " and also in my editor as it doesnt see any while or if statement for the continue statement.) . I am not able to understand why the continue statement doesnt work even though the hook is fired inside the loop .Could some one please explain?
Also , how would one achieve this (using a plugin and not the theme as I want the empty posts not to show even when I change theme) ? | Gutenberg blocks are not stored in the Wordpress files in a readable or debuggable format. Instead, they have their own separate git repos.
Here is the source for the Latest Posts Block:
<https://github.com/WordPress/gutenberg/tree/master/packages/block-library/src/latest-posts> |
360,481 | <p>How can I run a wp cli command when a wordpress hook is called on my website.</p>
<p>On user registration hook, I would like to run a wp cli command to activate a license.</p>
| [
{
"answer_id": 360792,
"author": "Tom Anderson",
"author_id": 171472,
"author_profile": "https://wordpress.stackexchange.com/users/171472",
"pm_score": 1,
"selected": false,
"text": "<p>Depends on what you want to do. If you want to run the PHP code that's behind the WP-CLI code you might consider looking at <a href=\"https://github.com/wp-cli/entity-command\" rel=\"nofollow noreferrer\">https://github.com/wp-cli/entity-command</a></p>\n\n<p>Maybe you don't actually need WP-CLI but the corresponding code behind it. Most WP-CLI commands have Wordpress equivalents. For example of what I was trying to do today, the <code>wp menu create \"My Menu\"</code> command is defined here:\n<a href=\"https://github.com/wp-cli/entity-command/blob/master/src/Menu_Command.php\" rel=\"nofollow noreferrer\">https://github.com/wp-cli/entity-command/blob/master/src/Menu_Command.php</a>. (It was much easier to find documentation for WP-CLI for this because 99% of results for Wordpress describe how to do it via the admin panel.)</p>\n\n<p>Basically it just uses the WP function:</p>\n\n<pre><code>65: $menu_id = wp_create_nav_menu( $args[0] );\n</code></pre>\n\n<p>So <code>> wp menu create \"My Menu\"</code> on the commandline is roughly equivalent to <code>wp_create_nav_menu('My Menu')</code> in a <code>functions.php</code> file.</p>\n\n<p>Similarly, the plugin command would be addressed as a WP-CLI extension command defined in <a href=\"https://github.com/wp-cli/extension-command/blob/master/src/Plugin_Command.php\" rel=\"nofollow noreferrer\">Plugin_Command.php</a> which uses the Wordpress command <a href=\"https://developer.wordpress.org/reference/functions/activate_plugin/\" rel=\"nofollow noreferrer\">activate_plugin()</a>. If you want to know the WP version of the WP-CLI command you could look it up yourself or include the specific command you want to know in your question.</p>\n"
},
{
"answer_id": 360793,
"author": "edwardr",
"author_id": 25724,
"author_profile": "https://wordpress.stackexchange.com/users/25724",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the PHP exec() function to run wp-cli commands.</p>\n\n<p>Example: <code><?php exec('wp core download'); ?></code></p>\n\n<p>Use with care. Further reading:</p>\n\n<p><a href=\"https://www.php.net/manual/en/function.exec.php\" rel=\"nofollow noreferrer\">https://www.php.net/manual/en/function.exec.php</a></p>\n"
}
] | 2020/03/11 | [
"https://wordpress.stackexchange.com/questions/360481",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/184151/"
] | How can I run a wp cli command when a wordpress hook is called on my website.
On user registration hook, I would like to run a wp cli command to activate a license. | Depends on what you want to do. If you want to run the PHP code that's behind the WP-CLI code you might consider looking at <https://github.com/wp-cli/entity-command>
Maybe you don't actually need WP-CLI but the corresponding code behind it. Most WP-CLI commands have Wordpress equivalents. For example of what I was trying to do today, the `wp menu create "My Menu"` command is defined here:
<https://github.com/wp-cli/entity-command/blob/master/src/Menu_Command.php>. (It was much easier to find documentation for WP-CLI for this because 99% of results for Wordpress describe how to do it via the admin panel.)
Basically it just uses the WP function:
```
65: $menu_id = wp_create_nav_menu( $args[0] );
```
So `> wp menu create "My Menu"` on the commandline is roughly equivalent to `wp_create_nav_menu('My Menu')` in a `functions.php` file.
Similarly, the plugin command would be addressed as a WP-CLI extension command defined in [Plugin\_Command.php](https://github.com/wp-cli/extension-command/blob/master/src/Plugin_Command.php) which uses the Wordpress command [activate\_plugin()](https://developer.wordpress.org/reference/functions/activate_plugin/). If you want to know the WP version of the WP-CLI command you could look it up yourself or include the specific command you want to know in your question. |
360,490 | <p>I have a site that uses categories to output posts into categories.php. I don't have single posts using single.php </p>
<p>What I need is for a 'next 10' / 'previous 10' links in the category a site visitor is looking at. Here's my code from category.php</p>
<pre><code><?php if (is_category('black-metal')) : ?>
<h2><img src="<?php bloginfo('template_directory'); ?>/assets/img/black-metal-h2.png" alt="Black Metal" /></h2>
<?php $catquery = new WP_Query( 'cat=2&posts_per_page=10' ); ?>
<?php while($catquery->have_posts()) : $catquery->the_post(); ?>
<?php the_content(); ?>
<h3><?php the_title(); ?></h3>
<?php endwhile;
wp_reset_postdata();
?>
<?php elseif (is_category('death-metal')) : ?>
<?php $catquery = new WP_Query( 'cat=3&posts_per_page=10' ); ?>
<h2><img src="<?php bloginfo('template_directory'); ?>/assets/img/death-metal-h2.png" alt="Death Metal" /></h2>
<?php while($catquery->have_posts()) : $catquery->the_post(); ?>
<?php the_content(); ?>
<h3><?php the_title(); ?></h3>
<?php endwhile;
wp_reset_postdata();
?>
</code></pre>
<p>So for example if someone is looking at the Black Metal category, I want next 10/previous 10 links for that particular category. </p>
<p>Hope that makes sense. I've done a lot searching but haven't been able to find an answer to this.</p>
| [
{
"answer_id": 360792,
"author": "Tom Anderson",
"author_id": 171472,
"author_profile": "https://wordpress.stackexchange.com/users/171472",
"pm_score": 1,
"selected": false,
"text": "<p>Depends on what you want to do. If you want to run the PHP code that's behind the WP-CLI code you might consider looking at <a href=\"https://github.com/wp-cli/entity-command\" rel=\"nofollow noreferrer\">https://github.com/wp-cli/entity-command</a></p>\n\n<p>Maybe you don't actually need WP-CLI but the corresponding code behind it. Most WP-CLI commands have Wordpress equivalents. For example of what I was trying to do today, the <code>wp menu create \"My Menu\"</code> command is defined here:\n<a href=\"https://github.com/wp-cli/entity-command/blob/master/src/Menu_Command.php\" rel=\"nofollow noreferrer\">https://github.com/wp-cli/entity-command/blob/master/src/Menu_Command.php</a>. (It was much easier to find documentation for WP-CLI for this because 99% of results for Wordpress describe how to do it via the admin panel.)</p>\n\n<p>Basically it just uses the WP function:</p>\n\n<pre><code>65: $menu_id = wp_create_nav_menu( $args[0] );\n</code></pre>\n\n<p>So <code>> wp menu create \"My Menu\"</code> on the commandline is roughly equivalent to <code>wp_create_nav_menu('My Menu')</code> in a <code>functions.php</code> file.</p>\n\n<p>Similarly, the plugin command would be addressed as a WP-CLI extension command defined in <a href=\"https://github.com/wp-cli/extension-command/blob/master/src/Plugin_Command.php\" rel=\"nofollow noreferrer\">Plugin_Command.php</a> which uses the Wordpress command <a href=\"https://developer.wordpress.org/reference/functions/activate_plugin/\" rel=\"nofollow noreferrer\">activate_plugin()</a>. If you want to know the WP version of the WP-CLI command you could look it up yourself or include the specific command you want to know in your question.</p>\n"
},
{
"answer_id": 360793,
"author": "edwardr",
"author_id": 25724,
"author_profile": "https://wordpress.stackexchange.com/users/25724",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the PHP exec() function to run wp-cli commands.</p>\n\n<p>Example: <code><?php exec('wp core download'); ?></code></p>\n\n<p>Use with care. Further reading:</p>\n\n<p><a href=\"https://www.php.net/manual/en/function.exec.php\" rel=\"nofollow noreferrer\">https://www.php.net/manual/en/function.exec.php</a></p>\n"
}
] | 2020/03/11 | [
"https://wordpress.stackexchange.com/questions/360490",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/35299/"
] | I have a site that uses categories to output posts into categories.php. I don't have single posts using single.php
What I need is for a 'next 10' / 'previous 10' links in the category a site visitor is looking at. Here's my code from category.php
```
<?php if (is_category('black-metal')) : ?>
<h2><img src="<?php bloginfo('template_directory'); ?>/assets/img/black-metal-h2.png" alt="Black Metal" /></h2>
<?php $catquery = new WP_Query( 'cat=2&posts_per_page=10' ); ?>
<?php while($catquery->have_posts()) : $catquery->the_post(); ?>
<?php the_content(); ?>
<h3><?php the_title(); ?></h3>
<?php endwhile;
wp_reset_postdata();
?>
<?php elseif (is_category('death-metal')) : ?>
<?php $catquery = new WP_Query( 'cat=3&posts_per_page=10' ); ?>
<h2><img src="<?php bloginfo('template_directory'); ?>/assets/img/death-metal-h2.png" alt="Death Metal" /></h2>
<?php while($catquery->have_posts()) : $catquery->the_post(); ?>
<?php the_content(); ?>
<h3><?php the_title(); ?></h3>
<?php endwhile;
wp_reset_postdata();
?>
```
So for example if someone is looking at the Black Metal category, I want next 10/previous 10 links for that particular category.
Hope that makes sense. I've done a lot searching but haven't been able to find an answer to this. | Depends on what you want to do. If you want to run the PHP code that's behind the WP-CLI code you might consider looking at <https://github.com/wp-cli/entity-command>
Maybe you don't actually need WP-CLI but the corresponding code behind it. Most WP-CLI commands have Wordpress equivalents. For example of what I was trying to do today, the `wp menu create "My Menu"` command is defined here:
<https://github.com/wp-cli/entity-command/blob/master/src/Menu_Command.php>. (It was much easier to find documentation for WP-CLI for this because 99% of results for Wordpress describe how to do it via the admin panel.)
Basically it just uses the WP function:
```
65: $menu_id = wp_create_nav_menu( $args[0] );
```
So `> wp menu create "My Menu"` on the commandline is roughly equivalent to `wp_create_nav_menu('My Menu')` in a `functions.php` file.
Similarly, the plugin command would be addressed as a WP-CLI extension command defined in [Plugin\_Command.php](https://github.com/wp-cli/extension-command/blob/master/src/Plugin_Command.php) which uses the Wordpress command [activate\_plugin()](https://developer.wordpress.org/reference/functions/activate_plugin/). If you want to know the WP version of the WP-CLI command you could look it up yourself or include the specific command you want to know in your question. |
360,497 | <p>I try to create a new "Post" kind of group that can be used as a different list to display different info. Someone already created two for us, but I don't know how. can someone teach me how? Thanks</p>
<p><a href="https://i.stack.imgur.com/GDK8H.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GDK8H.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 360792,
"author": "Tom Anderson",
"author_id": 171472,
"author_profile": "https://wordpress.stackexchange.com/users/171472",
"pm_score": 1,
"selected": false,
"text": "<p>Depends on what you want to do. If you want to run the PHP code that's behind the WP-CLI code you might consider looking at <a href=\"https://github.com/wp-cli/entity-command\" rel=\"nofollow noreferrer\">https://github.com/wp-cli/entity-command</a></p>\n\n<p>Maybe you don't actually need WP-CLI but the corresponding code behind it. Most WP-CLI commands have Wordpress equivalents. For example of what I was trying to do today, the <code>wp menu create \"My Menu\"</code> command is defined here:\n<a href=\"https://github.com/wp-cli/entity-command/blob/master/src/Menu_Command.php\" rel=\"nofollow noreferrer\">https://github.com/wp-cli/entity-command/blob/master/src/Menu_Command.php</a>. (It was much easier to find documentation for WP-CLI for this because 99% of results for Wordpress describe how to do it via the admin panel.)</p>\n\n<p>Basically it just uses the WP function:</p>\n\n<pre><code>65: $menu_id = wp_create_nav_menu( $args[0] );\n</code></pre>\n\n<p>So <code>> wp menu create \"My Menu\"</code> on the commandline is roughly equivalent to <code>wp_create_nav_menu('My Menu')</code> in a <code>functions.php</code> file.</p>\n\n<p>Similarly, the plugin command would be addressed as a WP-CLI extension command defined in <a href=\"https://github.com/wp-cli/extension-command/blob/master/src/Plugin_Command.php\" rel=\"nofollow noreferrer\">Plugin_Command.php</a> which uses the Wordpress command <a href=\"https://developer.wordpress.org/reference/functions/activate_plugin/\" rel=\"nofollow noreferrer\">activate_plugin()</a>. If you want to know the WP version of the WP-CLI command you could look it up yourself or include the specific command you want to know in your question.</p>\n"
},
{
"answer_id": 360793,
"author": "edwardr",
"author_id": 25724,
"author_profile": "https://wordpress.stackexchange.com/users/25724",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the PHP exec() function to run wp-cli commands.</p>\n\n<p>Example: <code><?php exec('wp core download'); ?></code></p>\n\n<p>Use with care. Further reading:</p>\n\n<p><a href=\"https://www.php.net/manual/en/function.exec.php\" rel=\"nofollow noreferrer\">https://www.php.net/manual/en/function.exec.php</a></p>\n"
}
] | 2020/03/12 | [
"https://wordpress.stackexchange.com/questions/360497",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/184163/"
] | I try to create a new "Post" kind of group that can be used as a different list to display different info. Someone already created two for us, but I don't know how. can someone teach me how? Thanks
[](https://i.stack.imgur.com/GDK8H.png) | Depends on what you want to do. If you want to run the PHP code that's behind the WP-CLI code you might consider looking at <https://github.com/wp-cli/entity-command>
Maybe you don't actually need WP-CLI but the corresponding code behind it. Most WP-CLI commands have Wordpress equivalents. For example of what I was trying to do today, the `wp menu create "My Menu"` command is defined here:
<https://github.com/wp-cli/entity-command/blob/master/src/Menu_Command.php>. (It was much easier to find documentation for WP-CLI for this because 99% of results for Wordpress describe how to do it via the admin panel.)
Basically it just uses the WP function:
```
65: $menu_id = wp_create_nav_menu( $args[0] );
```
So `> wp menu create "My Menu"` on the commandline is roughly equivalent to `wp_create_nav_menu('My Menu')` in a `functions.php` file.
Similarly, the plugin command would be addressed as a WP-CLI extension command defined in [Plugin\_Command.php](https://github.com/wp-cli/extension-command/blob/master/src/Plugin_Command.php) which uses the Wordpress command [activate\_plugin()](https://developer.wordpress.org/reference/functions/activate_plugin/). If you want to know the WP version of the WP-CLI command you could look it up yourself or include the specific command you want to know in your question. |
360,521 | <p>All of my categories has a custom single post title type, such:
"How to TITLE Free"
and then the article.</p>
<p>I want to get another title if category is News. So i won't have "How To TITLE Free" for single posts titles, but instead I will have "TITLE" only.</p>
<p>How can I do this?
Thank you.</p>
| [
{
"answer_id": 360537,
"author": "Siddhesh Shirodkar",
"author_id": 163787,
"author_profile": "https://wordpress.stackexchange.com/users/163787",
"pm_score": 0,
"selected": false,
"text": "<p>use get_the_category() to get category of posts.\nCompare it with your required category like:</p>\n\n<pre><code>$category = get_the_category();\nif($category[0]->name == 'news') { \n echo the_title();\n} else {\n echo \"title\";\n}\n</code></pre>\n\n<p>Hope this helps</p>\n"
},
{
"answer_id": 360761,
"author": "Michael",
"author_id": 4884,
"author_profile": "https://wordpress.stackexchange.com/users/4884",
"pm_score": 1,
"selected": false,
"text": "<p>change this one line in your code:</p>\n\n<pre><code><h1 class=\"article-title entry-title\">How To <?php the_title(); ?> Free</h1>\n</code></pre>\n\n<p>to:\nCORRECTION:</p>\n\n<pre><code><h1 class=\"article-title entry-title\"><?php if( in_category( array('news') ) ) { the_title(); } else { ?> How To <?php the_title(); ?> Free<?php } ?></h1>\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/in_category/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/in_category/</a></p>\n"
}
] | 2020/03/12 | [
"https://wordpress.stackexchange.com/questions/360521",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114258/"
] | All of my categories has a custom single post title type, such:
"How to TITLE Free"
and then the article.
I want to get another title if category is News. So i won't have "How To TITLE Free" for single posts titles, but instead I will have "TITLE" only.
How can I do this?
Thank you. | change this one line in your code:
```
<h1 class="article-title entry-title">How To <?php the_title(); ?> Free</h1>
```
to:
CORRECTION:
```
<h1 class="article-title entry-title"><?php if( in_category( array('news') ) ) { the_title(); } else { ?> How To <?php the_title(); ?> Free<?php } ?></h1>
```
<https://developer.wordpress.org/reference/functions/in_category/> |
360,535 | <p>How can i update global variable URL? I am trying for the last 3 days, still no luck </p>
<pre><code>var output = '';
var pageNum = '';
url = '';
function post_ajax_get(pagination) {
$("#loading-animation").show();
var query = 'nazwa=';
var time = 'gr=';
var output = '';
$("[data-category-menu] a.current").each(function(){
if($(this).data('time')) {
if(time != 'gr=') {
time+= ',';
};
time+= $(this).data('time');
}
if($(this).data('slug')) {
if(query != 'nazwa=') {
query+= ',';
};
query+= $(this).data('slug');
}
if (query != 'nazwa=' && time == 'gr='){
output = query;
}
else if (query == 'nazwa=' && time != 'gr='){
output = time;
}
else if (query != 'nazwa=' && time != 'gr='){
output = time + '&' + query;
}
});
if(pagination) {
$("[data-pagination] a.current").each(function(){
if(output != '') output+= '&';
output+= $(this).data('slug');
});
}
url = window.location.protocol + '//' + window.location.host + '/' + window.location.pathname + '?' + output;
//window.location.href = url;
if ($('body.category').length > 0 && output == '') {
var adres = window.location.pathname;
var cat = adres.split('/')[3];
url = window.location.protocol + '//' + window.location.host + '/' + window.location.pathname + '?' + 'nazwa=' + cat;
$('[data-category-menu] li a').each(function() {
if($(this).attr('id') == cat) {
$(this).addClass('current');
}
$('[data-category-menu] li a.current').click(function() {
$(this).removeClass('current');
})
})
}
$('[data-category-menu] li a.current').click(function() {
updateURL();
})
function updateURL() {
console.log('fire');
url = window.location.protocol + '//' + window.location.host + '/' + window.location.pathname + '?' + 'nazwa=pusty';
}
console.log(url);
var pageNum = url.substr(url.indexOf("md_page=") + 8);
//var pagNum = pageNum.toString();
$('#md-products').load(url + ' #md-products > *', function() {
$("#loading-animation").hide();
$('#md-products [data-pagination] a').on('click', function() {
$(this).addClass('current');
post_ajax_get(true);
})
});
}
console.log(url);
</code></pre>
| [
{
"answer_id": 360524,
"author": "Mikhail",
"author_id": 88888,
"author_profile": "https://wordpress.stackexchange.com/users/88888",
"pm_score": 2,
"selected": false,
"text": "<p>There can be a case that theme implements hooks via <code>do_action(\"action_name\"</code>) but it's not forced to bind actual actions to it, as theme's developers might just did it to make theme more extensible, and in fact never use it inside theme.</p>\n\n<p>So you can just bind your own code via <code>add_action(\"colormag_before\", \"your_function_name\"</code>) in a child theme or plugin, and it will work.</p>\n\n<p>And obviously if you want just to check if hook is used already somewhere in theme, just search through theme's code for <code>add_action(\"colormag_before\"</code> (or <code>add_action( \"colormag_before\"</code> or <code>add_action('colormag_before'</code> or <code>add_action( 'colormag_before'</code>. these are just variation with different kinds of how it can be spelled)</p>\n\n<p>If you can search via regular expression it will be <code>add_action\\(\\s*['\"]colormag_before</code></p>\n"
},
{
"answer_id": 360532,
"author": "Alberto",
"author_id": 184173,
"author_profile": "https://wordpress.stackexchange.com/users/184173",
"pm_score": -1,
"selected": false,
"text": "<p>I've found the solution.</p>\n\n<p>In my plugin's code, for modifying the content I was only using the <code>is_page( $page_id )</code> condition to check if is the page I wanted to modify. Adding the <code>in_the_loop()</code> condition solved the problem.</p>\n\n<p>Anyway, thanks Mikhail for the contribution.</p>\n"
}
] | 2020/03/12 | [
"https://wordpress.stackexchange.com/questions/360535",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/184176/"
] | How can i update global variable URL? I am trying for the last 3 days, still no luck
```
var output = '';
var pageNum = '';
url = '';
function post_ajax_get(pagination) {
$("#loading-animation").show();
var query = 'nazwa=';
var time = 'gr=';
var output = '';
$("[data-category-menu] a.current").each(function(){
if($(this).data('time')) {
if(time != 'gr=') {
time+= ',';
};
time+= $(this).data('time');
}
if($(this).data('slug')) {
if(query != 'nazwa=') {
query+= ',';
};
query+= $(this).data('slug');
}
if (query != 'nazwa=' && time == 'gr='){
output = query;
}
else if (query == 'nazwa=' && time != 'gr='){
output = time;
}
else if (query != 'nazwa=' && time != 'gr='){
output = time + '&' + query;
}
});
if(pagination) {
$("[data-pagination] a.current").each(function(){
if(output != '') output+= '&';
output+= $(this).data('slug');
});
}
url = window.location.protocol + '//' + window.location.host + '/' + window.location.pathname + '?' + output;
//window.location.href = url;
if ($('body.category').length > 0 && output == '') {
var adres = window.location.pathname;
var cat = adres.split('/')[3];
url = window.location.protocol + '//' + window.location.host + '/' + window.location.pathname + '?' + 'nazwa=' + cat;
$('[data-category-menu] li a').each(function() {
if($(this).attr('id') == cat) {
$(this).addClass('current');
}
$('[data-category-menu] li a.current').click(function() {
$(this).removeClass('current');
})
})
}
$('[data-category-menu] li a.current').click(function() {
updateURL();
})
function updateURL() {
console.log('fire');
url = window.location.protocol + '//' + window.location.host + '/' + window.location.pathname + '?' + 'nazwa=pusty';
}
console.log(url);
var pageNum = url.substr(url.indexOf("md_page=") + 8);
//var pagNum = pageNum.toString();
$('#md-products').load(url + ' #md-products > *', function() {
$("#loading-animation").hide();
$('#md-products [data-pagination] a').on('click', function() {
$(this).addClass('current');
post_ajax_get(true);
})
});
}
console.log(url);
``` | There can be a case that theme implements hooks via `do_action("action_name"`) but it's not forced to bind actual actions to it, as theme's developers might just did it to make theme more extensible, and in fact never use it inside theme.
So you can just bind your own code via `add_action("colormag_before", "your_function_name"`) in a child theme or plugin, and it will work.
And obviously if you want just to check if hook is used already somewhere in theme, just search through theme's code for `add_action("colormag_before"` (or `add_action( "colormag_before"` or `add_action('colormag_before'` or `add_action( 'colormag_before'`. these are just variation with different kinds of how it can be spelled)
If you can search via regular expression it will be `add_action\(\s*['"]colormag_before` |
360,573 | <p>Stack Exchange long time listener, first time caller.</p>
<p>I have found examples on the developer.wordpress site but I have been still struggling.</p>
<p>Localizing scripts:
<a href="https://developer.wordpress.org/reference/functions/wp_localize_script/#comment-content-1391" rel="nofollow noreferrer">wp_localize_script()</a></p>
<p>In my theme's functions.php file, I have:</p>
<pre><code>function wp_my_ajax_script() {
wp_localize_script( 'ajax_handle_agent_search', 'myAjax', admin_url( 'admin-ajax.php' ));
wp_enqueue_script( 'ajax_handle_agent_search' );
}
add_action( 'wp_enqueue_scripts', 'wp_my_ajax_script' );
</code></pre>
<p>And on my page, I've added a HTML code wdiget that contains:</p>
<pre><code><script>
jQuery(document).ready( function() {
console.log("Document loaded");
jQuery("#searchButton").click( function(e) {
console.log("Search button clicked");
console.log("Ajax: " . myAjax);
e.preventDefault();
var zipCode = document.getElementById("inputField").value;
console.log("Zip code entered: " + zipCode);
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {
action: "zip_search_action",
zip_code : zipCode
},
success: function(response) {
if(response.type == "success") {
console.log("In success");
document.getElementById("results").html = response.data;
}
else {
console.log("In success, in else!");
}
},
error: function(errorThrown){
console.log("In error, error thrown!");
console.log(errorThrown);
}
})
});
});
</script>
<input type="text" id="inputField">
<input type="button" value="Search" id="searchButton">
</code></pre>
<p>Then I load the page, enter a zip code in to the input field and click the button. The developer tools console shows:</p>
<p><a href="https://i.stack.imgur.com/YetFO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YetFO.png" alt="Developer Tool console with error message"></a></p>
<p>I've been working on this for a few weeks now and I've gotten much better at developing for Wordpress, but web dev isn't my forte, so after I feel I've reached my limit, I'm reaching out for help. Any insight to get me moving forward would be much appreciated.</p>
<p>Thanks in advance! </p>
<p>=================================
EDIT 3/12/20 at 1342 CST</p>
<p>I've moved the JS code to it's own file in the theme's JS directory with the permissions 0755. Then I've added a new function to my functions.php file with the enqueue and localize function calls (as seen below)</p>
<pre><code>function my_load_scripts() {
wp_enqueue_script( 'zip_js', get_template_directory_uri() . '/js/zip_search.js' );
wp_localize_script( 'zip_js', 'Zip_JS', null);
}
add_action('wp_enqueue_scripts', 'my_load_scripts');
</code></pre>
<p>Now the console shows:
<a href="https://i.stack.imgur.com/lx8EH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lx8EH.png" alt="jQuery error"></a></p>
<h2>================================++++= EDIT 3/13/20 at 0806 CST</h2>
<p>I have gotten further. Atleast I believe so. Below is the code as it currently is in Wordpress followed by a screenshot of the console error.</p>
<p>In my JS file ():</p>
<pre><code>jQuery(document).ready( function() {
console.log("Document loaded");
jQuery("#searchButton").click( function(e) {
console.log("Search button clicked");
e.preventDefault();
var zipCode = document.getElementById("inputField").value;
console.log("Zip code entered: " + zipCode);
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {
action: "zip_search",
zip_code : zipCode
},
success: function(response) {
if(response.type == "success") {
console.log("In success");
//jQuery("#results").html(response.data);
document.getElementById("results").html = response.data;
}
else {
console.log("In success, in else!");
console.log(response);
}
},
error: function(errorThrown){
console.log("In error, error thrown!");
console.log(errorThrown);
}
});
});
});
</code></pre>
<p>In functions.php including my DB query this time:</p>
<pre><code>function my_load_scripts() {
// Enqueue javascript on the frontend.
wp_enqueue_script(
'zip_js',
get_template_directory_uri() . '/js/zip_search.js',
array('jquery')
);
// The wp_localize_script allows us to output the ajax_url path for our script to use.
wp_localize_script(
'zip_js',
'myAjax',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ) )
);
}
add_action( 'wp_enqueue_scripts', 'my_load_scripts' );
function zip_search()
{
global $wpdb;
$output = '';
$zip = $_REQUEST['zipCode'];
$query = 'SELECT county FROM Agent WHERE zip = %s';
$result = $wpdb->get_var( $wpdb->prepare($query, $zip) );
$output .= "<p>";
$output .= $result;
$output .= "</p>";
$query = 'SELECT zip, county, zone, agent FROM Agent WHERE county = %s';
$results = $wpdb->get_results( $wpdb->prepare($query, $result) );
$output .= "<ul>";
foreach( $results as $result )
{
$output .= "<li>".$result->zip." - ".$result->zone." - ".$result->agent."</li>";
}
$output .= "</ul>";
$result['type'] = "success";
$result['data'] = $output;
return json_encode($result);
die();
}
add_action('wp_ajax_zip_search_action', 'zip_search');
add_action( 'wp_ajax_nopriv_zip_search_action', 'zip_search' );
</code></pre>
<p>On my Wordpress page:</p>
<pre><code><input type="text" id="inputField">
<input type="button" value="Search" id="searchButton">
</code></pre>
<p>Console:
<a href="https://i.stack.imgur.com/lG35r.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lG35r.png" alt="New console error with status 200 and statusText of "OK""></a></p>
<hr>
<h2>EDIT: 3/13/2020 at 11:52am CST</h2>
<h2>Adding working code. Hopefully anyone that is having close to the same issue can see what I did to make this work and it will help somehow.</h2>
<p>JS:</p>
<pre><code>jQuery(document).ready( function() {
console.log("Document loaded");
jQuery("#searchButton").click( function(e) {
console.log("Search button clicked");
e.preventDefault();
var zipCode = document.getElementById("inputField").value;
console.log("Zip code entered: " + zipCode);
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {
'action': "zip_search",
'zip_code' : zipCode
},
success: function(response) {
console.log(response.data);
if(response.success) {
console.log("response.type == success");
jQuery("#results").html(response.data.data);
}
else {
console.log("response.type == else");
console.log(response.data);
}
},
error: function(errorThrown){
console.log("In error, error thrown!");
console.log(errorThrown);
}
})
})
})
</code></pre>
<p>functions.php:</p>
<pre><code>add_action('wp_ajax_zip_search', 'zip_search');
add_action('wp_ajax_nopriv_zip_search', 'zip_search' );
function zip_search()
{
global $wpdb;
$output = '';
$zip = $_REQUEST["zip_code"];
$query = 'SELECT county FROM Agent WHERE zip = %s';
$result = $wpdb->get_var( $wpdb->prepare($query, $zip) );
$output .= "<p>";
$output .= $result;
$output .= "</p>";
$query = 'SELECT zip, county, zone, agent FROM Agent WHERE county = %s';
$results = $wpdb->get_results( $wpdb->prepare($query, $result) );
$output .= "<ul>";
foreach( $results as $result )
{
$output .= "<li>".$result->zip." - ".$result->zone." - ".$result->agent."</li>";
}
$output .= "</ul>";
$response = array(
'data' => $output,
);
wp_send_json_success($response);
//return json_encode($response);
//die();
}
add_action( 'wp_enqueue_scripts', 'my_load_scripts' );
function my_load_scripts() {
// Enqueue javascript on the frontend.
wp_enqueue_script(
'zip_js',
get_template_directory_uri() . '/js/zip_search.js',
array('jquery')
);
// The wp_localize_script allows us to output the ajax_url path for our script to use.
wp_localize_script(
'zip_js',
'myAjax',
array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) )
);
}
</code></pre>
<p>HTML:</p>
<pre><code><input type="text" id="inputField" placeholder="Enter zip code here">
<input type="button" value="Search" id="searchButton">
</code></pre>
| [
{
"answer_id": 360524,
"author": "Mikhail",
"author_id": 88888,
"author_profile": "https://wordpress.stackexchange.com/users/88888",
"pm_score": 2,
"selected": false,
"text": "<p>There can be a case that theme implements hooks via <code>do_action(\"action_name\"</code>) but it's not forced to bind actual actions to it, as theme's developers might just did it to make theme more extensible, and in fact never use it inside theme.</p>\n\n<p>So you can just bind your own code via <code>add_action(\"colormag_before\", \"your_function_name\"</code>) in a child theme or plugin, and it will work.</p>\n\n<p>And obviously if you want just to check if hook is used already somewhere in theme, just search through theme's code for <code>add_action(\"colormag_before\"</code> (or <code>add_action( \"colormag_before\"</code> or <code>add_action('colormag_before'</code> or <code>add_action( 'colormag_before'</code>. these are just variation with different kinds of how it can be spelled)</p>\n\n<p>If you can search via regular expression it will be <code>add_action\\(\\s*['\"]colormag_before</code></p>\n"
},
{
"answer_id": 360532,
"author": "Alberto",
"author_id": 184173,
"author_profile": "https://wordpress.stackexchange.com/users/184173",
"pm_score": -1,
"selected": false,
"text": "<p>I've found the solution.</p>\n\n<p>In my plugin's code, for modifying the content I was only using the <code>is_page( $page_id )</code> condition to check if is the page I wanted to modify. Adding the <code>in_the_loop()</code> condition solved the problem.</p>\n\n<p>Anyway, thanks Mikhail for the contribution.</p>\n"
}
] | 2020/03/12 | [
"https://wordpress.stackexchange.com/questions/360573",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/184205/"
] | Stack Exchange long time listener, first time caller.
I have found examples on the developer.wordpress site but I have been still struggling.
Localizing scripts:
[wp\_localize\_script()](https://developer.wordpress.org/reference/functions/wp_localize_script/#comment-content-1391)
In my theme's functions.php file, I have:
```
function wp_my_ajax_script() {
wp_localize_script( 'ajax_handle_agent_search', 'myAjax', admin_url( 'admin-ajax.php' ));
wp_enqueue_script( 'ajax_handle_agent_search' );
}
add_action( 'wp_enqueue_scripts', 'wp_my_ajax_script' );
```
And on my page, I've added a HTML code wdiget that contains:
```
<script>
jQuery(document).ready( function() {
console.log("Document loaded");
jQuery("#searchButton").click( function(e) {
console.log("Search button clicked");
console.log("Ajax: " . myAjax);
e.preventDefault();
var zipCode = document.getElementById("inputField").value;
console.log("Zip code entered: " + zipCode);
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {
action: "zip_search_action",
zip_code : zipCode
},
success: function(response) {
if(response.type == "success") {
console.log("In success");
document.getElementById("results").html = response.data;
}
else {
console.log("In success, in else!");
}
},
error: function(errorThrown){
console.log("In error, error thrown!");
console.log(errorThrown);
}
})
});
});
</script>
<input type="text" id="inputField">
<input type="button" value="Search" id="searchButton">
```
Then I load the page, enter a zip code in to the input field and click the button. The developer tools console shows:
[](https://i.stack.imgur.com/YetFO.png)
I've been working on this for a few weeks now and I've gotten much better at developing for Wordpress, but web dev isn't my forte, so after I feel I've reached my limit, I'm reaching out for help. Any insight to get me moving forward would be much appreciated.
Thanks in advance!
=================================
EDIT 3/12/20 at 1342 CST
I've moved the JS code to it's own file in the theme's JS directory with the permissions 0755. Then I've added a new function to my functions.php file with the enqueue and localize function calls (as seen below)
```
function my_load_scripts() {
wp_enqueue_script( 'zip_js', get_template_directory_uri() . '/js/zip_search.js' );
wp_localize_script( 'zip_js', 'Zip_JS', null);
}
add_action('wp_enqueue_scripts', 'my_load_scripts');
```
Now the console shows:
[](https://i.stack.imgur.com/lx8EH.png)
================================++++= EDIT 3/13/20 at 0806 CST
--------------------------------------------------------------
I have gotten further. Atleast I believe so. Below is the code as it currently is in Wordpress followed by a screenshot of the console error.
In my JS file ():
```
jQuery(document).ready( function() {
console.log("Document loaded");
jQuery("#searchButton").click( function(e) {
console.log("Search button clicked");
e.preventDefault();
var zipCode = document.getElementById("inputField").value;
console.log("Zip code entered: " + zipCode);
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {
action: "zip_search",
zip_code : zipCode
},
success: function(response) {
if(response.type == "success") {
console.log("In success");
//jQuery("#results").html(response.data);
document.getElementById("results").html = response.data;
}
else {
console.log("In success, in else!");
console.log(response);
}
},
error: function(errorThrown){
console.log("In error, error thrown!");
console.log(errorThrown);
}
});
});
});
```
In functions.php including my DB query this time:
```
function my_load_scripts() {
// Enqueue javascript on the frontend.
wp_enqueue_script(
'zip_js',
get_template_directory_uri() . '/js/zip_search.js',
array('jquery')
);
// The wp_localize_script allows us to output the ajax_url path for our script to use.
wp_localize_script(
'zip_js',
'myAjax',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ) )
);
}
add_action( 'wp_enqueue_scripts', 'my_load_scripts' );
function zip_search()
{
global $wpdb;
$output = '';
$zip = $_REQUEST['zipCode'];
$query = 'SELECT county FROM Agent WHERE zip = %s';
$result = $wpdb->get_var( $wpdb->prepare($query, $zip) );
$output .= "<p>";
$output .= $result;
$output .= "</p>";
$query = 'SELECT zip, county, zone, agent FROM Agent WHERE county = %s';
$results = $wpdb->get_results( $wpdb->prepare($query, $result) );
$output .= "<ul>";
foreach( $results as $result )
{
$output .= "<li>".$result->zip." - ".$result->zone." - ".$result->agent."</li>";
}
$output .= "</ul>";
$result['type'] = "success";
$result['data'] = $output;
return json_encode($result);
die();
}
add_action('wp_ajax_zip_search_action', 'zip_search');
add_action( 'wp_ajax_nopriv_zip_search_action', 'zip_search' );
```
On my Wordpress page:
```
<input type="text" id="inputField">
<input type="button" value="Search" id="searchButton">
```
Console:
[](https://i.stack.imgur.com/lG35r.png)
---
EDIT: 3/13/2020 at 11:52am CST
------------------------------
Adding working code. Hopefully anyone that is having close to the same issue can see what I did to make this work and it will help somehow.
-------------------------------------------------------------------------------------------------------------------------------------------
JS:
```
jQuery(document).ready( function() {
console.log("Document loaded");
jQuery("#searchButton").click( function(e) {
console.log("Search button clicked");
e.preventDefault();
var zipCode = document.getElementById("inputField").value;
console.log("Zip code entered: " + zipCode);
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {
'action': "zip_search",
'zip_code' : zipCode
},
success: function(response) {
console.log(response.data);
if(response.success) {
console.log("response.type == success");
jQuery("#results").html(response.data.data);
}
else {
console.log("response.type == else");
console.log(response.data);
}
},
error: function(errorThrown){
console.log("In error, error thrown!");
console.log(errorThrown);
}
})
})
})
```
functions.php:
```
add_action('wp_ajax_zip_search', 'zip_search');
add_action('wp_ajax_nopriv_zip_search', 'zip_search' );
function zip_search()
{
global $wpdb;
$output = '';
$zip = $_REQUEST["zip_code"];
$query = 'SELECT county FROM Agent WHERE zip = %s';
$result = $wpdb->get_var( $wpdb->prepare($query, $zip) );
$output .= "<p>";
$output .= $result;
$output .= "</p>";
$query = 'SELECT zip, county, zone, agent FROM Agent WHERE county = %s';
$results = $wpdb->get_results( $wpdb->prepare($query, $result) );
$output .= "<ul>";
foreach( $results as $result )
{
$output .= "<li>".$result->zip." - ".$result->zone." - ".$result->agent."</li>";
}
$output .= "</ul>";
$response = array(
'data' => $output,
);
wp_send_json_success($response);
//return json_encode($response);
//die();
}
add_action( 'wp_enqueue_scripts', 'my_load_scripts' );
function my_load_scripts() {
// Enqueue javascript on the frontend.
wp_enqueue_script(
'zip_js',
get_template_directory_uri() . '/js/zip_search.js',
array('jquery')
);
// The wp_localize_script allows us to output the ajax_url path for our script to use.
wp_localize_script(
'zip_js',
'myAjax',
array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) )
);
}
```
HTML:
```
<input type="text" id="inputField" placeholder="Enter zip code here">
<input type="button" value="Search" id="searchButton">
``` | There can be a case that theme implements hooks via `do_action("action_name"`) but it's not forced to bind actual actions to it, as theme's developers might just did it to make theme more extensible, and in fact never use it inside theme.
So you can just bind your own code via `add_action("colormag_before", "your_function_name"`) in a child theme or plugin, and it will work.
And obviously if you want just to check if hook is used already somewhere in theme, just search through theme's code for `add_action("colormag_before"` (or `add_action( "colormag_before"` or `add_action('colormag_before'` or `add_action( 'colormag_before'`. these are just variation with different kinds of how it can be spelled)
If you can search via regular expression it will be `add_action\(\s*['"]colormag_before` |
360,593 | <p>Can't get my checkbox for metafield set true by default.</p>
<p>Everything is working fine, except default value.</p>
<p>I know there is a lot of questions and answers for it,</p>
<p>But I tried everything and still can't get it.</p>
<p>Here is my code:</p>
<pre><code>function theme_add_meta_box() {
add_meta_box( 'theme_post_sidebar_option', esc_html__( 'Additional Options', 'theme' ), 'theme_post_sidebar_settings', 'post', 'normal', 'high' );
}
add_action( 'add_meta_boxes', 'theme_add_meta_box' );
</code></pre>
<p>Then my options:</p>
<pre><code>function theme_post_sidebar_settings($post) {
$sidebar = get_post_meta($post->ID, '_theme_post_meta_sidebar', true);
wp_nonce_field( 'theme_update_post_sidebar_settings', 'theme_update_post_sidebar_nonce' );
?>
<input type="checkbox" name="theme_post_meta_sidebar_field" id="theme_post_meta_sidebar_field" value="1" <?php checked($sidebar); ?> />
<label for="theme_post_meta_sidebar_field"><?php esc_html_e( 'Sidebar', 'theme' ); ?></label>
<?php
}
</code></pre>
<p>Then my save function:</p>
<pre><code> function theme_save_post_sidebar_settings($post_id, $post) {
$edit_cap = get_post_type_object( $post->post_type )->cap->edit_post;
if( !current_user_can( $edit_cap, $post_id )) {
return;
}
if( !isset( $_POST['theme_update_post_sidebar_nonce']) || !wp_verify_nonce( $_POST['theme_update_post_sidebar_nonce'], 'theme_update_post_sidebar_settings' )) {
return;
}
if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
if(array_key_exists('theme_post_meta_sidebar_field', $_POST)) {
update_post_meta(
$post_id,
'_theme_post_meta_sidebar',
sanitize_text_field($_POST['theme_post_meta_sidebar_field'])
);
} else {
update_post_meta(
$post_id,
'_theme_post_meta_sidebar', null);
}
}
add_action( 'save_post', 'theme_save_post_sidebar_settings', 10, 2 );
</code></pre>
<p>Can someone help me, please?</p>
| [
{
"answer_id": 360590,
"author": "Fredy31",
"author_id": 8895,
"author_profile": "https://wordpress.stackexchange.com/users/8895",
"pm_score": 2,
"selected": false,
"text": "<p>Well, I'm a moron. It's under Settings->URL Modifications... the 'The front page url contains the language code instead of the page name or page id' checkbox.</p>\n"
},
{
"answer_id": 360886,
"author": "RobbTe",
"author_id": 124244,
"author_profile": "https://wordpress.stackexchange.com/users/124244",
"pm_score": 2,
"selected": true,
"text": "<p>Yes it is possible. For a more comprehensive answer, see: <a href=\"https://polylang.pro/doc/define-your-home-page-as-a-static-page/\" rel=\"nofollow noreferrer\">https://polylang.pro/doc/define-your-home-page-as-a-static-page/</a></p>\n"
}
] | 2020/03/12 | [
"https://wordpress.stackexchange.com/questions/360593",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/182186/"
] | Can't get my checkbox for metafield set true by default.
Everything is working fine, except default value.
I know there is a lot of questions and answers for it,
But I tried everything and still can't get it.
Here is my code:
```
function theme_add_meta_box() {
add_meta_box( 'theme_post_sidebar_option', esc_html__( 'Additional Options', 'theme' ), 'theme_post_sidebar_settings', 'post', 'normal', 'high' );
}
add_action( 'add_meta_boxes', 'theme_add_meta_box' );
```
Then my options:
```
function theme_post_sidebar_settings($post) {
$sidebar = get_post_meta($post->ID, '_theme_post_meta_sidebar', true);
wp_nonce_field( 'theme_update_post_sidebar_settings', 'theme_update_post_sidebar_nonce' );
?>
<input type="checkbox" name="theme_post_meta_sidebar_field" id="theme_post_meta_sidebar_field" value="1" <?php checked($sidebar); ?> />
<label for="theme_post_meta_sidebar_field"><?php esc_html_e( 'Sidebar', 'theme' ); ?></label>
<?php
}
```
Then my save function:
```
function theme_save_post_sidebar_settings($post_id, $post) {
$edit_cap = get_post_type_object( $post->post_type )->cap->edit_post;
if( !current_user_can( $edit_cap, $post_id )) {
return;
}
if( !isset( $_POST['theme_update_post_sidebar_nonce']) || !wp_verify_nonce( $_POST['theme_update_post_sidebar_nonce'], 'theme_update_post_sidebar_settings' )) {
return;
}
if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
if(array_key_exists('theme_post_meta_sidebar_field', $_POST)) {
update_post_meta(
$post_id,
'_theme_post_meta_sidebar',
sanitize_text_field($_POST['theme_post_meta_sidebar_field'])
);
} else {
update_post_meta(
$post_id,
'_theme_post_meta_sidebar', null);
}
}
add_action( 'save_post', 'theme_save_post_sidebar_settings', 10, 2 );
```
Can someone help me, please? | Yes it is possible. For a more comprehensive answer, see: <https://polylang.pro/doc/define-your-home-page-as-a-static-page/> |
360,596 | <p>I want security for my theme, so I took all different commands from my theme files.
If I need to escape these, how can I do it? :</p>
<pre><code><?php get_header(); ?>
<h1><?php _e( 'Page not found', 'html5blank' ); ?></h1>
<a href="<?php echo home_url(); ?>">
<?php
if ( $thumbnail_id = get_post_thumbnail_id() ) {
if ( $image_src = wp_get_attachment_image_src( $thumbnail_id, 'normal-bg' ) )
printf( ' style="background-image: url(%s);"', $image_src[0] );
}
?>>
<?php
// Set the Current Author Variable $curauth
$curauth = (isset($_GET['author_name'])) ? get_user_by('slug', $author_name) : get_userdata(intval($author));
?>
<?php echo get_avatar( get_the_author_email(), '20' ); ?>
<?php
function your_prefix_render_hfe_footer() {
if ( function_exists( 'hfe_render_footer' ) ) {
hfe_render_footer();
}
}
add_action( 'astra_footer', 'your_prefix_render_hfe_header' ); ?>
<?php footer_shortcode_elementor() ?>
-----------------------------
in function.php:
add_filter('comment_form_fields', 'wpb_move_comment_field_to_bottom');
if ( ! function_exists( 'WPScripts_enqueue' ) ) {
-----------------------------
<?php
global $post;
$tags = get_the_tags($post->ID);
if (is_array($tags) || is_object($tags)) {
foreach($tags as $tag)
{
echo '<a href="' . get_tag_link($tag->term_id) . '"><span class="badge badge-dark">' . $tag->name . '</span></a> ';
}
}
?>
<?php if (have_posts()): while (have_posts()) : the_post(); ?>
</code></pre>
<p>Thank you</p>
| [
{
"answer_id": 360598,
"author": "uPrompt",
"author_id": 155077,
"author_profile": "https://wordpress.stackexchange.com/users/155077",
"pm_score": -1,
"selected": false,
"text": "<p>Again, can't comment yet but I think this is what you're looking for:</p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/64967/how-to-properly-validate-data-from-get-or-request-using-wordpress-functions\">How to properly validate data from $_GET or $_REQUEST using WordPress functions?</a></p>\n\n<p>If your $_GET and $_POST are not trusted, you should always sanitize them. If you update or insert into the $wpdb, always use prepare.</p>\n"
},
{
"answer_id": 360678,
"author": "Faye",
"author_id": 76600,
"author_profile": "https://wordpress.stackexchange.com/users/76600",
"pm_score": 1,
"selected": false,
"text": "<p>Here's just a few examples of what escaping looks like:</p>\n\n<p><strong>Escaping URLS:</strong> </p>\n\n<pre><code><?php echo esc_url( home_url() ); ?>\n</code></pre>\n\n<p><strong>Escaping Content</strong></p>\n\n<pre><code><?php echo esc_html( get_the_title() ); ?>\n</code></pre>\n\n<p><strong>Escaping Attributes</strong></p>\n\n<pre><code><?php echo esc_attr( $my_class ); ?>\n</code></pre>\n\n<p><strong>Escaping Content but keep HTML</strong></p>\n\n<pre><code><?php echo wp_kses_post( get_the_content() ); ?>\n</code></pre>\n\n<p><strong>Escaping Emails</strong></p>\n\n<pre><code><?php echo sanitize_email( $email_address ) ); ?>\n</code></pre>\n\n<p>For more information about escaping, <a href=\"https://developer.wordpress.org/themes/theme-security/data-sanitization-escaping/\" rel=\"nofollow noreferrer\">here's a good resource on data sanitization</a>.</p>\n"
}
] | 2020/03/12 | [
"https://wordpress.stackexchange.com/questions/360596",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/172430/"
] | I want security for my theme, so I took all different commands from my theme files.
If I need to escape these, how can I do it? :
```
<?php get_header(); ?>
<h1><?php _e( 'Page not found', 'html5blank' ); ?></h1>
<a href="<?php echo home_url(); ?>">
<?php
if ( $thumbnail_id = get_post_thumbnail_id() ) {
if ( $image_src = wp_get_attachment_image_src( $thumbnail_id, 'normal-bg' ) )
printf( ' style="background-image: url(%s);"', $image_src[0] );
}
?>>
<?php
// Set the Current Author Variable $curauth
$curauth = (isset($_GET['author_name'])) ? get_user_by('slug', $author_name) : get_userdata(intval($author));
?>
<?php echo get_avatar( get_the_author_email(), '20' ); ?>
<?php
function your_prefix_render_hfe_footer() {
if ( function_exists( 'hfe_render_footer' ) ) {
hfe_render_footer();
}
}
add_action( 'astra_footer', 'your_prefix_render_hfe_header' ); ?>
<?php footer_shortcode_elementor() ?>
-----------------------------
in function.php:
add_filter('comment_form_fields', 'wpb_move_comment_field_to_bottom');
if ( ! function_exists( 'WPScripts_enqueue' ) ) {
-----------------------------
<?php
global $post;
$tags = get_the_tags($post->ID);
if (is_array($tags) || is_object($tags)) {
foreach($tags as $tag)
{
echo '<a href="' . get_tag_link($tag->term_id) . '"><span class="badge badge-dark">' . $tag->name . '</span></a> ';
}
}
?>
<?php if (have_posts()): while (have_posts()) : the_post(); ?>
```
Thank you | Here's just a few examples of what escaping looks like:
**Escaping URLS:**
```
<?php echo esc_url( home_url() ); ?>
```
**Escaping Content**
```
<?php echo esc_html( get_the_title() ); ?>
```
**Escaping Attributes**
```
<?php echo esc_attr( $my_class ); ?>
```
**Escaping Content but keep HTML**
```
<?php echo wp_kses_post( get_the_content() ); ?>
```
**Escaping Emails**
```
<?php echo sanitize_email( $email_address ) ); ?>
```
For more information about escaping, [here's a good resource on data sanitization](https://developer.wordpress.org/themes/theme-security/data-sanitization-escaping/). |
360,604 | <p>I dont know what is these mean so can you explain to fix it:</p>
<pre><code>class="home page-template-default page page-id-50 logged-in theme-html5blank-stable woocommerce-no-js ehf-header ehf-footer ehf-template-html5blank-stable ehf-stylesheet-html5blank-stable elementor-default elementor-kit-1715 elementor-page elementor-page-50"
</code></pre>
<p>here is my website link:</p>
<p><a href="http://www.migrate666.deniz-tasarim.site/" rel="nofollow noreferrer">http://www.migrate666.deniz-tasarim.site/</a></p>
<p>Thank you</p>
| [
{
"answer_id": 360607,
"author": "ahmet kaya",
"author_id": 172430,
"author_profile": "https://wordpress.stackexchange.com/users/172430",
"pm_score": 2,
"selected": false,
"text": "<p>Those are the classes echoed by <a href=\"https://developer.wordpress.org/reference/functions/body_class/\" rel=\"nofollow noreferrer\"><code>body_class()</code></a> and the problem was, I called the function outside of the <code><body></code> tag:</p>\n\n<pre><code><body>\n <?php body_class(); ?>\n</code></pre>\n\n<p>So I changed that to:</p>\n\n<pre><code><body <?php body_class(); ?>>\n</code></pre>\n\n<p>And that solved the problem. :)</p>\n"
},
{
"answer_id": 360616,
"author": "HK89",
"author_id": 179278,
"author_profile": "https://wordpress.stackexchange.com/users/179278",
"pm_score": 1,
"selected": true,
"text": "<blockquote>\n <p>It's Used to All class add to wordpress body element Using <em>body_class();</em> function.</p>\n</blockquote>\n\n<p>Specifically, it's used to adding body classes, removing body classes, conditionally adding body classes and some use cases.</p>\n\n<blockquote>\n <p><strong>The Body Class: What Can It Be Used For?</strong></p>\n</blockquote>\n\n<p>The body class in WordPress is a class or series of classes that are applied to the HTML body element. This is useful for applying unique styles to different areas of a WordPress site as body classes can be added conditionally. </p>\n\n<ul>\n<li>This is a really simple way to add body classes and is especially useful if you are creating a theme, using this below code is header.php body element </li>\n</ul>\n\n<blockquote>\n <p>< body <code><?php body_class();</code> ?> ></p>\n</blockquote>\n\n<p><strong>Adding Multiple Body Classes</strong> </p>\n\n<p>There may be times when you want to add more than one body class. This can be achieved using a simple</p>\n\n<blockquote>\n <p><code>< body <?php body_class( array( \"class-one\", \"class-two\", \"class-three\" ) ); ?>></code></p>\n</blockquote>\n\n<p><strong>Conditionally Adding a Body Class</strong></p>\n\n<p>This example uses the WooCommerce conditional method of is_shop() :</p>\n\n<pre><code><?php if ( is_shop() ) { body_class( 'is-woocommerce-shop' ); } else { body_class(); } ?>\n</code></pre>\n\n<p><strong>Adding a Body Class by Filter</strong></p>\n\n<p>It's possible to use a WordPress filter to add a body class, This code can either go in your themes functions.php or within your plugin.</p>\n\n<pre><code>add_filter( 'body_class','my_body_classes' );\nfunction my_body_classes( $classes ) {\n\n $classes[] = 'your-custom-class-name';\n\n return $classes;\n\n}\n</code></pre>\n\n<p><a href=\"https://code.tutsplus.com/tutorials/adding-to-the-body-class-in-wordpress--cms-21077\" rel=\"nofollow noreferrer\">refer Link</a> For More Knowledge</p>\n"
}
] | 2020/03/12 | [
"https://wordpress.stackexchange.com/questions/360604",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/172430/"
] | I dont know what is these mean so can you explain to fix it:
```
class="home page-template-default page page-id-50 logged-in theme-html5blank-stable woocommerce-no-js ehf-header ehf-footer ehf-template-html5blank-stable ehf-stylesheet-html5blank-stable elementor-default elementor-kit-1715 elementor-page elementor-page-50"
```
here is my website link:
<http://www.migrate666.deniz-tasarim.site/>
Thank you | >
> It's Used to All class add to wordpress body element Using *body\_class();* function.
>
>
>
Specifically, it's used to adding body classes, removing body classes, conditionally adding body classes and some use cases.
>
> **The Body Class: What Can It Be Used For?**
>
>
>
The body class in WordPress is a class or series of classes that are applied to the HTML body element. This is useful for applying unique styles to different areas of a WordPress site as body classes can be added conditionally.
* This is a really simple way to add body classes and is especially useful if you are creating a theme, using this below code is header.php body element
>
> < body `<?php body_class();` ?> >
>
>
>
**Adding Multiple Body Classes**
There may be times when you want to add more than one body class. This can be achieved using a simple
>
> `< body <?php body_class( array( "class-one", "class-two", "class-three" ) ); ?>>`
>
>
>
**Conditionally Adding a Body Class**
This example uses the WooCommerce conditional method of is\_shop() :
```
<?php if ( is_shop() ) { body_class( 'is-woocommerce-shop' ); } else { body_class(); } ?>
```
**Adding a Body Class by Filter**
It's possible to use a WordPress filter to add a body class, This code can either go in your themes functions.php or within your plugin.
```
add_filter( 'body_class','my_body_classes' );
function my_body_classes( $classes ) {
$classes[] = 'your-custom-class-name';
return $classes;
}
```
[refer Link](https://code.tutsplus.com/tutorials/adding-to-the-body-class-in-wordpress--cms-21077) For More Knowledge |
360,609 | <p>I am new in WordPress. I would like to know more about wp_query. I have below code in my WordPress site. </p>
<pre><code>$metaquery = array(
'relation' => 'AND',
array(
'relation' => 'AND',
array(
'key' => 'idonate_donor_bloodgroup',
'value' => sanitize_text_field( isset( $_GET['bloodgroup'] ) ? $_GET['bloodgroup'] : '' ),
'compare' => '='
),
array(
'key' => 'idonate_donor_availability',
'value' => sanitize_text_field( isset( $_GET['availability'] ) ? $_GET['availability'] : '' ),
'compare' => '='
),
),
array(
'relation' => 'OR',
array(
'key' => 'idonate_donor_country',
'value' => sanitize_text_field( isset( $_GET['country'] ) ? $_GET['country'] : '' ),
'compare' => '='
),
array(
'key' => 'idonate_donor_state',
'value' => esc_attr( isset( $_GET['state'] ) ? $_GET['state'] : '' ),
'compare' => '='
),
array(
'key' => 'idonate_donor_city',
'value' => esc_attr( isset( $_GET['city'] ) ? $_GET['city'] : '' ),
'compare' => '='
),
)
);
</code></pre>
<p>I would like to know What is the purpose of the <code>key</code> here ? Why should I use it ? How to generate this <code>key</code>? How to use this <code>key</code> ? Can I use anything as <code>key</code> ?</p>
| [
{
"answer_id": 360612,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": false,
"text": "<p><strong><em>Note (to other readers):</strong> If you are looking for a beginner-level guide on WordPress (post) meta queries, have a look at the other answer — or the linked article (written by <a href=\"https://rudrastyh.com/\" rel=\"nofollow noreferrer\">Misha</a>) — and you may also want to read <a href=\"https://wordpress.org/support/article/custom-fields/\" rel=\"nofollow noreferrer\">this article</a> which is a beginner-friendly introduction to custom fields or metadata which what <code>meta_query</code> (WordPress meta queries) is really for.</em></p>\n\n<h3>Original Answer</h3>\n\n<p>This was in reply to the \"<strong>What is the purpose of the <code>key</code> here ? Why should I use it ?</strong>\":</p>\n\n<blockquote>\n <p>That <code>key</code> parameter is the <strong>meta key</strong> (or the custom field's <em>name</em>\n — think of it like post slugs). And without it, WordPress/MySQL\n won't know what meta should be queried for since <code>WP_Query</code> doesn't\n query all (post) meta by default.</p>\n \n <p>You can find all the <code>WP_Query</code> parameters\n <a href=\"https://developer.wordpress.org/reference/classes/wp_query/parse_query/\" rel=\"nofollow noreferrer\">here</a>\n and\n <a href=\"https://developer.wordpress.org/reference/classes/wp_meta_query/__construct/\" rel=\"nofollow noreferrer\">here</a>\n for the <code>meta_query</code> (meta query clauses).</p>\n</blockquote>\n\n<h3>Additional Notes</h3>\n\n<p>These are additional details, which may be useful to you, in addition to the other answer.</p>\n\n<ol>\n<li><p>The <code>meta_query</code> parameter, or WordPress meta queries, are not only used with <code>WP_Query</code> or for searching/filtering posts, but also for searching/filtering terms like the default/built-in Category (<code>category</code>) taxonomy, comments, users, and sites in a Multisite network.</p>\n\n<p>However, the default Custom Fields editor/metabox is only available for posts. For terms, users, etc., you can code your own <em>metabox</em> or use a plugin like Advanced Custom Fields.</p></li>\n<li><p>In reply to the \"<strong>Can I use anything as key ?</strong>\":</p>\n\n<p><em>Yes, basically.</em></p>\n\n<p>But technically, a meta key is limited to <em>a maximum of 255 characters</em> and plugins/themes (and you) can use <a href=\"https://developer.wordpress.org/?s=sanitize_%7B%24object_type%7D_meta_%7B%24meta_key%7D\" rel=\"nofollow noreferrer\">filter hooks</a> to allow/disallow certain characters, limit the key length, etc.</p>\n\n<p>And despite what I said in the original answer (\"think of it like post <em>slugs</em>\"), meta key can actually be like a post <em>title</em> which contains spaces as in <code>Continue Reading</code> or <code>Favorite Music in the 90's</code>.</p></li>\n</ol>\n"
},
{
"answer_id": 360613,
"author": "HK89",
"author_id": 179278,
"author_profile": "https://wordpress.stackexchange.com/users/179278",
"pm_score": 2,
"selected": true,
"text": "<p>Basically meta_query parameter of WP_Query allows you to search WordPress posts / pages / custom post types by their meta data and sort the result.</p>\n\n<p>In this post I assume that you already have basic knowledge how to work with WP_Query class in WordPress. Before I begin, I want to show you some very simple examples. The similar examples you can find in WordPress Codex.</p>\n\n<p>As you know all the posts have the metadata you can populate in \"Custom fields\" metabox (the metabox by the way can be hidden). So, for example, if you want to get a post with meta key show_on_homepage and meta value on, you can do it the following way:</p>\n\n<pre><code>$rd_args = array(\n 'meta_key' => 'show_on_homepage',\n 'meta_value' => 'on'\n);\n\n$rd_query = new WP_Query( $rd_args );\n</code></pre>\n\n<blockquote>\n <ul>\n <li>Query Posts by a Meta Value</li>\n </ul>\n</blockquote>\n\n<p>The simple example below allows you to get all the posts with a specific custom field value. Let’s just get all the posts with custom field name \"color\" and custom field value white.</p>\n\n<pre><code>// the meta_key 'color' with the meta_value 'white'\n$rd_args = array(\n 'meta_query' => array(\n array(\n 'key' => 'color',\n 'value' => 'white'\n )\n )\n);\n\n$rd_query = new WP_Query( $rd_args );\n</code></pre>\n\n<p>If you look at the post edit page (in admin area) in any post which matches the query, you will see the following in the \"Custom Fields\" section:</p>\n\n<p><a href=\"https://i.stack.imgur.com/qybiJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/qybiJ.png\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://rudrastyh.com/wordpress/meta_query.html\" rel=\"nofollow noreferrer\">Refer this link</a> More Knowledge</p>\n"
}
] | 2020/03/13 | [
"https://wordpress.stackexchange.com/questions/360609",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/65189/"
] | I am new in WordPress. I would like to know more about wp\_query. I have below code in my WordPress site.
```
$metaquery = array(
'relation' => 'AND',
array(
'relation' => 'AND',
array(
'key' => 'idonate_donor_bloodgroup',
'value' => sanitize_text_field( isset( $_GET['bloodgroup'] ) ? $_GET['bloodgroup'] : '' ),
'compare' => '='
),
array(
'key' => 'idonate_donor_availability',
'value' => sanitize_text_field( isset( $_GET['availability'] ) ? $_GET['availability'] : '' ),
'compare' => '='
),
),
array(
'relation' => 'OR',
array(
'key' => 'idonate_donor_country',
'value' => sanitize_text_field( isset( $_GET['country'] ) ? $_GET['country'] : '' ),
'compare' => '='
),
array(
'key' => 'idonate_donor_state',
'value' => esc_attr( isset( $_GET['state'] ) ? $_GET['state'] : '' ),
'compare' => '='
),
array(
'key' => 'idonate_donor_city',
'value' => esc_attr( isset( $_GET['city'] ) ? $_GET['city'] : '' ),
'compare' => '='
),
)
);
```
I would like to know What is the purpose of the `key` here ? Why should I use it ? How to generate this `key`? How to use this `key` ? Can I use anything as `key` ? | Basically meta\_query parameter of WP\_Query allows you to search WordPress posts / pages / custom post types by their meta data and sort the result.
In this post I assume that you already have basic knowledge how to work with WP\_Query class in WordPress. Before I begin, I want to show you some very simple examples. The similar examples you can find in WordPress Codex.
As you know all the posts have the metadata you can populate in "Custom fields" metabox (the metabox by the way can be hidden). So, for example, if you want to get a post with meta key show\_on\_homepage and meta value on, you can do it the following way:
```
$rd_args = array(
'meta_key' => 'show_on_homepage',
'meta_value' => 'on'
);
$rd_query = new WP_Query( $rd_args );
```
>
> * Query Posts by a Meta Value
>
>
>
The simple example below allows you to get all the posts with a specific custom field value. Let’s just get all the posts with custom field name "color" and custom field value white.
```
// the meta_key 'color' with the meta_value 'white'
$rd_args = array(
'meta_query' => array(
array(
'key' => 'color',
'value' => 'white'
)
)
);
$rd_query = new WP_Query( $rd_args );
```
If you look at the post edit page (in admin area) in any post which matches the query, you will see the following in the "Custom Fields" section:
[](https://i.stack.imgur.com/qybiJ.png)
[Refer this link](https://rudrastyh.com/wordpress/meta_query.html) More Knowledge |
360,692 | <p>Hello everyone and I found you well, I have a problem with a dynamic site that contains over 200,000 photos, it is a news site. The site is built on the WordPress platform and has many changes to suit our business. In vain I complete the attribute alt for each photo he does not appear live. After many consultations a code must be added to the code attached to this post. My question is, what code should be added and where in this file?
If anyone can help me I would be grateful, thank you!</p>
<pre><code><?php
class home_main_post_below_list extends AQ_Block {
//set and create block
function __construct() {
$block_options = array(
'name' => 'Home main post with below list post',
'size' => 'span12',
);
//create the block
parent::__construct('home_main_post_below_list', $block_options);
}
//create form
function form($instance) {
$titles = isset($instance['titles']) ? esc_attr($instance['titles']) : 'Recent Posts';
$number_show = isset($instance['number_show']) ? absint($instance['number_show']) : 5;
?>
<p><label for="<?php echo $this->get_field_id('titles'); ?>"><?php _e('Title:', 'tl_back'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('titles'); ?>" name="<?php echo $this->get_field_name('titles'); ?>" type="text" value="<?php echo $titles; ?>" /></p>
<p><label for="<?php echo $this->get_field_id('number_show'); ?>"><?php _e('Number of posts to show:', 'tl_back'); ?></label>
<input id="<?php echo $this->get_field_id('number_show'); ?>" name="<?php echo $this->get_field_name('number_show'); ?>" type="text" value="<?php echo $number_show; ?>" size="3" /></p>
<label for="<?php echo $this->get_field_id('cats'); ?>"><?php _e('Select categories to include in the recent posts list:', 'tl_back'); ?>
<?php
$categories = get_categories('hide_empty=0');
echo "<br/>";
foreach ($categories as $cat) {
$option = '<input type="checkbox" id="' . $this->get_field_id('cats') . '[]" name="' . $this->get_field_name('cats') . '[]"';
if (isset($instance['cats'])) {
foreach ($instance['cats'] as $cats) {
if ($cats == $cat->term_id) {
$option = $option . ' checked="checked"';
}
}
}
$option .= ' value="' . $cat->term_id . '" />';
$option .= '&nbsp;';
$option .= $cat->cat_name;
$option .= '<br />';
echo $option;
}
?>
</label>
<?php
}
//create block
function block($instance) {
extract($instance);
$titles = apply_filters('widget_title', empty($instance['titles']) ? 'Recent Posts' : $instance['titles'], $instance, $this->id_base);
if (!isset($instance["cats"])) {
$cats = '';}
// array to call recent posts.
$themeloy_args = array(
'showposts' => $number_show,
'category__in' => $cats,
);
$themeloy_widget = null;
$themeloy_widget = new WP_Query($themeloy_args);
?>
<div class="widget post_list_medium_widget">
<?php if (!empty($instance['titles'])) {?><h3 class="widget-title"><span><?php echo $instance["titles"];?></span></h3><?php }?>
<div class="widget_container">
<div class="post_list_medium">
<?php
$i = 0;
while ($themeloy_widget->have_posts()) {
$i++;
$themeloy_widget->the_post();
$post_id = get_the_ID();
$thumb = themeloy_get_thumbnail(get_the_ID());
if ($i == 1) {
?>
<div class="list_item">
<div class="entry-thumb feature-item">
<a href="<?php the_permalink(); ?>">
<?php if ( has_post_thumbnail()) {
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post_id ), 'feature-large' );
?>
<img class="cat-feature-large-img" src="<?php echo $image[0]; ?>"/>
<?php }else{echo '<img class="cat-feature-large-img" src="'.get_template_directory_uri().'/images/demo/feature-large.jpg'.'">';} ?>
</a>
<div class="cat-feature-large">
<?php $post_cat = get_post_custom_values('cat_themeloy_select', get_the_ID());
$post_cat = ($post_cat[0] != '') ? $post_cat[0] : of_get_option('blog_category_post');
if($post_cat == '1'){echo '<p class="cat-slider">'; echo the_category(', ').'</p>';}?>
</div>
<?php echo themeloy_post_type(); ?>
</div>
<h2><a href="<?php the_permalink(); ?>" class="title"><?php the_title(); ?></a></h2>
<?php echo themeloy_post_meta(get_the_ID());?>
<p><?php echo themeloy_short_title(320, get_the_excerpt('')); ?> </p>
</div>
<div class="clear margin-buttons"></div>
<?php }else{?>
<div class="small-list-content">
<?php
$post_date = get_post_custom_values('date_themeloy_select', get_the_ID());
$post_date = ($post_date[0] != '') ? $post_date[0] : of_get_option('blog_date_post');
if($post_date == '1'){
?>
<div class="feature_post_style">
<span class="post_date"><span class="date_number"><?php echo get_the_date('d');?></span> <?php echo get_the_date('M');?>
<i class="icon-caret-right feature-icon-right"></i>
</span>
<span class="post_time"><i class="icon-time"></i> <?php echo get_the_time('H:i');?></span>
</div>
<?php }?>
<div class="feature-link feature-item">
<a href="<?php the_permalink(); ?>" class="feature-link">
<?php if ( has_post_thumbnail()) {
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post_id ), 'medium-feature' );
?>
<img src="<?php echo $image[0]; ?>"/>
<?php }else{echo '<img src="'.get_template_directory_uri().'/images/demo/medium-feature.jpg'.'">';} ?>
</a>
<?php echo themeloy_post_type(); ?>
</div>
<div class="list_desc">
<h4 class="list_title"><a class="post-title" href="<?php the_permalink(); ?>" rel="bookmark" title="<?php the_title_attribute(); ?>">
<?php the_title(); ?>
</a></h4>
<?php echo themeloy_post_meta(get_the_ID());?>
</div>
<div class="clear"></div>
</div>
<?php }}?>
</div>
</div>
</div>
<?php
wp_reset_query();
}
function update($new_instance, $old_instance) {
return $new_instance;
}
}
</code></pre>
| [
{
"answer_id": 360612,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": false,
"text": "<p><strong><em>Note (to other readers):</strong> If you are looking for a beginner-level guide on WordPress (post) meta queries, have a look at the other answer — or the linked article (written by <a href=\"https://rudrastyh.com/\" rel=\"nofollow noreferrer\">Misha</a>) — and you may also want to read <a href=\"https://wordpress.org/support/article/custom-fields/\" rel=\"nofollow noreferrer\">this article</a> which is a beginner-friendly introduction to custom fields or metadata which what <code>meta_query</code> (WordPress meta queries) is really for.</em></p>\n\n<h3>Original Answer</h3>\n\n<p>This was in reply to the \"<strong>What is the purpose of the <code>key</code> here ? Why should I use it ?</strong>\":</p>\n\n<blockquote>\n <p>That <code>key</code> parameter is the <strong>meta key</strong> (or the custom field's <em>name</em>\n — think of it like post slugs). And without it, WordPress/MySQL\n won't know what meta should be queried for since <code>WP_Query</code> doesn't\n query all (post) meta by default.</p>\n \n <p>You can find all the <code>WP_Query</code> parameters\n <a href=\"https://developer.wordpress.org/reference/classes/wp_query/parse_query/\" rel=\"nofollow noreferrer\">here</a>\n and\n <a href=\"https://developer.wordpress.org/reference/classes/wp_meta_query/__construct/\" rel=\"nofollow noreferrer\">here</a>\n for the <code>meta_query</code> (meta query clauses).</p>\n</blockquote>\n\n<h3>Additional Notes</h3>\n\n<p>These are additional details, which may be useful to you, in addition to the other answer.</p>\n\n<ol>\n<li><p>The <code>meta_query</code> parameter, or WordPress meta queries, are not only used with <code>WP_Query</code> or for searching/filtering posts, but also for searching/filtering terms like the default/built-in Category (<code>category</code>) taxonomy, comments, users, and sites in a Multisite network.</p>\n\n<p>However, the default Custom Fields editor/metabox is only available for posts. For terms, users, etc., you can code your own <em>metabox</em> or use a plugin like Advanced Custom Fields.</p></li>\n<li><p>In reply to the \"<strong>Can I use anything as key ?</strong>\":</p>\n\n<p><em>Yes, basically.</em></p>\n\n<p>But technically, a meta key is limited to <em>a maximum of 255 characters</em> and plugins/themes (and you) can use <a href=\"https://developer.wordpress.org/?s=sanitize_%7B%24object_type%7D_meta_%7B%24meta_key%7D\" rel=\"nofollow noreferrer\">filter hooks</a> to allow/disallow certain characters, limit the key length, etc.</p>\n\n<p>And despite what I said in the original answer (\"think of it like post <em>slugs</em>\"), meta key can actually be like a post <em>title</em> which contains spaces as in <code>Continue Reading</code> or <code>Favorite Music in the 90's</code>.</p></li>\n</ol>\n"
},
{
"answer_id": 360613,
"author": "HK89",
"author_id": 179278,
"author_profile": "https://wordpress.stackexchange.com/users/179278",
"pm_score": 2,
"selected": true,
"text": "<p>Basically meta_query parameter of WP_Query allows you to search WordPress posts / pages / custom post types by their meta data and sort the result.</p>\n\n<p>In this post I assume that you already have basic knowledge how to work with WP_Query class in WordPress. Before I begin, I want to show you some very simple examples. The similar examples you can find in WordPress Codex.</p>\n\n<p>As you know all the posts have the metadata you can populate in \"Custom fields\" metabox (the metabox by the way can be hidden). So, for example, if you want to get a post with meta key show_on_homepage and meta value on, you can do it the following way:</p>\n\n<pre><code>$rd_args = array(\n 'meta_key' => 'show_on_homepage',\n 'meta_value' => 'on'\n);\n\n$rd_query = new WP_Query( $rd_args );\n</code></pre>\n\n<blockquote>\n <ul>\n <li>Query Posts by a Meta Value</li>\n </ul>\n</blockquote>\n\n<p>The simple example below allows you to get all the posts with a specific custom field value. Let’s just get all the posts with custom field name \"color\" and custom field value white.</p>\n\n<pre><code>// the meta_key 'color' with the meta_value 'white'\n$rd_args = array(\n 'meta_query' => array(\n array(\n 'key' => 'color',\n 'value' => 'white'\n )\n )\n);\n\n$rd_query = new WP_Query( $rd_args );\n</code></pre>\n\n<p>If you look at the post edit page (in admin area) in any post which matches the query, you will see the following in the \"Custom Fields\" section:</p>\n\n<p><a href=\"https://i.stack.imgur.com/qybiJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/qybiJ.png\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://rudrastyh.com/wordpress/meta_query.html\" rel=\"nofollow noreferrer\">Refer this link</a> More Knowledge</p>\n"
}
] | 2020/03/14 | [
"https://wordpress.stackexchange.com/questions/360692",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/184266/"
] | Hello everyone and I found you well, I have a problem with a dynamic site that contains over 200,000 photos, it is a news site. The site is built on the WordPress platform and has many changes to suit our business. In vain I complete the attribute alt for each photo he does not appear live. After many consultations a code must be added to the code attached to this post. My question is, what code should be added and where in this file?
If anyone can help me I would be grateful, thank you!
```
<?php
class home_main_post_below_list extends AQ_Block {
//set and create block
function __construct() {
$block_options = array(
'name' => 'Home main post with below list post',
'size' => 'span12',
);
//create the block
parent::__construct('home_main_post_below_list', $block_options);
}
//create form
function form($instance) {
$titles = isset($instance['titles']) ? esc_attr($instance['titles']) : 'Recent Posts';
$number_show = isset($instance['number_show']) ? absint($instance['number_show']) : 5;
?>
<p><label for="<?php echo $this->get_field_id('titles'); ?>"><?php _e('Title:', 'tl_back'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('titles'); ?>" name="<?php echo $this->get_field_name('titles'); ?>" type="text" value="<?php echo $titles; ?>" /></p>
<p><label for="<?php echo $this->get_field_id('number_show'); ?>"><?php _e('Number of posts to show:', 'tl_back'); ?></label>
<input id="<?php echo $this->get_field_id('number_show'); ?>" name="<?php echo $this->get_field_name('number_show'); ?>" type="text" value="<?php echo $number_show; ?>" size="3" /></p>
<label for="<?php echo $this->get_field_id('cats'); ?>"><?php _e('Select categories to include in the recent posts list:', 'tl_back'); ?>
<?php
$categories = get_categories('hide_empty=0');
echo "<br/>";
foreach ($categories as $cat) {
$option = '<input type="checkbox" id="' . $this->get_field_id('cats') . '[]" name="' . $this->get_field_name('cats') . '[]"';
if (isset($instance['cats'])) {
foreach ($instance['cats'] as $cats) {
if ($cats == $cat->term_id) {
$option = $option . ' checked="checked"';
}
}
}
$option .= ' value="' . $cat->term_id . '" />';
$option .= ' ';
$option .= $cat->cat_name;
$option .= '<br />';
echo $option;
}
?>
</label>
<?php
}
//create block
function block($instance) {
extract($instance);
$titles = apply_filters('widget_title', empty($instance['titles']) ? 'Recent Posts' : $instance['titles'], $instance, $this->id_base);
if (!isset($instance["cats"])) {
$cats = '';}
// array to call recent posts.
$themeloy_args = array(
'showposts' => $number_show,
'category__in' => $cats,
);
$themeloy_widget = null;
$themeloy_widget = new WP_Query($themeloy_args);
?>
<div class="widget post_list_medium_widget">
<?php if (!empty($instance['titles'])) {?><h3 class="widget-title"><span><?php echo $instance["titles"];?></span></h3><?php }?>
<div class="widget_container">
<div class="post_list_medium">
<?php
$i = 0;
while ($themeloy_widget->have_posts()) {
$i++;
$themeloy_widget->the_post();
$post_id = get_the_ID();
$thumb = themeloy_get_thumbnail(get_the_ID());
if ($i == 1) {
?>
<div class="list_item">
<div class="entry-thumb feature-item">
<a href="<?php the_permalink(); ?>">
<?php if ( has_post_thumbnail()) {
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post_id ), 'feature-large' );
?>
<img class="cat-feature-large-img" src="<?php echo $image[0]; ?>"/>
<?php }else{echo '<img class="cat-feature-large-img" src="'.get_template_directory_uri().'/images/demo/feature-large.jpg'.'">';} ?>
</a>
<div class="cat-feature-large">
<?php $post_cat = get_post_custom_values('cat_themeloy_select', get_the_ID());
$post_cat = ($post_cat[0] != '') ? $post_cat[0] : of_get_option('blog_category_post');
if($post_cat == '1'){echo '<p class="cat-slider">'; echo the_category(', ').'</p>';}?>
</div>
<?php echo themeloy_post_type(); ?>
</div>
<h2><a href="<?php the_permalink(); ?>" class="title"><?php the_title(); ?></a></h2>
<?php echo themeloy_post_meta(get_the_ID());?>
<p><?php echo themeloy_short_title(320, get_the_excerpt('')); ?> </p>
</div>
<div class="clear margin-buttons"></div>
<?php }else{?>
<div class="small-list-content">
<?php
$post_date = get_post_custom_values('date_themeloy_select', get_the_ID());
$post_date = ($post_date[0] != '') ? $post_date[0] : of_get_option('blog_date_post');
if($post_date == '1'){
?>
<div class="feature_post_style">
<span class="post_date"><span class="date_number"><?php echo get_the_date('d');?></span> <?php echo get_the_date('M');?>
<i class="icon-caret-right feature-icon-right"></i>
</span>
<span class="post_time"><i class="icon-time"></i> <?php echo get_the_time('H:i');?></span>
</div>
<?php }?>
<div class="feature-link feature-item">
<a href="<?php the_permalink(); ?>" class="feature-link">
<?php if ( has_post_thumbnail()) {
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post_id ), 'medium-feature' );
?>
<img src="<?php echo $image[0]; ?>"/>
<?php }else{echo '<img src="'.get_template_directory_uri().'/images/demo/medium-feature.jpg'.'">';} ?>
</a>
<?php echo themeloy_post_type(); ?>
</div>
<div class="list_desc">
<h4 class="list_title"><a class="post-title" href="<?php the_permalink(); ?>" rel="bookmark" title="<?php the_title_attribute(); ?>">
<?php the_title(); ?>
</a></h4>
<?php echo themeloy_post_meta(get_the_ID());?>
</div>
<div class="clear"></div>
</div>
<?php }}?>
</div>
</div>
</div>
<?php
wp_reset_query();
}
function update($new_instance, $old_instance) {
return $new_instance;
}
}
``` | Basically meta\_query parameter of WP\_Query allows you to search WordPress posts / pages / custom post types by their meta data and sort the result.
In this post I assume that you already have basic knowledge how to work with WP\_Query class in WordPress. Before I begin, I want to show you some very simple examples. The similar examples you can find in WordPress Codex.
As you know all the posts have the metadata you can populate in "Custom fields" metabox (the metabox by the way can be hidden). So, for example, if you want to get a post with meta key show\_on\_homepage and meta value on, you can do it the following way:
```
$rd_args = array(
'meta_key' => 'show_on_homepage',
'meta_value' => 'on'
);
$rd_query = new WP_Query( $rd_args );
```
>
> * Query Posts by a Meta Value
>
>
>
The simple example below allows you to get all the posts with a specific custom field value. Let’s just get all the posts with custom field name "color" and custom field value white.
```
// the meta_key 'color' with the meta_value 'white'
$rd_args = array(
'meta_query' => array(
array(
'key' => 'color',
'value' => 'white'
)
)
);
$rd_query = new WP_Query( $rd_args );
```
If you look at the post edit page (in admin area) in any post which matches the query, you will see the following in the "Custom Fields" section:
[](https://i.stack.imgur.com/qybiJ.png)
[Refer this link](https://rudrastyh.com/wordpress/meta_query.html) More Knowledge |
360,708 | <p>I want to write a class to the body of all pages posts and custom posts (IE entire site)</p>
<p>I am using a front end editor that allows logged in users to edit posts and keep them out of the back-end.</p>
<ul>
<li>I have a custom post-type "emergency status"</li>
<li>It contains one post with a taxonomy "status"</li>
<li>It has the terms extreme, severe, very-high, high, moderate.</li>
</ul>
<p>I want to add a filter that checks the taxonomy of that post and then adds it to the body of the site.</p>
| [
{
"answer_id": 360711,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 0,
"selected": false,
"text": "<p>WordPress already does this if your theme has been built correctly. Specifically, WP will add classes to the body tag if you used <code>body_class</code> and to the posts containing element if you used <code>post_class</code></p>\n\n<p>For example, if you install WordPress, the default Hello World post is uncategorized, and has the following classes:</p>\n\n<pre><code>post-1 post type-post status-publish format-standard hentry category-uncategorized entry\n</code></pre>\n\n<p>Notice the <code>category-uncategorized</code> class.</p>\n\n<p>Similarly the <code><body></code> tag has these classes:</p>\n\n<pre><code>post-template-default single single-post postid-1 single-format-standard wp-embed-responsive singular image-filters-enabled\n</code></pre>\n\n<p>Other classes get added depending on the context, e.g. a class gets added if the admin toolbar is showing, or if the user is logged in, etc</p>\n"
},
{
"answer_id": 360714,
"author": "HK89",
"author_id": 179278,
"author_profile": "https://wordpress.stackexchange.com/users/179278",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <ul>\n <li><p>You can use the body_class filter in WordPress to add the Taxonomy Terms of a Custom Taxonomy as CSS classes to a post. The CSS class appears in the body element and is only used if the post has been assigned to the taxonomy.</p></li>\n <li><p>The code goes in your functions.php file.</p></li>\n </ul>\n</blockquote>\n\n<pre><code>add_filter( 'body_class', 'themeprefix_add_taxonomy_class' );\n // Add taxonomy terms name to body class\nfunction themeprefix_add_taxonomy_class( $classes ){\n if( is_singular() ) {\n global $post;\n $taxonomy_terms = get_the_terms($post->ID, 'your_taxonomy'); // change to your taxonomy\n if ( $taxonomy_terms ) {\n foreach ( $taxonomy_terms as $taxonomy_term ) {\n $classes[] = 'tax_' . $taxonomy_term->slug;\n }\n }\n }\n return $classes;\n}\n</code></pre>\n\n<ul>\n<li>Change ‘your_taxonomy’ to the actual taxonomy, the body_class filter is fed the results from a foreach loop done on the custom taxonomy, if any of the terms of that custom taxonomy are used by the post, they are added to the $classes array, in the above instance they have a prefix of ‘tax_’ followed by the term – you can change this prefix to suit or simply not have one.</li>\n</ul>\n"
}
] | 2020/03/14 | [
"https://wordpress.stackexchange.com/questions/360708",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/125332/"
] | I want to write a class to the body of all pages posts and custom posts (IE entire site)
I am using a front end editor that allows logged in users to edit posts and keep them out of the back-end.
* I have a custom post-type "emergency status"
* It contains one post with a taxonomy "status"
* It has the terms extreme, severe, very-high, high, moderate.
I want to add a filter that checks the taxonomy of that post and then adds it to the body of the site. | >
> * You can use the body\_class filter in WordPress to add the Taxonomy Terms of a Custom Taxonomy as CSS classes to a post. The CSS class appears in the body element and is only used if the post has been assigned to the taxonomy.
> * The code goes in your functions.php file.
>
>
>
```
add_filter( 'body_class', 'themeprefix_add_taxonomy_class' );
// Add taxonomy terms name to body class
function themeprefix_add_taxonomy_class( $classes ){
if( is_singular() ) {
global $post;
$taxonomy_terms = get_the_terms($post->ID, 'your_taxonomy'); // change to your taxonomy
if ( $taxonomy_terms ) {
foreach ( $taxonomy_terms as $taxonomy_term ) {
$classes[] = 'tax_' . $taxonomy_term->slug;
}
}
}
return $classes;
}
```
* Change ‘your\_taxonomy’ to the actual taxonomy, the body\_class filter is fed the results from a foreach loop done on the custom taxonomy, if any of the terms of that custom taxonomy are used by the post, they are added to the $classes array, in the above instance they have a prefix of ‘tax\_’ followed by the term – you can change this prefix to suit or simply not have one. |
360,709 | <p>I have two coupons, one $10 another $5. I want do next, if price be less $50 and customer enter discount coupon $10 replace this coupon by coupon $5.</p>
<p><strong>Example:</strong></p>
<p>The customer added an item in cart with total price $40 and he applied the coupon $10-Off. Now I need replace current coupon with $10-Off to my another coupon $5-Off and continue checkout.</p>
<p>What is the best and simple way I can use? I try change discount price like in code below and this working, but in other places WC show me old coupon and calculate all data from old coupon (in order page etc) so I really need <strong>REPLACE</strong> one coupon to another ( not calculate their price ) when this coupon added. It like customer enter $5-Off coupon directly to discount field</p>
<pre><code>// Change price for discount
if( ! function_exists('custom_discount') ){
function custom_discount( $price, $values, $instance ) {
//$price represents the current product price without discount
//$values represents the product object
//$instance represent the cart object
//Get subtotal
$subtotal = WC()->cart->get_subtotal();
$coupon = WC()->cart->get_discount_total();
//if price < 50 and we have active coupon then we need decrease price to $5
if( $subtotal < 50 && ! empty( WC()->cart->get_applied_coupons() ) ){
$price = $subtotal - 5; //Wrong way ...
}
return $price;
}
add_filter( 'woocommerce_get_discounted_price', 'custom_discount', 10, 3);
}
</code></pre>
| [
{
"answer_id": 360977,
"author": "Dragos Micu",
"author_id": 110131,
"author_profile": "https://wordpress.stackexchange.com/users/110131",
"pm_score": 0,
"selected": false,
"text": "<p>I have tested this and can confirm that it works, even after you change the products in the cart to be either below or over $50.</p>\n\n<pre><code><?php\n/**\n * @snippet Add / Remove A Coupon Dynamically based on Cart Subtotal with WooCommerce\n * @sourcecode http://wpharvest.com\n * @author Dragos Micu\n * @compatible WooCommerce 2.4.7\n */\nadd_action( 'woocommerce_calculate_totals', 'wpharvest_apply_coupons' );\nfunction wpharvest_apply_coupons($cart) {\n global $woocommerce;\n // Set your coupon codes\n $coupon10off = '$10-Off';\n $coupon5off = '$5-Off';\n\n // Get the cart subtotal\n $cart_subtotal = $cart->subtotal;\n // If cart subtotal is less than 50 add or remove coupons\n if ($cart_subtotal < 50) {\n if ( $woocommerce->cart->has_discount( $coupon10off ) ) {\n WC()->cart->remove_coupon( $coupon10off );\n $woocommerce->cart->add_discount( $coupon5off );\n }\n }\n // If cart subtotal is greater 49 add or remove coupons\n if ($cart_subtotal > 49 ) {\n if ( $woocommerce->cart->has_discount( $coupon5off ) ) {\n WC()->cart->remove_coupon( $coupon5off );\n $woocommerce->cart->add_discount( $coupon10off );\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 361044,
"author": "LoicTheAztec",
"author_id": 79855,
"author_profile": "https://wordpress.stackexchange.com/users/79855",
"pm_score": 2,
"selected": true,
"text": "<p>This requires to use an action hook like <code>woocommerce_calculate_totals</code> that is related to cart and <strong>Ajax enabled</strong>, because it will handle all changes made by the customer in cart page:</p>\n\n<pre><code>add_action( 'woocommerce_calculate_totals', 'discount_based_on_cart_subtotal', 10, 1 );\nfunction discount_based_on_cart_subtotal( $cart ) {\n if ( is_admin() && ! defined( 'DOING_AJAX' ) )\n return;\n\n // Avoiding hook repetitions\n if ( did_action( 'woocommerce_calculate_totals' ) >= 2 )\n return;\n\n // Your coupons settings below\n $coupon_05_off = '$5-Off';\n $coupon_10_off = '$10-Off';\n\n // When cart subtotal is below 50\n if ( $cart->subtotal < 50 ) {\n if ( $cart->has_discount( $coupon_10_off ) ) {\n $cart->remove_coupon( $coupon_10_off ); // Remove $10.00 fixed discount coupon\n if ( ! $cart->has_discount( $coupon_05_off ) ) {\n $cart->apply_coupon( $coupon_05_off ); // Add $5.00 fixed discount coupon\n }\n }\n\n }\n // When cart subtotal is up to 50\n else {\n if ( $cart->has_discount( $coupon_05_off ) ) {\n $cart->remove_coupon( $coupon_05_off ); // Remove $5.00 fixed discount coupon\n if ( ! $cart->has_discount( $coupon_10_off ) ) {\n $cart->apply_coupon( $coupon_10_off ); // Add $10.00 fixed discount coupon\n }\n }\n }\n}\n</code></pre>\n\n<p>Code goes in functions.php file of your active child theme (or active theme). Tested and work.</p>\n"
}
] | 2020/03/14 | [
"https://wordpress.stackexchange.com/questions/360709",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/51770/"
] | I have two coupons, one $10 another $5. I want do next, if price be less $50 and customer enter discount coupon $10 replace this coupon by coupon $5.
**Example:**
The customer added an item in cart with total price $40 and he applied the coupon $10-Off. Now I need replace current coupon with $10-Off to my another coupon $5-Off and continue checkout.
What is the best and simple way I can use? I try change discount price like in code below and this working, but in other places WC show me old coupon and calculate all data from old coupon (in order page etc) so I really need **REPLACE** one coupon to another ( not calculate their price ) when this coupon added. It like customer enter $5-Off coupon directly to discount field
```
// Change price for discount
if( ! function_exists('custom_discount') ){
function custom_discount( $price, $values, $instance ) {
//$price represents the current product price without discount
//$values represents the product object
//$instance represent the cart object
//Get subtotal
$subtotal = WC()->cart->get_subtotal();
$coupon = WC()->cart->get_discount_total();
//if price < 50 and we have active coupon then we need decrease price to $5
if( $subtotal < 50 && ! empty( WC()->cart->get_applied_coupons() ) ){
$price = $subtotal - 5; //Wrong way ...
}
return $price;
}
add_filter( 'woocommerce_get_discounted_price', 'custom_discount', 10, 3);
}
``` | This requires to use an action hook like `woocommerce_calculate_totals` that is related to cart and **Ajax enabled**, because it will handle all changes made by the customer in cart page:
```
add_action( 'woocommerce_calculate_totals', 'discount_based_on_cart_subtotal', 10, 1 );
function discount_based_on_cart_subtotal( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Avoiding hook repetitions
if ( did_action( 'woocommerce_calculate_totals' ) >= 2 )
return;
// Your coupons settings below
$coupon_05_off = '$5-Off';
$coupon_10_off = '$10-Off';
// When cart subtotal is below 50
if ( $cart->subtotal < 50 ) {
if ( $cart->has_discount( $coupon_10_off ) ) {
$cart->remove_coupon( $coupon_10_off ); // Remove $10.00 fixed discount coupon
if ( ! $cart->has_discount( $coupon_05_off ) ) {
$cart->apply_coupon( $coupon_05_off ); // Add $5.00 fixed discount coupon
}
}
}
// When cart subtotal is up to 50
else {
if ( $cart->has_discount( $coupon_05_off ) ) {
$cart->remove_coupon( $coupon_05_off ); // Remove $5.00 fixed discount coupon
if ( ! $cart->has_discount( $coupon_10_off ) ) {
$cart->apply_coupon( $coupon_10_off ); // Add $10.00 fixed discount coupon
}
}
}
}
```
Code goes in functions.php file of your active child theme (or active theme). Tested and work. |
360,721 | <p>I'm writing a simple plugin that shows on pages/posts a form with customized style for input fields, checkboxes, buttons, etc... via a shortcode. When user writes the shortcode in the page, it generates some CSS, some HTML and some JavaScript but result is not rendered as I want I think because of active theme CSS.
In fact if I wrote the same combination of CSS, HTML and JavaScript in a simple HTML file rendering is perfect and if, in WordPress, I change theme, rendering changes...</p>
<p>How can I prevent the active theme from interfering with my plugin by rendering the controls as if they were inserted in a simple HTML page?</p>
<p><strong>EDIT, added code:</strong></p>
<pre><code> <div class="chatbox-container">
<button class="chatbox-open">
<i class="fa fa-comment fa-2x" aria-hidden="true"></i>
</button>
<button class="chatbox-close">
<i class="fa fa-close fa-2x" aria-hidden="true"></i>
</button>
<section class="chatbox-popup">
<header class="chatbox-popup__header">
<aside style="flex:3">
<i class="fa fa-user-circle fa-4x chatbox-popup__avatar" aria-hidden="true"></i>
</aside>
<aside style="flex:8">
<h1>Tal Dei Tal</h1> Seller (Online)
</aside>
<aside style="flex:1">
<button class="chatbox-maximize"><i class="fa fa-window-maximize" aria-hidden="true"></i></button>
</aside>
</header>
<main class="chatbox-popup__main">
Some sample text, here GDPR terms...
</main>
<footer class="chatbox-popup__footer">
<aside style="flex:1;color:#888;text-align:center;">
<i class="fa fa-camera" aria-hidden="true"></i>
</aside>
<aside style="flex:10">
<textarea type="text" placeholder="Type your message here..." autofocus></textarea>
</aside>
<aside style="flex:1;color:#888;text-align:center;">
<i class="fa fa-paper-plane" aria-hidden="true"></i>
</aside>
</footer>
</section>
<section class="chatbox-panel">
<header class="chatbox-panel__header">
<aside style="flex:3">
<i class="fa fa-user-circle fa-3x chatbox-popup__avatar" aria-hidden="true"></i>
</aside>
<aside style="flex:6">
<h1>Tal Dei Tali</h1> Seller (Online)
</aside>
<aside style="flex:3;text-align:right;">
<button class="chatbox-minimize"><i class="fa fa-window-restore" aria-hidden="true"></i></button>
<button class="chatbox-panel-close"><i class="fa fa-close" aria-hidden="true"></i></button>
</aside>
</header>
<main class="chatbox-panel__main" style="flex:1">
Some sample text, here GDPR terms...
</main>
<footer class="chatbox-panel__footer">
<aside style="flex:1;color:#888;text-align:center;">
<i class="fa fa-camera" aria-hidden="true"></i>
</aside>
<aside style="flex:10">
<textarea type="text" placeholder="Type your message here..." autofocus></textarea>
</aside>
<aside style="flex:1;color:#888;text-align:center;">
<i class="fa fa-paper-plane" aria-hidden="true"></i>
</aside>
</footer>
</section>
</div>
<style type="text/css">
.chatbox-container {
all: initial;
font-family: "Lato", sans-serif;
}
.chatbox-container h1 {
margin: 0;
font-size: 16px;
line-height: 1;
}
.chatbox-container button {
color: inherit;
background-color: transparent;
border: 0;
outline: 0 !important;
cursor: pointer;
}
.chatbox-container button.chatbox-open {
position: fixed;
bottom: 0;
right: 0;
width: 52px;
height: 52px;
color: #fff;
background-color: #0360a5;
background-position: center center;
background-repeat: no-repeat;
box-shadow: 12px 15px 20px 0 rgba(46, 61, 73, 0.15);
border: 0;
border-radius: 50%;
cursor: pointer;
margin: 16px;
}
.chatbox-container button.chatbox-close {
position: fixed;
bottom: 0;
right: 0;
width: 52px;
height: 52px;
color: #fff;
background-color: #0360a5;
background-position: center center;
background-repeat: no-repeat;
box-shadow: 12px 15px 20px 0 rgba(46, 61, 73, 0.15);
border: 0;
border-radius: 50%;
cursor: pointer;
display: none;
margin: 16px calc(2 * 16px + 52px) 16px 16px;
}
.chatbox-container textarea {
box-sizing: border-box;
width: 100%;
margin: 0;
height: calc(16px + 16px / 2);
padding: 0 calc(16px / 2);
font-family: inherit;
font-size: 16px;
line-height: calc(16px + 16px / 2);
color: #888;
background-color: none;
border: 0;
outline: 0 !important;
resize: none;
overflow: hidden;
}
.chatbox-container textarea::-webkit-input-placeholder {
color: #888;
}
.chatbox-container textarea::-moz-placeholder {
color: #888;
}
.chatbox-container textarea:-ms-input-placeholder {
color: #888;
}
.chatbox-container textarea::-ms-input-placeholder {
color: #888;
}
.chatbox-container textarea::placeholder {
color: #888;
}
.chatbox-container .chatbox-popup {
display: -webkit-box;
display: flex;
position: fixed;
box-shadow: 5px 5px 25px 0 rgba(46, 61, 73, 0.2);
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
flex-direction: column;
display: none;
bottom: calc(2 * 16px + 52px);
right: 16px;
width: 377px;
height: auto;
background-color: #fff;
border-radius: 16px;
}
.chatbox-container .chatbox-popup .chatbox-popup__header {
box-sizing: border-box;
display: -webkit-box;
display: flex;
width: 100%;
padding: 16px;
color: #fff;
background-color: #0360a5;
-webkit-box-align: center;
align-items: center;
justify-content: space-around;
border-top-right-radius: 12px;
border-top-left-radius: 12px;
}
.chatbox-container .chatbox-popup .chatbox-popup__header .chatbox-popup__avatar {
margin-top: -32px;
background-color: #0360a5;
border: 5px solid rgba(0, 0, 0, 0.1);
border-radius: 50%;
}
.chat-container .chatbox-popup .chatbox-popup__main {
box-sizing: border-box;
width: 100%;
padding: calc(2 * 16px) 16px;
line-height: calc(16px + 16px / 2);
color: #888;
text-align: center;
}
.chatbox-container .chatbox-popup .chatbox-popup__footer {
box-sizing: border-box;
display: -webkit-box;
display: flex;
width: 100%;
padding: 16px;
border-top: 1px solid #ddd;
-webkit-box-align: center;
align-items: center;
justify-content: space-around;
border-bottom-right-radius: 12px;
border-bottom-left-radius: 12px;
}
.chatbox-container .chatbox-panel {
display: -webkit-box;
display: flex;
position: fixed;
box-shadow: 5px 5px 25px 0 rgba(46, 61, 73, 0.2);
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
flex-direction: column;
display: none;
top: 0;
right: 0;
bottom: 0;
width: 377px;
background-color: #fff;
}
.chatbox-container .chatbox-panel .chatbox-panel__header {
box-sizing: border-box;
display: -webkit-box;
display: flex;
width: 100%;
padding: 16px;
color: #fff;
background-color: #0360a5;
-webkit-box-align: center;
align-items: center;
justify-content: space-around;
-webkit-box-flex: 0;
flex: 0 0 auto;
}
.chatbox-container .chatbox-panel .chatbox-panel__main {
box-sizing: border-box;
width: 100%;
padding: calc(2 * 16px) 16px;
line-height: calc(16px + 16px / 2);
color: #888;
text-align: center;
-webkit-box-flex: 1;
flex: 1 1 auto;
}
.chatbox-container .chatbox-panel .chatbox-panel__footer {
box-sizing: border-box;
display: -webkit-box;
display: flex;
width: 100%;
padding: 16px;
border-top: 1px solid #ddd;
-webkit-box-align: center;
align-items: center;
justify-content: space-around;
-webkit-box-flex: 0;
flex: 0 0 auto;
}
</style>
</code></pre>
| [
{
"answer_id": 360739,
"author": "Davood Denavi",
"author_id": 184294,
"author_profile": "https://wordpress.stackexchange.com/users/184294",
"pm_score": -1,
"selected": false,
"text": "<p>I'd suggest looking at using a custom theme if you want to ignore CSS from your theme and them using plugins to get the functionality that is offered by your theme. Here is an article that will help you do this without any code: <a href=\"https://www.wpbeginner.com/wp-themes/how-to-easily-create-a-custom-wordpress-theme/\" rel=\"nofollow noreferrer\">https://www.wpbeginner.com/wp-themes/how-to-easily-create-a-custom-wordpress-theme/</a></p>\n\n<p>The other option if there are only some css elements you want to overwrite the properties of would be to tag things with !important. However, use of the !important tag is highly discouraged.</p>\n"
},
{
"answer_id": 360741,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 1,
"selected": false,
"text": "<p>You can make sure that your CSS is <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">enqueued</a> after your theme's CSS and also make sure that your CSS is using rules that are more specific. This will help in making your CSS override the theme's CSS.</p>\n\n<p>Worse-case scenario you could add !important to a few CSS rules if you are having a hard time overriding your theme.</p>\n\n<p>When you use <code>wp_enqueue_style</code> you should use the <code>wp_enqueue_scripts</code> hook, it offers a priority parameter. Here is an example.</p>\n\n<pre><code>function wpse_my_plugin_styles() {\n $plugin_url = plugin_dir_url( __FILE__ );\n wp_enqueue_style( 'my_styles', $plugin_url . \"/css/style.css\");\n}\n\nadd_action('wp_enqueue_scripts', 'wpse_my_plugin_styles', 999); \n</code></pre>\n\n<p>You could also create a <a href=\"https://developer.wordpress.org/themes/advanced-topics/child-themes/\" rel=\"nofollow noreferrer\">child theme</a>. This would allow you to customize the CSS however you want and not worry about it getting wiped out if the plugin updates.</p>\n"
},
{
"answer_id": 360762,
"author": "Tony Djukic",
"author_id": 60844,
"author_profile": "https://wordpress.stackexchange.com/users/60844",
"pm_score": 0,
"selected": false,
"text": "<p>Specificity in CSS is the most reasonable solution here because it's for 'a plugin' so it should be coded as though it could be successfully applied and utilized on any site regardless of theme. Yeah in this instance you could write a child theme or if you control the theme, edit the theme CSS itself, or add a bunch of !important declerations to you CSS but none of those are really WP Best Practices.</p>\n\n<p>So first you want to make sure that the stylesheet for your plugin is properly enqueued:</p>\n\n<pre><code>function yrplugin_enqueue_frontend() {\n //I organize my plugins with a lot of sub-directories so I put my stylesheets into a CSS folder\n //I also always include version numbers\n wp_enqueue_style( 'yrplugin-frnt-css' , plugins_url( 'css/style.css', __DIR__ ), array(), 'version-number-here' );\n //In case you want to enqueue some javascript...\n //wp_enqueue_script( 'yrplugin-frnt-js', plugins_url( 'js/frontend.js', __DIR__ ), array( 'jquery' ), 'version-number-here', true );\n}\nadd_action( 'wp_enqueue_scripts', 'yrplugin_enqueue_frontend', 100 );\n</code></pre>\n\n<p>For your shortcode wrap the contents of your output in something like this, if you haven't already. You can switch to a class if you plan on using multiple shortcodes in a single post that way you won't have duplicate IDs.</p>\n\n<pre><code><div id=\"yrplugin_container\">\n <!-- The rest of your HMTL -->\n</div>\n</code></pre>\n\n<p>Finally, for your CSS you'd be looking for more specific selectors:</p>\n\n<pre><code>#yrplugin_container input[type=text]{\n /* your css rules */\n}\n#yrplugin_container input[type=submit]{\n /* your css rules */\n}\n</code></pre>\n\n<p>If you use that sort of specificity, you shouldn't get much, if any interference from the main theme's stylesheet.</p>\n\n<p>If you still encounter issues you could then simply inline the CSS into the actual elements that the shortcode outputs like:</p>\n\n<pre><code><input type=\"text\" style=\"put your overriding css here\" />\n</code></pre>\n\n<p>That should cover it, let me know if you need more info.</p>\n"
},
{
"answer_id": 375030,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<p>There are only 2 ways to achieve this, neither are WordPress based:</p>\n<h1>1. Use an iframe</h1>\n<p>Make your shortcode display an iframe who's URL leads to the actual place that renders the HTML</p>\n<h1>2. Build a Web Component</h1>\n<p>Web components internal DOM are separated and isolated from the rest of the page, allowing you to load in your styles safe in the knowledge they'll only be applied to those DOM elements.</p>\n<hr />\n<p>Neither of these solutions are WordPress based, or require WordPress knowledge. These are general web development solutions to a general web development problem</p>\n"
}
] | 2020/03/14 | [
"https://wordpress.stackexchange.com/questions/360721",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/178523/"
] | I'm writing a simple plugin that shows on pages/posts a form with customized style for input fields, checkboxes, buttons, etc... via a shortcode. When user writes the shortcode in the page, it generates some CSS, some HTML and some JavaScript but result is not rendered as I want I think because of active theme CSS.
In fact if I wrote the same combination of CSS, HTML and JavaScript in a simple HTML file rendering is perfect and if, in WordPress, I change theme, rendering changes...
How can I prevent the active theme from interfering with my plugin by rendering the controls as if they were inserted in a simple HTML page?
**EDIT, added code:**
```
<div class="chatbox-container">
<button class="chatbox-open">
<i class="fa fa-comment fa-2x" aria-hidden="true"></i>
</button>
<button class="chatbox-close">
<i class="fa fa-close fa-2x" aria-hidden="true"></i>
</button>
<section class="chatbox-popup">
<header class="chatbox-popup__header">
<aside style="flex:3">
<i class="fa fa-user-circle fa-4x chatbox-popup__avatar" aria-hidden="true"></i>
</aside>
<aside style="flex:8">
<h1>Tal Dei Tal</h1> Seller (Online)
</aside>
<aside style="flex:1">
<button class="chatbox-maximize"><i class="fa fa-window-maximize" aria-hidden="true"></i></button>
</aside>
</header>
<main class="chatbox-popup__main">
Some sample text, here GDPR terms...
</main>
<footer class="chatbox-popup__footer">
<aside style="flex:1;color:#888;text-align:center;">
<i class="fa fa-camera" aria-hidden="true"></i>
</aside>
<aside style="flex:10">
<textarea type="text" placeholder="Type your message here..." autofocus></textarea>
</aside>
<aside style="flex:1;color:#888;text-align:center;">
<i class="fa fa-paper-plane" aria-hidden="true"></i>
</aside>
</footer>
</section>
<section class="chatbox-panel">
<header class="chatbox-panel__header">
<aside style="flex:3">
<i class="fa fa-user-circle fa-3x chatbox-popup__avatar" aria-hidden="true"></i>
</aside>
<aside style="flex:6">
<h1>Tal Dei Tali</h1> Seller (Online)
</aside>
<aside style="flex:3;text-align:right;">
<button class="chatbox-minimize"><i class="fa fa-window-restore" aria-hidden="true"></i></button>
<button class="chatbox-panel-close"><i class="fa fa-close" aria-hidden="true"></i></button>
</aside>
</header>
<main class="chatbox-panel__main" style="flex:1">
Some sample text, here GDPR terms...
</main>
<footer class="chatbox-panel__footer">
<aside style="flex:1;color:#888;text-align:center;">
<i class="fa fa-camera" aria-hidden="true"></i>
</aside>
<aside style="flex:10">
<textarea type="text" placeholder="Type your message here..." autofocus></textarea>
</aside>
<aside style="flex:1;color:#888;text-align:center;">
<i class="fa fa-paper-plane" aria-hidden="true"></i>
</aside>
</footer>
</section>
</div>
<style type="text/css">
.chatbox-container {
all: initial;
font-family: "Lato", sans-serif;
}
.chatbox-container h1 {
margin: 0;
font-size: 16px;
line-height: 1;
}
.chatbox-container button {
color: inherit;
background-color: transparent;
border: 0;
outline: 0 !important;
cursor: pointer;
}
.chatbox-container button.chatbox-open {
position: fixed;
bottom: 0;
right: 0;
width: 52px;
height: 52px;
color: #fff;
background-color: #0360a5;
background-position: center center;
background-repeat: no-repeat;
box-shadow: 12px 15px 20px 0 rgba(46, 61, 73, 0.15);
border: 0;
border-radius: 50%;
cursor: pointer;
margin: 16px;
}
.chatbox-container button.chatbox-close {
position: fixed;
bottom: 0;
right: 0;
width: 52px;
height: 52px;
color: #fff;
background-color: #0360a5;
background-position: center center;
background-repeat: no-repeat;
box-shadow: 12px 15px 20px 0 rgba(46, 61, 73, 0.15);
border: 0;
border-radius: 50%;
cursor: pointer;
display: none;
margin: 16px calc(2 * 16px + 52px) 16px 16px;
}
.chatbox-container textarea {
box-sizing: border-box;
width: 100%;
margin: 0;
height: calc(16px + 16px / 2);
padding: 0 calc(16px / 2);
font-family: inherit;
font-size: 16px;
line-height: calc(16px + 16px / 2);
color: #888;
background-color: none;
border: 0;
outline: 0 !important;
resize: none;
overflow: hidden;
}
.chatbox-container textarea::-webkit-input-placeholder {
color: #888;
}
.chatbox-container textarea::-moz-placeholder {
color: #888;
}
.chatbox-container textarea:-ms-input-placeholder {
color: #888;
}
.chatbox-container textarea::-ms-input-placeholder {
color: #888;
}
.chatbox-container textarea::placeholder {
color: #888;
}
.chatbox-container .chatbox-popup {
display: -webkit-box;
display: flex;
position: fixed;
box-shadow: 5px 5px 25px 0 rgba(46, 61, 73, 0.2);
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
flex-direction: column;
display: none;
bottom: calc(2 * 16px + 52px);
right: 16px;
width: 377px;
height: auto;
background-color: #fff;
border-radius: 16px;
}
.chatbox-container .chatbox-popup .chatbox-popup__header {
box-sizing: border-box;
display: -webkit-box;
display: flex;
width: 100%;
padding: 16px;
color: #fff;
background-color: #0360a5;
-webkit-box-align: center;
align-items: center;
justify-content: space-around;
border-top-right-radius: 12px;
border-top-left-radius: 12px;
}
.chatbox-container .chatbox-popup .chatbox-popup__header .chatbox-popup__avatar {
margin-top: -32px;
background-color: #0360a5;
border: 5px solid rgba(0, 0, 0, 0.1);
border-radius: 50%;
}
.chat-container .chatbox-popup .chatbox-popup__main {
box-sizing: border-box;
width: 100%;
padding: calc(2 * 16px) 16px;
line-height: calc(16px + 16px / 2);
color: #888;
text-align: center;
}
.chatbox-container .chatbox-popup .chatbox-popup__footer {
box-sizing: border-box;
display: -webkit-box;
display: flex;
width: 100%;
padding: 16px;
border-top: 1px solid #ddd;
-webkit-box-align: center;
align-items: center;
justify-content: space-around;
border-bottom-right-radius: 12px;
border-bottom-left-radius: 12px;
}
.chatbox-container .chatbox-panel {
display: -webkit-box;
display: flex;
position: fixed;
box-shadow: 5px 5px 25px 0 rgba(46, 61, 73, 0.2);
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
flex-direction: column;
display: none;
top: 0;
right: 0;
bottom: 0;
width: 377px;
background-color: #fff;
}
.chatbox-container .chatbox-panel .chatbox-panel__header {
box-sizing: border-box;
display: -webkit-box;
display: flex;
width: 100%;
padding: 16px;
color: #fff;
background-color: #0360a5;
-webkit-box-align: center;
align-items: center;
justify-content: space-around;
-webkit-box-flex: 0;
flex: 0 0 auto;
}
.chatbox-container .chatbox-panel .chatbox-panel__main {
box-sizing: border-box;
width: 100%;
padding: calc(2 * 16px) 16px;
line-height: calc(16px + 16px / 2);
color: #888;
text-align: center;
-webkit-box-flex: 1;
flex: 1 1 auto;
}
.chatbox-container .chatbox-panel .chatbox-panel__footer {
box-sizing: border-box;
display: -webkit-box;
display: flex;
width: 100%;
padding: 16px;
border-top: 1px solid #ddd;
-webkit-box-align: center;
align-items: center;
justify-content: space-around;
-webkit-box-flex: 0;
flex: 0 0 auto;
}
</style>
``` | You can make sure that your CSS is [enqueued](https://developer.wordpress.org/reference/functions/wp_enqueue_style/) after your theme's CSS and also make sure that your CSS is using rules that are more specific. This will help in making your CSS override the theme's CSS.
Worse-case scenario you could add !important to a few CSS rules if you are having a hard time overriding your theme.
When you use `wp_enqueue_style` you should use the `wp_enqueue_scripts` hook, it offers a priority parameter. Here is an example.
```
function wpse_my_plugin_styles() {
$plugin_url = plugin_dir_url( __FILE__ );
wp_enqueue_style( 'my_styles', $plugin_url . "/css/style.css");
}
add_action('wp_enqueue_scripts', 'wpse_my_plugin_styles', 999);
```
You could also create a [child theme](https://developer.wordpress.org/themes/advanced-topics/child-themes/). This would allow you to customize the CSS however you want and not worry about it getting wiped out if the plugin updates. |
360,745 | <p>I asked a <a href="https://wordpress.stackexchange.com/questions/360418/enhancing-gutenberg-featured-image-control">previous question</a>, and got a helpful answer that got me going quite a ways. The present problem is unrelated, but IMO reflects the dearth of documentation suitable for those of us who aren't familiar with some of the nuances of javascript, are completely new to Gutenberg development, and yet need to tweak the new Wordpress here and there. I'll state right up front that I'm new to javascript, and suspect that my issue is related to that fact.</p>
<p>As stated in my previous question, I'm working on modifying the featured image control in the admin edit screen of a custom post type. I want to add a checkbox, and a text input field to capture a user-supplied resource URL. I have a javascript file that loads on the page in question, along with all the requisite dependencies to work with Gutenberg, JSX, and all of the react-based components (react-devel, react-dom, babel, wp-blocks, wp-i18n, wp-element, wp-editor, wp-hooks). I've also got a filter in place that sets the script type of my .js file to 'text/babel' so JSX interprets correctly. I don't think I've missed anything.</p>
<p>Here's a version of my .js file that displays a heading and rich text field. It's not what I'm after but it does work and there aren't any complaints in the javascript console. At this point I'm still trying to figure out the building blocks I need, and how to use them.</p>
<pre><code>window.addEventListener("load", function(event){
console.log("featured_image.js loaded and functional...");
});
const el = wp.element.createElement;
// const withState = wp.compose.withState;
const setState = wp.data.setState;
const withSelect = wp.data.withSelect;
const withDispatch = wp.data.withDispatch;
const { CheckboxControl } = wp.editor;
const { RichText } = wp.editor;
const { useState } = wp.element;
const { TextControl } = wp.components
const { withState } = wp.compose;
wp.hooks.addFilter(
'editor.PostFeaturedImage',
'dsplugin/featured-image-as-video',
wrapPostFeaturedImage
);
//this works
const MyRichTextField =
<RichText
placeholder="placeholder text"
/>
;
function wrapPostFeaturedImage( OriginalComponent ) {
return function( props ) {
return (
el(
wp.element.Fragment,
{},
// 'Prepend above',
el(
OriginalComponent,
props
),
<strong>this is a test</strong>,
// MyCheckboxControl
MyRichTextField
)
);
}
}
</code></pre>
<p>Here's what the output looks like...</p>
<p><a href="https://i.stack.imgur.com/wjur5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wjur5.png" alt="featured image sidebar area"></a></p>
<p>When I try to add a checkboxControl though, using the same methodology I used for the RichText field, I run into problems. This code...</p>
<pre><code>const MyCheckboxControl =
const [ isChecked, setChecked ] = useState( true );
<CheckboxControl
heading="User"
label="Is author"
help="Is the user a author or not?"
checked={ isChecked }
onChange={ setChecked }
/>
;
</code></pre>
<p>Doesn't work. And the javascript console says...</p>
<pre><code>SyntaxError: ... Unexpected token (28:4)
27 | const MyCheckboxControl = () => (
> 28 | const [ isChecked, setChecked ] = useState( true );
| ^
29 | <CheckboxControl
30 | heading="User"
31 | label="Is author"
</code></pre>
<p>However, this is exactly how the <a href="https://developer.wordpress.org/block-editor/components/checkbox-control/" rel="nofollow noreferrer">Gutenberg documentation</a> says we should implement a CheckboxControl. At least when creating blocks. Are things different in the sidebar? I tried a TextControl, as follows...</p>
<pre><code>const MyTextControl = withState( {
className: '',
} )( ( { className, setState } ) => (
<TextControl
label="Additional CSS Class"
value={ className }
onChange={ ( className ) => setState( { className } ) }
/>
) );
</code></pre>
<p>No syntax error for the above definition, but when I try to use it down in the wrapPostFeaturedImage() function as follows:</p>
<pre><code>function wrapPostFeaturedImage( OriginalComponent ) {
return function( props ) {
return (
el(
wp.element.Fragment,
{},
// 'Prepend above',
el(
OriginalComponent,
props
),
<strong>this is a test</strong>,
// MyCheckboxControl
MyTextControl
)
);
}
}
</code></pre>
<p>I get the following warning below in the console, and nothing shows up after the "this is a test" heading.</p>
<pre><code>Warning: Functions are not valid as a React child.
This may happen if you return a Component instead of <Component /> from render.
Or maybe you meant to call this function rather than return it.
</code></pre>
<p>I feel like I have a fundamental disconnect with what's going on here. What am I missing?</p>
| [
{
"answer_id": 360739,
"author": "Davood Denavi",
"author_id": 184294,
"author_profile": "https://wordpress.stackexchange.com/users/184294",
"pm_score": -1,
"selected": false,
"text": "<p>I'd suggest looking at using a custom theme if you want to ignore CSS from your theme and them using plugins to get the functionality that is offered by your theme. Here is an article that will help you do this without any code: <a href=\"https://www.wpbeginner.com/wp-themes/how-to-easily-create-a-custom-wordpress-theme/\" rel=\"nofollow noreferrer\">https://www.wpbeginner.com/wp-themes/how-to-easily-create-a-custom-wordpress-theme/</a></p>\n\n<p>The other option if there are only some css elements you want to overwrite the properties of would be to tag things with !important. However, use of the !important tag is highly discouraged.</p>\n"
},
{
"answer_id": 360741,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 1,
"selected": false,
"text": "<p>You can make sure that your CSS is <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">enqueued</a> after your theme's CSS and also make sure that your CSS is using rules that are more specific. This will help in making your CSS override the theme's CSS.</p>\n\n<p>Worse-case scenario you could add !important to a few CSS rules if you are having a hard time overriding your theme.</p>\n\n<p>When you use <code>wp_enqueue_style</code> you should use the <code>wp_enqueue_scripts</code> hook, it offers a priority parameter. Here is an example.</p>\n\n<pre><code>function wpse_my_plugin_styles() {\n $plugin_url = plugin_dir_url( __FILE__ );\n wp_enqueue_style( 'my_styles', $plugin_url . \"/css/style.css\");\n}\n\nadd_action('wp_enqueue_scripts', 'wpse_my_plugin_styles', 999); \n</code></pre>\n\n<p>You could also create a <a href=\"https://developer.wordpress.org/themes/advanced-topics/child-themes/\" rel=\"nofollow noreferrer\">child theme</a>. This would allow you to customize the CSS however you want and not worry about it getting wiped out if the plugin updates.</p>\n"
},
{
"answer_id": 360762,
"author": "Tony Djukic",
"author_id": 60844,
"author_profile": "https://wordpress.stackexchange.com/users/60844",
"pm_score": 0,
"selected": false,
"text": "<p>Specificity in CSS is the most reasonable solution here because it's for 'a plugin' so it should be coded as though it could be successfully applied and utilized on any site regardless of theme. Yeah in this instance you could write a child theme or if you control the theme, edit the theme CSS itself, or add a bunch of !important declerations to you CSS but none of those are really WP Best Practices.</p>\n\n<p>So first you want to make sure that the stylesheet for your plugin is properly enqueued:</p>\n\n<pre><code>function yrplugin_enqueue_frontend() {\n //I organize my plugins with a lot of sub-directories so I put my stylesheets into a CSS folder\n //I also always include version numbers\n wp_enqueue_style( 'yrplugin-frnt-css' , plugins_url( 'css/style.css', __DIR__ ), array(), 'version-number-here' );\n //In case you want to enqueue some javascript...\n //wp_enqueue_script( 'yrplugin-frnt-js', plugins_url( 'js/frontend.js', __DIR__ ), array( 'jquery' ), 'version-number-here', true );\n}\nadd_action( 'wp_enqueue_scripts', 'yrplugin_enqueue_frontend', 100 );\n</code></pre>\n\n<p>For your shortcode wrap the contents of your output in something like this, if you haven't already. You can switch to a class if you plan on using multiple shortcodes in a single post that way you won't have duplicate IDs.</p>\n\n<pre><code><div id=\"yrplugin_container\">\n <!-- The rest of your HMTL -->\n</div>\n</code></pre>\n\n<p>Finally, for your CSS you'd be looking for more specific selectors:</p>\n\n<pre><code>#yrplugin_container input[type=text]{\n /* your css rules */\n}\n#yrplugin_container input[type=submit]{\n /* your css rules */\n}\n</code></pre>\n\n<p>If you use that sort of specificity, you shouldn't get much, if any interference from the main theme's stylesheet.</p>\n\n<p>If you still encounter issues you could then simply inline the CSS into the actual elements that the shortcode outputs like:</p>\n\n<pre><code><input type=\"text\" style=\"put your overriding css here\" />\n</code></pre>\n\n<p>That should cover it, let me know if you need more info.</p>\n"
},
{
"answer_id": 375030,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<p>There are only 2 ways to achieve this, neither are WordPress based:</p>\n<h1>1. Use an iframe</h1>\n<p>Make your shortcode display an iframe who's URL leads to the actual place that renders the HTML</p>\n<h1>2. Build a Web Component</h1>\n<p>Web components internal DOM are separated and isolated from the rest of the page, allowing you to load in your styles safe in the knowledge they'll only be applied to those DOM elements.</p>\n<hr />\n<p>Neither of these solutions are WordPress based, or require WordPress knowledge. These are general web development solutions to a general web development problem</p>\n"
}
] | 2020/03/15 | [
"https://wordpress.stackexchange.com/questions/360745",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/184100/"
] | I asked a [previous question](https://wordpress.stackexchange.com/questions/360418/enhancing-gutenberg-featured-image-control), and got a helpful answer that got me going quite a ways. The present problem is unrelated, but IMO reflects the dearth of documentation suitable for those of us who aren't familiar with some of the nuances of javascript, are completely new to Gutenberg development, and yet need to tweak the new Wordpress here and there. I'll state right up front that I'm new to javascript, and suspect that my issue is related to that fact.
As stated in my previous question, I'm working on modifying the featured image control in the admin edit screen of a custom post type. I want to add a checkbox, and a text input field to capture a user-supplied resource URL. I have a javascript file that loads on the page in question, along with all the requisite dependencies to work with Gutenberg, JSX, and all of the react-based components (react-devel, react-dom, babel, wp-blocks, wp-i18n, wp-element, wp-editor, wp-hooks). I've also got a filter in place that sets the script type of my .js file to 'text/babel' so JSX interprets correctly. I don't think I've missed anything.
Here's a version of my .js file that displays a heading and rich text field. It's not what I'm after but it does work and there aren't any complaints in the javascript console. At this point I'm still trying to figure out the building blocks I need, and how to use them.
```
window.addEventListener("load", function(event){
console.log("featured_image.js loaded and functional...");
});
const el = wp.element.createElement;
// const withState = wp.compose.withState;
const setState = wp.data.setState;
const withSelect = wp.data.withSelect;
const withDispatch = wp.data.withDispatch;
const { CheckboxControl } = wp.editor;
const { RichText } = wp.editor;
const { useState } = wp.element;
const { TextControl } = wp.components
const { withState } = wp.compose;
wp.hooks.addFilter(
'editor.PostFeaturedImage',
'dsplugin/featured-image-as-video',
wrapPostFeaturedImage
);
//this works
const MyRichTextField =
<RichText
placeholder="placeholder text"
/>
;
function wrapPostFeaturedImage( OriginalComponent ) {
return function( props ) {
return (
el(
wp.element.Fragment,
{},
// 'Prepend above',
el(
OriginalComponent,
props
),
<strong>this is a test</strong>,
// MyCheckboxControl
MyRichTextField
)
);
}
}
```
Here's what the output looks like...
[](https://i.stack.imgur.com/wjur5.png)
When I try to add a checkboxControl though, using the same methodology I used for the RichText field, I run into problems. This code...
```
const MyCheckboxControl =
const [ isChecked, setChecked ] = useState( true );
<CheckboxControl
heading="User"
label="Is author"
help="Is the user a author or not?"
checked={ isChecked }
onChange={ setChecked }
/>
;
```
Doesn't work. And the javascript console says...
```
SyntaxError: ... Unexpected token (28:4)
27 | const MyCheckboxControl = () => (
> 28 | const [ isChecked, setChecked ] = useState( true );
| ^
29 | <CheckboxControl
30 | heading="User"
31 | label="Is author"
```
However, this is exactly how the [Gutenberg documentation](https://developer.wordpress.org/block-editor/components/checkbox-control/) says we should implement a CheckboxControl. At least when creating blocks. Are things different in the sidebar? I tried a TextControl, as follows...
```
const MyTextControl = withState( {
className: '',
} )( ( { className, setState } ) => (
<TextControl
label="Additional CSS Class"
value={ className }
onChange={ ( className ) => setState( { className } ) }
/>
) );
```
No syntax error for the above definition, but when I try to use it down in the wrapPostFeaturedImage() function as follows:
```
function wrapPostFeaturedImage( OriginalComponent ) {
return function( props ) {
return (
el(
wp.element.Fragment,
{},
// 'Prepend above',
el(
OriginalComponent,
props
),
<strong>this is a test</strong>,
// MyCheckboxControl
MyTextControl
)
);
}
}
```
I get the following warning below in the console, and nothing shows up after the "this is a test" heading.
```
Warning: Functions are not valid as a React child.
This may happen if you return a Component instead of <Component /> from render.
Or maybe you meant to call this function rather than return it.
```
I feel like I have a fundamental disconnect with what's going on here. What am I missing? | You can make sure that your CSS is [enqueued](https://developer.wordpress.org/reference/functions/wp_enqueue_style/) after your theme's CSS and also make sure that your CSS is using rules that are more specific. This will help in making your CSS override the theme's CSS.
Worse-case scenario you could add !important to a few CSS rules if you are having a hard time overriding your theme.
When you use `wp_enqueue_style` you should use the `wp_enqueue_scripts` hook, it offers a priority parameter. Here is an example.
```
function wpse_my_plugin_styles() {
$plugin_url = plugin_dir_url( __FILE__ );
wp_enqueue_style( 'my_styles', $plugin_url . "/css/style.css");
}
add_action('wp_enqueue_scripts', 'wpse_my_plugin_styles', 999);
```
You could also create a [child theme](https://developer.wordpress.org/themes/advanced-topics/child-themes/). This would allow you to customize the CSS however you want and not worry about it getting wiped out if the plugin updates. |
360,758 | <p>I have a strange issue. I am including dashicons on the front-end through</p>
<pre><code>add_action( 'wp_enqueue_scripts', 'load_dashicons_front_end' );
function load_dashicons_front_end() {
wp_enqueue_style( 'dashicons' );
}
</code></pre>
<p>Then I enter dashicon HTML in the Navigation Label of my menu items, for example:</p>
<pre><code><span class="dashicons dashicons-admin-home"></span> Home
</code></pre>
<p>I also include some code on the blog archive that truncates the post titles to the first 7 words:</p>
<pre><code>add_filter( 'the_title', 'wpse_75691_trim_words' );
function wpse_75691_trim_words( $title )
{
// limit to 7 words
return wp_trim_words( $title, 7, '...' );
}
</code></pre>
<p>but dashicons disappear when the trim function runs. It works for the whole site apart from the blog page where I have the truncate code. I believe I have a similar problem with the OP on <a href="https://wordpress.org/support/topic/problem-displaying-font-awesome-after-wp_trim_words/" rel="nofollow noreferrer">this post</a>.</p>
<p>But I am not sure how to proceed. I am already running the function on the blog archive so the problem only exists there. </p>
| [
{
"answer_id": 360760,
"author": "quantum_leap",
"author_id": 153810,
"author_profile": "https://wordpress.stackexchange.com/users/153810",
"pm_score": -1,
"selected": false,
"text": "<p>I will post the solution that I have found from <a href=\"https://stackoverflow.com/questions/36078264/i-want-to-allow-html-tag-when-use-the-wp-trim-words\">this thread</a>, seems to be working and not stripping the dashicon tags:</p>\n\n<pre><code>add_filter( 'the_title', 'wpse_75691_trim_words' );\n\nfunction wpse_75691_trim_words( $title )\n{\n // limit to 7 words\n return force_balance_tags( html_entity_decode( wp_trim_words(htmlentities($title), 7, '...' ) ) );\n}\n</code></pre>\n"
},
{
"answer_id": 360788,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>Your problem is that your filter is trimming <em>all</em> titles to 7 \"words\". This includes blog posts, pages, menu item labels, revision names, and even product names, if you have products.</p>\n\n<p>You need to adjust your filter to be less aggressive and only target the titles that you need to truncate. For example, the following code will only truncate titles:</p>\n\n<ul>\n<li>For Posts</li>\n<li>In the main loop.</li>\n<li>On the front end.</li>\n</ul>\n\n<hr>\n\n<pre><code>function wpse_360758_trim_words( $title, $post_id ) {\n if ( is_admin() ) {\n return $title;\n }\n\n if ( in_the_loop() && 'post' === get_post_type( $post_id ) ) {\n $title = wp_trim_words( $title, 7, '...' );\n }\n\n return $title;\n}\nadd_filter( 'the_title', 'wpse_360758_trim_words', 10, 2 );\n</code></pre>\n"
}
] | 2020/03/15 | [
"https://wordpress.stackexchange.com/questions/360758",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/153810/"
] | I have a strange issue. I am including dashicons on the front-end through
```
add_action( 'wp_enqueue_scripts', 'load_dashicons_front_end' );
function load_dashicons_front_end() {
wp_enqueue_style( 'dashicons' );
}
```
Then I enter dashicon HTML in the Navigation Label of my menu items, for example:
```
<span class="dashicons dashicons-admin-home"></span> Home
```
I also include some code on the blog archive that truncates the post titles to the first 7 words:
```
add_filter( 'the_title', 'wpse_75691_trim_words' );
function wpse_75691_trim_words( $title )
{
// limit to 7 words
return wp_trim_words( $title, 7, '...' );
}
```
but dashicons disappear when the trim function runs. It works for the whole site apart from the blog page where I have the truncate code. I believe I have a similar problem with the OP on [this post](https://wordpress.org/support/topic/problem-displaying-font-awesome-after-wp_trim_words/).
But I am not sure how to proceed. I am already running the function on the blog archive so the problem only exists there. | Your problem is that your filter is trimming *all* titles to 7 "words". This includes blog posts, pages, menu item labels, revision names, and even product names, if you have products.
You need to adjust your filter to be less aggressive and only target the titles that you need to truncate. For example, the following code will only truncate titles:
* For Posts
* In the main loop.
* On the front end.
---
```
function wpse_360758_trim_words( $title, $post_id ) {
if ( is_admin() ) {
return $title;
}
if ( in_the_loop() && 'post' === get_post_type( $post_id ) ) {
$title = wp_trim_words( $title, 7, '...' );
}
return $title;
}
add_filter( 'the_title', 'wpse_360758_trim_words', 10, 2 );
``` |
360,785 | <p>After migrating my site to new hosting, it takes longer to load the site. During the migration, I copied only the <em>plugins</em> and <em>uploads</em> folders from the structure, which I pasted into the manually installed Wordpress on the new hosting. I think the site is slower now because of this. </p>
<p>The new hosting works on SSD so it's probably not the hosting fault. I use GTMetrix.com to estimate site loading but I would need advice on what I did wrong.
My site is <a href="https://consolezone.pl" rel="nofollow noreferrer">https://consolezone.pl</a>.</p>
| [
{
"answer_id": 360760,
"author": "quantum_leap",
"author_id": 153810,
"author_profile": "https://wordpress.stackexchange.com/users/153810",
"pm_score": -1,
"selected": false,
"text": "<p>I will post the solution that I have found from <a href=\"https://stackoverflow.com/questions/36078264/i-want-to-allow-html-tag-when-use-the-wp-trim-words\">this thread</a>, seems to be working and not stripping the dashicon tags:</p>\n\n<pre><code>add_filter( 'the_title', 'wpse_75691_trim_words' );\n\nfunction wpse_75691_trim_words( $title )\n{\n // limit to 7 words\n return force_balance_tags( html_entity_decode( wp_trim_words(htmlentities($title), 7, '...' ) ) );\n}\n</code></pre>\n"
},
{
"answer_id": 360788,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>Your problem is that your filter is trimming <em>all</em> titles to 7 \"words\". This includes blog posts, pages, menu item labels, revision names, and even product names, if you have products.</p>\n\n<p>You need to adjust your filter to be less aggressive and only target the titles that you need to truncate. For example, the following code will only truncate titles:</p>\n\n<ul>\n<li>For Posts</li>\n<li>In the main loop.</li>\n<li>On the front end.</li>\n</ul>\n\n<hr>\n\n<pre><code>function wpse_360758_trim_words( $title, $post_id ) {\n if ( is_admin() ) {\n return $title;\n }\n\n if ( in_the_loop() && 'post' === get_post_type( $post_id ) ) {\n $title = wp_trim_words( $title, 7, '...' );\n }\n\n return $title;\n}\nadd_filter( 'the_title', 'wpse_360758_trim_words', 10, 2 );\n</code></pre>\n"
}
] | 2020/03/15 | [
"https://wordpress.stackexchange.com/questions/360785",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/150377/"
] | After migrating my site to new hosting, it takes longer to load the site. During the migration, I copied only the *plugins* and *uploads* folders from the structure, which I pasted into the manually installed Wordpress on the new hosting. I think the site is slower now because of this.
The new hosting works on SSD so it's probably not the hosting fault. I use GTMetrix.com to estimate site loading but I would need advice on what I did wrong.
My site is <https://consolezone.pl>. | Your problem is that your filter is trimming *all* titles to 7 "words". This includes blog posts, pages, menu item labels, revision names, and even product names, if you have products.
You need to adjust your filter to be less aggressive and only target the titles that you need to truncate. For example, the following code will only truncate titles:
* For Posts
* In the main loop.
* On the front end.
---
```
function wpse_360758_trim_words( $title, $post_id ) {
if ( is_admin() ) {
return $title;
}
if ( in_the_loop() && 'post' === get_post_type( $post_id ) ) {
$title = wp_trim_words( $title, 7, '...' );
}
return $title;
}
add_filter( 'the_title', 'wpse_360758_trim_words', 10, 2 );
``` |
360,842 | <p>I have a custom pos type created in functions.php and working great - except I need to have categories enabled. I have looked through other answers here, and am still not able to figure it out. In my code i have <code>taxonomies => array('categories', 'tags')</code> but it is not working.</p>
<p>Here is my code:</p>
<pre><code>function custom_post_type() {
// Set UI labels for Custom Post Type
$labels = array(
'name' => _x('Trade Alerts', 'Post Type General Name', 'Avada'),
'singular_name' => _x('Trade Alert', 'Post Type Singular Name', 'Avada'),
'menu_name' => __('Trade Alerts', 'Avada'),
'parent_item_colon' => __('Parent Trade Alert', 'Avada'),
'all_items' => __('All Trade Alerts', 'Avada'),
'view_item' => __('View Trade Alert', 'Avada'),
'add_new_item' => __('Add New Trade Alert', 'Avada'),
'add_new' => __('Add New', 'Avada'),
'edit_item' => __('Edit Trade Alert', 'Avada'),
'update_item' => __('Update Trade Alert', 'Avada'),
'search_items' => __('Search Trade Alert', 'Avada'),
'not_found' => __('Not Found', 'Avada'),
'not_found_in_trash' => __('Not found in Trash', 'Avada'),
);
// Set other options for Custom Post Type
$args = array(
'label' => __('trade alerts', 'Avada'),
'description' => __('Trade alerts with Forex stuff', 'Avada'),
'labels' => $labels,
// Features this CPT supports in Post Editor
'supports' => array('title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'revisions', 'custom-fields'),
// You can associate this CPT with a taxonomy or custom taxonomy.
'taxonomies' => array('categories', 'tags'),
/* A hierarchical CPT is like Pages and can have
* Parent and child items. A non-hierarchical CPT
* is like Posts.
*/
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'show_in_admin_bar' => true,
'menu_position' => 5,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'page',
);
</code></pre>
| [
{
"answer_id": 360760,
"author": "quantum_leap",
"author_id": 153810,
"author_profile": "https://wordpress.stackexchange.com/users/153810",
"pm_score": -1,
"selected": false,
"text": "<p>I will post the solution that I have found from <a href=\"https://stackoverflow.com/questions/36078264/i-want-to-allow-html-tag-when-use-the-wp-trim-words\">this thread</a>, seems to be working and not stripping the dashicon tags:</p>\n\n<pre><code>add_filter( 'the_title', 'wpse_75691_trim_words' );\n\nfunction wpse_75691_trim_words( $title )\n{\n // limit to 7 words\n return force_balance_tags( html_entity_decode( wp_trim_words(htmlentities($title), 7, '...' ) ) );\n}\n</code></pre>\n"
},
{
"answer_id": 360788,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>Your problem is that your filter is trimming <em>all</em> titles to 7 \"words\". This includes blog posts, pages, menu item labels, revision names, and even product names, if you have products.</p>\n\n<p>You need to adjust your filter to be less aggressive and only target the titles that you need to truncate. For example, the following code will only truncate titles:</p>\n\n<ul>\n<li>For Posts</li>\n<li>In the main loop.</li>\n<li>On the front end.</li>\n</ul>\n\n<hr>\n\n<pre><code>function wpse_360758_trim_words( $title, $post_id ) {\n if ( is_admin() ) {\n return $title;\n }\n\n if ( in_the_loop() && 'post' === get_post_type( $post_id ) ) {\n $title = wp_trim_words( $title, 7, '...' );\n }\n\n return $title;\n}\nadd_filter( 'the_title', 'wpse_360758_trim_words', 10, 2 );\n</code></pre>\n"
}
] | 2020/03/16 | [
"https://wordpress.stackexchange.com/questions/360842",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/154852/"
] | I have a custom pos type created in functions.php and working great - except I need to have categories enabled. I have looked through other answers here, and am still not able to figure it out. In my code i have `taxonomies => array('categories', 'tags')` but it is not working.
Here is my code:
```
function custom_post_type() {
// Set UI labels for Custom Post Type
$labels = array(
'name' => _x('Trade Alerts', 'Post Type General Name', 'Avada'),
'singular_name' => _x('Trade Alert', 'Post Type Singular Name', 'Avada'),
'menu_name' => __('Trade Alerts', 'Avada'),
'parent_item_colon' => __('Parent Trade Alert', 'Avada'),
'all_items' => __('All Trade Alerts', 'Avada'),
'view_item' => __('View Trade Alert', 'Avada'),
'add_new_item' => __('Add New Trade Alert', 'Avada'),
'add_new' => __('Add New', 'Avada'),
'edit_item' => __('Edit Trade Alert', 'Avada'),
'update_item' => __('Update Trade Alert', 'Avada'),
'search_items' => __('Search Trade Alert', 'Avada'),
'not_found' => __('Not Found', 'Avada'),
'not_found_in_trash' => __('Not found in Trash', 'Avada'),
);
// Set other options for Custom Post Type
$args = array(
'label' => __('trade alerts', 'Avada'),
'description' => __('Trade alerts with Forex stuff', 'Avada'),
'labels' => $labels,
// Features this CPT supports in Post Editor
'supports' => array('title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'revisions', 'custom-fields'),
// You can associate this CPT with a taxonomy or custom taxonomy.
'taxonomies' => array('categories', 'tags'),
/* A hierarchical CPT is like Pages and can have
* Parent and child items. A non-hierarchical CPT
* is like Posts.
*/
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'show_in_admin_bar' => true,
'menu_position' => 5,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'page',
);
``` | Your problem is that your filter is trimming *all* titles to 7 "words". This includes blog posts, pages, menu item labels, revision names, and even product names, if you have products.
You need to adjust your filter to be less aggressive and only target the titles that you need to truncate. For example, the following code will only truncate titles:
* For Posts
* In the main loop.
* On the front end.
---
```
function wpse_360758_trim_words( $title, $post_id ) {
if ( is_admin() ) {
return $title;
}
if ( in_the_loop() && 'post' === get_post_type( $post_id ) ) {
$title = wp_trim_words( $title, 7, '...' );
}
return $title;
}
add_filter( 'the_title', 'wpse_360758_trim_words', 10, 2 );
``` |
360,845 | <p>I've developed a custom theme with a custom post type named <code>events</code>. For some reason, however, WP refuses to use my archive page template with the file name <code>archive-events.php</code> per WP's template hierarchy. WP keeps defaulting to <code>index.php</code> as the template for this post type.</p>
<p>Previously I had a page configured in WP that was set to the slug <code>/events/</code> which is now the slug of the custom post type. That page is now deleted, and I don't know if this is the issue that is causing WP to refuse to use <code>archive-events.php</code> for my archive listing for the custom post type. I've tried modifying and re-saving my permalink structure, and that hasn't worked. Currently the permastruct is set to "Post name," i.e. <code>http://my.domain/post-name/</code></p>
<p>More details:</p>
<ul>
<li>I've registered a custom post type of <code>events</code> (code below)</li>
<li>The slug of the post type is "events" and individual posts are rendering successfully at <code>http://domain.com/events/post-name</code></li>
<li>The archive page for the post type is accessible at <code>/events/</code> but is using <code>index.php</code> even though I've created an archive template for the post type as <code>archive-events.php</code></li>
<li>To confirm what template WP is using to render the archive page for the custom post type, I've created a function that outputs the <code>$GLOBALS['current_theme_template']</code> being used to render the page. This confirms that WP is using <code>index.php</code> to render the archive page.</li>
<li>In my <code>header.php</code> file I'm echoing the function <code>get_post_type_archive_link('events')</code> to confirm that WP thinks that the archive page for my custom post type should be <code>http://domain.com/events/</code></li>
<li>The <code>archive.php</code> and <code>index.php</code> WP templates are served as expected, but the template for the custom post type is skipped by WP no matter what</li>
<li>As a test, I renamed my existing custom post type to something new, remapped all of my queries to that CPT, and updated my template names accordingly. Still, WP refuses to serve <code>cpt-archive.php</code> as the template for the custom post type and serves either <code>archive.php</code> or <code>index.php</code> instead.</li>
</ul>
<p>Here's my <code>functions.php</code> code to register the post type:</p>
<pre><code>function registerEvents()
{
$labels = array(
'name' => _x( 'Events', 'Post type general name', 'textdomain' ),
'singular_name' => _x( 'Event', 'Post type singular name', 'textdomain' ),
'menu_name' => _x( 'Events', 'Admin Menu text', 'textdomain' ),
'name_admin_bar' => _x( 'Events', 'Add New on Toolbar', 'textdomain' ),
<snip>
);
$args = array(
'labels' => $labels,
'public' => true,
'hierarchical' => false,
'publicly_queryable' => true,
'exclude_from_search' => false,
'show_ui' => true,
'show_in_menu' => true,
'show_in_rest' => false,
'menu_position' => 5,
'menu_icon' => 'dashicons-calendar-alt',
'capability_type' => 'post',
'has_archive' => true,
'query_var' => true,
'delete_with_user' => false,
'supports' => array(
'title',
'editor',
'excerpt',
'thumbnail',
'page-attributes'
),
'taxonomies' => array( 'kind' ), // Custom tax previously registered
'rewrite' => array( 'slug' => 'events', 'with_front' => false ),
);
register_post_type( 'events', $args );
}
add_action( 'init', 'registerEvents' );
</code></pre>
| [
{
"answer_id": 360760,
"author": "quantum_leap",
"author_id": 153810,
"author_profile": "https://wordpress.stackexchange.com/users/153810",
"pm_score": -1,
"selected": false,
"text": "<p>I will post the solution that I have found from <a href=\"https://stackoverflow.com/questions/36078264/i-want-to-allow-html-tag-when-use-the-wp-trim-words\">this thread</a>, seems to be working and not stripping the dashicon tags:</p>\n\n<pre><code>add_filter( 'the_title', 'wpse_75691_trim_words' );\n\nfunction wpse_75691_trim_words( $title )\n{\n // limit to 7 words\n return force_balance_tags( html_entity_decode( wp_trim_words(htmlentities($title), 7, '...' ) ) );\n}\n</code></pre>\n"
},
{
"answer_id": 360788,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>Your problem is that your filter is trimming <em>all</em> titles to 7 \"words\". This includes blog posts, pages, menu item labels, revision names, and even product names, if you have products.</p>\n\n<p>You need to adjust your filter to be less aggressive and only target the titles that you need to truncate. For example, the following code will only truncate titles:</p>\n\n<ul>\n<li>For Posts</li>\n<li>In the main loop.</li>\n<li>On the front end.</li>\n</ul>\n\n<hr>\n\n<pre><code>function wpse_360758_trim_words( $title, $post_id ) {\n if ( is_admin() ) {\n return $title;\n }\n\n if ( in_the_loop() && 'post' === get_post_type( $post_id ) ) {\n $title = wp_trim_words( $title, 7, '...' );\n }\n\n return $title;\n}\nadd_filter( 'the_title', 'wpse_360758_trim_words', 10, 2 );\n</code></pre>\n"
}
] | 2020/03/16 | [
"https://wordpress.stackexchange.com/questions/360845",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/184374/"
] | I've developed a custom theme with a custom post type named `events`. For some reason, however, WP refuses to use my archive page template with the file name `archive-events.php` per WP's template hierarchy. WP keeps defaulting to `index.php` as the template for this post type.
Previously I had a page configured in WP that was set to the slug `/events/` which is now the slug of the custom post type. That page is now deleted, and I don't know if this is the issue that is causing WP to refuse to use `archive-events.php` for my archive listing for the custom post type. I've tried modifying and re-saving my permalink structure, and that hasn't worked. Currently the permastruct is set to "Post name," i.e. `http://my.domain/post-name/`
More details:
* I've registered a custom post type of `events` (code below)
* The slug of the post type is "events" and individual posts are rendering successfully at `http://domain.com/events/post-name`
* The archive page for the post type is accessible at `/events/` but is using `index.php` even though I've created an archive template for the post type as `archive-events.php`
* To confirm what template WP is using to render the archive page for the custom post type, I've created a function that outputs the `$GLOBALS['current_theme_template']` being used to render the page. This confirms that WP is using `index.php` to render the archive page.
* In my `header.php` file I'm echoing the function `get_post_type_archive_link('events')` to confirm that WP thinks that the archive page for my custom post type should be `http://domain.com/events/`
* The `archive.php` and `index.php` WP templates are served as expected, but the template for the custom post type is skipped by WP no matter what
* As a test, I renamed my existing custom post type to something new, remapped all of my queries to that CPT, and updated my template names accordingly. Still, WP refuses to serve `cpt-archive.php` as the template for the custom post type and serves either `archive.php` or `index.php` instead.
Here's my `functions.php` code to register the post type:
```
function registerEvents()
{
$labels = array(
'name' => _x( 'Events', 'Post type general name', 'textdomain' ),
'singular_name' => _x( 'Event', 'Post type singular name', 'textdomain' ),
'menu_name' => _x( 'Events', 'Admin Menu text', 'textdomain' ),
'name_admin_bar' => _x( 'Events', 'Add New on Toolbar', 'textdomain' ),
<snip>
);
$args = array(
'labels' => $labels,
'public' => true,
'hierarchical' => false,
'publicly_queryable' => true,
'exclude_from_search' => false,
'show_ui' => true,
'show_in_menu' => true,
'show_in_rest' => false,
'menu_position' => 5,
'menu_icon' => 'dashicons-calendar-alt',
'capability_type' => 'post',
'has_archive' => true,
'query_var' => true,
'delete_with_user' => false,
'supports' => array(
'title',
'editor',
'excerpt',
'thumbnail',
'page-attributes'
),
'taxonomies' => array( 'kind' ), // Custom tax previously registered
'rewrite' => array( 'slug' => 'events', 'with_front' => false ),
);
register_post_type( 'events', $args );
}
add_action( 'init', 'registerEvents' );
``` | Your problem is that your filter is trimming *all* titles to 7 "words". This includes blog posts, pages, menu item labels, revision names, and even product names, if you have products.
You need to adjust your filter to be less aggressive and only target the titles that you need to truncate. For example, the following code will only truncate titles:
* For Posts
* In the main loop.
* On the front end.
---
```
function wpse_360758_trim_words( $title, $post_id ) {
if ( is_admin() ) {
return $title;
}
if ( in_the_loop() && 'post' === get_post_type( $post_id ) ) {
$title = wp_trim_words( $title, 7, '...' );
}
return $title;
}
add_filter( 'the_title', 'wpse_360758_trim_words', 10, 2 );
``` |
360,860 | <p><strong>This is common.js</strong></p>
<pre><code>jQuery(function ($) {
var commonJs = {
init: function () {
},
showAlert: function () {
},
}
});
</code></pre>
<p><strong>This is add.js</strong></p>
<pre><code>jQuery(function ($) {
var addJs = {
init: function () {
console.log(commonJs.showAlert);
},
}
});
</code></pre>
<p>I want to use common js function <strong>commonJs.showAlert</strong> in add.js</p>
<p>How can i access that?</p>
| [
{
"answer_id": 360862,
"author": "Yugma Patel",
"author_id": 184390,
"author_profile": "https://wordpress.stackexchange.com/users/184390",
"pm_score": -1,
"selected": true,
"text": "<p>Please simply place commonJs var outside the jQuery function and try again. It will work for you.</p>\n"
},
{
"answer_id": 361007,
"author": "Shweta Danej",
"author_id": 150546,
"author_profile": "https://wordpress.stackexchange.com/users/150546",
"pm_score": 0,
"selected": false,
"text": "<pre><code>var commonJs;\njQuery(function ($) {\n\n commonJs = {\n init: function () {\n },\n showAlert: function () {\n },\n\n }\n\n});\n</code></pre>\n\n<p>I just had to put this variable outside <strong>jQuery(function ($)</strong> and it worked.</p>\n"
}
] | 2020/03/17 | [
"https://wordpress.stackexchange.com/questions/360860",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/150546/"
] | **This is common.js**
```
jQuery(function ($) {
var commonJs = {
init: function () {
},
showAlert: function () {
},
}
});
```
**This is add.js**
```
jQuery(function ($) {
var addJs = {
init: function () {
console.log(commonJs.showAlert);
},
}
});
```
I want to use common js function **commonJs.showAlert** in add.js
How can i access that? | Please simply place commonJs var outside the jQuery function and try again. It will work for you. |
360,972 | <p>I'm working on a theme that should style all native WordPress blocks via CSS, including potentially extending them with custom 'style' options in the block editor via JS. Does anyone know of a list or reference site which lists all native blocks, ideally including information on the WordPress version(s) where they were introduced and links to their registerBlockStyle 'names' (ie, <code>core/button</code> or <code>core/buttons</code>)? Searching in the Codex, Handbook and in Google isn't getting me anywhere so far.</p>
<p>Obviously I can go in and add every block to a Page and style it but it's hard to keep track of what's needed. An updated version of the <a href="https://wordpress.org/plugins/block-unit-test/" rel="noreferrer">Block Unit Test plugin</a> might help too, but it looks like that's not being updated.</p>
<p>If I have to roll my own so be it (and I'll happily share) but I figured why reinvent the wheel... :) Thanks!</p>
| [
{
"answer_id": 360975,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": false,
"text": "<p>Not at the moment, but, you can go to a page with the block editor, open the browser dev tools, go to the console, and run the following:</p>\n<pre class=\"lang-js prettyprint-override\"><code>// grab all block types\nconst types = wp.blocks.getBlockTypes();\n\n// filter to just the core blocks\nconst core_blocks = types.filter(\n type => type.name.startsWith( 'core/' )\n);\n\n// grab just the names\nconst block_names = core_blocks.map( type => type.name );\n\n// display in the console\nconsole.log( block_names );\n</code></pre>\n"
},
{
"answer_id": 402759,
"author": "Mike Ritter",
"author_id": 77750,
"author_profile": "https://wordpress.stackexchange.com/users/77750",
"pm_score": 0,
"selected": false,
"text": "<p>WordPress now has a list of <strong>core blocks</strong> in the developer docs at <a href=\"https://developer.wordpress.org/block-editor/reference-guides/core-blocks/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/block-editor/reference-guides/core-blocks/</a>.</p>\n<p>Note: Layout is not straightforward if you are accustomed to templating languages. JavaScript is used extensively to assign tags, attributes, concatenate, and more.</p>\n<p>Learn more about WordPress' use of React and JSX to create elements at <a href=\"https://github.com/WordPress/gutenberg/blob/368f8545c8c495681a937d421c0056843a3d88cf/packages/element/README.md\" rel=\"nofollow noreferrer\">https://github.com/WordPress/gutenberg/blob/368f8545c8c495681a937d421c0056843a3d88cf/packages/element/README.md</a></p>\n"
}
] | 2020/03/18 | [
"https://wordpress.stackexchange.com/questions/360972",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/16/"
] | I'm working on a theme that should style all native WordPress blocks via CSS, including potentially extending them with custom 'style' options in the block editor via JS. Does anyone know of a list or reference site which lists all native blocks, ideally including information on the WordPress version(s) where they were introduced and links to their registerBlockStyle 'names' (ie, `core/button` or `core/buttons`)? Searching in the Codex, Handbook and in Google isn't getting me anywhere so far.
Obviously I can go in and add every block to a Page and style it but it's hard to keep track of what's needed. An updated version of the [Block Unit Test plugin](https://wordpress.org/plugins/block-unit-test/) might help too, but it looks like that's not being updated.
If I have to roll my own so be it (and I'll happily share) but I figured why reinvent the wheel... :) Thanks! | Not at the moment, but, you can go to a page with the block editor, open the browser dev tools, go to the console, and run the following:
```js
// grab all block types
const types = wp.blocks.getBlockTypes();
// filter to just the core blocks
const core_blocks = types.filter(
type => type.name.startsWith( 'core/' )
);
// grab just the names
const block_names = core_blocks.map( type => type.name );
// display in the console
console.log( block_names );
``` |
360,987 | <p>I know how to put only 5 posts per page with pagination. But let say I have 4000 posts but I don’t want to let people to be able to see all my posts. I just want to display 20 posts in 4 pages (5 per pages). </p>
<pre><code>$args = array(
'post_type' => 'blog_posts',
'posts_per_page' => '5',
);
$query = new WP_Query($args);
</code></pre>
| [
{
"answer_id": 360993,
"author": "Mikhail",
"author_id": 88888,
"author_profile": "https://wordpress.stackexchange.com/users/88888",
"pm_score": 2,
"selected": true,
"text": "<p>I consider the right way could be filtering of total number of found posts like this.</p>\n\n<pre><code>function my_custom_found_posts_limiter( $found_posts, $wp_query ) {\n\n $maximum_of_post_items = 100; // place your desired value here or read if from option\\setting.\n\n if ( ! is_admin() && $wp_query->is_main_query() && $wp_query->is_post_type_archive( 'blog_posts' ) ) {\n if ( $found_posts > $maximum_of_post_items ) {\n return $maximum_of_post_items; // we return maximum amount, so pagination will be aware of this number.\n }\n }\n\n return $found_posts;\n}\nadd_filter( 'found_posts', 'my_custom_found_posts_limiter', 10, 2 );\n</code></pre>\n\n<p>See source code here <a href=\"https://core.trac.wordpress.org/browser/tags/5.3/src/wp-includes/class-wp-query.php#L3234\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/browser/tags/5.3/src/wp-includes/class-wp-query.php#L3234</a></p>\n\n<p>and lines after this filter is applied to have better understanding of how it will work.</p>\n\n<p>NB: I've used <code>is_main_query()</code> conditional and <code>is_post_type_archive</code> meaning it will be used for main Post archive loop or CPT archive page loop, but you can adjust the way you want.</p>\n\n<p>UPD: added <code>!is_admin()</code> - check so it will not fire in wp-admin.</p>\n"
},
{
"answer_id": 361013,
"author": "G. Bonini",
"author_id": 184502,
"author_profile": "https://wordpress.stackexchange.com/users/184502",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the post_limits filter:</p>\n\n<pre><code>function my_posts_limits( $limit, $query ) {\n\n if ( ! is_admin() && $query->is_main_query() ) {\n return 'LIMIT 0, 25';\n }\n\n return $limit;\n}\nadd_filter( 'post_limits', 'my_posts_limits', 10, 2 );\n</code></pre>\n\n<p>This will work for your main query and won't affect the admin.</p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/post_limits\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Filter_Reference/post_limits</a></p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/288974/limit-wp-query-to-only-x-results-total-not-per-page?rq=1\">Limit WP_Query to only X results (total, not per page)</a></p>\n"
}
] | 2020/03/18 | [
"https://wordpress.stackexchange.com/questions/360987",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/57405/"
] | I know how to put only 5 posts per page with pagination. But let say I have 4000 posts but I don’t want to let people to be able to see all my posts. I just want to display 20 posts in 4 pages (5 per pages).
```
$args = array(
'post_type' => 'blog_posts',
'posts_per_page' => '5',
);
$query = new WP_Query($args);
``` | I consider the right way could be filtering of total number of found posts like this.
```
function my_custom_found_posts_limiter( $found_posts, $wp_query ) {
$maximum_of_post_items = 100; // place your desired value here or read if from option\setting.
if ( ! is_admin() && $wp_query->is_main_query() && $wp_query->is_post_type_archive( 'blog_posts' ) ) {
if ( $found_posts > $maximum_of_post_items ) {
return $maximum_of_post_items; // we return maximum amount, so pagination will be aware of this number.
}
}
return $found_posts;
}
add_filter( 'found_posts', 'my_custom_found_posts_limiter', 10, 2 );
```
See source code here <https://core.trac.wordpress.org/browser/tags/5.3/src/wp-includes/class-wp-query.php#L3234>
and lines after this filter is applied to have better understanding of how it will work.
NB: I've used `is_main_query()` conditional and `is_post_type_archive` meaning it will be used for main Post archive loop or CPT archive page loop, but you can adjust the way you want.
UPD: added `!is_admin()` - check so it will not fire in wp-admin. |
361,052 | <p>I am looking to make a few different displays on the home page of terms within certain taxonomies as well as their image field as defined by ACF.</p>
<p>I have been looking online and found 2 main different ways to do this and would like to initially ask what is the difference between the two:?</p>
<pre><code>WP_Term_Query();
</code></pre>
<p>and</p>
<pre><code>get_terms();
</code></pre>
<p>This is the code I have so far but it does not seem to work with the_title() and the_permalink().</p>
<p>Also, it displays the ACF image field of the first result but then repeats the same image for the others.
The ACF custom image field on the term is 'artist_thumbnail_image'</p>
<pre><code><?php
$args = array(
'taxonomy' => 'artist',
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => false,
'meta_key' => 'artist_featured',
'meta_value' => '1',
'meta_compare' => '==',
);
$the_query = new WP_Term_Query($args);
foreach ($the_query->get_terms() as $term) { ?>
<?php echo $term->name; ?>
<?php
$featuredartistid = $term->term_id;
$featuredartist = get_field('artist', $featuredartistid);
$featuredartistthumbnailimage = get_field('artist_thumbnail_image', $featuredartist);
$featuredartistthumbnailimagesize = 'thumbnail'; ?>
<a href="<?php echo the_permalink(); ?>">
<?php echo wp_get_attachment_image($artistthumbnailimage, $artistthumbnailimagesize); ?>
</a>
<?php } ?>
</code></pre>
| [
{
"answer_id": 360993,
"author": "Mikhail",
"author_id": 88888,
"author_profile": "https://wordpress.stackexchange.com/users/88888",
"pm_score": 2,
"selected": true,
"text": "<p>I consider the right way could be filtering of total number of found posts like this.</p>\n\n<pre><code>function my_custom_found_posts_limiter( $found_posts, $wp_query ) {\n\n $maximum_of_post_items = 100; // place your desired value here or read if from option\\setting.\n\n if ( ! is_admin() && $wp_query->is_main_query() && $wp_query->is_post_type_archive( 'blog_posts' ) ) {\n if ( $found_posts > $maximum_of_post_items ) {\n return $maximum_of_post_items; // we return maximum amount, so pagination will be aware of this number.\n }\n }\n\n return $found_posts;\n}\nadd_filter( 'found_posts', 'my_custom_found_posts_limiter', 10, 2 );\n</code></pre>\n\n<p>See source code here <a href=\"https://core.trac.wordpress.org/browser/tags/5.3/src/wp-includes/class-wp-query.php#L3234\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/browser/tags/5.3/src/wp-includes/class-wp-query.php#L3234</a></p>\n\n<p>and lines after this filter is applied to have better understanding of how it will work.</p>\n\n<p>NB: I've used <code>is_main_query()</code> conditional and <code>is_post_type_archive</code> meaning it will be used for main Post archive loop or CPT archive page loop, but you can adjust the way you want.</p>\n\n<p>UPD: added <code>!is_admin()</code> - check so it will not fire in wp-admin.</p>\n"
},
{
"answer_id": 361013,
"author": "G. Bonini",
"author_id": 184502,
"author_profile": "https://wordpress.stackexchange.com/users/184502",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the post_limits filter:</p>\n\n<pre><code>function my_posts_limits( $limit, $query ) {\n\n if ( ! is_admin() && $query->is_main_query() ) {\n return 'LIMIT 0, 25';\n }\n\n return $limit;\n}\nadd_filter( 'post_limits', 'my_posts_limits', 10, 2 );\n</code></pre>\n\n<p>This will work for your main query and won't affect the admin.</p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/post_limits\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Filter_Reference/post_limits</a></p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/288974/limit-wp-query-to-only-x-results-total-not-per-page?rq=1\">Limit WP_Query to only X results (total, not per page)</a></p>\n"
}
] | 2020/03/19 | [
"https://wordpress.stackexchange.com/questions/361052",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68090/"
] | I am looking to make a few different displays on the home page of terms within certain taxonomies as well as their image field as defined by ACF.
I have been looking online and found 2 main different ways to do this and would like to initially ask what is the difference between the two:?
```
WP_Term_Query();
```
and
```
get_terms();
```
This is the code I have so far but it does not seem to work with the\_title() and the\_permalink().
Also, it displays the ACF image field of the first result but then repeats the same image for the others.
The ACF custom image field on the term is 'artist\_thumbnail\_image'
```
<?php
$args = array(
'taxonomy' => 'artist',
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => false,
'meta_key' => 'artist_featured',
'meta_value' => '1',
'meta_compare' => '==',
);
$the_query = new WP_Term_Query($args);
foreach ($the_query->get_terms() as $term) { ?>
<?php echo $term->name; ?>
<?php
$featuredartistid = $term->term_id;
$featuredartist = get_field('artist', $featuredartistid);
$featuredartistthumbnailimage = get_field('artist_thumbnail_image', $featuredartist);
$featuredartistthumbnailimagesize = 'thumbnail'; ?>
<a href="<?php echo the_permalink(); ?>">
<?php echo wp_get_attachment_image($artistthumbnailimage, $artistthumbnailimagesize); ?>
</a>
<?php } ?>
``` | I consider the right way could be filtering of total number of found posts like this.
```
function my_custom_found_posts_limiter( $found_posts, $wp_query ) {
$maximum_of_post_items = 100; // place your desired value here or read if from option\setting.
if ( ! is_admin() && $wp_query->is_main_query() && $wp_query->is_post_type_archive( 'blog_posts' ) ) {
if ( $found_posts > $maximum_of_post_items ) {
return $maximum_of_post_items; // we return maximum amount, so pagination will be aware of this number.
}
}
return $found_posts;
}
add_filter( 'found_posts', 'my_custom_found_posts_limiter', 10, 2 );
```
See source code here <https://core.trac.wordpress.org/browser/tags/5.3/src/wp-includes/class-wp-query.php#L3234>
and lines after this filter is applied to have better understanding of how it will work.
NB: I've used `is_main_query()` conditional and `is_post_type_archive` meaning it will be used for main Post archive loop or CPT archive page loop, but you can adjust the way you want.
UPD: added `!is_admin()` - check so it will not fire in wp-admin. |
361,138 | <p>I got the sku to to show in the cart for each item - Does anyone have the correct php code to get the sku under each product name on all pages?</p>
| [
{
"answer_id": 360993,
"author": "Mikhail",
"author_id": 88888,
"author_profile": "https://wordpress.stackexchange.com/users/88888",
"pm_score": 2,
"selected": true,
"text": "<p>I consider the right way could be filtering of total number of found posts like this.</p>\n\n<pre><code>function my_custom_found_posts_limiter( $found_posts, $wp_query ) {\n\n $maximum_of_post_items = 100; // place your desired value here or read if from option\\setting.\n\n if ( ! is_admin() && $wp_query->is_main_query() && $wp_query->is_post_type_archive( 'blog_posts' ) ) {\n if ( $found_posts > $maximum_of_post_items ) {\n return $maximum_of_post_items; // we return maximum amount, so pagination will be aware of this number.\n }\n }\n\n return $found_posts;\n}\nadd_filter( 'found_posts', 'my_custom_found_posts_limiter', 10, 2 );\n</code></pre>\n\n<p>See source code here <a href=\"https://core.trac.wordpress.org/browser/tags/5.3/src/wp-includes/class-wp-query.php#L3234\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/browser/tags/5.3/src/wp-includes/class-wp-query.php#L3234</a></p>\n\n<p>and lines after this filter is applied to have better understanding of how it will work.</p>\n\n<p>NB: I've used <code>is_main_query()</code> conditional and <code>is_post_type_archive</code> meaning it will be used for main Post archive loop or CPT archive page loop, but you can adjust the way you want.</p>\n\n<p>UPD: added <code>!is_admin()</code> - check so it will not fire in wp-admin.</p>\n"
},
{
"answer_id": 361013,
"author": "G. Bonini",
"author_id": 184502,
"author_profile": "https://wordpress.stackexchange.com/users/184502",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the post_limits filter:</p>\n\n<pre><code>function my_posts_limits( $limit, $query ) {\n\n if ( ! is_admin() && $query->is_main_query() ) {\n return 'LIMIT 0, 25';\n }\n\n return $limit;\n}\nadd_filter( 'post_limits', 'my_posts_limits', 10, 2 );\n</code></pre>\n\n<p>This will work for your main query and won't affect the admin.</p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/post_limits\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Filter_Reference/post_limits</a></p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/288974/limit-wp-query-to-only-x-results-total-not-per-page?rq=1\">Limit WP_Query to only X results (total, not per page)</a></p>\n"
}
] | 2020/03/21 | [
"https://wordpress.stackexchange.com/questions/361138",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/184591/"
] | I got the sku to to show in the cart for each item - Does anyone have the correct php code to get the sku under each product name on all pages? | I consider the right way could be filtering of total number of found posts like this.
```
function my_custom_found_posts_limiter( $found_posts, $wp_query ) {
$maximum_of_post_items = 100; // place your desired value here or read if from option\setting.
if ( ! is_admin() && $wp_query->is_main_query() && $wp_query->is_post_type_archive( 'blog_posts' ) ) {
if ( $found_posts > $maximum_of_post_items ) {
return $maximum_of_post_items; // we return maximum amount, so pagination will be aware of this number.
}
}
return $found_posts;
}
add_filter( 'found_posts', 'my_custom_found_posts_limiter', 10, 2 );
```
See source code here <https://core.trac.wordpress.org/browser/tags/5.3/src/wp-includes/class-wp-query.php#L3234>
and lines after this filter is applied to have better understanding of how it will work.
NB: I've used `is_main_query()` conditional and `is_post_type_archive` meaning it will be used for main Post archive loop or CPT archive page loop, but you can adjust the way you want.
UPD: added `!is_admin()` - check so it will not fire in wp-admin. |
361,146 | <p>I'm trying to install Wordpress 5.3.2 on NetBSD (unix). phpinfo() tells me I am running Apache/2.4.33 (Unix) PHP/7.2.6</p>
<p>/wp-admin/setup-config.php?step=1 has a message at the bottom of the window (below the "submit" button) saying "There has been a critical error on your website". </p>
<p>Thinking to set WP_DEBUG to "true" in the hope of getting an error message, I manually configured wp-config.php, but on install.php I get a blank screen. </p>
<p>The server log says "Call to undefined function wp_kses_normalize_entities()". </p>
<p>I've tried using /wp-admin/setup-config.php to configure php-config.php as well, and looking up the server log I see other errors: "Call to undefined function mysql_connect()" (from wp-includes/wp-db.php) and "Call to undefined function json_encode()" from wp-includes/functions.php:3820</p>
<p>As this is at the installation stage, so the only thing I have altered is wp-config.php (each time editing from the default file).I've not got as far as a Wordpress dashboard, so there are no plugins to disable. What do I do?</p>
| [
{
"answer_id": 360993,
"author": "Mikhail",
"author_id": 88888,
"author_profile": "https://wordpress.stackexchange.com/users/88888",
"pm_score": 2,
"selected": true,
"text": "<p>I consider the right way could be filtering of total number of found posts like this.</p>\n\n<pre><code>function my_custom_found_posts_limiter( $found_posts, $wp_query ) {\n\n $maximum_of_post_items = 100; // place your desired value here or read if from option\\setting.\n\n if ( ! is_admin() && $wp_query->is_main_query() && $wp_query->is_post_type_archive( 'blog_posts' ) ) {\n if ( $found_posts > $maximum_of_post_items ) {\n return $maximum_of_post_items; // we return maximum amount, so pagination will be aware of this number.\n }\n }\n\n return $found_posts;\n}\nadd_filter( 'found_posts', 'my_custom_found_posts_limiter', 10, 2 );\n</code></pre>\n\n<p>See source code here <a href=\"https://core.trac.wordpress.org/browser/tags/5.3/src/wp-includes/class-wp-query.php#L3234\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/browser/tags/5.3/src/wp-includes/class-wp-query.php#L3234</a></p>\n\n<p>and lines after this filter is applied to have better understanding of how it will work.</p>\n\n<p>NB: I've used <code>is_main_query()</code> conditional and <code>is_post_type_archive</code> meaning it will be used for main Post archive loop or CPT archive page loop, but you can adjust the way you want.</p>\n\n<p>UPD: added <code>!is_admin()</code> - check so it will not fire in wp-admin.</p>\n"
},
{
"answer_id": 361013,
"author": "G. Bonini",
"author_id": 184502,
"author_profile": "https://wordpress.stackexchange.com/users/184502",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the post_limits filter:</p>\n\n<pre><code>function my_posts_limits( $limit, $query ) {\n\n if ( ! is_admin() && $query->is_main_query() ) {\n return 'LIMIT 0, 25';\n }\n\n return $limit;\n}\nadd_filter( 'post_limits', 'my_posts_limits', 10, 2 );\n</code></pre>\n\n<p>This will work for your main query and won't affect the admin.</p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/post_limits\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Filter_Reference/post_limits</a></p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/288974/limit-wp-query-to-only-x-results-total-not-per-page?rq=1\">Limit WP_Query to only X results (total, not per page)</a></p>\n"
}
] | 2020/03/21 | [
"https://wordpress.stackexchange.com/questions/361146",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/184599/"
] | I'm trying to install Wordpress 5.3.2 on NetBSD (unix). phpinfo() tells me I am running Apache/2.4.33 (Unix) PHP/7.2.6
/wp-admin/setup-config.php?step=1 has a message at the bottom of the window (below the "submit" button) saying "There has been a critical error on your website".
Thinking to set WP\_DEBUG to "true" in the hope of getting an error message, I manually configured wp-config.php, but on install.php I get a blank screen.
The server log says "Call to undefined function wp\_kses\_normalize\_entities()".
I've tried using /wp-admin/setup-config.php to configure php-config.php as well, and looking up the server log I see other errors: "Call to undefined function mysql\_connect()" (from wp-includes/wp-db.php) and "Call to undefined function json\_encode()" from wp-includes/functions.php:3820
As this is at the installation stage, so the only thing I have altered is wp-config.php (each time editing from the default file).I've not got as far as a Wordpress dashboard, so there are no plugins to disable. What do I do? | I consider the right way could be filtering of total number of found posts like this.
```
function my_custom_found_posts_limiter( $found_posts, $wp_query ) {
$maximum_of_post_items = 100; // place your desired value here or read if from option\setting.
if ( ! is_admin() && $wp_query->is_main_query() && $wp_query->is_post_type_archive( 'blog_posts' ) ) {
if ( $found_posts > $maximum_of_post_items ) {
return $maximum_of_post_items; // we return maximum amount, so pagination will be aware of this number.
}
}
return $found_posts;
}
add_filter( 'found_posts', 'my_custom_found_posts_limiter', 10, 2 );
```
See source code here <https://core.trac.wordpress.org/browser/tags/5.3/src/wp-includes/class-wp-query.php#L3234>
and lines after this filter is applied to have better understanding of how it will work.
NB: I've used `is_main_query()` conditional and `is_post_type_archive` meaning it will be used for main Post archive loop or CPT archive page loop, but you can adjust the way you want.
UPD: added `!is_admin()` - check so it will not fire in wp-admin. |
361,203 | <p>I want the permalinks to be like youtube generated from letters and numbers in 9 digits I modified this code</p>
<pre><code>add_filter( 'wp_unique_post_slug', 'unique_slug_108286', 10, 4 );
function unique_slug_108286( $slug) {
$n=4;
$slug = bin2hex(random_bytes($n)); //just an example
return $slug;
}
</code></pre>
<p>so it's worked and gave me a random slug , but the problem is that this slug is changed every time I entered the post at the backend , so I need it to be generated once and unique</p>
<p>I also found this solution it also worked but the same problem It's changed every time I enter the post </p>
<pre><code>add_filter( 'wp_unique_post_slug', 'unique_slug_so_11762070', 10, 6 );
function unique_slug_so_11762070( $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug ) {
$new_slug = so_11762070_unique_post_slug('guid');
return $new_slug;
}
# From: https://stackoverflow.com/a/11762698
function so_11762070_unique_post_slug($col,$table='wp_posts'){
global $wpdb;
$alphabet = array_merge( range(0, 9), range('a','z') );
$already_exists = true;
do {
$guidchr = array();
for ($i=0; $i<32; $i++)
$guidchr[] = $alphabet[array_rand( $alphabet )];
$guid = sprintf( "%s", implode("", array_slice($guidchr, 0, 12, true)) );
// check that GUID is unique
$already_exists = (boolean) $wpdb->get_var("
SELECT COUNT($col) as the_amount FROM $table WHERE $col = '$guid'
");
} while (true == $already_exists);
return $guid;
}
</code></pre>
| [
{
"answer_id": 361209,
"author": "Shazzad",
"author_id": 42967,
"author_profile": "https://wordpress.stackexchange.com/users/42967",
"pm_score": 1,
"selected": false,
"text": "<p>The second argument of <code>wp_unique_post_slug</code> filter is post id. You can utilize that to generate the slug only once while creating the post for the first time.</p>\n\n<p><strong>Method 1:</strong></p>\n\n<pre><code>add_filter( 'wp_unique_post_slug', 'unique_slug_108286', 10, 2 );\nfunction unique_slug_108286( $slug, $postId ) {\n if ( ! $postId ) {\n $n = 4;\n $slug = bin2hex( random_bytes( $n ) ); //just an example\n }\n return $slug;\n}\n</code></pre>\n\n<p><em>Other method would be using post meta to indicate whether a slug has been generated.</em></p>\n\n<p><strong>Method 2:</strong></p>\n\n<pre><code>add_filter( 'wp_unique_post_slug', 'unique_slug_108286', 10, 2 );\nfunction unique_slug_108286( $slug, $postId ) {\n if ( $postId && ! get_post_meta( $postId, 'slug_generated', true ) ) {\n $n = 4;\n $slug = bin2hex( random_bytes( $n ) ); //just an example\n update_post_meta( $postId, 'slug_generated', true );\n }\n return $slug;\n}\n</code></pre>\n"
},
{
"answer_id": 361214,
"author": "Akel",
"author_id": 184638,
"author_profile": "https://wordpress.stackexchange.com/users/184638",
"pm_score": 0,
"selected": false,
"text": "<p>OK finally I found the solution </p>\n\n<pre><code>function append_slug($data) {\n global $post_ID;\n\n if (empty($data['post_name'])) {\n $n=4;\n $data['post_name'] = bin2hex(random_bytes($n));\n }\n\n return $data;\n}\n</code></pre>\n\n<p>thank you all for help </p>\n"
}
] | 2020/03/22 | [
"https://wordpress.stackexchange.com/questions/361203",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/184638/"
] | I want the permalinks to be like youtube generated from letters and numbers in 9 digits I modified this code
```
add_filter( 'wp_unique_post_slug', 'unique_slug_108286', 10, 4 );
function unique_slug_108286( $slug) {
$n=4;
$slug = bin2hex(random_bytes($n)); //just an example
return $slug;
}
```
so it's worked and gave me a random slug , but the problem is that this slug is changed every time I entered the post at the backend , so I need it to be generated once and unique
I also found this solution it also worked but the same problem It's changed every time I enter the post
```
add_filter( 'wp_unique_post_slug', 'unique_slug_so_11762070', 10, 6 );
function unique_slug_so_11762070( $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug ) {
$new_slug = so_11762070_unique_post_slug('guid');
return $new_slug;
}
# From: https://stackoverflow.com/a/11762698
function so_11762070_unique_post_slug($col,$table='wp_posts'){
global $wpdb;
$alphabet = array_merge( range(0, 9), range('a','z') );
$already_exists = true;
do {
$guidchr = array();
for ($i=0; $i<32; $i++)
$guidchr[] = $alphabet[array_rand( $alphabet )];
$guid = sprintf( "%s", implode("", array_slice($guidchr, 0, 12, true)) );
// check that GUID is unique
$already_exists = (boolean) $wpdb->get_var("
SELECT COUNT($col) as the_amount FROM $table WHERE $col = '$guid'
");
} while (true == $already_exists);
return $guid;
}
``` | The second argument of `wp_unique_post_slug` filter is post id. You can utilize that to generate the slug only once while creating the post for the first time.
**Method 1:**
```
add_filter( 'wp_unique_post_slug', 'unique_slug_108286', 10, 2 );
function unique_slug_108286( $slug, $postId ) {
if ( ! $postId ) {
$n = 4;
$slug = bin2hex( random_bytes( $n ) ); //just an example
}
return $slug;
}
```
*Other method would be using post meta to indicate whether a slug has been generated.*
**Method 2:**
```
add_filter( 'wp_unique_post_slug', 'unique_slug_108286', 10, 2 );
function unique_slug_108286( $slug, $postId ) {
if ( $postId && ! get_post_meta( $postId, 'slug_generated', true ) ) {
$n = 4;
$slug = bin2hex( random_bytes( $n ) ); //just an example
update_post_meta( $postId, 'slug_generated', true );
}
return $slug;
}
``` |
361,204 | <p>I am working on a project that needs a website with region specific pages. One of the key requirements is that while the blog, about and other pages are the same for all regions pricing, staff, booking and events pages would be specific to the region. </p>
<p>Think something like this: <a href="https://locations.massageenvy.com/utah/american-fork/356-north-750-west.html" rel="nofollow noreferrer">https://locations.massageenvy.com/utah/american-fork/356-north-750-west.html</a></p>
<p>One caveat in this case is that we don't necessarily have a specific store location, but rather a service area (kind of like handyman service websites).</p>
<p>Is MultiSite with subdirectories the correct solution in this case? Is there a different (better) way to build a site like this?</p>
<p>If multisite is the correct solution, is there an existing plugin for building a location search feature?</p>
| [
{
"answer_id": 361209,
"author": "Shazzad",
"author_id": 42967,
"author_profile": "https://wordpress.stackexchange.com/users/42967",
"pm_score": 1,
"selected": false,
"text": "<p>The second argument of <code>wp_unique_post_slug</code> filter is post id. You can utilize that to generate the slug only once while creating the post for the first time.</p>\n\n<p><strong>Method 1:</strong></p>\n\n<pre><code>add_filter( 'wp_unique_post_slug', 'unique_slug_108286', 10, 2 );\nfunction unique_slug_108286( $slug, $postId ) {\n if ( ! $postId ) {\n $n = 4;\n $slug = bin2hex( random_bytes( $n ) ); //just an example\n }\n return $slug;\n}\n</code></pre>\n\n<p><em>Other method would be using post meta to indicate whether a slug has been generated.</em></p>\n\n<p><strong>Method 2:</strong></p>\n\n<pre><code>add_filter( 'wp_unique_post_slug', 'unique_slug_108286', 10, 2 );\nfunction unique_slug_108286( $slug, $postId ) {\n if ( $postId && ! get_post_meta( $postId, 'slug_generated', true ) ) {\n $n = 4;\n $slug = bin2hex( random_bytes( $n ) ); //just an example\n update_post_meta( $postId, 'slug_generated', true );\n }\n return $slug;\n}\n</code></pre>\n"
},
{
"answer_id": 361214,
"author": "Akel",
"author_id": 184638,
"author_profile": "https://wordpress.stackexchange.com/users/184638",
"pm_score": 0,
"selected": false,
"text": "<p>OK finally I found the solution </p>\n\n<pre><code>function append_slug($data) {\n global $post_ID;\n\n if (empty($data['post_name'])) {\n $n=4;\n $data['post_name'] = bin2hex(random_bytes($n));\n }\n\n return $data;\n}\n</code></pre>\n\n<p>thank you all for help </p>\n"
}
] | 2020/03/22 | [
"https://wordpress.stackexchange.com/questions/361204",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/184644/"
] | I am working on a project that needs a website with region specific pages. One of the key requirements is that while the blog, about and other pages are the same for all regions pricing, staff, booking and events pages would be specific to the region.
Think something like this: <https://locations.massageenvy.com/utah/american-fork/356-north-750-west.html>
One caveat in this case is that we don't necessarily have a specific store location, but rather a service area (kind of like handyman service websites).
Is MultiSite with subdirectories the correct solution in this case? Is there a different (better) way to build a site like this?
If multisite is the correct solution, is there an existing plugin for building a location search feature? | The second argument of `wp_unique_post_slug` filter is post id. You can utilize that to generate the slug only once while creating the post for the first time.
**Method 1:**
```
add_filter( 'wp_unique_post_slug', 'unique_slug_108286', 10, 2 );
function unique_slug_108286( $slug, $postId ) {
if ( ! $postId ) {
$n = 4;
$slug = bin2hex( random_bytes( $n ) ); //just an example
}
return $slug;
}
```
*Other method would be using post meta to indicate whether a slug has been generated.*
**Method 2:**
```
add_filter( 'wp_unique_post_slug', 'unique_slug_108286', 10, 2 );
function unique_slug_108286( $slug, $postId ) {
if ( $postId && ! get_post_meta( $postId, 'slug_generated', true ) ) {
$n = 4;
$slug = bin2hex( random_bytes( $n ) ); //just an example
update_post_meta( $postId, 'slug_generated', true );
}
return $slug;
}
``` |
361,205 | <p>I have a website that sells gaming related stuff, i need to show some buffs as icons/small images under every product below the product image, on the archive/category page, apparently there is no such option nor plugin on the internet that can help me (i would like to be corrected on this please)</p>
<p>So i am trying to work around this on my own, i have very basic coding knowledge.</p>
<p>They way i am trying to do it is by: </p>
<ol>
<li>These icons are common to the products but their combinations are unique per
product, to make it easy i made them as attributes so i can easily assign
them per product.</li>
<li>Installed the variation swatches for woocommerce plugin so
attributes can have there own images </li>
<li>Made an attribute and made its sub-attributes as my icons and attached
images.</li>
<li>All my products are simple downloadable products so variation
swatches for woocommerce is of no help as it only works for variable
products, but it gave attributes their own images.</li>
<li>Currently i can output the values on attributes on my product cat/archive page with the following
code but not images as i have no idea how to call them.</li>
</ol>
<p>I can display the attributes and there values using the following code </p>
<pre><code><?php
add_action( 'woocommerce_after_shop_loop_item', 'loop_attributes', 20 );
function loop_attributes() {
global $product;
if( ! is_object( $product ) ) {
$product = wc_get_product( get_the_id() );
}
$win_val = $product->get_attribute('pa_wins');
$hour_val = $product->get_attribute('pa_hours');
$badge_val = $product->get_attribute('pa_badges');
$token_val = $product->get_attribute('pa_token');
echo '<img src="' . $token_val . '" class="aligncenter" style="margin-bottom: 20px;" />';
echo '<span class="attrs1"><i style="color:#1c7e5a;" class="fas fa-trophy"></i> Wins:</span>'.'<span
class="attrs2"> '.$win_val.' </span>';
echo '<span class="attrs1"><i style="color:#1c7e5a;" class="fas fa-hourglass"></i> Hours:
</span>'.'<span class="attrs2"> '.$hour_val.' </span>';
echo '<span class="attrs1"><i style="color:#1c7e5a;" class="fas fa-ribbon"></i> Badges:
</span>'.'<span class="attrs2"> '.$badge_val.' </span>';
}
add_filter( 'woocommerce_hide_invisible_variations', '__return_false' );
?>
</code></pre>
<p>The code above shows the corresponding attribute name and their values on the product cat/archive page, </p>
<p>The attribute pa_token has images attached to their values, </p>
<p>I want the pa_token to output its attached images instead of values, in the below example the code for pa_token is a representation of what i want its not a working code,</p>
<pre><code>echo '<img src="' . $token_val . '" class="aligncenter" style="margin-bottom: 20px;" />';
</code></pre>
<p>I need advice if this is a good approach or is there already a solution for this ? If not then how can i go about calling the images attached to the attributes! </p>
<p><strong>Update 1:</strong></p>
<p>When i put this code</p>
<pre><code>function loop_attributes() {
global $product;
if( ! is_object( $product ) ) {
$product = wc_get_product( get_the_id() );
}
echo '<pre>', print_r($product->get_attributes(), 1), '</pre>';
$token_val = $product->get_attribute('pa_token');
echo '<pre>', print_r($token_val, 1), '</pre>';
}
add_action( 'woocommerce_after_shop_loop_item', 'loop_attributes', 10, 0 );
</code></pre>
<p>I get the following output</p>
<pre><code>Array
(
[pa_token] => WC_Product_Attribute Object
(
[data:protected] => Array
(
[id] => 9
[name] => pa_token
[options] => Array
(
[0] => 210
[1] => 211
)
[position] => 6
[visible] => 1
[variation] =>
)
)
)
a, bb
</code></pre>
<p>a, bb are the sub attributes/values that have images attached to them</p>
<p>pa_token-> a - Icon 1, bb - Icon 2</p>
<p><strong>Update 2:</strong></p>
<p>So if i do the following code </p>
<pre><code>var_dump( get_term_meta( 210 ) );
</code></pre>
<p>I get the following output, looks like we are heading to the right path</p>
<pre><code>array(6) { ["order_pa_token"]=> array(1) { [0]=> string(1) "0" }
["product_attribute_image"]=> array(1) { [0]=> string(5) "12706" }
["image_size"]=> array(1) { [0]=> string(9) "thumbnail" } ["show_tooltip"]=>
array(1) { [0]=> string(4) "text" } ["tooltip_text"]=> array(1) { [0]=>
string(3) "aaa" } ["tooltip_image"]=> array(1) { [0]=> string(1) "0" } }
</code></pre>
<p>I guess we have the meta now, now what should be the relevant code to only output the images with there tooltips on the category/archive page ? </p>
<p><strong>Update 3:</strong></p>
<p>By updating the code to :</p>
<pre><code>function loop_attributes() {
global $product;
if( ! is_object( $product ) ) {
$product = wc_get_product( get_the_id() );
}
// Get Product Variations - WC_Product_Attribute Object
$product_attributes = $product->get_attributes();
// Not empty, contains values
if ( !empty( $product_attributes ) ) {
foreach ( $product_attributes as $product_attribute ) {
// Get options
$attribute_options = $product_attribute->get_options();
// Not empty, contains values
if ( !empty( $attribute_options ) ) {
foreach ($attribute_options as $key => $attribute_option ) {
// WP_Term Object
$term = get_term($attribute_option); // <-- your term ID
echo '<pre>', print_r($term, 1), '</pre>';
}
}
}
}
}
add_action( 'woocommerce_after_shop_loop_item', 'loop_attributes', 10, 0 );
</code></pre>
<p>i get the below output</p>
<pre><code><pre>
WP_Term Object
(
[term_id] => 210
[name] => a
[slug] => aa
[term_group] => 0
[term_taxonomy_id] => 210
[taxonomy] => pa_token
[description] =>
[parent] => 0
[count] => 2
[filter] => raw
)
</pre>
<pre>
WP_Term Object
(
[term_id] => 211
[name] => bb
[slug] => bb
[term_group] => 0
[term_taxonomy_id] => 211
[taxonomy] => pa_token
[description] =>
[parent] => 0
[count] => 2
[filter] => raw
)
</pre>
</code></pre>
<p><strong>Update 4:</strong></p>
<p>So i was not able to solve my problem earlier, then i switched the plugin to Category and Taxonomy Image by Aftab Hussain and used the following code to call images on the category/archive loop page:</p>
<pre><code>add_action( 'woocommerce_after_shop_loop_item',
'attribute_img_loop', 20 );
function attribute_img_loop() {
global $product;
// Check that we got the instance of the WC_Product object, to be sure (can
be removed)
if( ! is_object( $product ) ) {
$product = wc_get_product( get_the_id() );
}
$token_imgs = get_the_terms( get_the_ID(), 'pa_token');
foreach ( (array) $token_imgs as $token_img ) {
$terms = $token_img->term_id;
$meta_image = get_wp_term_image($terms);
echo '<ul><li><img src="' . $meta_image . '" class="tokenimg" " /></li>
</ul>';
}
}
</code></pre>
<p>pa_token is my attribute with sub attributes that have images</p>
<p>foreach loop is used to output all the sub attributes used per product, otherwise it will output only the first result.</p>
<p>(array) inside foreach loop is used to not return anything if the value is null, otherwise all the other products with no attributes get an ugly php debug error on the main page, let me know if there is a non hack way to handle this.</p>
<p>Thanks for your help guys for giving me the right direction. </p>
| [
{
"answer_id": 361246,
"author": "7uc1f3r",
"author_id": 182113,
"author_profile": "https://wordpress.stackexchange.com/users/182113",
"pm_score": 0,
"selected": false,
"text": "<p>I don't use the plugin you use for adding images. You can run the following code, this will give you more information about where to find the path to the image.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function loop_attributes() {\n global $product;\n\n if( ! is_object( $product ) ) {\n $product = wc_get_product( get_the_id() );\n }\n\n // Get Product Variations - WC_Product_Attribute Object\n $product_attributes = $product->get_attributes();\n\n // Not empty, contains values\n if ( !empty( $product_attributes ) ) {\n\n foreach ( $product_attributes as $product_attribute ) {\n // Get options\n $attribute_options = $product_attribute->get_options();\n\n // Not empty, contains values\n if ( !empty( $attribute_options ) ) {\n\n foreach ($attribute_options as $key => $attribute_option ) {\n // WP_Term Object\n $term = get_term($attribute_option); // <-- your term ID\n\n echo '<pre>', print_r($term, 1), '</pre>';\n }\n }\n }\n }\n}\nadd_action( 'woocommerce_after_shop_loop_item', 'loop_attributes', 10, 0 );\n</code></pre>\n"
},
{
"answer_id": 361585,
"author": "ulvayaam",
"author_id": 166733,
"author_profile": "https://wordpress.stackexchange.com/users/166733",
"pm_score": 2,
"selected": true,
"text": "<p>So I was not able to solve my problem earlier, then I switched the plugin to \"<a href=\"https://wordpress.org/plugins/wp-custom-taxonomy-image/\" rel=\"nofollow noreferrer\">Category and Taxonomy Image</a>\" (by Aftab Hussain) and used the following code to display the icons on category/archive pages:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'woocommerce_after_shop_loop_item', 'attribute_img_loop', 20 );\nfunction attribute_img_loop() {\n global $product;\n\n // Check that we got the instance of the WC_Product object, to be sure (can\n // be removed)\n if ( ! is_object( $product ) ) {\n $product = wc_get_product( get_the_ID() );\n }\n\n $token_imgs = get_the_terms( get_the_ID(), 'pa_token' );\n\n foreach ( (array) $token_imgs as $token_img ) {\n $terms = $token_img->term_id;\n\n $meta_image = get_wp_term_image( $terms );\n echo '<ul><li><img src=\"' . $meta_image . '\" class=\"tokenimg\" /></li></ul>';\n }\n}\n</code></pre>\n\n<ul>\n<li><p><code>pa_token</code> is my attribute with sub-attributes/terms that have images.</p></li>\n<li><p><code>foreach</code> loop is used to output all the sub-attributes used per product, otherwise it will output only the first result.</p></li>\n<li><p><code>(array)</code> inside the <code>foreach</code> loop is used to not return anything if the value is null, otherwise all the other products with no attributes get an ugly PHP debug error on the main page.</p></li>\n</ul>\n\n<p>Thanks for your help guys, for giving me the right direction.</p>\n\n<p><strong>Notes from Sally:</strong></p>\n\n<ol>\n<li><p>I'd just remove the <code>$product</code> since you don't really need it there because you used <code>get_the_terms()</code> and not a WooCommerce-specific function for getting the <code>pa_token</code> terms.</p></li>\n<li><p>I don't recommend the <code>(array) $token_imgs</code>. Instead, make sure the <code>$token_imgs</code> is not a <code>WP_Error</code> instance and that it's not an empty array.</p></li>\n<li><p>Instead of multiple <code>ul</code> (<code><ul><li></li></ul> <ul><li></li></ul> <ul><li></li></ul>...</code>), I'd use multiple <code>li</code> (<code><ul><li></li> <li></li> <li></li>...</ul></code>). :)</p></li>\n</ol>\n\n<p>So my code would be:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'woocommerce_after_shop_loop_item', 'attribute_img_loop', 20 );\nfunction attribute_img_loop() {\n $token_imgs = get_the_terms( get_the_ID(), 'pa_token' );\n if ( ! is_wp_error( $token_imgs ) && ! empty( $token_imgs ) ) {\n echo '<ul>';\n foreach ( $token_imgs as $term ) {\n $meta_image = get_wp_term_image( $term->term_id );\n echo '<li><img src=\"' . $meta_image . '\" class=\"tokenimg\" /></li>';\n }\n echo '</ul>';\n }\n}\n</code></pre>\n"
}
] | 2020/03/22 | [
"https://wordpress.stackexchange.com/questions/361205",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/166733/"
] | I have a website that sells gaming related stuff, i need to show some buffs as icons/small images under every product below the product image, on the archive/category page, apparently there is no such option nor plugin on the internet that can help me (i would like to be corrected on this please)
So i am trying to work around this on my own, i have very basic coding knowledge.
They way i am trying to do it is by:
1. These icons are common to the products but their combinations are unique per
product, to make it easy i made them as attributes so i can easily assign
them per product.
2. Installed the variation swatches for woocommerce plugin so
attributes can have there own images
3. Made an attribute and made its sub-attributes as my icons and attached
images.
4. All my products are simple downloadable products so variation
swatches for woocommerce is of no help as it only works for variable
products, but it gave attributes their own images.
5. Currently i can output the values on attributes on my product cat/archive page with the following
code but not images as i have no idea how to call them.
I can display the attributes and there values using the following code
```
<?php
add_action( 'woocommerce_after_shop_loop_item', 'loop_attributes', 20 );
function loop_attributes() {
global $product;
if( ! is_object( $product ) ) {
$product = wc_get_product( get_the_id() );
}
$win_val = $product->get_attribute('pa_wins');
$hour_val = $product->get_attribute('pa_hours');
$badge_val = $product->get_attribute('pa_badges');
$token_val = $product->get_attribute('pa_token');
echo '<img src="' . $token_val . '" class="aligncenter" style="margin-bottom: 20px;" />';
echo '<span class="attrs1"><i style="color:#1c7e5a;" class="fas fa-trophy"></i> Wins:</span>'.'<span
class="attrs2"> '.$win_val.' </span>';
echo '<span class="attrs1"><i style="color:#1c7e5a;" class="fas fa-hourglass"></i> Hours:
</span>'.'<span class="attrs2"> '.$hour_val.' </span>';
echo '<span class="attrs1"><i style="color:#1c7e5a;" class="fas fa-ribbon"></i> Badges:
</span>'.'<span class="attrs2"> '.$badge_val.' </span>';
}
add_filter( 'woocommerce_hide_invisible_variations', '__return_false' );
?>
```
The code above shows the corresponding attribute name and their values on the product cat/archive page,
The attribute pa\_token has images attached to their values,
I want the pa\_token to output its attached images instead of values, in the below example the code for pa\_token is a representation of what i want its not a working code,
```
echo '<img src="' . $token_val . '" class="aligncenter" style="margin-bottom: 20px;" />';
```
I need advice if this is a good approach or is there already a solution for this ? If not then how can i go about calling the images attached to the attributes!
**Update 1:**
When i put this code
```
function loop_attributes() {
global $product;
if( ! is_object( $product ) ) {
$product = wc_get_product( get_the_id() );
}
echo '<pre>', print_r($product->get_attributes(), 1), '</pre>';
$token_val = $product->get_attribute('pa_token');
echo '<pre>', print_r($token_val, 1), '</pre>';
}
add_action( 'woocommerce_after_shop_loop_item', 'loop_attributes', 10, 0 );
```
I get the following output
```
Array
(
[pa_token] => WC_Product_Attribute Object
(
[data:protected] => Array
(
[id] => 9
[name] => pa_token
[options] => Array
(
[0] => 210
[1] => 211
)
[position] => 6
[visible] => 1
[variation] =>
)
)
)
a, bb
```
a, bb are the sub attributes/values that have images attached to them
pa\_token-> a - Icon 1, bb - Icon 2
**Update 2:**
So if i do the following code
```
var_dump( get_term_meta( 210 ) );
```
I get the following output, looks like we are heading to the right path
```
array(6) { ["order_pa_token"]=> array(1) { [0]=> string(1) "0" }
["product_attribute_image"]=> array(1) { [0]=> string(5) "12706" }
["image_size"]=> array(1) { [0]=> string(9) "thumbnail" } ["show_tooltip"]=>
array(1) { [0]=> string(4) "text" } ["tooltip_text"]=> array(1) { [0]=>
string(3) "aaa" } ["tooltip_image"]=> array(1) { [0]=> string(1) "0" } }
```
I guess we have the meta now, now what should be the relevant code to only output the images with there tooltips on the category/archive page ?
**Update 3:**
By updating the code to :
```
function loop_attributes() {
global $product;
if( ! is_object( $product ) ) {
$product = wc_get_product( get_the_id() );
}
// Get Product Variations - WC_Product_Attribute Object
$product_attributes = $product->get_attributes();
// Not empty, contains values
if ( !empty( $product_attributes ) ) {
foreach ( $product_attributes as $product_attribute ) {
// Get options
$attribute_options = $product_attribute->get_options();
// Not empty, contains values
if ( !empty( $attribute_options ) ) {
foreach ($attribute_options as $key => $attribute_option ) {
// WP_Term Object
$term = get_term($attribute_option); // <-- your term ID
echo '<pre>', print_r($term, 1), '</pre>';
}
}
}
}
}
add_action( 'woocommerce_after_shop_loop_item', 'loop_attributes', 10, 0 );
```
i get the below output
```
<pre>
WP_Term Object
(
[term_id] => 210
[name] => a
[slug] => aa
[term_group] => 0
[term_taxonomy_id] => 210
[taxonomy] => pa_token
[description] =>
[parent] => 0
[count] => 2
[filter] => raw
)
</pre>
<pre>
WP_Term Object
(
[term_id] => 211
[name] => bb
[slug] => bb
[term_group] => 0
[term_taxonomy_id] => 211
[taxonomy] => pa_token
[description] =>
[parent] => 0
[count] => 2
[filter] => raw
)
</pre>
```
**Update 4:**
So i was not able to solve my problem earlier, then i switched the plugin to Category and Taxonomy Image by Aftab Hussain and used the following code to call images on the category/archive loop page:
```
add_action( 'woocommerce_after_shop_loop_item',
'attribute_img_loop', 20 );
function attribute_img_loop() {
global $product;
// Check that we got the instance of the WC_Product object, to be sure (can
be removed)
if( ! is_object( $product ) ) {
$product = wc_get_product( get_the_id() );
}
$token_imgs = get_the_terms( get_the_ID(), 'pa_token');
foreach ( (array) $token_imgs as $token_img ) {
$terms = $token_img->term_id;
$meta_image = get_wp_term_image($terms);
echo '<ul><li><img src="' . $meta_image . '" class="tokenimg" " /></li>
</ul>';
}
}
```
pa\_token is my attribute with sub attributes that have images
foreach loop is used to output all the sub attributes used per product, otherwise it will output only the first result.
(array) inside foreach loop is used to not return anything if the value is null, otherwise all the other products with no attributes get an ugly php debug error on the main page, let me know if there is a non hack way to handle this.
Thanks for your help guys for giving me the right direction. | So I was not able to solve my problem earlier, then I switched the plugin to "[Category and Taxonomy Image](https://wordpress.org/plugins/wp-custom-taxonomy-image/)" (by Aftab Hussain) and used the following code to display the icons on category/archive pages:
```php
add_action( 'woocommerce_after_shop_loop_item', 'attribute_img_loop', 20 );
function attribute_img_loop() {
global $product;
// Check that we got the instance of the WC_Product object, to be sure (can
// be removed)
if ( ! is_object( $product ) ) {
$product = wc_get_product( get_the_ID() );
}
$token_imgs = get_the_terms( get_the_ID(), 'pa_token' );
foreach ( (array) $token_imgs as $token_img ) {
$terms = $token_img->term_id;
$meta_image = get_wp_term_image( $terms );
echo '<ul><li><img src="' . $meta_image . '" class="tokenimg" /></li></ul>';
}
}
```
* `pa_token` is my attribute with sub-attributes/terms that have images.
* `foreach` loop is used to output all the sub-attributes used per product, otherwise it will output only the first result.
* `(array)` inside the `foreach` loop is used to not return anything if the value is null, otherwise all the other products with no attributes get an ugly PHP debug error on the main page.
Thanks for your help guys, for giving me the right direction.
**Notes from Sally:**
1. I'd just remove the `$product` since you don't really need it there because you used `get_the_terms()` and not a WooCommerce-specific function for getting the `pa_token` terms.
2. I don't recommend the `(array) $token_imgs`. Instead, make sure the `$token_imgs` is not a `WP_Error` instance and that it's not an empty array.
3. Instead of multiple `ul` (`<ul><li></li></ul> <ul><li></li></ul> <ul><li></li></ul>...`), I'd use multiple `li` (`<ul><li></li> <li></li> <li></li>...</ul>`). :)
So my code would be:
```php
add_action( 'woocommerce_after_shop_loop_item', 'attribute_img_loop', 20 );
function attribute_img_loop() {
$token_imgs = get_the_terms( get_the_ID(), 'pa_token' );
if ( ! is_wp_error( $token_imgs ) && ! empty( $token_imgs ) ) {
echo '<ul>';
foreach ( $token_imgs as $term ) {
$meta_image = get_wp_term_image( $term->term_id );
echo '<li><img src="' . $meta_image . '" class="tokenimg" /></li>';
}
echo '</ul>';
}
}
``` |
361,265 | <p>I want to compare two prices in my database. I get a row with any id:</p>
<pre><code>$price1 = $wpdb->get_row( "SELECT * FROM $wpdb->prices WHERE id = 10" );
</code></pre>
<p>I want to get up the row from this table means I want to get row same bellow but if row by id 9 is deleted it's missing:</p>
<pre><code>$price1 = $wpdb->get_row( "SELECT * FROM $wpdb->prices WHERE id = 9" );
</code></pre>
<p>How do this?</p>
| [
{
"answer_id": 361246,
"author": "7uc1f3r",
"author_id": 182113,
"author_profile": "https://wordpress.stackexchange.com/users/182113",
"pm_score": 0,
"selected": false,
"text": "<p>I don't use the plugin you use for adding images. You can run the following code, this will give you more information about where to find the path to the image.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function loop_attributes() {\n global $product;\n\n if( ! is_object( $product ) ) {\n $product = wc_get_product( get_the_id() );\n }\n\n // Get Product Variations - WC_Product_Attribute Object\n $product_attributes = $product->get_attributes();\n\n // Not empty, contains values\n if ( !empty( $product_attributes ) ) {\n\n foreach ( $product_attributes as $product_attribute ) {\n // Get options\n $attribute_options = $product_attribute->get_options();\n\n // Not empty, contains values\n if ( !empty( $attribute_options ) ) {\n\n foreach ($attribute_options as $key => $attribute_option ) {\n // WP_Term Object\n $term = get_term($attribute_option); // <-- your term ID\n\n echo '<pre>', print_r($term, 1), '</pre>';\n }\n }\n }\n }\n}\nadd_action( 'woocommerce_after_shop_loop_item', 'loop_attributes', 10, 0 );\n</code></pre>\n"
},
{
"answer_id": 361585,
"author": "ulvayaam",
"author_id": 166733,
"author_profile": "https://wordpress.stackexchange.com/users/166733",
"pm_score": 2,
"selected": true,
"text": "<p>So I was not able to solve my problem earlier, then I switched the plugin to \"<a href=\"https://wordpress.org/plugins/wp-custom-taxonomy-image/\" rel=\"nofollow noreferrer\">Category and Taxonomy Image</a>\" (by Aftab Hussain) and used the following code to display the icons on category/archive pages:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'woocommerce_after_shop_loop_item', 'attribute_img_loop', 20 );\nfunction attribute_img_loop() {\n global $product;\n\n // Check that we got the instance of the WC_Product object, to be sure (can\n // be removed)\n if ( ! is_object( $product ) ) {\n $product = wc_get_product( get_the_ID() );\n }\n\n $token_imgs = get_the_terms( get_the_ID(), 'pa_token' );\n\n foreach ( (array) $token_imgs as $token_img ) {\n $terms = $token_img->term_id;\n\n $meta_image = get_wp_term_image( $terms );\n echo '<ul><li><img src=\"' . $meta_image . '\" class=\"tokenimg\" /></li></ul>';\n }\n}\n</code></pre>\n\n<ul>\n<li><p><code>pa_token</code> is my attribute with sub-attributes/terms that have images.</p></li>\n<li><p><code>foreach</code> loop is used to output all the sub-attributes used per product, otherwise it will output only the first result.</p></li>\n<li><p><code>(array)</code> inside the <code>foreach</code> loop is used to not return anything if the value is null, otherwise all the other products with no attributes get an ugly PHP debug error on the main page.</p></li>\n</ul>\n\n<p>Thanks for your help guys, for giving me the right direction.</p>\n\n<p><strong>Notes from Sally:</strong></p>\n\n<ol>\n<li><p>I'd just remove the <code>$product</code> since you don't really need it there because you used <code>get_the_terms()</code> and not a WooCommerce-specific function for getting the <code>pa_token</code> terms.</p></li>\n<li><p>I don't recommend the <code>(array) $token_imgs</code>. Instead, make sure the <code>$token_imgs</code> is not a <code>WP_Error</code> instance and that it's not an empty array.</p></li>\n<li><p>Instead of multiple <code>ul</code> (<code><ul><li></li></ul> <ul><li></li></ul> <ul><li></li></ul>...</code>), I'd use multiple <code>li</code> (<code><ul><li></li> <li></li> <li></li>...</ul></code>). :)</p></li>\n</ol>\n\n<p>So my code would be:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'woocommerce_after_shop_loop_item', 'attribute_img_loop', 20 );\nfunction attribute_img_loop() {\n $token_imgs = get_the_terms( get_the_ID(), 'pa_token' );\n if ( ! is_wp_error( $token_imgs ) && ! empty( $token_imgs ) ) {\n echo '<ul>';\n foreach ( $token_imgs as $term ) {\n $meta_image = get_wp_term_image( $term->term_id );\n echo '<li><img src=\"' . $meta_image . '\" class=\"tokenimg\" /></li>';\n }\n echo '</ul>';\n }\n}\n</code></pre>\n"
}
] | 2020/03/23 | [
"https://wordpress.stackexchange.com/questions/361265",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/175073/"
] | I want to compare two prices in my database. I get a row with any id:
```
$price1 = $wpdb->get_row( "SELECT * FROM $wpdb->prices WHERE id = 10" );
```
I want to get up the row from this table means I want to get row same bellow but if row by id 9 is deleted it's missing:
```
$price1 = $wpdb->get_row( "SELECT * FROM $wpdb->prices WHERE id = 9" );
```
How do this? | So I was not able to solve my problem earlier, then I switched the plugin to "[Category and Taxonomy Image](https://wordpress.org/plugins/wp-custom-taxonomy-image/)" (by Aftab Hussain) and used the following code to display the icons on category/archive pages:
```php
add_action( 'woocommerce_after_shop_loop_item', 'attribute_img_loop', 20 );
function attribute_img_loop() {
global $product;
// Check that we got the instance of the WC_Product object, to be sure (can
// be removed)
if ( ! is_object( $product ) ) {
$product = wc_get_product( get_the_ID() );
}
$token_imgs = get_the_terms( get_the_ID(), 'pa_token' );
foreach ( (array) $token_imgs as $token_img ) {
$terms = $token_img->term_id;
$meta_image = get_wp_term_image( $terms );
echo '<ul><li><img src="' . $meta_image . '" class="tokenimg" /></li></ul>';
}
}
```
* `pa_token` is my attribute with sub-attributes/terms that have images.
* `foreach` loop is used to output all the sub-attributes used per product, otherwise it will output only the first result.
* `(array)` inside the `foreach` loop is used to not return anything if the value is null, otherwise all the other products with no attributes get an ugly PHP debug error on the main page.
Thanks for your help guys, for giving me the right direction.
**Notes from Sally:**
1. I'd just remove the `$product` since you don't really need it there because you used `get_the_terms()` and not a WooCommerce-specific function for getting the `pa_token` terms.
2. I don't recommend the `(array) $token_imgs`. Instead, make sure the `$token_imgs` is not a `WP_Error` instance and that it's not an empty array.
3. Instead of multiple `ul` (`<ul><li></li></ul> <ul><li></li></ul> <ul><li></li></ul>...`), I'd use multiple `li` (`<ul><li></li> <li></li> <li></li>...</ul>`). :)
So my code would be:
```php
add_action( 'woocommerce_after_shop_loop_item', 'attribute_img_loop', 20 );
function attribute_img_loop() {
$token_imgs = get_the_terms( get_the_ID(), 'pa_token' );
if ( ! is_wp_error( $token_imgs ) && ! empty( $token_imgs ) ) {
echo '<ul>';
foreach ( $token_imgs as $term ) {
$meta_image = get_wp_term_image( $term->term_id );
echo '<li><img src="' . $meta_image . '" class="tokenimg" /></li>';
}
echo '</ul>';
}
}
``` |
361,330 | <p>I have a custom plugin and want it on occasions to fire the kind of notice that appears and disapears in the left corner like this one:</p>
<p><a href="https://i.stack.imgur.com/vvFwm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vvFwm.png" alt="snackbar notice"></a></p>
<p>I found some code <a href="https://developer.wordpress.org/block-editor/components/snackbar/#development-guidelines" rel="nofollow noreferrer">in the Gutenberg docs here</a>:</p>
<pre><code>const MySnackbarNotice = () => (
<Snackbar>
Post published successfully.
</Snackbar>
);
</code></pre>
<p>But adding this to my admin-enqueued js script obviously doesn't work.</p>
<p>Thanks!</p>
| [
{
"answer_id": 376902,
"author": "Andre Gagnon",
"author_id": 196421,
"author_profile": "https://wordpress.stackexchange.com/users/196421",
"pm_score": 4,
"selected": true,
"text": "<p>WordPress has some global actions you can use here. If you want to add your own notice in the lower corner (like the screenshot), you can do that like this:</p>\n<pre class=\"lang-js prettyprint-override\"><code> wp.data.dispatch("core/notices").createNotice(\n "success", // Can be one of: success, info, warning, error.\n "This is my custom message.", // Text string to display.\n {\n type: "snackbar",\n isDismissible: true, // Whether the user can dismiss the notice.\n // Any actions the user can perform.\n actions: [\n {\n url: '#',\n label: 'View post',\n },\n ],\n }\n );\n</code></pre>\n<p>The important part here is <code>type: "snackbar"</code>. You can also leave out the snackbar part and it will appear in the UI above the content:</p>\n<p><a href=\"https://i.stack.imgur.com/XPQsp.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/XPQsp.png\" alt=\"enter image description here\" /></a></p>\n<p>Here's the full article on WordPress' Block Editor Handbook: <a href=\"https://developer.wordpress.org/block-editor/tutorials/notices/\" rel=\"noreferrer\">https://developer.wordpress.org/block-editor/tutorials/notices/</a></p>\n"
},
{
"answer_id": 398805,
"author": "Max S.",
"author_id": 102418,
"author_profile": "https://wordpress.stackexchange.com/users/102418",
"pm_score": 1,
"selected": false,
"text": "<p>Although Andre's answer is partially correct, it's limited to the Javascript function only, and the linked tutorial doesn't provide a complete answer. Here's a complete solution which includes front and back:</p>\n<pre><code>add_action('admin_footer-post.php','my_pre_post_update_hook');\nadd_action('admin_footer-post-new.php','my_pre_post_update_hook');\nfunction my_pre_post_update_hook(){\n global $post;\n ?>\n <script type="text/javascript">\n jQuery(document).ready(function() {\n // We listen to Ajax calls made via fetch\n var temp_fetch = window.fetch;\n window.fetch = function() {\n return new Promise((resolve, reject) => {\n temp_fetch.apply(this, arguments)\n .then((response) => {\n if( response.url.indexOf("/wp-json/wp/v2/posts") > -1 &&\n response.type === 'basic'\n ){\n var clone = response.clone();\n\n clone.json().then(function (json) {\n if( typeof json.code !== 'undefined' &&\n typeof json.code === 'string' &&\n typeof json.message !== 'undefined' &&\n typeof json.message === 'string'\n ){\n wp.data.dispatch("core/notices").createNotice(\n json.code,\n json.message,\n {\n // type: "snackbar", // Optional\n id: 'custom_post_site_save',\n isDismissible: true\n }\n );\n\n // Close default "Post saved" notice\n wp.data.dispatch( 'core/notices' ).removeNotice('SAVE_POST_NOTICE_ID');\n\n // You can see all active notices by this command:\n // wp.data.select('core/notices').getNotices();\n }\n });\n }\n\n resolve(response);\n })\n .catch((error) => {\n reject(error);\n })\n });\n };\n\n // If you want to listen to Ajax calls made via jQuery\n // jQuery(document).bind("ajaxSend", function(event, request, settings){\n // }).bind("ajaxComplete", function(event, request, settings){\n // });\n });\n </script>\n <?php\n}\n\nadd_action( 'pre_post_update', 'custom_post_site_save', 10, 2);\nfunction custom_post_site_save($post_id, $post_data) {\n if (wp_is_post_revision($post_id)) { // If this is just a revision, don't do anything.\n return;\n } elseif (isset($post_data['post_content']) && strpos($post_data['post_content'], 'myTextString') !== false) {\n $code = 'error'; // Can be one of: success, info, warning, error.\n $response_body = 'My custom message ...';\n\n $error = new WP_Error($code, $response_body);\n wp_die($error, 200);\n }\n}\n</code></pre>\n"
}
] | 2020/03/24 | [
"https://wordpress.stackexchange.com/questions/361330",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89973/"
] | I have a custom plugin and want it on occasions to fire the kind of notice that appears and disapears in the left corner like this one:
[](https://i.stack.imgur.com/vvFwm.png)
I found some code [in the Gutenberg docs here](https://developer.wordpress.org/block-editor/components/snackbar/#development-guidelines):
```
const MySnackbarNotice = () => (
<Snackbar>
Post published successfully.
</Snackbar>
);
```
But adding this to my admin-enqueued js script obviously doesn't work.
Thanks! | WordPress has some global actions you can use here. If you want to add your own notice in the lower corner (like the screenshot), you can do that like this:
```js
wp.data.dispatch("core/notices").createNotice(
"success", // Can be one of: success, info, warning, error.
"This is my custom message.", // Text string to display.
{
type: "snackbar",
isDismissible: true, // Whether the user can dismiss the notice.
// Any actions the user can perform.
actions: [
{
url: '#',
label: 'View post',
},
],
}
);
```
The important part here is `type: "snackbar"`. You can also leave out the snackbar part and it will appear in the UI above the content:
[](https://i.stack.imgur.com/XPQsp.png)
Here's the full article on WordPress' Block Editor Handbook: <https://developer.wordpress.org/block-editor/tutorials/notices/> |
361,364 | <p>I'd like to have the checkout billing form on two columns. Is there a way to wrap half of the fields in a div and the other hald in another so that it's easy to use a <code>float</code> or <code>flexbox</code>?</p>
<p>The form is invoked in <code>form-billing.php</code> via <code>woocommerce_form_field</code> in a <code>forEach</code> loop, but I'm clueless as to where I could find the form template itself to modify it.</p>
<p>I'm also aware that a <code>woocommerce_checkout_fields</code> filter exists, but that doesn't seem helpful to wrap fields in some divs.</p>
| [
{
"answer_id": 361490,
"author": "7uc1f3r",
"author_id": 182113,
"author_profile": "https://wordpress.stackexchange.com/users/182113",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>woocommerce_form_field in the foreach loop</p>\n \n <p><a href=\"https://github.com/woocommerce/woocommerce/blob/master/templates/checkout/form-billing.php#L39\" rel=\"nofollow noreferrer\">https://github.com/woocommerce/woocommerce/blob/master/templates/checkout/form-billing.php#L39</a></p>\n</blockquote>\n\n<hr>\n\n<blockquote>\n <p>refers to</p>\n \n <p><a href=\"https://github.com/woocommerce/woocommerce/blob/master/includes/wc-template-functions.php#L2607\" rel=\"nofollow noreferrer\">https://github.com/woocommerce/woocommerce/blob/master/includes/wc-template-functions.php#L2607</a></p>\n</blockquote>\n\n<p>So you can adapt the following code to your needs</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function change_woocommerce_field_markup( $field, $key, $args, $value ) {\n // Remove the .form-row class from the current field wrapper\n $field = str_replace('form-row', '', $field);\n\n // Wrap the field (and its wrapper) in a new custom div, adding .form-row so the reshuffling works as expected, and adding the field priority\n $field = '<div class=\"form-row single-field-wrapper\" data-priority=\"' . $args['priority'] . '\">' . $field . '</div>';\n\n return $field;\n}\nadd_filter( 'woocommerce_form_field', 'change_woocommerce_field_markup', 10, 4 );\n</code></pre>\n\n<p>Or</p>\n\n<p>In the template file (<a href=\"https://github.com/woocommerce/woocommerce/blob/master/templates/checkout/form-billing.php#L38\" rel=\"nofollow noreferrer\">form-billing.php</a>), in the foreach loop. Add div(s) with an if statement where needed.</p>\n"
},
{
"answer_id": 362940,
"author": "Buzut",
"author_id": 77030,
"author_profile": "https://wordpress.stackexchange.com/users/77030",
"pm_score": 1,
"selected": true,
"text": "<p>My question was wrong because I had forgotten some things I had tried earlier. Splitting the form field within two divs is easy task:</p>\n\n<pre><code>// form-billing.php\n<div class=\"woocommerce-billing-fields__field-wrapper\">\n <?php\n $fields = $checkout->get_checkout_fields('billing');\n $fields_half_count = round(count($fields) / 2);\n $i = 0;\n\n echo '<div class=\"one\">';\n foreach ($fields as $key => $field) {\n if ($i++ == $fields_half_count) echo '</div><div class=\"two\">';\n woocommerce_form_field($key, $field, $checkout->get_value($key));\n }\n echo '</div>';\n ?>\n</div>\n</code></pre>\n\n<p>Now the issue is that the when the checkout JS kicks in, it rearranges all fields and places them in one div.</p>\n\n<p>One could disable it, but it's used to get shipping rates based on shipping country, manages the fields based on country too (US has states, Spain has provinces etc…), so disabling it isn't really an option.</p>\n\n<p>The only workaround I've found so far is to use the CSS <code>column-count: 2</code> on <code>.woocommerce-billing-fields__field-wrapper</code> to have the browser display it on two columns.</p>\n\n<p>The layout isn't perfect, but it's the best option I've found so far. Otherwise, one needs to use a custom JS to handle the work done by the WooCommerce checkout JS.</p>\n"
}
] | 2020/03/24 | [
"https://wordpress.stackexchange.com/questions/361364",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77030/"
] | I'd like to have the checkout billing form on two columns. Is there a way to wrap half of the fields in a div and the other hald in another so that it's easy to use a `float` or `flexbox`?
The form is invoked in `form-billing.php` via `woocommerce_form_field` in a `forEach` loop, but I'm clueless as to where I could find the form template itself to modify it.
I'm also aware that a `woocommerce_checkout_fields` filter exists, but that doesn't seem helpful to wrap fields in some divs. | My question was wrong because I had forgotten some things I had tried earlier. Splitting the form field within two divs is easy task:
```
// form-billing.php
<div class="woocommerce-billing-fields__field-wrapper">
<?php
$fields = $checkout->get_checkout_fields('billing');
$fields_half_count = round(count($fields) / 2);
$i = 0;
echo '<div class="one">';
foreach ($fields as $key => $field) {
if ($i++ == $fields_half_count) echo '</div><div class="two">';
woocommerce_form_field($key, $field, $checkout->get_value($key));
}
echo '</div>';
?>
</div>
```
Now the issue is that the when the checkout JS kicks in, it rearranges all fields and places them in one div.
One could disable it, but it's used to get shipping rates based on shipping country, manages the fields based on country too (US has states, Spain has provinces etc…), so disabling it isn't really an option.
The only workaround I've found so far is to use the CSS `column-count: 2` on `.woocommerce-billing-fields__field-wrapper` to have the browser display it on two columns.
The layout isn't perfect, but it's the best option I've found so far. Otherwise, one needs to use a custom JS to handle the work done by the WooCommerce checkout JS. |
361,369 | <p>I want to change the default template for my pages to a template called <code>fullwidthpage.php</code>.</p>
<p>I have seen <a href="https://wordpress.stackexchange.com/q/196289/172169">this question posted and answered</a> for pre-Gutenberg Wordpress, but I have not found a working answer for Gutenberg Wordpress (version 5.3.2 at the time of this question). </p>
<p><a href="https://wordpress.stackexchange.com/a/328272/172169">This</a> is the non-working answer I found. When I try the non-working answer the template is set to <code>fullwidthpage.php</code> but when I try to update the page I get a message that says "Updating failed."</p>
| [
{
"answer_id": 361412,
"author": "J. A.",
"author_id": 163393,
"author_profile": "https://wordpress.stackexchange.com/users/163393",
"pm_score": 0,
"selected": false,
"text": "<p>On the right hand side of your editor, at the top there are two tabs: Document and Block, click on document and go down until you see Page Attributes there is a slide down menu there where you can choose your template. See image attached:\n<a href=\"https://i.stack.imgur.com/ingKu.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ingKu.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 392009,
"author": "harceo",
"author_id": 207344,
"author_profile": "https://wordpress.stackexchange.com/users/207344",
"pm_score": 1,
"selected": false,
"text": "<p>I was looking for the same thing.\n<a href=\"https://wordpress.stackexchange.com/a/346866/207344\">This Answer</a> by SkyShab did the trick. Posted below for convenience.</p>\n<pre><code>\nwp.data.dispatch('core/editor').editPost( {template: "template-name.php"} )\n\n</code></pre>\n"
}
] | 2020/03/24 | [
"https://wordpress.stackexchange.com/questions/361369",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/172169/"
] | I want to change the default template for my pages to a template called `fullwidthpage.php`.
I have seen [this question posted and answered](https://wordpress.stackexchange.com/q/196289/172169) for pre-Gutenberg Wordpress, but I have not found a working answer for Gutenberg Wordpress (version 5.3.2 at the time of this question).
[This](https://wordpress.stackexchange.com/a/328272/172169) is the non-working answer I found. When I try the non-working answer the template is set to `fullwidthpage.php` but when I try to update the page I get a message that says "Updating failed." | I was looking for the same thing.
[This Answer](https://wordpress.stackexchange.com/a/346866/207344) by SkyShab did the trick. Posted below for convenience.
```
wp.data.dispatch('core/editor').editPost( {template: "template-name.php"} )
``` |
361,514 | <p>I am using Azure Cloud, multisite WordPress and have enabled these codes in wp-config.php file.</p>
<pre><code> // Enable WP_DEBUG mode
define( 'WP_DEBUG', true );
// Enable Debug logging to the /wp-content/debug.log file
define( 'WP_DEBUG_LOG', true );
// Disable display of errors and warnings
define( 'WP_DEBUG_DISPLAY', true );
@ini_set( 'display_errors', 0 );
// Use dev versions of core JS and CSS files (only needed if you are modifying these core files)
define( 'SCRIPT_DEBUG', true );
</code></pre>
<p>But there is no change. It shows a blank page only and I am unable to find any debug.log file in wp-content folder nor showing any error on the page if I apply "var_dump". What settings should I apply or check? </p>
| [
{
"answer_id": 361516,
"author": "butlerblog",
"author_id": 38603,
"author_profile": "https://wordpress.stackexchange.com/users/38603",
"pm_score": 1,
"selected": false,
"text": "<p>Take out the <code>@ini_set</code>. I'm not sure what your intent is there, but you're doing two different things. Your setting for <code>WP_DEBUG_DISPLAY</code> is telling it to display errors (set to <code>true</code>), and then you're turning around and telling it not to (<code>ini_set</code> to 0).</p>\n\n<p>The value of <code>WP_DEBUG_DISPLAY</code> is used to determine whether <code>ini_set()</code> to set <code>display_errors</code> to 1 or 0. So not only is there no need to set it again, you're actually defining the exact opposite value of what you just set. See <a href=\"https://developer.wordpress.org/reference/functions/wp_debug_mode/\" rel=\"nofollow noreferrer\"><code>wp_debug_mode()</code> where this is set</a>.</p>\n\n<p>The debug.log file will only be created if there is an actual error to display, but it may not necessarily be saved to /wp-content/debug.log by default. If you're not certain it's logging to the default, you can use the <code>WP_DEBUG_LOG</code> constant to define a custom error log file name and location. For example, instead of setting <code>WP_DEBUG_LOG</code> to <code>true</code> (which specifies the default), define the location of the log file when defining the constant:</p>\n\n<p><code>define( 'WP_DEBUG_LOG', dirname( __FILE__ ) . '/wp-content/my.log' );</code></p>\n\n<p>Instead of testing this with <code>var_dump()</code>, try writing something to the error log:</p>\n\n<p><code>error_log( 'checking my error log' );</code></p>\n\n<p>Then check to make sure the error was written to the error log location you expect it (whether custom or default as described above).</p>\n\n<p>It is possible that the issue you have is a fatal error occurring before WP initializes, in which case you'll need to explore something other than WP for the problem. In that case, you probably do need the <code>ini_set()</code> function, but you need to set it to 1 to display the error on the screen (you have it set to 0, which suppresses on-screen messaging).</p>\n"
},
{
"answer_id": 409297,
"author": "Vijay Hardaha",
"author_id": 218789,
"author_profile": "https://wordpress.stackexchange.com/users/218789",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://azureossd.github.io/2015/10/09/logging-php-errors-in-wordpress-2/\" rel=\"nofollow noreferrer\">https://azureossd.github.io/2015/10/09/logging-php-errors-in-wordpress-2/</a></p>\n<p>This article says that you need to enable log errors in <code>user.ini</code> using <code>log_errors=on</code></p>\n"
}
] | 2020/03/26 | [
"https://wordpress.stackexchange.com/questions/361514",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/184876/"
] | I am using Azure Cloud, multisite WordPress and have enabled these codes in wp-config.php file.
```
// Enable WP_DEBUG mode
define( 'WP_DEBUG', true );
// Enable Debug logging to the /wp-content/debug.log file
define( 'WP_DEBUG_LOG', true );
// Disable display of errors and warnings
define( 'WP_DEBUG_DISPLAY', true );
@ini_set( 'display_errors', 0 );
// Use dev versions of core JS and CSS files (only needed if you are modifying these core files)
define( 'SCRIPT_DEBUG', true );
```
But there is no change. It shows a blank page only and I am unable to find any debug.log file in wp-content folder nor showing any error on the page if I apply "var\_dump". What settings should I apply or check? | Take out the `@ini_set`. I'm not sure what your intent is there, but you're doing two different things. Your setting for `WP_DEBUG_DISPLAY` is telling it to display errors (set to `true`), and then you're turning around and telling it not to (`ini_set` to 0).
The value of `WP_DEBUG_DISPLAY` is used to determine whether `ini_set()` to set `display_errors` to 1 or 0. So not only is there no need to set it again, you're actually defining the exact opposite value of what you just set. See [`wp_debug_mode()` where this is set](https://developer.wordpress.org/reference/functions/wp_debug_mode/).
The debug.log file will only be created if there is an actual error to display, but it may not necessarily be saved to /wp-content/debug.log by default. If you're not certain it's logging to the default, you can use the `WP_DEBUG_LOG` constant to define a custom error log file name and location. For example, instead of setting `WP_DEBUG_LOG` to `true` (which specifies the default), define the location of the log file when defining the constant:
`define( 'WP_DEBUG_LOG', dirname( __FILE__ ) . '/wp-content/my.log' );`
Instead of testing this with `var_dump()`, try writing something to the error log:
`error_log( 'checking my error log' );`
Then check to make sure the error was written to the error log location you expect it (whether custom or default as described above).
It is possible that the issue you have is a fatal error occurring before WP initializes, in which case you'll need to explore something other than WP for the problem. In that case, you probably do need the `ini_set()` function, but you need to set it to 1 to display the error on the screen (you have it set to 0, which suppresses on-screen messaging). |
361,559 | <p>I created a simple form for my users to can change their passwords. but there is a problem and I am confused! I tried a lot to change my password but my pass will not be changed by <code>wp_set_password()</code> and I do not know the reason really. </p>
<pre><code><?php /* Template Name: user-edit-password */ ?>
<?php
$user = wp_get_current_user();
$userID = $user->ID;
$has_error = false;
$has_success = false;
$message = array();
if( isset($_POST['karneta_pass_submit']) ){
if( !isset($_POST['security']) || !wp_verify_nonce($_POST['security'],'edit-profile-password-nonce') ){
print('do not damage that');
} else {
$currentpass = sanitize_text_field($_POST['karneta_currentpass']);
$newpass = sanitize_text_field($_POST['karneta_newpass']);
$repeatnewpass = sanitize_text_field($_POST['karneta_repeatnewpass']);
if( wp_check_password($currentpass, $user->data->user_pass, $UserID) ){
if( empty($currentpass) || empty($newpass) || empty($repeatnewpass) ){
$has_error = true;
$message[] = "fill all the fields";
}
elseif( $newpass !== $repeatnewpass ){
$has_error = true;
$message[] = "they are not the same";
}
else {
wp_set_password($newpass,$UserID);
$has_success = true;
$message[] = "password changed successfully";
}
} else {
$has_error = true;
$message[] = "the old password is not correct";
}
}
}
?>
<div class="usereditprofile">
<div class="usereditprofilediv">
<div>
<?php if( $has_error ){ ?>
<div class="userprofile_message error">
<?php foreach ($message as $item) { ?>
<p><?php echo $item; ?></p>
<?php } ?>
</div>
<?php } ?>
<?php if( $has_success ){ ?>
<div class="userprofile_message success">
<?php foreach ($message as $sitem) { ?>
<p><?php echo $sitem; ?></p>
<?php } ?>
</div>
<?php } ?>
</div>
<form action="" method="post" class="usereditprofileform">
<?php wp_nonce_field('edit-profile-password-nonce', 'security'); ?>
<input type="password" placeholder="old password" value="" name="karneta_currentpass" required>
<input type="password" placeholder="new password" value="" name="karneta_newpass" required>
<input type="password" placeholder="repeat new password" value="" name="karneta_repeatnewpass" required>
<input type="submit" value="change your pass" name="karneta_pass_submit">
</form>
</div>
</div>
</code></pre>
| [
{
"answer_id": 361516,
"author": "butlerblog",
"author_id": 38603,
"author_profile": "https://wordpress.stackexchange.com/users/38603",
"pm_score": 1,
"selected": false,
"text": "<p>Take out the <code>@ini_set</code>. I'm not sure what your intent is there, but you're doing two different things. Your setting for <code>WP_DEBUG_DISPLAY</code> is telling it to display errors (set to <code>true</code>), and then you're turning around and telling it not to (<code>ini_set</code> to 0).</p>\n\n<p>The value of <code>WP_DEBUG_DISPLAY</code> is used to determine whether <code>ini_set()</code> to set <code>display_errors</code> to 1 or 0. So not only is there no need to set it again, you're actually defining the exact opposite value of what you just set. See <a href=\"https://developer.wordpress.org/reference/functions/wp_debug_mode/\" rel=\"nofollow noreferrer\"><code>wp_debug_mode()</code> where this is set</a>.</p>\n\n<p>The debug.log file will only be created if there is an actual error to display, but it may not necessarily be saved to /wp-content/debug.log by default. If you're not certain it's logging to the default, you can use the <code>WP_DEBUG_LOG</code> constant to define a custom error log file name and location. For example, instead of setting <code>WP_DEBUG_LOG</code> to <code>true</code> (which specifies the default), define the location of the log file when defining the constant:</p>\n\n<p><code>define( 'WP_DEBUG_LOG', dirname( __FILE__ ) . '/wp-content/my.log' );</code></p>\n\n<p>Instead of testing this with <code>var_dump()</code>, try writing something to the error log:</p>\n\n<p><code>error_log( 'checking my error log' );</code></p>\n\n<p>Then check to make sure the error was written to the error log location you expect it (whether custom or default as described above).</p>\n\n<p>It is possible that the issue you have is a fatal error occurring before WP initializes, in which case you'll need to explore something other than WP for the problem. In that case, you probably do need the <code>ini_set()</code> function, but you need to set it to 1 to display the error on the screen (you have it set to 0, which suppresses on-screen messaging).</p>\n"
},
{
"answer_id": 409297,
"author": "Vijay Hardaha",
"author_id": 218789,
"author_profile": "https://wordpress.stackexchange.com/users/218789",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://azureossd.github.io/2015/10/09/logging-php-errors-in-wordpress-2/\" rel=\"nofollow noreferrer\">https://azureossd.github.io/2015/10/09/logging-php-errors-in-wordpress-2/</a></p>\n<p>This article says that you need to enable log errors in <code>user.ini</code> using <code>log_errors=on</code></p>\n"
}
] | 2020/03/26 | [
"https://wordpress.stackexchange.com/questions/361559",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/157522/"
] | I created a simple form for my users to can change their passwords. but there is a problem and I am confused! I tried a lot to change my password but my pass will not be changed by `wp_set_password()` and I do not know the reason really.
```
<?php /* Template Name: user-edit-password */ ?>
<?php
$user = wp_get_current_user();
$userID = $user->ID;
$has_error = false;
$has_success = false;
$message = array();
if( isset($_POST['karneta_pass_submit']) ){
if( !isset($_POST['security']) || !wp_verify_nonce($_POST['security'],'edit-profile-password-nonce') ){
print('do not damage that');
} else {
$currentpass = sanitize_text_field($_POST['karneta_currentpass']);
$newpass = sanitize_text_field($_POST['karneta_newpass']);
$repeatnewpass = sanitize_text_field($_POST['karneta_repeatnewpass']);
if( wp_check_password($currentpass, $user->data->user_pass, $UserID) ){
if( empty($currentpass) || empty($newpass) || empty($repeatnewpass) ){
$has_error = true;
$message[] = "fill all the fields";
}
elseif( $newpass !== $repeatnewpass ){
$has_error = true;
$message[] = "they are not the same";
}
else {
wp_set_password($newpass,$UserID);
$has_success = true;
$message[] = "password changed successfully";
}
} else {
$has_error = true;
$message[] = "the old password is not correct";
}
}
}
?>
<div class="usereditprofile">
<div class="usereditprofilediv">
<div>
<?php if( $has_error ){ ?>
<div class="userprofile_message error">
<?php foreach ($message as $item) { ?>
<p><?php echo $item; ?></p>
<?php } ?>
</div>
<?php } ?>
<?php if( $has_success ){ ?>
<div class="userprofile_message success">
<?php foreach ($message as $sitem) { ?>
<p><?php echo $sitem; ?></p>
<?php } ?>
</div>
<?php } ?>
</div>
<form action="" method="post" class="usereditprofileform">
<?php wp_nonce_field('edit-profile-password-nonce', 'security'); ?>
<input type="password" placeholder="old password" value="" name="karneta_currentpass" required>
<input type="password" placeholder="new password" value="" name="karneta_newpass" required>
<input type="password" placeholder="repeat new password" value="" name="karneta_repeatnewpass" required>
<input type="submit" value="change your pass" name="karneta_pass_submit">
</form>
</div>
</div>
``` | Take out the `@ini_set`. I'm not sure what your intent is there, but you're doing two different things. Your setting for `WP_DEBUG_DISPLAY` is telling it to display errors (set to `true`), and then you're turning around and telling it not to (`ini_set` to 0).
The value of `WP_DEBUG_DISPLAY` is used to determine whether `ini_set()` to set `display_errors` to 1 or 0. So not only is there no need to set it again, you're actually defining the exact opposite value of what you just set. See [`wp_debug_mode()` where this is set](https://developer.wordpress.org/reference/functions/wp_debug_mode/).
The debug.log file will only be created if there is an actual error to display, but it may not necessarily be saved to /wp-content/debug.log by default. If you're not certain it's logging to the default, you can use the `WP_DEBUG_LOG` constant to define a custom error log file name and location. For example, instead of setting `WP_DEBUG_LOG` to `true` (which specifies the default), define the location of the log file when defining the constant:
`define( 'WP_DEBUG_LOG', dirname( __FILE__ ) . '/wp-content/my.log' );`
Instead of testing this with `var_dump()`, try writing something to the error log:
`error_log( 'checking my error log' );`
Then check to make sure the error was written to the error log location you expect it (whether custom or default as described above).
It is possible that the issue you have is a fatal error occurring before WP initializes, in which case you'll need to explore something other than WP for the problem. In that case, you probably do need the `ini_set()` function, but you need to set it to 1 to display the error on the screen (you have it set to 0, which suppresses on-screen messaging). |
361,576 | <h1>Background</h1>
<p>I'm developing a <a href="https://github.com/badAd/wordpress" rel="nofollow noreferrer">plugin for WordPress</a>. I initially used <code>file_get_contents()</code> for two purposes:</p>
<ol>
<li>A remote file (which I changed to <code>wp_remote_post()</code>)</li>
<li>A local file in the plugin dir (what this question is about)</li>
</ol>
<p>WordPress staff told me to NOT use <code>file_get_contents()</code> for remote <code>_POST</code> requests (usage 1. above), but to use <code>wp_remost_post()</code> instead.</p>
<p>From their email concerning usage 1. (above):</p>
<blockquote>
<h2>Using file_get_contents on remote files</h2>
<p>Many hosts block the use of file_get_contents on remote content. This is a security measure that we fully endorse.</p>
<p>Thankfully, WordPress comes with an extensive HTTP API that can be used instead. It’s fast and more extensive than most home-grown alternatives. It’ll fall back to curl if it has to, but it’ll use a lot of WordPress’ native functionality first.</p>
</blockquote>
<p>So, I did. But...</p>
<h1>Solving usage <em>1. A remote file</em> (above) got me to reading and thinking about a better tool for usage <em>2. A local file</em> (above)</h1>
<p>In the <a href="https://developer.wordpress.org/plugins/http-api/" rel="nofollow noreferrer">WordPress HTTP API</a> docs, there is no alternative for <code>file_get_contents()</code> on local files, nothing like <code>wp_file_get_contents()</code>.</p>
<p><em>(I understand this may seem strange since local files of a plugin are often static, but I am writing extra files to save cost, and I politely don't want to open that discussion. Besides, <a href="https://wordpress.org/plugins/string-locator/" rel="nofollow noreferrer">this approved plugin from someone else</a>, <a href="https://plugins.trac.wordpress.org/browser/string-locator/trunk/string-locator.php" rel="nofollow noreferrer">code here</a>, uses <code>file_get_contents()</code>, thus proving my own need is legitimate, but it doesn't prove that <code>file_get_contents()</code> is 'proper' WordPress-practice.)</em></p>
<p>From <a href="https://www.tutdepot.com/alternative-functions-file_get_contents/" rel="nofollow noreferrer">this blog post</a>, clearly this was a big discussion for <code>file_get_contents()</code> for <em>remote files</em>. But, I don't see much on the web about a WordPress function for <em>local files</em>. From the post:</p>
<blockquote>
<p>Like many others I’ve used the native PHP function file_get_contents() to receive the content from a remote file because the functions is very easy to use. But is it the best way to do that? I see many scripts using that function and even WordPress plugins are using this function while WordPress has a native function to receive remote content.</p>
</blockquote>
<p>...I want to take that discussion to <em>local files</em> and build this plugin right.</p>
<h1>My code (current and attempted)</h1>
<p>I simply need to confirm whether a local file in the plugin directory exists, then confirm whether it contains a certain string. I thought it best to use <code>file_get_contents()</code> for local files in PHP from <a href="https://stackoverflow.com/questions/9059026/php-check-if-file-contains-a-string">this question on SE</a>. But, this is WordPress. Currently, I am using:</p>
<pre><code>if ( ( ! $wp_filesystem->exists ( $check_this_file ) )
|| (strpos ( file_get_contents ( $check_this_file ),
$check_this_string ) === false ) )
</code></pre>
<p>I tried using <a href="https://developer.wordpress.org/reference/classes/wp_filesystem_direct/get_contents/" rel="nofollow noreferrer">WP_Filesystem_Direct::get_contents</a> instead:</p>
<pre><code>if ( ( ! $wp_filesystem->exists ( $check_this_file ) )
|| (strpos ( WP_Filesystem_Direct::get_contents ( $check_this_file ),
$check_this_string ) === false ) )
</code></pre>
<p>...but I got this error:</p>
<blockquote>
<p><code>Deprecated: Non-static method WP_Filesystem_Direct::get_contents() should not be called statically</code></p>
</blockquote>
<h1>What should I do?</h1>
<p>I'm not sure because there isn't even a #get-contents tag on WP.SE at the time of asking, but the function exists both in the framework and in the docs.</p>
<p>I want to know the "WordPress way" for plugins to read a plugin file's contents for a string test:</p>
<ul>
<li><code>file_get_contents()</code> (what I have now)</li>
<li><code>WP_Filesystem_Direct::get_contents()</code> (but how do I make it work without the error?)</li>
<li>or some <em><strong>proper-reliable</strong></em> usage of <code>wp_filesystem()</code> or similar</li>
</ul>
| [
{
"answer_id": 362729,
"author": "Jesse",
"author_id": 152716,
"author_profile": "https://wordpress.stackexchange.com/users/152716",
"pm_score": 0,
"selected": false,
"text": "<h1><code>$wp_filesystem->get_contents()</code></h1>\n\n<p><code>$wp_filesystem->get_contents()</code> replaced <code>file_get_contents()</code> perfectly as a drop-in replacement. Of course, it must be initiated with <code>WP_Filesystem();</code> first.</p>\n\n<p>Here is a before and after example...</p>\n\n<p>Before:</p>\n\n<pre><code>if ( (strpos ( file_get_contents ( $check_this_file ),\n $check_this_string ) === false) ) {...}\n</code></pre>\n\n<p>After:</p>\n\n<pre><code>WP_Filesystem();\nif ( (strpos ( $wp_filesystem->get_contents ( $check_this_file ),\n $check_this_string ) === false) ) {...}\n</code></pre>\n"
},
{
"answer_id": 386703,
"author": "Mohammad Mursaleen",
"author_id": 35899,
"author_profile": "https://wordpress.stackexchange.com/users/35899",
"pm_score": 1,
"selected": false,
"text": "<p>The alternate of using <code>file_get_contents()</code> is to initiate <code>WP_Filesystem</code> and use its <code>$wp_filesystem->get_contents</code> method.</p>\n<p>Here is a clean example method on how to use it</p>\n<p><strong>Example</strong></p>\n<pre><code><?php\n /**\n * This method gets a list of the most popular Google web fonts. \n * Initialize the WP filesystem and no more using file_put_contents function\n *\n * @see wp_filesystem()\n * @see get_parent_theme_file_path()\n * @return array A list of Google web fonts\n */\n function mm_get_google_fonts() {\n \n // Call globals\n global $wp_filesystem;\n\n // You have to require following file in the front-end only. In the back-end; its already included\n require_once ( ABSPATH . '/wp-admin/includes/file.php' );\n\n // Initiate\n WP_Filesystem();\n \n $local_file = get_parent_theme_file_path( '/assets/json/google-web-fonts.json' );\n $content = '';\n \n if ( $wp_filesystem->exists( $local_file ) ) {\n\n // following is alternate to\n // $content = json_decode( file_get_contents( $local_file ) );\n\n $content = json_decode( $wp_filesystem->get_contents( $local_file ) );\n\n } // End If Statement\n \n return $content;\n \n} \n?>\n</code></pre>\n<p>For more information you can <a href=\"https://developer.wordpress.org/reference/functions/wp_filesystem/\" rel=\"nofollow noreferrer\">visit the official documenation of WP_Filesystem</a></p>\n"
},
{
"answer_id": 412672,
"author": "Ron",
"author_id": 228912,
"author_profile": "https://wordpress.stackexchange.com/users/228912",
"pm_score": 1,
"selected": false,
"text": "<p>$wp_filesystem->get_contents is wrong for this purpose, since you can't know what filesystem path the file is going to be accessible at using WP_Filesystem . If the user has WP_Filesystem using chrooted FTP or SFTP to the WP install dir, the server path /path/to/site/wp will need to actually be /site/wp in order for WP_Filesystem to find the file. But if you're not chrooted, it's at /path/to/site/wp</p>\n<p>To reliably read your file you need to instantiate WP_Filesystem_Direct and then use that.</p>\n<pre><code>$wpfsd = new WP_Filesystem_Direct( false );\n$wpfsd->get_contents ( $check_this_file )\n</code></pre>\n"
}
] | 2020/03/27 | [
"https://wordpress.stackexchange.com/questions/361576",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/152716/"
] | Background
==========
I'm developing a [plugin for WordPress](https://github.com/badAd/wordpress). I initially used `file_get_contents()` for two purposes:
1. A remote file (which I changed to `wp_remote_post()`)
2. A local file in the plugin dir (what this question is about)
WordPress staff told me to NOT use `file_get_contents()` for remote `_POST` requests (usage 1. above), but to use `wp_remost_post()` instead.
From their email concerning usage 1. (above):
>
> Using file\_get\_contents on remote files
> -----------------------------------------
>
>
> Many hosts block the use of file\_get\_contents on remote content. This is a security measure that we fully endorse.
>
>
> Thankfully, WordPress comes with an extensive HTTP API that can be used instead. It’s fast and more extensive than most home-grown alternatives. It’ll fall back to curl if it has to, but it’ll use a lot of WordPress’ native functionality first.
>
>
>
So, I did. But...
Solving usage *1. A remote file* (above) got me to reading and thinking about a better tool for usage *2. A local file* (above)
===============================================================================================================================
In the [WordPress HTTP API](https://developer.wordpress.org/plugins/http-api/) docs, there is no alternative for `file_get_contents()` on local files, nothing like `wp_file_get_contents()`.
*(I understand this may seem strange since local files of a plugin are often static, but I am writing extra files to save cost, and I politely don't want to open that discussion. Besides, [this approved plugin from someone else](https://wordpress.org/plugins/string-locator/), [code here](https://plugins.trac.wordpress.org/browser/string-locator/trunk/string-locator.php), uses `file_get_contents()`, thus proving my own need is legitimate, but it doesn't prove that `file_get_contents()` is 'proper' WordPress-practice.)*
From [this blog post](https://www.tutdepot.com/alternative-functions-file_get_contents/), clearly this was a big discussion for `file_get_contents()` for *remote files*. But, I don't see much on the web about a WordPress function for *local files*. From the post:
>
> Like many others I’ve used the native PHP function file\_get\_contents() to receive the content from a remote file because the functions is very easy to use. But is it the best way to do that? I see many scripts using that function and even WordPress plugins are using this function while WordPress has a native function to receive remote content.
>
>
>
...I want to take that discussion to *local files* and build this plugin right.
My code (current and attempted)
===============================
I simply need to confirm whether a local file in the plugin directory exists, then confirm whether it contains a certain string. I thought it best to use `file_get_contents()` for local files in PHP from [this question on SE](https://stackoverflow.com/questions/9059026/php-check-if-file-contains-a-string). But, this is WordPress. Currently, I am using:
```
if ( ( ! $wp_filesystem->exists ( $check_this_file ) )
|| (strpos ( file_get_contents ( $check_this_file ),
$check_this_string ) === false ) )
```
I tried using [WP\_Filesystem\_Direct::get\_contents](https://developer.wordpress.org/reference/classes/wp_filesystem_direct/get_contents/) instead:
```
if ( ( ! $wp_filesystem->exists ( $check_this_file ) )
|| (strpos ( WP_Filesystem_Direct::get_contents ( $check_this_file ),
$check_this_string ) === false ) )
```
...but I got this error:
>
> `Deprecated: Non-static method WP_Filesystem_Direct::get_contents() should not be called statically`
>
>
>
What should I do?
=================
I'm not sure because there isn't even a #get-contents tag on WP.SE at the time of asking, but the function exists both in the framework and in the docs.
I want to know the "WordPress way" for plugins to read a plugin file's contents for a string test:
* `file_get_contents()` (what I have now)
* `WP_Filesystem_Direct::get_contents()` (but how do I make it work without the error?)
* or some ***proper-reliable*** usage of `wp_filesystem()` or similar | The alternate of using `file_get_contents()` is to initiate `WP_Filesystem` and use its `$wp_filesystem->get_contents` method.
Here is a clean example method on how to use it
**Example**
```
<?php
/**
* This method gets a list of the most popular Google web fonts.
* Initialize the WP filesystem and no more using file_put_contents function
*
* @see wp_filesystem()
* @see get_parent_theme_file_path()
* @return array A list of Google web fonts
*/
function mm_get_google_fonts() {
// Call globals
global $wp_filesystem;
// You have to require following file in the front-end only. In the back-end; its already included
require_once ( ABSPATH . '/wp-admin/includes/file.php' );
// Initiate
WP_Filesystem();
$local_file = get_parent_theme_file_path( '/assets/json/google-web-fonts.json' );
$content = '';
if ( $wp_filesystem->exists( $local_file ) ) {
// following is alternate to
// $content = json_decode( file_get_contents( $local_file ) );
$content = json_decode( $wp_filesystem->get_contents( $local_file ) );
} // End If Statement
return $content;
}
?>
```
For more information you can [visit the official documenation of WP\_Filesystem](https://developer.wordpress.org/reference/functions/wp_filesystem/) |
361,581 | <p>I want to add <strong>Like & Dislike</strong> functionality into my custom post type, called <code>game</code>.</p>
<p>I have placed like and dislike icon links in my post footer.</p>
<p><strong>Desired Behaviour:</strong></p>
<p>When a user clicks the like icon, I want to check if (s)he already voted for it and if not then create or update post like count meta key inside the post meta and same goes for the user meta.</p>
<p><strong>Problem:</strong></p>
<p>The problem is when a user clicks the like button, I have to handle it inside the JavaScript but I am not sure how to call</p>
<pre><code>set_post_meta($post->ID)
</code></pre>
<p>or</p>
<pre><code>update_post_meta($post->ID)
</code></pre>
<p>from JavaScript.</p>
<p><strong>Loop:</strong></p>
<pre><code><?php while ( $r->have_posts() ) : $r->the_post();?>
<?php if (has_post_thumbnail()): ?>
<?php the_post_thumbnail('small'); ?>
<?php endif;?>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<div class="game-footer">
<div class="like-dislike-btn-div">
<i class="game-footer-like-btn fa fa-thumbs-o-up">0</i>
<i class="game-footer-dislike-btn fa fa-thumbs-o-down">0</i>
</div>
</div>
<?php endwhile; ?>
</code></pre>
| [
{
"answer_id": 361589,
"author": "Christmas",
"author_id": 184919,
"author_profile": "https://wordpress.stackexchange.com/users/184919",
"pm_score": 1,
"selected": false,
"text": "<p>I don't understand how u can count like in javascript only.\nUse wp_ajax_ACTION Hook to call your PHP functions, in your functions.php or in a plugin.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/files/wp-admin/admin-ajax.php/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/files/wp-admin/admin-ajax.php/</a></p>\n\n<pre><code>add_action(\"wp_ajax_my_function\", \"my_function\");\n\nfunction my_function() {\n // Get parameters send by javascript xhr method\n\n // Do some stuff\n}\n</code></pre>\n\n<p>add_action(\"wp_ajax_nopriv_my_function\") for no user logged in.</p>\n"
},
{
"answer_id": 362707,
"author": "BlueSuiter",
"author_id": 92665,
"author_profile": "https://wordpress.stackexchange.com/users/92665",
"pm_score": 3,
"selected": true,
"text": "<p>I hope you are doing well. Here, I am sharing code for recording likes. The code for <code>single.php</code> have the javascript code for making an ajax call to a wp function. This wp function have the code to store like expressions and it will return you the total number of like expressions recorded on post.</p>\n\n<p>I have curated it for only the Logged in users.</p>\n\n<p>Place this code in your <strong>functions.php</strong></p>\n\n<pre><code>/* Ajax call */\nadd_action('wp_ajax_likeExpression', 'likeExpression');\nfunction likeExpression() {\n if(is_user_logged_in()){\n $post_id = $_GET['post_id'];\n $userId = get_current_user_id();\n $metaKey = '_like_on_game_post_';\n $userLikes = get_user_meta($userId, $metaKey, true);\n\n if(empty($userLikes)){\n update_user_meta($userId, $metaKey, wp_json_encode([$post_id]));\n }else{\n $userLikes = json_decode($userLikes);\n if(!in_array($post_id, $userLikes)){\n array_push($userLikes, $post_id);\n update_user_meta($userId, $metaKey, wp_json_encode($userLikes));\n }\n }\n\n $postLikeCount = get_post_meta($post_id, '_like_count_on_post_', true);\n update_post_meta($post_id, '_like_count_on_post_', ++$postLikeCount);\n exit($postLikeCount);\n }\n}\n</code></pre>\n\n<p>Place this in <strong>single.php</strong>, (<em>before footer ends</em>)</p>\n\n<pre><code><?php if(is_user_logged_in()): ?>\n <script>\n jQuery(function($){\n $('.game-footer-like-btn').on('click', function(){\n $.ajax({\n url: '<?php echo admin_url('admin-ajax.php?action=likeExpression&post_id='.get_the_ID()) ?>',\n method: 'get',\n }).done(function(res){\n console.log(res)\n //if its done\n });\n });\n });\n </script>\n<?php endif; ?>\n</code></pre>\n\n<p>Please, feel free to contact if you any query. \nThank You :)</p>\n"
}
] | 2020/03/27 | [
"https://wordpress.stackexchange.com/questions/361581",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123788/"
] | I want to add **Like & Dislike** functionality into my custom post type, called `game`.
I have placed like and dislike icon links in my post footer.
**Desired Behaviour:**
When a user clicks the like icon, I want to check if (s)he already voted for it and if not then create or update post like count meta key inside the post meta and same goes for the user meta.
**Problem:**
The problem is when a user clicks the like button, I have to handle it inside the JavaScript but I am not sure how to call
```
set_post_meta($post->ID)
```
or
```
update_post_meta($post->ID)
```
from JavaScript.
**Loop:**
```
<?php while ( $r->have_posts() ) : $r->the_post();?>
<?php if (has_post_thumbnail()): ?>
<?php the_post_thumbnail('small'); ?>
<?php endif;?>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<div class="game-footer">
<div class="like-dislike-btn-div">
<i class="game-footer-like-btn fa fa-thumbs-o-up">0</i>
<i class="game-footer-dislike-btn fa fa-thumbs-o-down">0</i>
</div>
</div>
<?php endwhile; ?>
``` | I hope you are doing well. Here, I am sharing code for recording likes. The code for `single.php` have the javascript code for making an ajax call to a wp function. This wp function have the code to store like expressions and it will return you the total number of like expressions recorded on post.
I have curated it for only the Logged in users.
Place this code in your **functions.php**
```
/* Ajax call */
add_action('wp_ajax_likeExpression', 'likeExpression');
function likeExpression() {
if(is_user_logged_in()){
$post_id = $_GET['post_id'];
$userId = get_current_user_id();
$metaKey = '_like_on_game_post_';
$userLikes = get_user_meta($userId, $metaKey, true);
if(empty($userLikes)){
update_user_meta($userId, $metaKey, wp_json_encode([$post_id]));
}else{
$userLikes = json_decode($userLikes);
if(!in_array($post_id, $userLikes)){
array_push($userLikes, $post_id);
update_user_meta($userId, $metaKey, wp_json_encode($userLikes));
}
}
$postLikeCount = get_post_meta($post_id, '_like_count_on_post_', true);
update_post_meta($post_id, '_like_count_on_post_', ++$postLikeCount);
exit($postLikeCount);
}
}
```
Place this in **single.php**, (*before footer ends*)
```
<?php if(is_user_logged_in()): ?>
<script>
jQuery(function($){
$('.game-footer-like-btn').on('click', function(){
$.ajax({
url: '<?php echo admin_url('admin-ajax.php?action=likeExpression&post_id='.get_the_ID()) ?>',
method: 'get',
}).done(function(res){
console.log(res)
//if its done
});
});
});
</script>
<?php endif; ?>
```
Please, feel free to contact if you any query.
Thank You :) |
362,699 | <p>I have a custom taxonomy called "Sources" (using Custom Post Type UI), where the sources are the names of publications where articles were originally published. Each post is an article, with a source selected. What I need to do is to show the source in the metadata under the post title. I'm using the Avada theme. Currently the title area of a post looks like this:</p>
<p><strong>Article Title</strong></p>
<p>By Author Name | Month, Year</p>
<p>What I want is this:</p>
<p><strong>Article Title</strong></p>
<p>Author Name, <em>Source</em>, Month, Year</p>
<p>Here's an example post I'm working with in my dev environment:</p>
<p><a href="http://dev.universaltheosophy.com/articles/the-logos-and-meditation/" rel="nofollow noreferrer">http://dev.universaltheosophy.com/articles/the-logos-and-meditation/</a> </p>
<p>I'd love to be able to do this with add_action in my child theme's functions.php, and hook it before the date or after the author name. But I'm not sure how to do that.</p>
<p>All I see in the theme's single post file file is:</p>
<pre><code><?php if ( 'below' === Avada()->settings->get( 'blog_post_title' ) ) : ?>
<?php if ( 'below_title' === Avada()->settings->get( 'blog_post_meta_position' ) ) : ?>
<div class="fusion-post-title-meta-wrap">
<?php endif; ?>
<?php $title_size = ( false === avada_is_page_title_bar_enabled( $post->ID ) ? '1' : '2' ); ?>
<?php echo avada_render_post_title( $post->ID, false, '', $title_size ); // phpcs:ignore WordPress.Security.EscapeOutput ?>
<?php if ( 'below_title' === Avada()->settings->get( 'blog_post_meta_position' ) ) : ?>
<?php echo avada_render_post_metadata( 'single' ); // phpcs:ignore WordPress.Security.EscapeOutput ?>
</div>
<?php endif; ?>
<?php endif; ?>
</code></pre>
<p>And I see in the theme's files:</p>
<pre><code> // Render author meta data.
if ( $settings['post_meta_author'] ) {
ob_start();
the_author_posts_link();
$author_post_link = ob_get_clean();
// Check if rich snippets are enabled.
if ( fusion_library()->get_option( 'disable_date_rich_snippet_pages' ) && fusion_library()->get_option( 'disable_rich_snippet_author' ) ) {
/* translators: The author. */
$metadata .= sprintf( esc_html__( 'By %s', 'Avada' ), '<span class="vcard"><span class="fn">' . $author_post_link . '</span></span>' );
} else {
/* translators: The author. */
$metadata .= sprintf( esc_html__( 'By %s', 'Avada' ), '<span>' . $author_post_link . '</span>' );
}
$metadata .= '<span class="fusion-inline-sep">|</span>';
} else { // If author meta data won't be visible, render just the invisible author rich snippet.
$author .= fusion_render_rich_snippets_for_pages( false, true, false );
}
// Render the updated meta data or at least the rich snippet if enabled.
if ( $settings['post_meta_date'] ) {
$metadata .= fusion_render_rich_snippets_for_pages( false, false, true );
$formatted_date = get_the_time( fusion_library()->get_option( 'date_format' ) );
$date_markup = '<span>' . $formatted_date . '</span><span class="fusion-inline-sep">|</span>';
$metadata .= apply_filters( 'fusion_post_metadata_date', $date_markup, $formatted_date );
} else {
$date .= fusion_render_rich_snippets_for_pages( false, false, true );
}
</code></pre>
<p>Other than this, I'm not sure what other info I need. Any help will be much appreciated! Keep in mind I'm very amateur at this.</p>
| [
{
"answer_id": 361589,
"author": "Christmas",
"author_id": 184919,
"author_profile": "https://wordpress.stackexchange.com/users/184919",
"pm_score": 1,
"selected": false,
"text": "<p>I don't understand how u can count like in javascript only.\nUse wp_ajax_ACTION Hook to call your PHP functions, in your functions.php or in a plugin.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/files/wp-admin/admin-ajax.php/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/files/wp-admin/admin-ajax.php/</a></p>\n\n<pre><code>add_action(\"wp_ajax_my_function\", \"my_function\");\n\nfunction my_function() {\n // Get parameters send by javascript xhr method\n\n // Do some stuff\n}\n</code></pre>\n\n<p>add_action(\"wp_ajax_nopriv_my_function\") for no user logged in.</p>\n"
},
{
"answer_id": 362707,
"author": "BlueSuiter",
"author_id": 92665,
"author_profile": "https://wordpress.stackexchange.com/users/92665",
"pm_score": 3,
"selected": true,
"text": "<p>I hope you are doing well. Here, I am sharing code for recording likes. The code for <code>single.php</code> have the javascript code for making an ajax call to a wp function. This wp function have the code to store like expressions and it will return you the total number of like expressions recorded on post.</p>\n\n<p>I have curated it for only the Logged in users.</p>\n\n<p>Place this code in your <strong>functions.php</strong></p>\n\n<pre><code>/* Ajax call */\nadd_action('wp_ajax_likeExpression', 'likeExpression');\nfunction likeExpression() {\n if(is_user_logged_in()){\n $post_id = $_GET['post_id'];\n $userId = get_current_user_id();\n $metaKey = '_like_on_game_post_';\n $userLikes = get_user_meta($userId, $metaKey, true);\n\n if(empty($userLikes)){\n update_user_meta($userId, $metaKey, wp_json_encode([$post_id]));\n }else{\n $userLikes = json_decode($userLikes);\n if(!in_array($post_id, $userLikes)){\n array_push($userLikes, $post_id);\n update_user_meta($userId, $metaKey, wp_json_encode($userLikes));\n }\n }\n\n $postLikeCount = get_post_meta($post_id, '_like_count_on_post_', true);\n update_post_meta($post_id, '_like_count_on_post_', ++$postLikeCount);\n exit($postLikeCount);\n }\n}\n</code></pre>\n\n<p>Place this in <strong>single.php</strong>, (<em>before footer ends</em>)</p>\n\n<pre><code><?php if(is_user_logged_in()): ?>\n <script>\n jQuery(function($){\n $('.game-footer-like-btn').on('click', function(){\n $.ajax({\n url: '<?php echo admin_url('admin-ajax.php?action=likeExpression&post_id='.get_the_ID()) ?>',\n method: 'get',\n }).done(function(res){\n console.log(res)\n //if its done\n });\n });\n });\n </script>\n<?php endif; ?>\n</code></pre>\n\n<p>Please, feel free to contact if you any query. \nThank You :)</p>\n"
}
] | 2020/03/29 | [
"https://wordpress.stackexchange.com/questions/362699",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73388/"
] | I have a custom taxonomy called "Sources" (using Custom Post Type UI), where the sources are the names of publications where articles were originally published. Each post is an article, with a source selected. What I need to do is to show the source in the metadata under the post title. I'm using the Avada theme. Currently the title area of a post looks like this:
**Article Title**
By Author Name | Month, Year
What I want is this:
**Article Title**
Author Name, *Source*, Month, Year
Here's an example post I'm working with in my dev environment:
<http://dev.universaltheosophy.com/articles/the-logos-and-meditation/>
I'd love to be able to do this with add\_action in my child theme's functions.php, and hook it before the date or after the author name. But I'm not sure how to do that.
All I see in the theme's single post file file is:
```
<?php if ( 'below' === Avada()->settings->get( 'blog_post_title' ) ) : ?>
<?php if ( 'below_title' === Avada()->settings->get( 'blog_post_meta_position' ) ) : ?>
<div class="fusion-post-title-meta-wrap">
<?php endif; ?>
<?php $title_size = ( false === avada_is_page_title_bar_enabled( $post->ID ) ? '1' : '2' ); ?>
<?php echo avada_render_post_title( $post->ID, false, '', $title_size ); // phpcs:ignore WordPress.Security.EscapeOutput ?>
<?php if ( 'below_title' === Avada()->settings->get( 'blog_post_meta_position' ) ) : ?>
<?php echo avada_render_post_metadata( 'single' ); // phpcs:ignore WordPress.Security.EscapeOutput ?>
</div>
<?php endif; ?>
<?php endif; ?>
```
And I see in the theme's files:
```
// Render author meta data.
if ( $settings['post_meta_author'] ) {
ob_start();
the_author_posts_link();
$author_post_link = ob_get_clean();
// Check if rich snippets are enabled.
if ( fusion_library()->get_option( 'disable_date_rich_snippet_pages' ) && fusion_library()->get_option( 'disable_rich_snippet_author' ) ) {
/* translators: The author. */
$metadata .= sprintf( esc_html__( 'By %s', 'Avada' ), '<span class="vcard"><span class="fn">' . $author_post_link . '</span></span>' );
} else {
/* translators: The author. */
$metadata .= sprintf( esc_html__( 'By %s', 'Avada' ), '<span>' . $author_post_link . '</span>' );
}
$metadata .= '<span class="fusion-inline-sep">|</span>';
} else { // If author meta data won't be visible, render just the invisible author rich snippet.
$author .= fusion_render_rich_snippets_for_pages( false, true, false );
}
// Render the updated meta data or at least the rich snippet if enabled.
if ( $settings['post_meta_date'] ) {
$metadata .= fusion_render_rich_snippets_for_pages( false, false, true );
$formatted_date = get_the_time( fusion_library()->get_option( 'date_format' ) );
$date_markup = '<span>' . $formatted_date . '</span><span class="fusion-inline-sep">|</span>';
$metadata .= apply_filters( 'fusion_post_metadata_date', $date_markup, $formatted_date );
} else {
$date .= fusion_render_rich_snippets_for_pages( false, false, true );
}
```
Other than this, I'm not sure what other info I need. Any help will be much appreciated! Keep in mind I'm very amateur at this. | I hope you are doing well. Here, I am sharing code for recording likes. The code for `single.php` have the javascript code for making an ajax call to a wp function. This wp function have the code to store like expressions and it will return you the total number of like expressions recorded on post.
I have curated it for only the Logged in users.
Place this code in your **functions.php**
```
/* Ajax call */
add_action('wp_ajax_likeExpression', 'likeExpression');
function likeExpression() {
if(is_user_logged_in()){
$post_id = $_GET['post_id'];
$userId = get_current_user_id();
$metaKey = '_like_on_game_post_';
$userLikes = get_user_meta($userId, $metaKey, true);
if(empty($userLikes)){
update_user_meta($userId, $metaKey, wp_json_encode([$post_id]));
}else{
$userLikes = json_decode($userLikes);
if(!in_array($post_id, $userLikes)){
array_push($userLikes, $post_id);
update_user_meta($userId, $metaKey, wp_json_encode($userLikes));
}
}
$postLikeCount = get_post_meta($post_id, '_like_count_on_post_', true);
update_post_meta($post_id, '_like_count_on_post_', ++$postLikeCount);
exit($postLikeCount);
}
}
```
Place this in **single.php**, (*before footer ends*)
```
<?php if(is_user_logged_in()): ?>
<script>
jQuery(function($){
$('.game-footer-like-btn').on('click', function(){
$.ajax({
url: '<?php echo admin_url('admin-ajax.php?action=likeExpression&post_id='.get_the_ID()) ?>',
method: 'get',
}).done(function(res){
console.log(res)
//if its done
});
});
});
</script>
<?php endif; ?>
```
Please, feel free to contact if you any query.
Thank You :) |
362,708 | <p>I had a website which it’s domain is expired: <a href="https://mrafiee.net" rel="nofollow noreferrer">https://mrafiee.net</a>
I also have another active domain and website: <a href="https://rafiee.net" rel="nofollow noreferrer">https://rafiee.net</a></p>
<p>I have created a subdomain under my active domain: <a href="https://old.rafiee.net" rel="nofollow noreferrer">https://old.rafiee.net</a>
I copied all content in mrafiee.net foolder (which is an add-on domain in my cpanel) in my host, to old.rafiee.net folder.</p>
<p>I expected to reach my website when I go to <a href="https://old.rafiee.net" rel="nofollow noreferrer">https://old.rafiee.net</a>, but it redirects me to <a href="https://mrafiee.net" rel="nofollow noreferrer">https://mrafiee.net</a> which is already expired.</p>
<p>I would be very grateful if someone can help me to solve this issue.
Thansk</p>
| [
{
"answer_id": 361589,
"author": "Christmas",
"author_id": 184919,
"author_profile": "https://wordpress.stackexchange.com/users/184919",
"pm_score": 1,
"selected": false,
"text": "<p>I don't understand how u can count like in javascript only.\nUse wp_ajax_ACTION Hook to call your PHP functions, in your functions.php or in a plugin.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/files/wp-admin/admin-ajax.php/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/files/wp-admin/admin-ajax.php/</a></p>\n\n<pre><code>add_action(\"wp_ajax_my_function\", \"my_function\");\n\nfunction my_function() {\n // Get parameters send by javascript xhr method\n\n // Do some stuff\n}\n</code></pre>\n\n<p>add_action(\"wp_ajax_nopriv_my_function\") for no user logged in.</p>\n"
},
{
"answer_id": 362707,
"author": "BlueSuiter",
"author_id": 92665,
"author_profile": "https://wordpress.stackexchange.com/users/92665",
"pm_score": 3,
"selected": true,
"text": "<p>I hope you are doing well. Here, I am sharing code for recording likes. The code for <code>single.php</code> have the javascript code for making an ajax call to a wp function. This wp function have the code to store like expressions and it will return you the total number of like expressions recorded on post.</p>\n\n<p>I have curated it for only the Logged in users.</p>\n\n<p>Place this code in your <strong>functions.php</strong></p>\n\n<pre><code>/* Ajax call */\nadd_action('wp_ajax_likeExpression', 'likeExpression');\nfunction likeExpression() {\n if(is_user_logged_in()){\n $post_id = $_GET['post_id'];\n $userId = get_current_user_id();\n $metaKey = '_like_on_game_post_';\n $userLikes = get_user_meta($userId, $metaKey, true);\n\n if(empty($userLikes)){\n update_user_meta($userId, $metaKey, wp_json_encode([$post_id]));\n }else{\n $userLikes = json_decode($userLikes);\n if(!in_array($post_id, $userLikes)){\n array_push($userLikes, $post_id);\n update_user_meta($userId, $metaKey, wp_json_encode($userLikes));\n }\n }\n\n $postLikeCount = get_post_meta($post_id, '_like_count_on_post_', true);\n update_post_meta($post_id, '_like_count_on_post_', ++$postLikeCount);\n exit($postLikeCount);\n }\n}\n</code></pre>\n\n<p>Place this in <strong>single.php</strong>, (<em>before footer ends</em>)</p>\n\n<pre><code><?php if(is_user_logged_in()): ?>\n <script>\n jQuery(function($){\n $('.game-footer-like-btn').on('click', function(){\n $.ajax({\n url: '<?php echo admin_url('admin-ajax.php?action=likeExpression&post_id='.get_the_ID()) ?>',\n method: 'get',\n }).done(function(res){\n console.log(res)\n //if its done\n });\n });\n });\n </script>\n<?php endif; ?>\n</code></pre>\n\n<p>Please, feel free to contact if you any query. \nThank You :)</p>\n"
}
] | 2020/03/29 | [
"https://wordpress.stackexchange.com/questions/362708",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/171493/"
] | I had a website which it’s domain is expired: <https://mrafiee.net>
I also have another active domain and website: <https://rafiee.net>
I have created a subdomain under my active domain: <https://old.rafiee.net>
I copied all content in mrafiee.net foolder (which is an add-on domain in my cpanel) in my host, to old.rafiee.net folder.
I expected to reach my website when I go to <https://old.rafiee.net>, but it redirects me to <https://mrafiee.net> which is already expired.
I would be very grateful if someone can help me to solve this issue.
Thansk | I hope you are doing well. Here, I am sharing code for recording likes. The code for `single.php` have the javascript code for making an ajax call to a wp function. This wp function have the code to store like expressions and it will return you the total number of like expressions recorded on post.
I have curated it for only the Logged in users.
Place this code in your **functions.php**
```
/* Ajax call */
add_action('wp_ajax_likeExpression', 'likeExpression');
function likeExpression() {
if(is_user_logged_in()){
$post_id = $_GET['post_id'];
$userId = get_current_user_id();
$metaKey = '_like_on_game_post_';
$userLikes = get_user_meta($userId, $metaKey, true);
if(empty($userLikes)){
update_user_meta($userId, $metaKey, wp_json_encode([$post_id]));
}else{
$userLikes = json_decode($userLikes);
if(!in_array($post_id, $userLikes)){
array_push($userLikes, $post_id);
update_user_meta($userId, $metaKey, wp_json_encode($userLikes));
}
}
$postLikeCount = get_post_meta($post_id, '_like_count_on_post_', true);
update_post_meta($post_id, '_like_count_on_post_', ++$postLikeCount);
exit($postLikeCount);
}
}
```
Place this in **single.php**, (*before footer ends*)
```
<?php if(is_user_logged_in()): ?>
<script>
jQuery(function($){
$('.game-footer-like-btn').on('click', function(){
$.ajax({
url: '<?php echo admin_url('admin-ajax.php?action=likeExpression&post_id='.get_the_ID()) ?>',
method: 'get',
}).done(function(res){
console.log(res)
//if its done
});
});
});
</script>
<?php endif; ?>
```
Please, feel free to contact if you any query.
Thank You :) |
362,795 | <p>I using the below code to get modified data for the post, but I need to get the same modified post for my other custom posts. For example, it works if i change post to test( my custom post type name)"if( 'post' === get_post_type() )", but i need for both test, post and movies etc.</p>
<pre><code>function et_last_modified_date_blog( $the_date ) {
if ( 'post' === get_post_type() ) {
$the_time = get_post_time( 'His' );
$the_modified = get_post_modified_time( 'His' );
$last_modified = sprintf( __( 'Last updated %s', 'Divi' ), esc_html( get_post_modified_time( 'M j, Y' ) ) );
$date = $the_modified !== $the_time ? $last_modified : get_post_time( 'M j, Y' );
return $date;
}
}
add_action( 'get_the_date', 'et_last_modified_date_blog' );
add_action( 'get_the_time', 'et_last_modified_date_blog' );
</code></pre>
| [
{
"answer_id": 362797,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 3,
"selected": true,
"text": "<p>In your if statement just add more conditions like this.</p>\n\n<pre><code>function et_last_modified_date_blog( $the_date ) {\n if ( 'post' === get_post_type() || 'movies' === get_post_type() || 'etc' === get_post_type()) {\n $the_time = get_post_time( 'His' );\n $the_modified = get_post_modified_time( 'His' );\n\n $last_modified = sprintf( __( 'Last updated %s', 'Divi' ), esc_html( get_post_modified_time( 'M j, Y' ) ) );\n $date = $the_modified !== $the_time ? $last_modified : get_post_time( 'M j, Y' );\n\n return $date;\n }\n}\nadd_action( 'get_the_date', 'et_last_modified_date_blog' );\nadd_action( 'get_the_time', 'et_last_modified_date_blog' );\n</code></pre>\n\n<p>The \"||\" means OR. So the condition would read If post type equals post or movies or etc.</p>\n"
},
{
"answer_id": 362800,
"author": "mikerojas",
"author_id": 184808,
"author_profile": "https://wordpress.stackexchange.com/users/184808",
"pm_score": 1,
"selected": false,
"text": "<p>Another way is to use <code>in_array</code>. Also you do not return the original date if your check fails. See code below for fix.</p>\n\n<pre><code>function et_last_modified_date_blog( $the_date ) {\n // all post types were are checking for\n $post_types = array('post', 'movies');\n\n // check to see if current post type is in the $post_types array\n if (in_array(get_post_type(), $post_types)) {\n $the_time = get_post_time( 'His' );\n $the_modified = get_post_modified_time( 'His' );\n\n $last_modified = sprintf( __( 'Last updated %s', 'Divi' ), esc_html( get_post_modified_time( 'M j, Y' ) ) );\n $date = $the_modified !== $the_time ? $last_modified : get_post_time( 'M j, Y' );\n\n return $date;\n }\n\n // NOTE: you should return the original date here in case your check \"fails\"\n return $the_date;\n}\nadd_action( 'get_the_date', 'et_last_modified_date_blog' );\nadd_action( 'get_the_time', 'et_last_modified_date_blog' );\n</code></pre>\n"
}
] | 2020/03/30 | [
"https://wordpress.stackexchange.com/questions/362795",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/185081/"
] | I using the below code to get modified data for the post, but I need to get the same modified post for my other custom posts. For example, it works if i change post to test( my custom post type name)"if( 'post' === get\_post\_type() )", but i need for both test, post and movies etc.
```
function et_last_modified_date_blog( $the_date ) {
if ( 'post' === get_post_type() ) {
$the_time = get_post_time( 'His' );
$the_modified = get_post_modified_time( 'His' );
$last_modified = sprintf( __( 'Last updated %s', 'Divi' ), esc_html( get_post_modified_time( 'M j, Y' ) ) );
$date = $the_modified !== $the_time ? $last_modified : get_post_time( 'M j, Y' );
return $date;
}
}
add_action( 'get_the_date', 'et_last_modified_date_blog' );
add_action( 'get_the_time', 'et_last_modified_date_blog' );
``` | In your if statement just add more conditions like this.
```
function et_last_modified_date_blog( $the_date ) {
if ( 'post' === get_post_type() || 'movies' === get_post_type() || 'etc' === get_post_type()) {
$the_time = get_post_time( 'His' );
$the_modified = get_post_modified_time( 'His' );
$last_modified = sprintf( __( 'Last updated %s', 'Divi' ), esc_html( get_post_modified_time( 'M j, Y' ) ) );
$date = $the_modified !== $the_time ? $last_modified : get_post_time( 'M j, Y' );
return $date;
}
}
add_action( 'get_the_date', 'et_last_modified_date_blog' );
add_action( 'get_the_time', 'et_last_modified_date_blog' );
```
The "||" means OR. So the condition would read If post type equals post or movies or etc. |
362,834 | <p>At the bottom of a post, I show all that tags that post has. </p>
<p>If the current post is the only post with tag X, then I don't want tag X to show in the list. Because if someone clicks on that, they'll be taken to an archive page where the post they were just looking at is the only post listed. Useless.</p>
<p>Otherwise I don't have a problem with tags that only have one post.</p>
<p>It's a custom post type with custom taxonomies (three different taxonomies: topic, name, simile)</p>
<p>Here is how I am displaying the topic taxonomy:</p>
<pre><code><p class="meta-tag-list">
<?php
echo get_the_term_list( $post->ID, 'topic',
'', ' ', '' );
?> </p>
</code></pre>
<p>Does a function already exist that would let me do this?</p>
| [
{
"answer_id": 362840,
"author": "西門 正 Code Guy",
"author_id": 35701,
"author_profile": "https://wordpress.stackexchange.com/users/35701",
"pm_score": 2,
"selected": true,
"text": "<p>Because <a href=\"https://developer.wordpress.org/reference/functions/get_the_term_list/\" rel=\"nofollow noreferrer\">get_the_term_list()</a> create the html link for you.\nSo </p>\n\n<ol>\n<li>you need to use <a href=\"https://developer.wordpress.org/reference/functions/wp_get_object_terms/\" rel=\"nofollow noreferrer\">wp_get_object_terms</a> to get a list of terms info first with count for handling.</li>\n<li>compare each tag count, if the count > 1 then create the link and output</li>\n</ol>\n\n<p>I have just tried. It works</p>\n\n<pre><code><p class=\"meta-tag-list\"> \n<?php\n$terms = wp_get_object_terms($post->ID, 'category'); // replace 'category' (default Post post type taxonomy name) with your taxonomy such as 'topic'\nforeach ($terms as $key => $term) {\n if( $term->count > 1 ) { // if the count is > 1, output, if not, then nothing will happen\n $link = get_term_link( $term->term_id );\n echo '<a href=\"' . esc_url( $link ) . '\" rel=\"tag\">' . $term->name . '</a>';\n }\n}\n?> \n</p>\n</code></pre>\n"
},
{
"answer_id": 362842,
"author": "Michael",
"author_id": 4884,
"author_profile": "https://wordpress.stackexchange.com/users/4884",
"pm_score": 2,
"selected": false,
"text": "<p>you can try using a filter function (added into functions.php of your (child) theme), specific to your taxonomy 'topic':\n(based on <a href=\"https://developer.wordpress.org/reference/functions/get_the_term_list/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_the_term_list/</a> and <a href=\"https://developer.wordpress.org/reference/functions/get_the_terms/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_the_terms/</a> )</p>\n\n<pre><code>// define the get_the_terms callback \nfunction filter_get_the_topic_terms( $terms, $postid, $taxonomy ) {\n if( !is_admin() && $taxonomy == 'topic' ) : // make filter magic happen here... \n $filtered_terms = array();\n foreach( $terms as $term ) :\n if( $term->count > 1 ) {\n $filtered_terms[] = $term;\n }\n endforeach;\n $terms = $filtered_terms;\n endif;\n return $terms;\n}\n// add the filter \nadd_filter( 'get_the_terms', 'filter_get_the_topic_terms', 10, 3 );\n</code></pre>\n"
}
] | 2020/03/31 | [
"https://wordpress.stackexchange.com/questions/362834",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/184735/"
] | At the bottom of a post, I show all that tags that post has.
If the current post is the only post with tag X, then I don't want tag X to show in the list. Because if someone clicks on that, they'll be taken to an archive page where the post they were just looking at is the only post listed. Useless.
Otherwise I don't have a problem with tags that only have one post.
It's a custom post type with custom taxonomies (three different taxonomies: topic, name, simile)
Here is how I am displaying the topic taxonomy:
```
<p class="meta-tag-list">
<?php
echo get_the_term_list( $post->ID, 'topic',
'', ' ', '' );
?> </p>
```
Does a function already exist that would let me do this? | Because [get\_the\_term\_list()](https://developer.wordpress.org/reference/functions/get_the_term_list/) create the html link for you.
So
1. you need to use [wp\_get\_object\_terms](https://developer.wordpress.org/reference/functions/wp_get_object_terms/) to get a list of terms info first with count for handling.
2. compare each tag count, if the count > 1 then create the link and output
I have just tried. It works
```
<p class="meta-tag-list">
<?php
$terms = wp_get_object_terms($post->ID, 'category'); // replace 'category' (default Post post type taxonomy name) with your taxonomy such as 'topic'
foreach ($terms as $key => $term) {
if( $term->count > 1 ) { // if the count is > 1, output, if not, then nothing will happen
$link = get_term_link( $term->term_id );
echo '<a href="' . esc_url( $link ) . '" rel="tag">' . $term->name . '</a>';
}
}
?>
</p>
``` |
362,853 | <p>My Website, How to Stop Spamming in <a href="https://www.findtricks.in/thop-tv-mod-apk/" rel="nofollow noreferrer">WordPress</a>, Plz Help Me.</p>
| [
{
"answer_id": 362840,
"author": "西門 正 Code Guy",
"author_id": 35701,
"author_profile": "https://wordpress.stackexchange.com/users/35701",
"pm_score": 2,
"selected": true,
"text": "<p>Because <a href=\"https://developer.wordpress.org/reference/functions/get_the_term_list/\" rel=\"nofollow noreferrer\">get_the_term_list()</a> create the html link for you.\nSo </p>\n\n<ol>\n<li>you need to use <a href=\"https://developer.wordpress.org/reference/functions/wp_get_object_terms/\" rel=\"nofollow noreferrer\">wp_get_object_terms</a> to get a list of terms info first with count for handling.</li>\n<li>compare each tag count, if the count > 1 then create the link and output</li>\n</ol>\n\n<p>I have just tried. It works</p>\n\n<pre><code><p class=\"meta-tag-list\"> \n<?php\n$terms = wp_get_object_terms($post->ID, 'category'); // replace 'category' (default Post post type taxonomy name) with your taxonomy such as 'topic'\nforeach ($terms as $key => $term) {\n if( $term->count > 1 ) { // if the count is > 1, output, if not, then nothing will happen\n $link = get_term_link( $term->term_id );\n echo '<a href=\"' . esc_url( $link ) . '\" rel=\"tag\">' . $term->name . '</a>';\n }\n}\n?> \n</p>\n</code></pre>\n"
},
{
"answer_id": 362842,
"author": "Michael",
"author_id": 4884,
"author_profile": "https://wordpress.stackexchange.com/users/4884",
"pm_score": 2,
"selected": false,
"text": "<p>you can try using a filter function (added into functions.php of your (child) theme), specific to your taxonomy 'topic':\n(based on <a href=\"https://developer.wordpress.org/reference/functions/get_the_term_list/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_the_term_list/</a> and <a href=\"https://developer.wordpress.org/reference/functions/get_the_terms/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_the_terms/</a> )</p>\n\n<pre><code>// define the get_the_terms callback \nfunction filter_get_the_topic_terms( $terms, $postid, $taxonomy ) {\n if( !is_admin() && $taxonomy == 'topic' ) : // make filter magic happen here... \n $filtered_terms = array();\n foreach( $terms as $term ) :\n if( $term->count > 1 ) {\n $filtered_terms[] = $term;\n }\n endforeach;\n $terms = $filtered_terms;\n endif;\n return $terms;\n}\n// add the filter \nadd_filter( 'get_the_terms', 'filter_get_the_topic_terms', 10, 3 );\n</code></pre>\n"
}
] | 2020/03/31 | [
"https://wordpress.stackexchange.com/questions/362853",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/185128/"
] | My Website, How to Stop Spamming in [WordPress](https://www.findtricks.in/thop-tv-mod-apk/), Plz Help Me. | Because [get\_the\_term\_list()](https://developer.wordpress.org/reference/functions/get_the_term_list/) create the html link for you.
So
1. you need to use [wp\_get\_object\_terms](https://developer.wordpress.org/reference/functions/wp_get_object_terms/) to get a list of terms info first with count for handling.
2. compare each tag count, if the count > 1 then create the link and output
I have just tried. It works
```
<p class="meta-tag-list">
<?php
$terms = wp_get_object_terms($post->ID, 'category'); // replace 'category' (default Post post type taxonomy name) with your taxonomy such as 'topic'
foreach ($terms as $key => $term) {
if( $term->count > 1 ) { // if the count is > 1, output, if not, then nothing will happen
$link = get_term_link( $term->term_id );
echo '<a href="' . esc_url( $link ) . '" rel="tag">' . $term->name . '</a>';
}
}
?>
</p>
``` |
362,855 | <p>I created like system in wordpress. And I created 'sayim_beyenme' table and created 'say_post_id' and 'total_post_likes' datas. Now I want to display my posts orderby total likes per each post. I get posts ids with array_map, but I dont know how can I order these posts by total_post_like values. For testing I have used 'title'
This is my codes:</p>
<pre><code><?php
$results = $db->prepare("SELECT say_post_id FROM sayim_beyenme ORDER BY total_post_likes DESC LIMIT 3");
$results->execute();
$results = $results->fetchAll();
$like_posts = array_map(function(&$r) { return $r['say_post_id']; }, $results);
if($like_posts) {
$postlar = new WP_Query(array(
'paged' => get_query_var('paged', 1),
'post_type' => array('post'),
'posts_per_page' => 9,
'post__in' => $like_posts,
'orderby' => 'title',
'order' => 'ASC',
));
</code></pre>
| [
{
"answer_id": 362840,
"author": "西門 正 Code Guy",
"author_id": 35701,
"author_profile": "https://wordpress.stackexchange.com/users/35701",
"pm_score": 2,
"selected": true,
"text": "<p>Because <a href=\"https://developer.wordpress.org/reference/functions/get_the_term_list/\" rel=\"nofollow noreferrer\">get_the_term_list()</a> create the html link for you.\nSo </p>\n\n<ol>\n<li>you need to use <a href=\"https://developer.wordpress.org/reference/functions/wp_get_object_terms/\" rel=\"nofollow noreferrer\">wp_get_object_terms</a> to get a list of terms info first with count for handling.</li>\n<li>compare each tag count, if the count > 1 then create the link and output</li>\n</ol>\n\n<p>I have just tried. It works</p>\n\n<pre><code><p class=\"meta-tag-list\"> \n<?php\n$terms = wp_get_object_terms($post->ID, 'category'); // replace 'category' (default Post post type taxonomy name) with your taxonomy such as 'topic'\nforeach ($terms as $key => $term) {\n if( $term->count > 1 ) { // if the count is > 1, output, if not, then nothing will happen\n $link = get_term_link( $term->term_id );\n echo '<a href=\"' . esc_url( $link ) . '\" rel=\"tag\">' . $term->name . '</a>';\n }\n}\n?> \n</p>\n</code></pre>\n"
},
{
"answer_id": 362842,
"author": "Michael",
"author_id": 4884,
"author_profile": "https://wordpress.stackexchange.com/users/4884",
"pm_score": 2,
"selected": false,
"text": "<p>you can try using a filter function (added into functions.php of your (child) theme), specific to your taxonomy 'topic':\n(based on <a href=\"https://developer.wordpress.org/reference/functions/get_the_term_list/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_the_term_list/</a> and <a href=\"https://developer.wordpress.org/reference/functions/get_the_terms/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_the_terms/</a> )</p>\n\n<pre><code>// define the get_the_terms callback \nfunction filter_get_the_topic_terms( $terms, $postid, $taxonomy ) {\n if( !is_admin() && $taxonomy == 'topic' ) : // make filter magic happen here... \n $filtered_terms = array();\n foreach( $terms as $term ) :\n if( $term->count > 1 ) {\n $filtered_terms[] = $term;\n }\n endforeach;\n $terms = $filtered_terms;\n endif;\n return $terms;\n}\n// add the filter \nadd_filter( 'get_the_terms', 'filter_get_the_topic_terms', 10, 3 );\n</code></pre>\n"
}
] | 2020/03/31 | [
"https://wordpress.stackexchange.com/questions/362855",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/125615/"
] | I created like system in wordpress. And I created 'sayim\_beyenme' table and created 'say\_post\_id' and 'total\_post\_likes' datas. Now I want to display my posts orderby total likes per each post. I get posts ids with array\_map, but I dont know how can I order these posts by total\_post\_like values. For testing I have used 'title'
This is my codes:
```
<?php
$results = $db->prepare("SELECT say_post_id FROM sayim_beyenme ORDER BY total_post_likes DESC LIMIT 3");
$results->execute();
$results = $results->fetchAll();
$like_posts = array_map(function(&$r) { return $r['say_post_id']; }, $results);
if($like_posts) {
$postlar = new WP_Query(array(
'paged' => get_query_var('paged', 1),
'post_type' => array('post'),
'posts_per_page' => 9,
'post__in' => $like_posts,
'orderby' => 'title',
'order' => 'ASC',
));
``` | Because [get\_the\_term\_list()](https://developer.wordpress.org/reference/functions/get_the_term_list/) create the html link for you.
So
1. you need to use [wp\_get\_object\_terms](https://developer.wordpress.org/reference/functions/wp_get_object_terms/) to get a list of terms info first with count for handling.
2. compare each tag count, if the count > 1 then create the link and output
I have just tried. It works
```
<p class="meta-tag-list">
<?php
$terms = wp_get_object_terms($post->ID, 'category'); // replace 'category' (default Post post type taxonomy name) with your taxonomy such as 'topic'
foreach ($terms as $key => $term) {
if( $term->count > 1 ) { // if the count is > 1, output, if not, then nothing will happen
$link = get_term_link( $term->term_id );
echo '<a href="' . esc_url( $link ) . '" rel="tag">' . $term->name . '</a>';
}
}
?>
</p>
``` |
362,882 | <p>I'm trying to accomplish this simple task through different plugins, but I can't find the right one for different reasons.</p>
<p>I have a Login Page with a login form. When user logs in, he's redirected to a specific page (based on user role). If the user visits again the Login Page, the login form displays a Welcome message with dashboard, profile and logout links (see pics).</p>
<p><a href="https://i.stack.imgur.com/Hdznf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Hdznf.png" alt="enter image description here"></a></p>
<p>Since I need to avoid that and need logged in user to only visit the specific page based on their role, I'd like to redirect away logged in users from Login Page to Specific Page.</p>
<p>eg: Paul is a user with "apple" role. He logs in and gets redirected to Apple Page. Then he browses the website and try to visit the Login Page. As he tries, he's redirected to Apple Page. The same applies to Ron, whose role is "banana", so when he tries to visit Login Page he's redirected to Banana Page.</p>
<p>My biggest issue is that every plugin helps with redirection AFTER login, and that is easly manageable. Do you know any easy way to accomplish that or any suggestion on where to look? </p>
| [
{
"answer_id": 362840,
"author": "西門 正 Code Guy",
"author_id": 35701,
"author_profile": "https://wordpress.stackexchange.com/users/35701",
"pm_score": 2,
"selected": true,
"text": "<p>Because <a href=\"https://developer.wordpress.org/reference/functions/get_the_term_list/\" rel=\"nofollow noreferrer\">get_the_term_list()</a> create the html link for you.\nSo </p>\n\n<ol>\n<li>you need to use <a href=\"https://developer.wordpress.org/reference/functions/wp_get_object_terms/\" rel=\"nofollow noreferrer\">wp_get_object_terms</a> to get a list of terms info first with count for handling.</li>\n<li>compare each tag count, if the count > 1 then create the link and output</li>\n</ol>\n\n<p>I have just tried. It works</p>\n\n<pre><code><p class=\"meta-tag-list\"> \n<?php\n$terms = wp_get_object_terms($post->ID, 'category'); // replace 'category' (default Post post type taxonomy name) with your taxonomy such as 'topic'\nforeach ($terms as $key => $term) {\n if( $term->count > 1 ) { // if the count is > 1, output, if not, then nothing will happen\n $link = get_term_link( $term->term_id );\n echo '<a href=\"' . esc_url( $link ) . '\" rel=\"tag\">' . $term->name . '</a>';\n }\n}\n?> \n</p>\n</code></pre>\n"
},
{
"answer_id": 362842,
"author": "Michael",
"author_id": 4884,
"author_profile": "https://wordpress.stackexchange.com/users/4884",
"pm_score": 2,
"selected": false,
"text": "<p>you can try using a filter function (added into functions.php of your (child) theme), specific to your taxonomy 'topic':\n(based on <a href=\"https://developer.wordpress.org/reference/functions/get_the_term_list/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_the_term_list/</a> and <a href=\"https://developer.wordpress.org/reference/functions/get_the_terms/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_the_terms/</a> )</p>\n\n<pre><code>// define the get_the_terms callback \nfunction filter_get_the_topic_terms( $terms, $postid, $taxonomy ) {\n if( !is_admin() && $taxonomy == 'topic' ) : // make filter magic happen here... \n $filtered_terms = array();\n foreach( $terms as $term ) :\n if( $term->count > 1 ) {\n $filtered_terms[] = $term;\n }\n endforeach;\n $terms = $filtered_terms;\n endif;\n return $terms;\n}\n// add the filter \nadd_filter( 'get_the_terms', 'filter_get_the_topic_terms', 10, 3 );\n</code></pre>\n"
}
] | 2020/03/31 | [
"https://wordpress.stackexchange.com/questions/362882",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89820/"
] | I'm trying to accomplish this simple task through different plugins, but I can't find the right one for different reasons.
I have a Login Page with a login form. When user logs in, he's redirected to a specific page (based on user role). If the user visits again the Login Page, the login form displays a Welcome message with dashboard, profile and logout links (see pics).
[](https://i.stack.imgur.com/Hdznf.png)
Since I need to avoid that and need logged in user to only visit the specific page based on their role, I'd like to redirect away logged in users from Login Page to Specific Page.
eg: Paul is a user with "apple" role. He logs in and gets redirected to Apple Page. Then he browses the website and try to visit the Login Page. As he tries, he's redirected to Apple Page. The same applies to Ron, whose role is "banana", so when he tries to visit Login Page he's redirected to Banana Page.
My biggest issue is that every plugin helps with redirection AFTER login, and that is easly manageable. Do you know any easy way to accomplish that or any suggestion on where to look? | Because [get\_the\_term\_list()](https://developer.wordpress.org/reference/functions/get_the_term_list/) create the html link for you.
So
1. you need to use [wp\_get\_object\_terms](https://developer.wordpress.org/reference/functions/wp_get_object_terms/) to get a list of terms info first with count for handling.
2. compare each tag count, if the count > 1 then create the link and output
I have just tried. It works
```
<p class="meta-tag-list">
<?php
$terms = wp_get_object_terms($post->ID, 'category'); // replace 'category' (default Post post type taxonomy name) with your taxonomy such as 'topic'
foreach ($terms as $key => $term) {
if( $term->count > 1 ) { // if the count is > 1, output, if not, then nothing will happen
$link = get_term_link( $term->term_id );
echo '<a href="' . esc_url( $link ) . '" rel="tag">' . $term->name . '</a>';
}
}
?>
</p>
``` |
362,888 | <p>This must be a very amateurish question but... </p>
<p>I'm using page templates from the dropdown menu in page editor but I can't find their source code. I know that usually this can be found in themes/"theme name"/page-templates, but no matter how hard I look, I just can't find the files for several of the templates I'm using ("Full-Width Template", "Page with Navigation Only" etc.). Any tips?</p>
<p>Thanks a lot!</p>
| [
{
"answer_id": 362897,
"author": "Eshban",
"author_id": 162989,
"author_profile": "https://wordpress.stackexchange.com/users/162989",
"pm_score": 0,
"selected": false,
"text": "<p>I suggest you to download the starter theme from <a href=\"https://underscores.me/\" rel=\"nofollow noreferrer\">Underscores.me</a></p>\n\n<p>Once you download it will you get a complete structure of a custom theme with all files available and sample code in it. It is just like a prototype. It helps you a lot and give you best understanding.</p>\n"
},
{
"answer_id": 362898,
"author": "Elex",
"author_id": 113687,
"author_profile": "https://wordpress.stackexchange.com/users/113687",
"pm_score": 2,
"selected": true,
"text": "<p>You can simply right click on your Template Select on the edit page, Inspect Element (on Chrome) then you can check the different options in the select like \"page-template.php\" as value and find your template file. :)</p>\n\n<pre><code><select id=\"inspector-select-control-0\" class=\"components-select-control__input\">\n <option value=\"\">Default</option>\n <option value=\"page-my-account.php\">My Account</option>\n</select>\n</code></pre>\n\n<p>It should look like this with your own templates.</p>\n"
}
] | 2020/03/31 | [
"https://wordpress.stackexchange.com/questions/362888",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/183438/"
] | This must be a very amateurish question but...
I'm using page templates from the dropdown menu in page editor but I can't find their source code. I know that usually this can be found in themes/"theme name"/page-templates, but no matter how hard I look, I just can't find the files for several of the templates I'm using ("Full-Width Template", "Page with Navigation Only" etc.). Any tips?
Thanks a lot! | You can simply right click on your Template Select on the edit page, Inspect Element (on Chrome) then you can check the different options in the select like "page-template.php" as value and find your template file. :)
```
<select id="inspector-select-control-0" class="components-select-control__input">
<option value="">Default</option>
<option value="page-my-account.php">My Account</option>
</select>
```
It should look like this with your own templates. |
362,901 | <pre><code>//Get Services and save to database first.
for($i = 0; $i < count($_POST["wc_service_id"]); $i++) {
$wc_service_id = $_POST["wc_service_id"][$i];
$wc_service_name = $_POST["wc_service_name"][$i];
$wc_service_code = $_POST["wc_service_code"][$i];
$wc_service_qty = $_POST["wc_service_qty"][$i];
$wc_service_price = $_POST["wc_service_price"][$i];
$insert_query = "INSERT INTO `".$computer_repair_items."` VALUES(NULL, '".$wc_service_name."', 'services', '".$post_id."')";
$wpdb->query(
$wpdb->prepare($insert_query)
);
$order_item_id = $wpdb->insert_id;
$insert_query = "INSERT INTO `".$computer_repair_items_meta."`
VALUES(NULL, '".$order_item_id."', 'wc_service_code', '".$wc_service_code."'),
(NULL, '".$order_item_id."', 'wc_service_id', '".$wc_service_id."'),
(NULL, '".$order_item_id."', 'wc_service_qty', '".$wc_service_qty."'),
(NULL, '".$order_item_id."', 'wc_service_price', '".$wc_service_price."')";
$wpdb->query(
$wpdb->prepare($insert_query)
);
}//Services Processed nicely
</code></pre>
<p>With code above its working completely fine only problem i am getting this Notice: when debug mode is on. And i shouldn't have any notices. </p>
<p>Notice: wpdb::prepare was called incorrectly. The query argument of wpdb::prepare() must have a placeholder.</p>
<p>Is there any suggestion? I know removing prepare( would take away the problem. But i want to keep the query prepared if you think its not necessary please explain. </p>
<p>Also adding %s, %d for first query, is good. But what for 2nd Query where i have 3 values? </p>
<p>Thanks in advance for reply.</p>
| [
{
"answer_id": 362915,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 3,
"selected": true,
"text": "<p><em>You don't need to remove the <code>prepare()</code>, but you just need to do it properly.</em></p>\n\n<p>And please check the <code>$wpdb->prepare()</code> <a href=\"https://developer.wordpress.org/reference/classes/wpdb/prepare/\" rel=\"nofollow noreferrer\">reference</a> for the function's syntax etc., but basically, instead of (wrapped for brevity):</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$insert_query = \"INSERT INTO `\".$computer_repair_items.\"`\n VALUES(NULL, '\".$wc_service_name.\"', 'services', '\".$post_id.\"')\";\n$wpdb->query(\n $wpdb->prepare($insert_query)\n);\n</code></pre>\n\n<p>you should do it like this: (presuming <code>$computer_repair_items</code> is a valid table name)</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$insert_query = $wpdb->prepare(\n \"INSERT INTO `$computer_repair_items` VALUES(NULL, %s, 'services', %d)\",\n $wc_service_name, // 2nd parameter; replaces the %s (first placeholder)\n $post_id // 3rd parameter; replaces the %d (second placeholder)\n);\n$wpdb->query( $insert_query );\n</code></pre>\n\n<p>I.e. You <em>must</em> pass at least two parameters to <code>$wpdb->prepare()</code>:</p>\n\n<ol>\n<li><p>The <strong>first parameter</strong> is the SQL command and should be in the same format as accepted by the PHP's <a href=\"https://www.php.net/manual/en/function.sprintf.php\" rel=\"nofollow noreferrer\"><code>sprintf()</code></a> function, i.e. using placeholders such as <code>%s</code> for strings and <code>%d</code> for integers.</p></li>\n<li><p>The second parameter should be the replacement value for the first placeholder in the SQL command mentioned above, i.e. the first parameter. So in the example I gave, the second parameter is <code>$wc_service_name</code> which the value replaces the <code>%s</code> in the SQL command. <em>But note that you should <strong>not</strong> wrap the placeholder in quotes, so <code>'%s'</code> and <code>\"%s\"</code> for examples, are incorrect and just use <code>%s</code>.</em></p></li>\n<li><p>Depending on your SQL command, you can also have the third, fourth, fifth, etc. parameters, just as in the example I gave where I have a third parameter which is <code>$post_id</code> for the <code>%d</code> placeholder.</p></li>\n</ol>\n\n<p>And actually, for <strong>single</strong> <code>INSERT</code> operations, you could simply use <a href=\"https://developer.wordpress.org/reference/classes/wpdb/insert/\" rel=\"nofollow noreferrer\"><code>$wpdb->insert()</code></a>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>// Make sure you replace the column NAMES.\n$wpdb->insert( $computer_repair_items, [\n 'column' => $wc_service_name,\n 'column2' => 'services',\n 'column3' => $post_id,\n] );\n</code></pre>\n\n<p>For multiple inserts, you can try something like:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$insert_values = [];\nforeach ( [\n [ 'wc_service_code', $wc_service_code ],\n [ 'wc_service_id', $wc_service_id ],\n [ 'wc_service_qty', $wc_service_qty ],\n [ 'wc_service_price', $wc_service_price ],\n] as $row ) {\n $insert_values[] = $wpdb->prepare( \"(NULL, %d, %s, %s)\",\n $order_item_id, $row[0], $row[1] );\n}\n\n$insert_query = \"INSERT INTO `$computer_repair_items_meta`\n VALUES \" . implode( ',', $insert_values );\n$wpdb->query( $insert_query );\n</code></pre>\n\n<p>Or just call <code>$wpdb->insert()</code> multiple times..</p>\n"
},
{
"answer_id": 362916,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>Your code is extremely unsafe. </p>\n\n<p>You're not using <code>$wpdb->prepare()</code> properly. You can't just use it on a string as a magic fix. There is nothing in this line of code that protects you from SQL injection attacks, because you're taking submitted values from <code>$_POST</code> and inserting them directly into an SQL query:</p>\n\n<pre><code>\"INSERT INTO `\".$computer_repair_items.\"` VALUES(NULL, '\".$wc_service_name.\"', 'services', '\".$post_id.\"')\";\n</code></pre>\n\n<p>The whole point of <code>$wpdb->prepare()</code>, <a href=\"https://developer.wordpress.org/reference/classes/wpdb/#protect-queries-against-sql-injection-attacks\" rel=\"nofollow noreferrer\">as documented</a>, is to safely insert variables into an SQL query. To do this you need to provide it 2 things:</p>\n\n<ol>\n<li>An SQL string with placeholders where the variables need to go.</li>\n<li>The variables that will go into those placeholders, separately.</li>\n</ol>\n\n<p>So instead of: </p>\n\n<pre><code>$insert_query = \"INSERT INTO `\".$computer_repair_items.\"` VALUES(NULL, '\".$wc_service_name.\"', 'services', '\".$post_id.\"')\";\n$wpdb->query(\n $wpdb->prepare($insert_query)\n);\n</code></pre>\n\n<p>You need to do this:</p>\n\n<pre><code>$insert_query = \"INSERT INTO `{$computer_repair_items}` VALUES( NULL, %s, 'services', %s )\";\n\n$wpdb->query(\n $wpdb->prepare( $insert_query, $wc_service_name, $post_id );\n);\n</code></pre>\n\n<p>Note that:</p>\n\n<ul>\n<li><code>$wpdb->prepare()</code> can't insert the table name from a variable, but the table name should not be coming from an unsafe source. I'm assuming that you've defined in manually in your code earlier.</li>\n<li>The first <code>%s</code> will be replaced with a safely escaped version of <code>$wc_service_name</code>, with quotes added automatically.</li>\n<li>The second <code>%s</code> will be replaced with a safely escaped version of <code>$post_id</code>, with quotes added automatically, just because this is what your original code did. If that column is actually an integer column, then use <code>%d</code> instead of <code>%s</code>.</li>\n</ul>\n\n<p>All that being said, <code>$wpdb</code> actually has <a href=\"https://developer.wordpress.org/reference/classes/wpdb/insert/\" rel=\"nofollow noreferrer\">a method</a> for <code>INSERT</code> queries that automatically prepares the query for you. For our example you would use it like this:</p>\n\n<pre><code>$wpdb->insert(\n $computer_repair_items,\n [\n $wc_service_name,\n $post_id,\n ],\n [\n '%s',\n '%s',\n ]\n);\n</code></pre>\n"
}
] | 2020/03/31 | [
"https://wordpress.stackexchange.com/questions/362901",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/170243/"
] | ```
//Get Services and save to database first.
for($i = 0; $i < count($_POST["wc_service_id"]); $i++) {
$wc_service_id = $_POST["wc_service_id"][$i];
$wc_service_name = $_POST["wc_service_name"][$i];
$wc_service_code = $_POST["wc_service_code"][$i];
$wc_service_qty = $_POST["wc_service_qty"][$i];
$wc_service_price = $_POST["wc_service_price"][$i];
$insert_query = "INSERT INTO `".$computer_repair_items."` VALUES(NULL, '".$wc_service_name."', 'services', '".$post_id."')";
$wpdb->query(
$wpdb->prepare($insert_query)
);
$order_item_id = $wpdb->insert_id;
$insert_query = "INSERT INTO `".$computer_repair_items_meta."`
VALUES(NULL, '".$order_item_id."', 'wc_service_code', '".$wc_service_code."'),
(NULL, '".$order_item_id."', 'wc_service_id', '".$wc_service_id."'),
(NULL, '".$order_item_id."', 'wc_service_qty', '".$wc_service_qty."'),
(NULL, '".$order_item_id."', 'wc_service_price', '".$wc_service_price."')";
$wpdb->query(
$wpdb->prepare($insert_query)
);
}//Services Processed nicely
```
With code above its working completely fine only problem i am getting this Notice: when debug mode is on. And i shouldn't have any notices.
Notice: wpdb::prepare was called incorrectly. The query argument of wpdb::prepare() must have a placeholder.
Is there any suggestion? I know removing prepare( would take away the problem. But i want to keep the query prepared if you think its not necessary please explain.
Also adding %s, %d for first query, is good. But what for 2nd Query where i have 3 values?
Thanks in advance for reply. | *You don't need to remove the `prepare()`, but you just need to do it properly.*
And please check the `$wpdb->prepare()` [reference](https://developer.wordpress.org/reference/classes/wpdb/prepare/) for the function's syntax etc., but basically, instead of (wrapped for brevity):
```php
$insert_query = "INSERT INTO `".$computer_repair_items."`
VALUES(NULL, '".$wc_service_name."', 'services', '".$post_id."')";
$wpdb->query(
$wpdb->prepare($insert_query)
);
```
you should do it like this: (presuming `$computer_repair_items` is a valid table name)
```php
$insert_query = $wpdb->prepare(
"INSERT INTO `$computer_repair_items` VALUES(NULL, %s, 'services', %d)",
$wc_service_name, // 2nd parameter; replaces the %s (first placeholder)
$post_id // 3rd parameter; replaces the %d (second placeholder)
);
$wpdb->query( $insert_query );
```
I.e. You *must* pass at least two parameters to `$wpdb->prepare()`:
1. The **first parameter** is the SQL command and should be in the same format as accepted by the PHP's [`sprintf()`](https://www.php.net/manual/en/function.sprintf.php) function, i.e. using placeholders such as `%s` for strings and `%d` for integers.
2. The second parameter should be the replacement value for the first placeholder in the SQL command mentioned above, i.e. the first parameter. So in the example I gave, the second parameter is `$wc_service_name` which the value replaces the `%s` in the SQL command. *But note that you should **not** wrap the placeholder in quotes, so `'%s'` and `"%s"` for examples, are incorrect and just use `%s`.*
3. Depending on your SQL command, you can also have the third, fourth, fifth, etc. parameters, just as in the example I gave where I have a third parameter which is `$post_id` for the `%d` placeholder.
And actually, for **single** `INSERT` operations, you could simply use [`$wpdb->insert()`](https://developer.wordpress.org/reference/classes/wpdb/insert/):
```php
// Make sure you replace the column NAMES.
$wpdb->insert( $computer_repair_items, [
'column' => $wc_service_name,
'column2' => 'services',
'column3' => $post_id,
] );
```
For multiple inserts, you can try something like:
```php
$insert_values = [];
foreach ( [
[ 'wc_service_code', $wc_service_code ],
[ 'wc_service_id', $wc_service_id ],
[ 'wc_service_qty', $wc_service_qty ],
[ 'wc_service_price', $wc_service_price ],
] as $row ) {
$insert_values[] = $wpdb->prepare( "(NULL, %d, %s, %s)",
$order_item_id, $row[0], $row[1] );
}
$insert_query = "INSERT INTO `$computer_repair_items_meta`
VALUES " . implode( ',', $insert_values );
$wpdb->query( $insert_query );
```
Or just call `$wpdb->insert()` multiple times.. |
362,907 | <p>It is my first form trying on wordpress.I changed some names such as "name","e-mail" etc. to "name1" , "email1" etc.Because without these changing, submit button refers to 404 page.</p>
<p>There is no any registration on database when I check it</p>
<blockquote>
<p>I dont know any idea about what is the spesific code as problem so I
give my all codes.If you know enough information, probably you can
solve this easyly.But if you dont enough information, probably you
will give negative point to question and go away from my question.Or
maybe, you can close my question and write "give us spesific
code/question".I write again, there is no problem with my question or
asking style, it is completly your information.</p>
</blockquote>
<pre><code><!-- data mata -->
<div class="reservation-info">
<form class="reservation-form" method="post">
<h2>Make a reservation</h2>
<div class="field">
<input type="text" name="name1" placeholder="Name" required>
</div>
<div class="field">
<input type="datetime-local" name="date1" placeholder="Date" step="300" required>
</div>
<div class="field">
<input type="text" name="email1" placeholder="E-Mail">
</div>
<div class="field">
<input type="tel" name="phone1" placeholder="Phone Number" required>
</div>
<div class="field">
<textarea name="message1" placeholder="Message" requires></textarea>
</div>
<div class="g-recaptcha" data-sitekey="6LeKTjMUAAAAAJuZI0qqIBRp92slJoG4SESblWHw"></div>
<input type="submit" name="reservation1" class="button" value="Send">
<input type="hidden" name="hidden" value="1">
</form>
</div>
</code></pre>
<hr>
<pre><code><?php
function lapizzeria_database(){
global $wpdb;
global $lapizzeria_db_version;
$lapizzeria_db_version = "1.0";
$table = $wpdb->prefix . 'reservations1';
$charset_collate = $wpdb->get_charset_collate();
// SQL Statement
$sql = "CREATE TABLE $table (
id mediumint(9) NOT NULL AUTO_INCREMENT,
name1 varchar(50) NOT NULL,
date1 datetime NOT NULL,
email1 varchar(50) DEFAULT '' NOT NULL,
phone1 varchar(10) NOT NULL,
message1 longtext NOT NULL,
PRIMARY KEY (id)
) $charset_collate; ";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
add_action('after_setup_theme', 'lapizzeria_database');
</code></pre>
<hr>
<pre><code>function lapizzeria_save_reservation() {
if(isset($_POST['reservation1']) && $_POST['hidden'] == "1") {
// read the value from recaptcha response
$captcha = $_POST['g-recaptcha-response'];
// Send the values to the server
$fields = array(
'secret' => '6LeKTjMUAAAAAFeaj6Hq941AFvASw9sBJjeiCDyB',
'response' => $captcha,
'remoteip' => $_SERVER['REMOTE_ADDR']
);
// Start the request to the server
$ch = curl_init('https://www.google.com/recaptcha/api/siteverify');
// configure the request
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
// Send the encode values in the URL
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
// Read the return value
$response = json_decode(curl_exec($ch));
if($response->success) {
global $wpdb;
$name = sanitize_text_field( $_POST['name1'] ) ;
$date = sanitize_text_field( $_POST['date1'] ) ;
$email = sanitize_email( $_POST['email1'] );
$phone = sanitize_text_field( $_POST['phone1'] ) ;
$message = sanitize_text_field( $_POST['message1'] ) ;
$table = $wpdb->prefix . 'reservations1';
$data = array(
'name1' => $name1,
'date1' => $date1,
'email1' => $email1,
'phone1' => $phone1,
'message1' => $message1
);
$format = array(
'%s',
'%s',
'%s',
'%s',
'%s'
);
$wpdb->insert($table, $data, $format );
$url = get_page_by_title('Thanks for your reservation!');
wp_redirect( get_permalink($url) );
exit();
}
}
}
add_action('init', 'lapizzeria_save_reservation');
?>
</code></pre>
<hr>
<pre><code>function lapizzeria_reservations() { ?>
<div class="wrap">
<h1>Reservations</h1>
<table class="wp-list-table widefat striped">
<thead>
<tr>
<th class="manage-column">ID</th>
<th class="manage-column">Name</th>
<th class="manage-column">Date of Reservation</th>
<th class="manage-column">Email</th>
<th class="manage-column">Phone Number</th>
<th class="manage-column">Message</th>
<th class="manage-column">Delete</th>
</tr>
</thead>
<tbody>
<?php
global $wpdb;
$table = $wpdb->prefix . 'reservations1';
$reservations = $wpdb->get_results("SELECT * FROM $table", ARRAY_A);
foreach($reservations as $reservation): ?>
<tr>
<td><?php echo $reservation['id']; ?></td>
<td><?php echo $reservation['name1']; ?></td>
<td><?php echo $reservation['date1']; ?></td>
<td><?php echo $reservation['email1']; ?></td>
<td><?php echo $reservation['phone1']; ?></td>
<td><?php echo $reservation['message1']; ?></td>
<td>
<a href="#" class="remove_reservation" data-reservation="<?php echo $reservation1['id']; ?>">Remove</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php }
?>
</code></pre>
| [
{
"answer_id": 362915,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 3,
"selected": true,
"text": "<p><em>You don't need to remove the <code>prepare()</code>, but you just need to do it properly.</em></p>\n\n<p>And please check the <code>$wpdb->prepare()</code> <a href=\"https://developer.wordpress.org/reference/classes/wpdb/prepare/\" rel=\"nofollow noreferrer\">reference</a> for the function's syntax etc., but basically, instead of (wrapped for brevity):</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$insert_query = \"INSERT INTO `\".$computer_repair_items.\"`\n VALUES(NULL, '\".$wc_service_name.\"', 'services', '\".$post_id.\"')\";\n$wpdb->query(\n $wpdb->prepare($insert_query)\n);\n</code></pre>\n\n<p>you should do it like this: (presuming <code>$computer_repair_items</code> is a valid table name)</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$insert_query = $wpdb->prepare(\n \"INSERT INTO `$computer_repair_items` VALUES(NULL, %s, 'services', %d)\",\n $wc_service_name, // 2nd parameter; replaces the %s (first placeholder)\n $post_id // 3rd parameter; replaces the %d (second placeholder)\n);\n$wpdb->query( $insert_query );\n</code></pre>\n\n<p>I.e. You <em>must</em> pass at least two parameters to <code>$wpdb->prepare()</code>:</p>\n\n<ol>\n<li><p>The <strong>first parameter</strong> is the SQL command and should be in the same format as accepted by the PHP's <a href=\"https://www.php.net/manual/en/function.sprintf.php\" rel=\"nofollow noreferrer\"><code>sprintf()</code></a> function, i.e. using placeholders such as <code>%s</code> for strings and <code>%d</code> for integers.</p></li>\n<li><p>The second parameter should be the replacement value for the first placeholder in the SQL command mentioned above, i.e. the first parameter. So in the example I gave, the second parameter is <code>$wc_service_name</code> which the value replaces the <code>%s</code> in the SQL command. <em>But note that you should <strong>not</strong> wrap the placeholder in quotes, so <code>'%s'</code> and <code>\"%s\"</code> for examples, are incorrect and just use <code>%s</code>.</em></p></li>\n<li><p>Depending on your SQL command, you can also have the third, fourth, fifth, etc. parameters, just as in the example I gave where I have a third parameter which is <code>$post_id</code> for the <code>%d</code> placeholder.</p></li>\n</ol>\n\n<p>And actually, for <strong>single</strong> <code>INSERT</code> operations, you could simply use <a href=\"https://developer.wordpress.org/reference/classes/wpdb/insert/\" rel=\"nofollow noreferrer\"><code>$wpdb->insert()</code></a>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>// Make sure you replace the column NAMES.\n$wpdb->insert( $computer_repair_items, [\n 'column' => $wc_service_name,\n 'column2' => 'services',\n 'column3' => $post_id,\n] );\n</code></pre>\n\n<p>For multiple inserts, you can try something like:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$insert_values = [];\nforeach ( [\n [ 'wc_service_code', $wc_service_code ],\n [ 'wc_service_id', $wc_service_id ],\n [ 'wc_service_qty', $wc_service_qty ],\n [ 'wc_service_price', $wc_service_price ],\n] as $row ) {\n $insert_values[] = $wpdb->prepare( \"(NULL, %d, %s, %s)\",\n $order_item_id, $row[0], $row[1] );\n}\n\n$insert_query = \"INSERT INTO `$computer_repair_items_meta`\n VALUES \" . implode( ',', $insert_values );\n$wpdb->query( $insert_query );\n</code></pre>\n\n<p>Or just call <code>$wpdb->insert()</code> multiple times..</p>\n"
},
{
"answer_id": 362916,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>Your code is extremely unsafe. </p>\n\n<p>You're not using <code>$wpdb->prepare()</code> properly. You can't just use it on a string as a magic fix. There is nothing in this line of code that protects you from SQL injection attacks, because you're taking submitted values from <code>$_POST</code> and inserting them directly into an SQL query:</p>\n\n<pre><code>\"INSERT INTO `\".$computer_repair_items.\"` VALUES(NULL, '\".$wc_service_name.\"', 'services', '\".$post_id.\"')\";\n</code></pre>\n\n<p>The whole point of <code>$wpdb->prepare()</code>, <a href=\"https://developer.wordpress.org/reference/classes/wpdb/#protect-queries-against-sql-injection-attacks\" rel=\"nofollow noreferrer\">as documented</a>, is to safely insert variables into an SQL query. To do this you need to provide it 2 things:</p>\n\n<ol>\n<li>An SQL string with placeholders where the variables need to go.</li>\n<li>The variables that will go into those placeholders, separately.</li>\n</ol>\n\n<p>So instead of: </p>\n\n<pre><code>$insert_query = \"INSERT INTO `\".$computer_repair_items.\"` VALUES(NULL, '\".$wc_service_name.\"', 'services', '\".$post_id.\"')\";\n$wpdb->query(\n $wpdb->prepare($insert_query)\n);\n</code></pre>\n\n<p>You need to do this:</p>\n\n<pre><code>$insert_query = \"INSERT INTO `{$computer_repair_items}` VALUES( NULL, %s, 'services', %s )\";\n\n$wpdb->query(\n $wpdb->prepare( $insert_query, $wc_service_name, $post_id );\n);\n</code></pre>\n\n<p>Note that:</p>\n\n<ul>\n<li><code>$wpdb->prepare()</code> can't insert the table name from a variable, but the table name should not be coming from an unsafe source. I'm assuming that you've defined in manually in your code earlier.</li>\n<li>The first <code>%s</code> will be replaced with a safely escaped version of <code>$wc_service_name</code>, with quotes added automatically.</li>\n<li>The second <code>%s</code> will be replaced with a safely escaped version of <code>$post_id</code>, with quotes added automatically, just because this is what your original code did. If that column is actually an integer column, then use <code>%d</code> instead of <code>%s</code>.</li>\n</ul>\n\n<p>All that being said, <code>$wpdb</code> actually has <a href=\"https://developer.wordpress.org/reference/classes/wpdb/insert/\" rel=\"nofollow noreferrer\">a method</a> for <code>INSERT</code> queries that automatically prepares the query for you. For our example you would use it like this:</p>\n\n<pre><code>$wpdb->insert(\n $computer_repair_items,\n [\n $wc_service_name,\n $post_id,\n ],\n [\n '%s',\n '%s',\n ]\n);\n</code></pre>\n"
}
] | 2020/03/31 | [
"https://wordpress.stackexchange.com/questions/362907",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180385/"
] | It is my first form trying on wordpress.I changed some names such as "name","e-mail" etc. to "name1" , "email1" etc.Because without these changing, submit button refers to 404 page.
There is no any registration on database when I check it
>
> I dont know any idea about what is the spesific code as problem so I
> give my all codes.If you know enough information, probably you can
> solve this easyly.But if you dont enough information, probably you
> will give negative point to question and go away from my question.Or
> maybe, you can close my question and write "give us spesific
> code/question".I write again, there is no problem with my question or
> asking style, it is completly your information.
>
>
>
```
<!-- data mata -->
<div class="reservation-info">
<form class="reservation-form" method="post">
<h2>Make a reservation</h2>
<div class="field">
<input type="text" name="name1" placeholder="Name" required>
</div>
<div class="field">
<input type="datetime-local" name="date1" placeholder="Date" step="300" required>
</div>
<div class="field">
<input type="text" name="email1" placeholder="E-Mail">
</div>
<div class="field">
<input type="tel" name="phone1" placeholder="Phone Number" required>
</div>
<div class="field">
<textarea name="message1" placeholder="Message" requires></textarea>
</div>
<div class="g-recaptcha" data-sitekey="6LeKTjMUAAAAAJuZI0qqIBRp92slJoG4SESblWHw"></div>
<input type="submit" name="reservation1" class="button" value="Send">
<input type="hidden" name="hidden" value="1">
</form>
</div>
```
---
```
<?php
function lapizzeria_database(){
global $wpdb;
global $lapizzeria_db_version;
$lapizzeria_db_version = "1.0";
$table = $wpdb->prefix . 'reservations1';
$charset_collate = $wpdb->get_charset_collate();
// SQL Statement
$sql = "CREATE TABLE $table (
id mediumint(9) NOT NULL AUTO_INCREMENT,
name1 varchar(50) NOT NULL,
date1 datetime NOT NULL,
email1 varchar(50) DEFAULT '' NOT NULL,
phone1 varchar(10) NOT NULL,
message1 longtext NOT NULL,
PRIMARY KEY (id)
) $charset_collate; ";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
add_action('after_setup_theme', 'lapizzeria_database');
```
---
```
function lapizzeria_save_reservation() {
if(isset($_POST['reservation1']) && $_POST['hidden'] == "1") {
// read the value from recaptcha response
$captcha = $_POST['g-recaptcha-response'];
// Send the values to the server
$fields = array(
'secret' => '6LeKTjMUAAAAAFeaj6Hq941AFvASw9sBJjeiCDyB',
'response' => $captcha,
'remoteip' => $_SERVER['REMOTE_ADDR']
);
// Start the request to the server
$ch = curl_init('https://www.google.com/recaptcha/api/siteverify');
// configure the request
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
// Send the encode values in the URL
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
// Read the return value
$response = json_decode(curl_exec($ch));
if($response->success) {
global $wpdb;
$name = sanitize_text_field( $_POST['name1'] ) ;
$date = sanitize_text_field( $_POST['date1'] ) ;
$email = sanitize_email( $_POST['email1'] );
$phone = sanitize_text_field( $_POST['phone1'] ) ;
$message = sanitize_text_field( $_POST['message1'] ) ;
$table = $wpdb->prefix . 'reservations1';
$data = array(
'name1' => $name1,
'date1' => $date1,
'email1' => $email1,
'phone1' => $phone1,
'message1' => $message1
);
$format = array(
'%s',
'%s',
'%s',
'%s',
'%s'
);
$wpdb->insert($table, $data, $format );
$url = get_page_by_title('Thanks for your reservation!');
wp_redirect( get_permalink($url) );
exit();
}
}
}
add_action('init', 'lapizzeria_save_reservation');
?>
```
---
```
function lapizzeria_reservations() { ?>
<div class="wrap">
<h1>Reservations</h1>
<table class="wp-list-table widefat striped">
<thead>
<tr>
<th class="manage-column">ID</th>
<th class="manage-column">Name</th>
<th class="manage-column">Date of Reservation</th>
<th class="manage-column">Email</th>
<th class="manage-column">Phone Number</th>
<th class="manage-column">Message</th>
<th class="manage-column">Delete</th>
</tr>
</thead>
<tbody>
<?php
global $wpdb;
$table = $wpdb->prefix . 'reservations1';
$reservations = $wpdb->get_results("SELECT * FROM $table", ARRAY_A);
foreach($reservations as $reservation): ?>
<tr>
<td><?php echo $reservation['id']; ?></td>
<td><?php echo $reservation['name1']; ?></td>
<td><?php echo $reservation['date1']; ?></td>
<td><?php echo $reservation['email1']; ?></td>
<td><?php echo $reservation['phone1']; ?></td>
<td><?php echo $reservation['message1']; ?></td>
<td>
<a href="#" class="remove_reservation" data-reservation="<?php echo $reservation1['id']; ?>">Remove</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php }
?>
``` | *You don't need to remove the `prepare()`, but you just need to do it properly.*
And please check the `$wpdb->prepare()` [reference](https://developer.wordpress.org/reference/classes/wpdb/prepare/) for the function's syntax etc., but basically, instead of (wrapped for brevity):
```php
$insert_query = "INSERT INTO `".$computer_repair_items."`
VALUES(NULL, '".$wc_service_name."', 'services', '".$post_id."')";
$wpdb->query(
$wpdb->prepare($insert_query)
);
```
you should do it like this: (presuming `$computer_repair_items` is a valid table name)
```php
$insert_query = $wpdb->prepare(
"INSERT INTO `$computer_repair_items` VALUES(NULL, %s, 'services', %d)",
$wc_service_name, // 2nd parameter; replaces the %s (first placeholder)
$post_id // 3rd parameter; replaces the %d (second placeholder)
);
$wpdb->query( $insert_query );
```
I.e. You *must* pass at least two parameters to `$wpdb->prepare()`:
1. The **first parameter** is the SQL command and should be in the same format as accepted by the PHP's [`sprintf()`](https://www.php.net/manual/en/function.sprintf.php) function, i.e. using placeholders such as `%s` for strings and `%d` for integers.
2. The second parameter should be the replacement value for the first placeholder in the SQL command mentioned above, i.e. the first parameter. So in the example I gave, the second parameter is `$wc_service_name` which the value replaces the `%s` in the SQL command. *But note that you should **not** wrap the placeholder in quotes, so `'%s'` and `"%s"` for examples, are incorrect and just use `%s`.*
3. Depending on your SQL command, you can also have the third, fourth, fifth, etc. parameters, just as in the example I gave where I have a third parameter which is `$post_id` for the `%d` placeholder.
And actually, for **single** `INSERT` operations, you could simply use [`$wpdb->insert()`](https://developer.wordpress.org/reference/classes/wpdb/insert/):
```php
// Make sure you replace the column NAMES.
$wpdb->insert( $computer_repair_items, [
'column' => $wc_service_name,
'column2' => 'services',
'column3' => $post_id,
] );
```
For multiple inserts, you can try something like:
```php
$insert_values = [];
foreach ( [
[ 'wc_service_code', $wc_service_code ],
[ 'wc_service_id', $wc_service_id ],
[ 'wc_service_qty', $wc_service_qty ],
[ 'wc_service_price', $wc_service_price ],
] as $row ) {
$insert_values[] = $wpdb->prepare( "(NULL, %d, %s, %s)",
$order_item_id, $row[0], $row[1] );
}
$insert_query = "INSERT INTO `$computer_repair_items_meta`
VALUES " . implode( ',', $insert_values );
$wpdb->query( $insert_query );
```
Or just call `$wpdb->insert()` multiple times.. |
362,987 | <p>I am creating in personal plugin where I recover data from a personal table.
Con add_action('the_content', 'my_plugin_content'); posso far vedere il contenuto in una pagina.
I would like to save the content in wp_posts with add_filter ('save_post', 'my_plugin_content'), but the content is empty.</p>
<pre><code>function my_plugin_content($content){
$current_page = $wp->request;
include_once(plugin_dir_path( __FILE__ ).'views/view.php');
$obj = new Loader;
$content.=$obj->controller($current_page);
$my_post = array();
$my_post['ID'] = $post->ID;
$my_post['post_content']=$cont;
}
</code></pre>
<p>in another file I run the data recovery query that I refer to the file loader that loads the views</p>
<p>File loader</p>
<pre class="lang-php prettyprint-override"><code>public function view($view, array $dati){
require(DIR_PLUGIN.'views/'.$view.'_v.php');
}
</code></pre>
<p>File view</p>
<pre class="lang-php prettyprint-override"><code> <?php foreach($dati as $p){ echo '<p><strong>'.$p->NAME.'</strong></p>; }?>
</code></pre>
| [
{
"answer_id": 362915,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 3,
"selected": true,
"text": "<p><em>You don't need to remove the <code>prepare()</code>, but you just need to do it properly.</em></p>\n\n<p>And please check the <code>$wpdb->prepare()</code> <a href=\"https://developer.wordpress.org/reference/classes/wpdb/prepare/\" rel=\"nofollow noreferrer\">reference</a> for the function's syntax etc., but basically, instead of (wrapped for brevity):</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$insert_query = \"INSERT INTO `\".$computer_repair_items.\"`\n VALUES(NULL, '\".$wc_service_name.\"', 'services', '\".$post_id.\"')\";\n$wpdb->query(\n $wpdb->prepare($insert_query)\n);\n</code></pre>\n\n<p>you should do it like this: (presuming <code>$computer_repair_items</code> is a valid table name)</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$insert_query = $wpdb->prepare(\n \"INSERT INTO `$computer_repair_items` VALUES(NULL, %s, 'services', %d)\",\n $wc_service_name, // 2nd parameter; replaces the %s (first placeholder)\n $post_id // 3rd parameter; replaces the %d (second placeholder)\n);\n$wpdb->query( $insert_query );\n</code></pre>\n\n<p>I.e. You <em>must</em> pass at least two parameters to <code>$wpdb->prepare()</code>:</p>\n\n<ol>\n<li><p>The <strong>first parameter</strong> is the SQL command and should be in the same format as accepted by the PHP's <a href=\"https://www.php.net/manual/en/function.sprintf.php\" rel=\"nofollow noreferrer\"><code>sprintf()</code></a> function, i.e. using placeholders such as <code>%s</code> for strings and <code>%d</code> for integers.</p></li>\n<li><p>The second parameter should be the replacement value for the first placeholder in the SQL command mentioned above, i.e. the first parameter. So in the example I gave, the second parameter is <code>$wc_service_name</code> which the value replaces the <code>%s</code> in the SQL command. <em>But note that you should <strong>not</strong> wrap the placeholder in quotes, so <code>'%s'</code> and <code>\"%s\"</code> for examples, are incorrect and just use <code>%s</code>.</em></p></li>\n<li><p>Depending on your SQL command, you can also have the third, fourth, fifth, etc. parameters, just as in the example I gave where I have a third parameter which is <code>$post_id</code> for the <code>%d</code> placeholder.</p></li>\n</ol>\n\n<p>And actually, for <strong>single</strong> <code>INSERT</code> operations, you could simply use <a href=\"https://developer.wordpress.org/reference/classes/wpdb/insert/\" rel=\"nofollow noreferrer\"><code>$wpdb->insert()</code></a>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>// Make sure you replace the column NAMES.\n$wpdb->insert( $computer_repair_items, [\n 'column' => $wc_service_name,\n 'column2' => 'services',\n 'column3' => $post_id,\n] );\n</code></pre>\n\n<p>For multiple inserts, you can try something like:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$insert_values = [];\nforeach ( [\n [ 'wc_service_code', $wc_service_code ],\n [ 'wc_service_id', $wc_service_id ],\n [ 'wc_service_qty', $wc_service_qty ],\n [ 'wc_service_price', $wc_service_price ],\n] as $row ) {\n $insert_values[] = $wpdb->prepare( \"(NULL, %d, %s, %s)\",\n $order_item_id, $row[0], $row[1] );\n}\n\n$insert_query = \"INSERT INTO `$computer_repair_items_meta`\n VALUES \" . implode( ',', $insert_values );\n$wpdb->query( $insert_query );\n</code></pre>\n\n<p>Or just call <code>$wpdb->insert()</code> multiple times..</p>\n"
},
{
"answer_id": 362916,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>Your code is extremely unsafe. </p>\n\n<p>You're not using <code>$wpdb->prepare()</code> properly. You can't just use it on a string as a magic fix. There is nothing in this line of code that protects you from SQL injection attacks, because you're taking submitted values from <code>$_POST</code> and inserting them directly into an SQL query:</p>\n\n<pre><code>\"INSERT INTO `\".$computer_repair_items.\"` VALUES(NULL, '\".$wc_service_name.\"', 'services', '\".$post_id.\"')\";\n</code></pre>\n\n<p>The whole point of <code>$wpdb->prepare()</code>, <a href=\"https://developer.wordpress.org/reference/classes/wpdb/#protect-queries-against-sql-injection-attacks\" rel=\"nofollow noreferrer\">as documented</a>, is to safely insert variables into an SQL query. To do this you need to provide it 2 things:</p>\n\n<ol>\n<li>An SQL string with placeholders where the variables need to go.</li>\n<li>The variables that will go into those placeholders, separately.</li>\n</ol>\n\n<p>So instead of: </p>\n\n<pre><code>$insert_query = \"INSERT INTO `\".$computer_repair_items.\"` VALUES(NULL, '\".$wc_service_name.\"', 'services', '\".$post_id.\"')\";\n$wpdb->query(\n $wpdb->prepare($insert_query)\n);\n</code></pre>\n\n<p>You need to do this:</p>\n\n<pre><code>$insert_query = \"INSERT INTO `{$computer_repair_items}` VALUES( NULL, %s, 'services', %s )\";\n\n$wpdb->query(\n $wpdb->prepare( $insert_query, $wc_service_name, $post_id );\n);\n</code></pre>\n\n<p>Note that:</p>\n\n<ul>\n<li><code>$wpdb->prepare()</code> can't insert the table name from a variable, but the table name should not be coming from an unsafe source. I'm assuming that you've defined in manually in your code earlier.</li>\n<li>The first <code>%s</code> will be replaced with a safely escaped version of <code>$wc_service_name</code>, with quotes added automatically.</li>\n<li>The second <code>%s</code> will be replaced with a safely escaped version of <code>$post_id</code>, with quotes added automatically, just because this is what your original code did. If that column is actually an integer column, then use <code>%d</code> instead of <code>%s</code>.</li>\n</ul>\n\n<p>All that being said, <code>$wpdb</code> actually has <a href=\"https://developer.wordpress.org/reference/classes/wpdb/insert/\" rel=\"nofollow noreferrer\">a method</a> for <code>INSERT</code> queries that automatically prepares the query for you. For our example you would use it like this:</p>\n\n<pre><code>$wpdb->insert(\n $computer_repair_items,\n [\n $wc_service_name,\n $post_id,\n ],\n [\n '%s',\n '%s',\n ]\n);\n</code></pre>\n"
}
] | 2020/04/01 | [
"https://wordpress.stackexchange.com/questions/362987",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/185239/"
] | I am creating in personal plugin where I recover data from a personal table.
Con add\_action('the\_content', 'my\_plugin\_content'); posso far vedere il contenuto in una pagina.
I would like to save the content in wp\_posts with add\_filter ('save\_post', 'my\_plugin\_content'), but the content is empty.
```
function my_plugin_content($content){
$current_page = $wp->request;
include_once(plugin_dir_path( __FILE__ ).'views/view.php');
$obj = new Loader;
$content.=$obj->controller($current_page);
$my_post = array();
$my_post['ID'] = $post->ID;
$my_post['post_content']=$cont;
}
```
in another file I run the data recovery query that I refer to the file loader that loads the views
File loader
```php
public function view($view, array $dati){
require(DIR_PLUGIN.'views/'.$view.'_v.php');
}
```
File view
```php
<?php foreach($dati as $p){ echo '<p><strong>'.$p->NAME.'</strong></p>; }?>
``` | *You don't need to remove the `prepare()`, but you just need to do it properly.*
And please check the `$wpdb->prepare()` [reference](https://developer.wordpress.org/reference/classes/wpdb/prepare/) for the function's syntax etc., but basically, instead of (wrapped for brevity):
```php
$insert_query = "INSERT INTO `".$computer_repair_items."`
VALUES(NULL, '".$wc_service_name."', 'services', '".$post_id."')";
$wpdb->query(
$wpdb->prepare($insert_query)
);
```
you should do it like this: (presuming `$computer_repair_items` is a valid table name)
```php
$insert_query = $wpdb->prepare(
"INSERT INTO `$computer_repair_items` VALUES(NULL, %s, 'services', %d)",
$wc_service_name, // 2nd parameter; replaces the %s (first placeholder)
$post_id // 3rd parameter; replaces the %d (second placeholder)
);
$wpdb->query( $insert_query );
```
I.e. You *must* pass at least two parameters to `$wpdb->prepare()`:
1. The **first parameter** is the SQL command and should be in the same format as accepted by the PHP's [`sprintf()`](https://www.php.net/manual/en/function.sprintf.php) function, i.e. using placeholders such as `%s` for strings and `%d` for integers.
2. The second parameter should be the replacement value for the first placeholder in the SQL command mentioned above, i.e. the first parameter. So in the example I gave, the second parameter is `$wc_service_name` which the value replaces the `%s` in the SQL command. *But note that you should **not** wrap the placeholder in quotes, so `'%s'` and `"%s"` for examples, are incorrect and just use `%s`.*
3. Depending on your SQL command, you can also have the third, fourth, fifth, etc. parameters, just as in the example I gave where I have a third parameter which is `$post_id` for the `%d` placeholder.
And actually, for **single** `INSERT` operations, you could simply use [`$wpdb->insert()`](https://developer.wordpress.org/reference/classes/wpdb/insert/):
```php
// Make sure you replace the column NAMES.
$wpdb->insert( $computer_repair_items, [
'column' => $wc_service_name,
'column2' => 'services',
'column3' => $post_id,
] );
```
For multiple inserts, you can try something like:
```php
$insert_values = [];
foreach ( [
[ 'wc_service_code', $wc_service_code ],
[ 'wc_service_id', $wc_service_id ],
[ 'wc_service_qty', $wc_service_qty ],
[ 'wc_service_price', $wc_service_price ],
] as $row ) {
$insert_values[] = $wpdb->prepare( "(NULL, %d, %s, %s)",
$order_item_id, $row[0], $row[1] );
}
$insert_query = "INSERT INTO `$computer_repair_items_meta`
VALUES " . implode( ',', $insert_values );
$wpdb->query( $insert_query );
```
Or just call `$wpdb->insert()` multiple times.. |
363,018 | <p>In the saga so far, you can see my</p>
<ol>
<li><a href="https://wordpress.stackexchange.com/questions/360418/enhancing-gutenberg-featured-image-control">First post/question</a></li>
<li><a href="https://wordpress.stackexchange.com/questions/360745/using-gutenberg-block-components-in-admin-interface-controls">Second post/question</a></li>
</ol>
<p>This is my third (and hopefully final) question. I've got everything working except for saving the data in the WP database. Incidentally, <a href="https://css-tricks.com/managing-wordpress-metadata-in-gutenberg-using-a-sidebar-plugin/" rel="nofollow noreferrer">this tutorial</a> is a goldmine for an understanding of how things work in the new Gutenberg way, and how all the different pieces fit together and interact. </p>
<p>As stated previously (see links above), I'm working on customizing the featured image block in the standard post editor sidebar. Here's a screenshot of what I have:</p>
<p><a href="https://i.stack.imgur.com/s1SGB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/s1SGB.png" alt="[FIXME]"></a></p>
<p>When you click the checkbox, the text field appears. And when you uncheck it it goes away. You can type text in the field and the page goes through all the motions of working as it should. When you save, you get a "success" message. However, nothing is being saved to the database, and that's my problem. I have independent SQL access to the DB, and there's nothing in the wp_postmeta table for any test post I create with metadata that should be saved.</p>
<p>I can click the checkbox, enter something in the text field, tab away, and see that the datastore has my information by executing the following in the debug console:</p>
<p><code>wp.data.select('core/editor').getEditedPostAttribute('meta')</code></p>
<p>which returns...
<code>Object { _featured_image_video_url: "this is a test", _featured_image_is_video: true }</code></p>
<p>as expected. But there's no joy if you save the page and look in the DB. Nothing there.</p>
<p>Here's my current JavaScript code</p>
<pre><code>const el = wp.element.createElement;
const { setState, withSelect, dispatch, select} = wp.data;
const { CheckboxControl, TextControl } = wp.components;
const { useState } = wp.element;
const { withState } = wp.compose;
const { __ } = wp.i18n;
//this replaces the default with our custom Featured Image code
wp.hooks.addFilter(
'editor.PostFeaturedImage',
'dsplugin/featured-image-as-video',
wrapPostFeaturedImage
);
//create a checkbox that takes properties
const MyCheckboxControl = (props) => {
const [ isChecked, setChecked ] = useState( false );
return(
<CheckboxControl
label={ __("Image is a video", "dsplugin") }
checked={ isChecked }
onChange={ () =>{
if (isChecked){
setChecked(false);
dispatch('core/editor').editPost({meta: {_featured_image_is_video: false}})
}else{
setChecked(true);
dispatch('core/editor').editPost({meta: {_featured_image_is_video: true}})
}
props.onChange.call();
} }
/>
)
};
// //this the std TextControl from the example in the documentation
// const MyTextControl = withState({ videoURL: '', }) (({ videoURL, setState }) => (
// <TextControl
// // label="Video URL to use with featured image"
// value={ videoURL }
// placeholder={ __("Enter video URL to play when clicked", "dsplugin") }
// onChange={ ( videoURL ) => {
// //update the text field
// setState( { videoURL } );
//
// //save the new value to the DB
// // meta.featured_image_video_url = videoURL;
// // withDispach( 'core/editor' ).editPost( {meta});
// } }
// />
// ) );
class MyTextControl extends wp.element.Component{
constructor(){
super()
this.state = {
videoURL: ''
}
}
render() {
const { videoURL, setState} = this.props;
// const videoURL = select('core/editor').getEditedPostAttribute('meta').featured_image_video_url;
return(
<TextControl
// select('core/editor').getEditedPostAttribute('meta').featured_image_video_url }
value={ videoURL }
placeholder={ __("Enter video URL to play when clicked", "dsplugin") }
onChange={ ( videoURL ) => {
//save the new value to the DB
const currentMeta = select( 'core/editor' ).getEditedPostAttribute( 'meta' );
const newMeta = { ...currentMeta, _featured_image_video_url: videoURL };
dispatch('core/editor').editPost({meta: newMeta})
} }
/>
)
}
};
//we put it all together in a wrapper component with a custom state to show/hide the TextControl
class MyFeaturedImageControls extends wp.element.Component{
constructor(){
super()
this.state = {
isHidden: true
}
}
toggleHidden(){
this.setState({
isHidden: !this.state.isHidden
})
}
render() {
return(
<div>
<h4>{ __("Image Options", "dsplugin") }</h4>
<MyCheckboxControl onChange={this.toggleHidden.bind(this)}/>
{ !this.state.isHidden && <MyTextControl /> }
</div>
)
}
};
//here's the function that wraps the original Featured Image content and adds
//our custom controls below
function wrapPostFeaturedImage( OriginalComponent ) {
// Get meta field information from the DB.
let meta = select( 'core/editor' ).getCurrentPostAttribute( 'meta' );
console.log ("metadata follows:");
console.log(meta);
return function( props ) {
return (
el(
wp.element.Fragment,
{},
// 'Prepend above',
el(
OriginalComponent,
props
),
<MyFeaturedImageControls />
)
);
}
}
</code></pre>
<p>And the PHP code that supports it:</p>
<pre><code>//add metadata fields for use with featured image metabox
function register_resource_item_featured_image_metadata() {
register_meta(
'post',
'_featured_image_video_url',
array(
'object_subtype' => 'ds_resource_item',
'show_in_rest' => true, #must be true to work in Guttenberg
'type' => 'string',
'single' => true,
'sanitize_callback' => 'sanitize_text_field',
'auth_callback' => function() {
return current_user_can('edit_posts');
}
)
);
register_meta(
'post',
'_featured_image_is_video',
array(
'object_subtype' => 'ds_resource_item',
'show_in_rest' => true, #must be true to work in Guttenberg
'single' => true,
// 'sanitize_callback' => 'rest_sanitize_boolean',
'type' => 'boolean',
// 'auth_callback' => function() {
// return current_user_can('edit_posts');
// }
)
);
}
add_action( 'init', 'register_resource_item_featured_image_metadata' );
</code></pre>
<p>Again... being so new to all of this, I think I'm missing some small detail. I realize my code is incomplete, and you'll see a few things commented out for debugging purposes. But as it stands, I think I should at least be saving a newly entered value to the DB based on what's there now. I also realize I still have to put code in place to fetch an initial value from the db and populate the text field. But first things first. </p>
<p>Thanks for the help.</p>
<p><strong>Update:</strong>
Here's the php code that defines the custom post type I'm using with this code:</p>
<pre><code> $args = array(
"label" => __( "Resource Items", "dstheme" ),
"labels" => $labels,
"description" => "DS Resource Items are the foundational content type for resources.",
"public" => true,
"publicly_queryable" => true,
"show_ui" => true,
"delete_with_user" => false,
"show_in_rest" => true,
"rest_base" => "dsr_item",
"rest_controller_class" => "WP_REST_Posts_Controller",
"has_archive" => false,
"show_in_menu" => true,
"show_in_nav_menus" => true,
"exclude_from_search" => false,
"capability_type" => "post",
"map_meta_cap" => true,
"hierarchical" => false,
//modify the slug below to change what shows in the URL when an DSResourceItem is accessed
"rewrite" => array( "slug" => "resource-item", "with_front" => true ),
"query_var" => true,
"menu_position" => 5,
"menu_icon" => "dashicons-images-alt2",
"supports" => array( "title", "editor", "thumbnail", "custom-fields" ),
"taxonomies" => array( "post_tag" ),
);
register_post_type( "ds_resource_item", $args );
</code></pre>
| [
{
"answer_id": 363047,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": false,
"text": "<h3>Your JavaScript code works for me. The metadata do get saved.</h3>\n\n<p>But perhaps you'd like to try <a href=\"https://gist.github.com/5ally/d13a0d3e46aa33bc0f3f39f15d6194b7\" rel=\"nofollow noreferrer\">my code</a> which is pretty much completed, i.e. on page load, the checkbox is auto-checked/unchecked (and the text box is also shown/hidden) depending on the current <em>database</em> value. Secondly, I did it just as the Gutenberg team did it with the original <a href=\"https://github.com/WordPress/gutenberg/blob/4857ad58c1241b3d63d21a6880c989b85746c3dc/packages/editor/src/components/post-featured-image/index.js\" rel=\"nofollow noreferrer\">component for the featured image</a> and it's actually easy.. I mean, I'm just hoping you can learn some good stuff from my code. :)</p>\n\n<p>Nonetheless, regarding the question or getting your code to saving the metadata, one issue I noted before I posted the original answer, is the <code>auth_callback</code> for the <code>_featured_image_is_video</code> meta:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>register_meta(\n 'post',\n '_featured_image_is_video',\n array(\n ...\n // 'auth_callback' => function() {\n // return current_user_can('edit_posts');\n // }\n )\n);\n</code></pre>\n\n<p>Why did you comment out the <code>auth_callback</code>? Because if you do that, then it would default to <a href=\"https://developer.wordpress.org/reference/functions/__return_false/\" rel=\"nofollow noreferrer\"><code>__return_false()</code></a> for protected meta (where the name begins with <code>_</code>/underscore), which means no one is allowed to edit the meta via the REST API! :p</p>\n\n<p>So try un-commenting it out. But I'm not sure about that because if you actually had it commented in your actual code, then you would've noticed it since WordPress/Gutenberg would display a notice on the post editing screen saying the post could not be updated (because you have no permission to edit the meta or that the <code>auth_callback</code> always returns <code>false</code>).</p>\n\n<p><strong>To other readers:</strong></p>\n\n<p>Make sure your <em>custom</em> post type supports custom fields, because the REST API handbook <a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/modifying-responses/#read-and-write-a-post-meta-field-in-post-responses\" rel=\"nofollow noreferrer\">says</a>:</p>\n\n<blockquote>\n <p>Note that for meta fields registered on custom post types, the post\n type must have <code>custom-fields</code> support. Otherwise the meta fields will\n not appear in the REST API.</p>\n</blockquote>\n\n<p>And when the meta fields do not appear in the REST API, the meta fields will not be saved/updated via the REST API.</p>\n"
},
{
"answer_id": 364111,
"author": "Andrew",
"author_id": 184100,
"author_profile": "https://wordpress.stackexchange.com/users/184100",
"pm_score": 2,
"selected": true,
"text": "<p>So I figured it out. @Sally is correct that the basic code I wrote works. However, there's one small caveat that is worth mentioning here and I'll also document a method of testing database connectivity from any post edit page <strong>without any UI code</strong>.</p>\n\n<p>Firstly, no javascript is required for wordpress to recognize the presence of a metadata variable on an gutenberg/react-based post edit page. Only the register_meta() call in PHP is needed. It is sufficient to put a piece of code such as the following in your plugin file for the metadata variable to exist and for a post's edit page to know how to save it to the database.</p>\n\n<pre><code>function register_resource_item_featured_image_metadata() {\n register_meta(\n 'post',\n '_featured_image_video_url',\n array(\n 'object_subtype' => 'optional', #omit unless you're dealing with a custom post type\n 'show_in_rest' => true, #must be true to work in Guttenberg\n 'type' => 'string',\n 'single' => true,\n 'sanitize_callback' => 'sanitize_text_field',\n 'auth_callback' => function() {\n return current_user_can('edit_posts');\n }\n )\n );\n}\nadd_action( 'init', 'register_resource_item_featured_image_metadata' );\n\n</code></pre>\n\n<p>With only the above, you won't have any way of setting/changing this metadata field from the WordPress UI, but you can do the following for testing purposes:</p>\n\n<ol>\n<li>Edit any post (or create a new one).</li>\n<li>Open the dev console on that post's edit page (right-click somewhere and <strong>inspect element</strong>)</li>\n<li>In the console type the following and press return <code>wp.data.select('core/editor').getEditedPostAttribute('meta')</code></li>\n</ol>\n\n<p>This will return something like <code>Object { _featured_image_video_url: \"\"}</code>, which proves the system has properly registered and recognized your metadata variable, and that the DB has no value for it.</p>\n\n<ol start=\"4\">\n<li>Now execute the following in the console: <code>wp.data.dispatch('core/editor').editPost({meta: {_featured_image_video_url: 'http://some_url'}})</code></li>\n<li>Press the <strong>Update</strong> button in the edit window, and wait for the page to save.</li>\n<li>Re-load the page and in the console again, re-execute the first command <code>wp.data.select('core/editor').getEditedPostAttribute('meta')</code></li>\n</ol>\n\n<p>This time you should see <code>Object { _featured_image_video_url: \"http://some_url\"}</code>, which proves you've successfully saved a value to the database for that parameter. (when you re-loaded the page, wordpress fetched the metadata values for that page and stored them in memory along with the rest of the page data).</p>\n\n<p>If you have a SQL server admin tool like MySQL Workbench, you can further verify this by running the following query: </p>\n\n<p><code>select * from wp_postmeta where post_id = 15727</code></p>\n\n<p>Substitute the post ID from your page's URL for the number in the query above. </p>\n\n<pre><code> vvvvv\n(https://localhost/wp/wp-admin/post.php?post=15727&action=edit)\n ^^^^^\n</code></pre>\n\n<p><strong>My Problem</strong>\nI was doing all of this, however, I have my plugin split into two pieces. The main plugin file has all the initialization code, and at the end of the file there's an include as follows: </p>\n\n<pre><code>//load other plugin code a front-end user won't use if admin user\nif( is_admin() ){\n require plugin_dir_path( __FILE__ ) . 'admin-code.php';\n}\n</code></pre>\n\n<p>Without thinking, I put my register_meta() calls and their associated add_action(), in the admin-code.php file, which only gets loaded if is_admin() returns true. When I save a post on my system (click the Update button), the if statement above executes 3 times. The first time, is_admin() returns <strong>false</strong>, the last two times it returns <strong>true</strong>. I don't claim to know the intricacies of why that's the case, but obviously, not having the _featured_image_video_url meta variable defined the first pass through the code is a problem, and the cause of my issue with saving the variable. If I move the register_meta() code to a place in the file where it executes every time, everything works beautifully.</p>\n\n<p>Hope this helps someone somewhere. Thank you very much Sally for your help in stripping away the noise so I could discover the root cause. Between the two of us, I think we've plugged a few gaping holes in pulling all the pieces together to enhance existing parts of the Gutenberg editor UI, at least for those that are new to React/js.</p>\n"
}
] | 2020/04/02 | [
"https://wordpress.stackexchange.com/questions/363018",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/184100/"
] | In the saga so far, you can see my
1. [First post/question](https://wordpress.stackexchange.com/questions/360418/enhancing-gutenberg-featured-image-control)
2. [Second post/question](https://wordpress.stackexchange.com/questions/360745/using-gutenberg-block-components-in-admin-interface-controls)
This is my third (and hopefully final) question. I've got everything working except for saving the data in the WP database. Incidentally, [this tutorial](https://css-tricks.com/managing-wordpress-metadata-in-gutenberg-using-a-sidebar-plugin/) is a goldmine for an understanding of how things work in the new Gutenberg way, and how all the different pieces fit together and interact.
As stated previously (see links above), I'm working on customizing the featured image block in the standard post editor sidebar. Here's a screenshot of what I have:
[![[FIXME]](https://i.stack.imgur.com/s1SGB.png)](https://i.stack.imgur.com/s1SGB.png)
When you click the checkbox, the text field appears. And when you uncheck it it goes away. You can type text in the field and the page goes through all the motions of working as it should. When you save, you get a "success" message. However, nothing is being saved to the database, and that's my problem. I have independent SQL access to the DB, and there's nothing in the wp\_postmeta table for any test post I create with metadata that should be saved.
I can click the checkbox, enter something in the text field, tab away, and see that the datastore has my information by executing the following in the debug console:
`wp.data.select('core/editor').getEditedPostAttribute('meta')`
which returns...
`Object { _featured_image_video_url: "this is a test", _featured_image_is_video: true }`
as expected. But there's no joy if you save the page and look in the DB. Nothing there.
Here's my current JavaScript code
```
const el = wp.element.createElement;
const { setState, withSelect, dispatch, select} = wp.data;
const { CheckboxControl, TextControl } = wp.components;
const { useState } = wp.element;
const { withState } = wp.compose;
const { __ } = wp.i18n;
//this replaces the default with our custom Featured Image code
wp.hooks.addFilter(
'editor.PostFeaturedImage',
'dsplugin/featured-image-as-video',
wrapPostFeaturedImage
);
//create a checkbox that takes properties
const MyCheckboxControl = (props) => {
const [ isChecked, setChecked ] = useState( false );
return(
<CheckboxControl
label={ __("Image is a video", "dsplugin") }
checked={ isChecked }
onChange={ () =>{
if (isChecked){
setChecked(false);
dispatch('core/editor').editPost({meta: {_featured_image_is_video: false}})
}else{
setChecked(true);
dispatch('core/editor').editPost({meta: {_featured_image_is_video: true}})
}
props.onChange.call();
} }
/>
)
};
// //this the std TextControl from the example in the documentation
// const MyTextControl = withState({ videoURL: '', }) (({ videoURL, setState }) => (
// <TextControl
// // label="Video URL to use with featured image"
// value={ videoURL }
// placeholder={ __("Enter video URL to play when clicked", "dsplugin") }
// onChange={ ( videoURL ) => {
// //update the text field
// setState( { videoURL } );
//
// //save the new value to the DB
// // meta.featured_image_video_url = videoURL;
// // withDispach( 'core/editor' ).editPost( {meta});
// } }
// />
// ) );
class MyTextControl extends wp.element.Component{
constructor(){
super()
this.state = {
videoURL: ''
}
}
render() {
const { videoURL, setState} = this.props;
// const videoURL = select('core/editor').getEditedPostAttribute('meta').featured_image_video_url;
return(
<TextControl
// select('core/editor').getEditedPostAttribute('meta').featured_image_video_url }
value={ videoURL }
placeholder={ __("Enter video URL to play when clicked", "dsplugin") }
onChange={ ( videoURL ) => {
//save the new value to the DB
const currentMeta = select( 'core/editor' ).getEditedPostAttribute( 'meta' );
const newMeta = { ...currentMeta, _featured_image_video_url: videoURL };
dispatch('core/editor').editPost({meta: newMeta})
} }
/>
)
}
};
//we put it all together in a wrapper component with a custom state to show/hide the TextControl
class MyFeaturedImageControls extends wp.element.Component{
constructor(){
super()
this.state = {
isHidden: true
}
}
toggleHidden(){
this.setState({
isHidden: !this.state.isHidden
})
}
render() {
return(
<div>
<h4>{ __("Image Options", "dsplugin") }</h4>
<MyCheckboxControl onChange={this.toggleHidden.bind(this)}/>
{ !this.state.isHidden && <MyTextControl /> }
</div>
)
}
};
//here's the function that wraps the original Featured Image content and adds
//our custom controls below
function wrapPostFeaturedImage( OriginalComponent ) {
// Get meta field information from the DB.
let meta = select( 'core/editor' ).getCurrentPostAttribute( 'meta' );
console.log ("metadata follows:");
console.log(meta);
return function( props ) {
return (
el(
wp.element.Fragment,
{},
// 'Prepend above',
el(
OriginalComponent,
props
),
<MyFeaturedImageControls />
)
);
}
}
```
And the PHP code that supports it:
```
//add metadata fields for use with featured image metabox
function register_resource_item_featured_image_metadata() {
register_meta(
'post',
'_featured_image_video_url',
array(
'object_subtype' => 'ds_resource_item',
'show_in_rest' => true, #must be true to work in Guttenberg
'type' => 'string',
'single' => true,
'sanitize_callback' => 'sanitize_text_field',
'auth_callback' => function() {
return current_user_can('edit_posts');
}
)
);
register_meta(
'post',
'_featured_image_is_video',
array(
'object_subtype' => 'ds_resource_item',
'show_in_rest' => true, #must be true to work in Guttenberg
'single' => true,
// 'sanitize_callback' => 'rest_sanitize_boolean',
'type' => 'boolean',
// 'auth_callback' => function() {
// return current_user_can('edit_posts');
// }
)
);
}
add_action( 'init', 'register_resource_item_featured_image_metadata' );
```
Again... being so new to all of this, I think I'm missing some small detail. I realize my code is incomplete, and you'll see a few things commented out for debugging purposes. But as it stands, I think I should at least be saving a newly entered value to the DB based on what's there now. I also realize I still have to put code in place to fetch an initial value from the db and populate the text field. But first things first.
Thanks for the help.
**Update:**
Here's the php code that defines the custom post type I'm using with this code:
```
$args = array(
"label" => __( "Resource Items", "dstheme" ),
"labels" => $labels,
"description" => "DS Resource Items are the foundational content type for resources.",
"public" => true,
"publicly_queryable" => true,
"show_ui" => true,
"delete_with_user" => false,
"show_in_rest" => true,
"rest_base" => "dsr_item",
"rest_controller_class" => "WP_REST_Posts_Controller",
"has_archive" => false,
"show_in_menu" => true,
"show_in_nav_menus" => true,
"exclude_from_search" => false,
"capability_type" => "post",
"map_meta_cap" => true,
"hierarchical" => false,
//modify the slug below to change what shows in the URL when an DSResourceItem is accessed
"rewrite" => array( "slug" => "resource-item", "with_front" => true ),
"query_var" => true,
"menu_position" => 5,
"menu_icon" => "dashicons-images-alt2",
"supports" => array( "title", "editor", "thumbnail", "custom-fields" ),
"taxonomies" => array( "post_tag" ),
);
register_post_type( "ds_resource_item", $args );
``` | So I figured it out. @Sally is correct that the basic code I wrote works. However, there's one small caveat that is worth mentioning here and I'll also document a method of testing database connectivity from any post edit page **without any UI code**.
Firstly, no javascript is required for wordpress to recognize the presence of a metadata variable on an gutenberg/react-based post edit page. Only the register\_meta() call in PHP is needed. It is sufficient to put a piece of code such as the following in your plugin file for the metadata variable to exist and for a post's edit page to know how to save it to the database.
```
function register_resource_item_featured_image_metadata() {
register_meta(
'post',
'_featured_image_video_url',
array(
'object_subtype' => 'optional', #omit unless you're dealing with a custom post type
'show_in_rest' => true, #must be true to work in Guttenberg
'type' => 'string',
'single' => true,
'sanitize_callback' => 'sanitize_text_field',
'auth_callback' => function() {
return current_user_can('edit_posts');
}
)
);
}
add_action( 'init', 'register_resource_item_featured_image_metadata' );
```
With only the above, you won't have any way of setting/changing this metadata field from the WordPress UI, but you can do the following for testing purposes:
1. Edit any post (or create a new one).
2. Open the dev console on that post's edit page (right-click somewhere and **inspect element**)
3. In the console type the following and press return `wp.data.select('core/editor').getEditedPostAttribute('meta')`
This will return something like `Object { _featured_image_video_url: ""}`, which proves the system has properly registered and recognized your metadata variable, and that the DB has no value for it.
4. Now execute the following in the console: `wp.data.dispatch('core/editor').editPost({meta: {_featured_image_video_url: 'http://some_url'}})`
5. Press the **Update** button in the edit window, and wait for the page to save.
6. Re-load the page and in the console again, re-execute the first command `wp.data.select('core/editor').getEditedPostAttribute('meta')`
This time you should see `Object { _featured_image_video_url: "http://some_url"}`, which proves you've successfully saved a value to the database for that parameter. (when you re-loaded the page, wordpress fetched the metadata values for that page and stored them in memory along with the rest of the page data).
If you have a SQL server admin tool like MySQL Workbench, you can further verify this by running the following query:
`select * from wp_postmeta where post_id = 15727`
Substitute the post ID from your page's URL for the number in the query above.
```
vvvvv
(https://localhost/wp/wp-admin/post.php?post=15727&action=edit)
^^^^^
```
**My Problem**
I was doing all of this, however, I have my plugin split into two pieces. The main plugin file has all the initialization code, and at the end of the file there's an include as follows:
```
//load other plugin code a front-end user won't use if admin user
if( is_admin() ){
require plugin_dir_path( __FILE__ ) . 'admin-code.php';
}
```
Without thinking, I put my register\_meta() calls and their associated add\_action(), in the admin-code.php file, which only gets loaded if is\_admin() returns true. When I save a post on my system (click the Update button), the if statement above executes 3 times. The first time, is\_admin() returns **false**, the last two times it returns **true**. I don't claim to know the intricacies of why that's the case, but obviously, not having the \_featured\_image\_video\_url meta variable defined the first pass through the code is a problem, and the cause of my issue with saving the variable. If I move the register\_meta() code to a place in the file where it executes every time, everything works beautifully.
Hope this helps someone somewhere. Thank you very much Sally for your help in stripping away the noise so I could discover the root cause. Between the two of us, I think we've plugged a few gaping holes in pulling all the pieces together to enhance existing parts of the Gutenberg editor UI, at least for those that are new to React/js. |
363,042 | <p>WordPress 5.4 introduced the <em>Site Health Status</em> dashboard widget (<a href="https://github.com/WordPress/WordPress/commit/2c4480958bc230cbe89978738a26156c5346e785" rel="nofollow noreferrer">source</a>). </p>
<p>The dashboard widget shows the status of the <a href="https://make.wordpress.org/core/2019/04/25/site-health-check-in-5-2/" rel="nofollow noreferrer">site health check</a>:</p>
<p><a href="https://i.stack.imgur.com/HhwuG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HhwuG.png" alt="Screenshot of dashboard widgets including the site health status"></a></p>
<p>How can I remove the <em>Site Health Status</em> dashboard widget?</p>
| [
{
"answer_id": 363043,
"author": "Sven",
"author_id": 32946,
"author_profile": "https://wordpress.stackexchange.com/users/32946",
"pm_score": 4,
"selected": true,
"text": "<p>The following snippet removes the <a href=\"https://github.com/WordPress/WordPress/blob/5.4-branch/wp-admin/includes/dashboard.php#L56\" rel=\"noreferrer\">registered site health dashboard widget</a> from the dashboard. Add the code to your plugin or <code>functions.php</code> file:</p>\n\n<pre><code>add_action('wp_dashboard_setup', 'remove_site_health_dashboard_widget');\nfunction remove_site_health_dashboard_widget()\n{\n remove_meta_box('dashboard_site_health', 'dashboard', 'normal');\n}\n</code></pre>\n"
},
{
"answer_id": 363046,
"author": "Admiral Noisy Bottom",
"author_id": 181142,
"author_profile": "https://wordpress.stackexchange.com/users/181142",
"pm_score": 0,
"selected": false,
"text": "<p>Log in to your Dashboard. On the screen showing the \"Site Health\" widget, click the <strong>\"Screen Options\"</strong> menu item at the top right of your screen and turn off \"Site Health\" and any other widgets you don't want to see.</p>\n\n<p>Each time you login the Site Health functions will not appear. This is a per user function, therefore turning it off only removes it for you and not other users.</p>\n"
},
{
"answer_id": 364437,
"author": "Alan Fuller",
"author_id": 121883,
"author_profile": "https://wordpress.stackexchange.com/users/121883",
"pm_score": 0,
"selected": false,
"text": "<p>I created a free, lightweight, plugin to solve this issue</p>\n\n<p><a href=\"https://wordpress.org/plugins/remove-site-heath-from-dashboard/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/remove-site-heath-from-dashboard/</a></p>\n"
},
{
"answer_id": 374410,
"author": "giorgos",
"author_id": 80294,
"author_profile": "https://wordpress.stackexchange.com/users/80294",
"pm_score": 0,
"selected": false,
"text": "<p>Putting this in your <code>functions.php</code> will remove Site Health widget from the dashboard:</p>\n<pre><code>add_action( 'wp_dashboard_setup', 'remove_site_health_widget' );\nfunction remove_site_health_widget() {\n global $wp_meta_boxes;\n unset( $wp_meta_boxes['dashboard']['normal']['core']['dashboard_site_health'] );\n}\n</code></pre>\n<p>And this will remove the respective option from the menu:</p>\n<pre><code>add_action( 'admin_menu', 'remove_site_health_submenu', 999 );\nfunction remove_site_health_submenu() {\n $page = remove_submenu_page( 'tools.php', 'site-health.php' );\n}\n</code></pre>\n<p>I don't believe that removing Site Health altogether is advisable, though, as it is a nice feature that can help you fix problems that might otherwise be undetected. What I suggest, instead, is <a href=\"https://www.gsarigiannidis.gr/how-to-hide-wordpress-site-health-from-everyone-but-you/\" rel=\"nofollow noreferrer\">hiding it from everyone except for the main Admin</a>.</p>\n"
}
] | 2020/04/02 | [
"https://wordpress.stackexchange.com/questions/363042",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/32946/"
] | WordPress 5.4 introduced the *Site Health Status* dashboard widget ([source](https://github.com/WordPress/WordPress/commit/2c4480958bc230cbe89978738a26156c5346e785)).
The dashboard widget shows the status of the [site health check](https://make.wordpress.org/core/2019/04/25/site-health-check-in-5-2/):
[](https://i.stack.imgur.com/HhwuG.png)
How can I remove the *Site Health Status* dashboard widget? | The following snippet removes the [registered site health dashboard widget](https://github.com/WordPress/WordPress/blob/5.4-branch/wp-admin/includes/dashboard.php#L56) from the dashboard. Add the code to your plugin or `functions.php` file:
```
add_action('wp_dashboard_setup', 'remove_site_health_dashboard_widget');
function remove_site_health_dashboard_widget()
{
remove_meta_box('dashboard_site_health', 'dashboard', 'normal');
}
``` |
363,059 | <p>My search-results are not displayed. Instead searches show a 404. See <a href="https://startupsagainstcorona.com/solutions/" rel="nofollow noreferrer">https://startupsagainstcorona.com/solutions/</a> for testing. Can someone help?</p>
<p>What did I do?</p>
<ol>
<li>I implemented the standard WP-search using get_search_form(). This
worked fine, as you can see on the page.</li>
<li>I added the search.php and searchform.php in the root-folder of the template. Those phps came from
the twentyseventeen-template of WP, as I am using a custom template and the files have been missing.
<blockquote>
<p>The searchform-layout changed accordingly.</p>
</blockquote></li>
</ol>
<p>Unfortuntately, the search.php seems to be inactive in a way. Everytime, entering a search, delivers a 404.</p>
<p>Here the code of the search.php:</p>
<pre><code><get_header(); ?>
<div class="wrap">
<header class="page-header">
<?php if ( have_posts() ) : ?>
<h1 class="page-title"><?php printf( __( 'Search Results for: %s', 'twentyseventeen' ), '<span>' . get_search_query() . '</span>' ); ?></h1>
<?php else : ?>
<h1 class="page-title"><?php _e( 'Nothing Found', 'twentyseventeen' ); ?></h1>
<?php endif; ?>
</header><!-- .page-header -->
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php
if ( have_posts() ) :
/* Start the Loop */
while ( have_posts() ) :
the_post();
/**
* Run the loop for the search to output the results.
* If you want to overload this in a child theme then include a file
* called content-search.php and that will be used instead.
*/
get_template_part( 'template-parts/content', 'search' );
endwhile; // End of the loop.
the_posts_pagination(
array(
'prev_text' => twentyseventeen_get_svg( array( 'icon' => 'arrow-left' ) ) . '<span class="screen-reader-text">' . __( 'Previous page', 'twentyseventeen' ) . '</span>',
'next_text' => '<span class="screen-reader-text">' . __( 'Next page', 'twentyseventeen' ) . '</span>' . twentyseventeen_get_svg( array( 'icon' => 'arrow-right' ) ),
'before_page_number' => '<span class="meta-nav screen-reader-text">' . __( 'Page', 'twentyseventeen' ) . ' </span>',
)
);
else :
?>
<p><?php _e( 'Sorry, but nothing matched your search terms. Please try again with some different keywords.', 'twentyseventeen' ); ?></p>
<?php
get_search_form();
endif;
?>
</main><!-- #main -->
</div><!-- #primary -->
<?php //get_sidebar(); ?>
</div><!-- .wrap -->
<?php
get_footer();
</code></pre>
<p>And here the code for the searchform.php:</p>
<pre><code><?php
/**
* Template for displaying search forms in Twenty Seventeen
*
* @package WordPress
* @subpackage Twenty_Seventeen
* @since 1.0
* @version 1.0
*/
?>
<?php $unique_id = esc_attr( twentyseventeen_unique_id( 'search-form-' ) ); ?>
<form role="search" method="get" class="search-form" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<label for="<?php echo $unique_id; ?>">
<span class="screen-reader-text"><?php echo _x( 'Search for:', 'label', 'twentyseventeen' ); ?></span>
</label>
<input type="search" id="<?php echo $unique_id; ?>" class="search-field" placeholder="<?php echo esc_attr_x( 'Search &hellip;', 'placeholder', 'twentyseventeen' ); ?>" value="<?php echo get_search_query(); ?>" name="s" />
</form>
</code></pre>
<p>Appreciate any hint.</p>
<p>Best,
Max</p>
| [
{
"answer_id": 363043,
"author": "Sven",
"author_id": 32946,
"author_profile": "https://wordpress.stackexchange.com/users/32946",
"pm_score": 4,
"selected": true,
"text": "<p>The following snippet removes the <a href=\"https://github.com/WordPress/WordPress/blob/5.4-branch/wp-admin/includes/dashboard.php#L56\" rel=\"noreferrer\">registered site health dashboard widget</a> from the dashboard. Add the code to your plugin or <code>functions.php</code> file:</p>\n\n<pre><code>add_action('wp_dashboard_setup', 'remove_site_health_dashboard_widget');\nfunction remove_site_health_dashboard_widget()\n{\n remove_meta_box('dashboard_site_health', 'dashboard', 'normal');\n}\n</code></pre>\n"
},
{
"answer_id": 363046,
"author": "Admiral Noisy Bottom",
"author_id": 181142,
"author_profile": "https://wordpress.stackexchange.com/users/181142",
"pm_score": 0,
"selected": false,
"text": "<p>Log in to your Dashboard. On the screen showing the \"Site Health\" widget, click the <strong>\"Screen Options\"</strong> menu item at the top right of your screen and turn off \"Site Health\" and any other widgets you don't want to see.</p>\n\n<p>Each time you login the Site Health functions will not appear. This is a per user function, therefore turning it off only removes it for you and not other users.</p>\n"
},
{
"answer_id": 364437,
"author": "Alan Fuller",
"author_id": 121883,
"author_profile": "https://wordpress.stackexchange.com/users/121883",
"pm_score": 0,
"selected": false,
"text": "<p>I created a free, lightweight, plugin to solve this issue</p>\n\n<p><a href=\"https://wordpress.org/plugins/remove-site-heath-from-dashboard/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/remove-site-heath-from-dashboard/</a></p>\n"
},
{
"answer_id": 374410,
"author": "giorgos",
"author_id": 80294,
"author_profile": "https://wordpress.stackexchange.com/users/80294",
"pm_score": 0,
"selected": false,
"text": "<p>Putting this in your <code>functions.php</code> will remove Site Health widget from the dashboard:</p>\n<pre><code>add_action( 'wp_dashboard_setup', 'remove_site_health_widget' );\nfunction remove_site_health_widget() {\n global $wp_meta_boxes;\n unset( $wp_meta_boxes['dashboard']['normal']['core']['dashboard_site_health'] );\n}\n</code></pre>\n<p>And this will remove the respective option from the menu:</p>\n<pre><code>add_action( 'admin_menu', 'remove_site_health_submenu', 999 );\nfunction remove_site_health_submenu() {\n $page = remove_submenu_page( 'tools.php', 'site-health.php' );\n}\n</code></pre>\n<p>I don't believe that removing Site Health altogether is advisable, though, as it is a nice feature that can help you fix problems that might otherwise be undetected. What I suggest, instead, is <a href=\"https://www.gsarigiannidis.gr/how-to-hide-wordpress-site-health-from-everyone-but-you/\" rel=\"nofollow noreferrer\">hiding it from everyone except for the main Admin</a>.</p>\n"
}
] | 2020/04/02 | [
"https://wordpress.stackexchange.com/questions/363059",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/185295/"
] | My search-results are not displayed. Instead searches show a 404. See <https://startupsagainstcorona.com/solutions/> for testing. Can someone help?
What did I do?
1. I implemented the standard WP-search using get\_search\_form(). This
worked fine, as you can see on the page.
2. I added the search.php and searchform.php in the root-folder of the template. Those phps came from
the twentyseventeen-template of WP, as I am using a custom template and the files have been missing.
>
> The searchform-layout changed accordingly.
>
>
>
Unfortuntately, the search.php seems to be inactive in a way. Everytime, entering a search, delivers a 404.
Here the code of the search.php:
```
<get_header(); ?>
<div class="wrap">
<header class="page-header">
<?php if ( have_posts() ) : ?>
<h1 class="page-title"><?php printf( __( 'Search Results for: %s', 'twentyseventeen' ), '<span>' . get_search_query() . '</span>' ); ?></h1>
<?php else : ?>
<h1 class="page-title"><?php _e( 'Nothing Found', 'twentyseventeen' ); ?></h1>
<?php endif; ?>
</header><!-- .page-header -->
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php
if ( have_posts() ) :
/* Start the Loop */
while ( have_posts() ) :
the_post();
/**
* Run the loop for the search to output the results.
* If you want to overload this in a child theme then include a file
* called content-search.php and that will be used instead.
*/
get_template_part( 'template-parts/content', 'search' );
endwhile; // End of the loop.
the_posts_pagination(
array(
'prev_text' => twentyseventeen_get_svg( array( 'icon' => 'arrow-left' ) ) . '<span class="screen-reader-text">' . __( 'Previous page', 'twentyseventeen' ) . '</span>',
'next_text' => '<span class="screen-reader-text">' . __( 'Next page', 'twentyseventeen' ) . '</span>' . twentyseventeen_get_svg( array( 'icon' => 'arrow-right' ) ),
'before_page_number' => '<span class="meta-nav screen-reader-text">' . __( 'Page', 'twentyseventeen' ) . ' </span>',
)
);
else :
?>
<p><?php _e( 'Sorry, but nothing matched your search terms. Please try again with some different keywords.', 'twentyseventeen' ); ?></p>
<?php
get_search_form();
endif;
?>
</main><!-- #main -->
</div><!-- #primary -->
<?php //get_sidebar(); ?>
</div><!-- .wrap -->
<?php
get_footer();
```
And here the code for the searchform.php:
```
<?php
/**
* Template for displaying search forms in Twenty Seventeen
*
* @package WordPress
* @subpackage Twenty_Seventeen
* @since 1.0
* @version 1.0
*/
?>
<?php $unique_id = esc_attr( twentyseventeen_unique_id( 'search-form-' ) ); ?>
<form role="search" method="get" class="search-form" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<label for="<?php echo $unique_id; ?>">
<span class="screen-reader-text"><?php echo _x( 'Search for:', 'label', 'twentyseventeen' ); ?></span>
</label>
<input type="search" id="<?php echo $unique_id; ?>" class="search-field" placeholder="<?php echo esc_attr_x( 'Search …', 'placeholder', 'twentyseventeen' ); ?>" value="<?php echo get_search_query(); ?>" name="s" />
</form>
```
Appreciate any hint.
Best,
Max | The following snippet removes the [registered site health dashboard widget](https://github.com/WordPress/WordPress/blob/5.4-branch/wp-admin/includes/dashboard.php#L56) from the dashboard. Add the code to your plugin or `functions.php` file:
```
add_action('wp_dashboard_setup', 'remove_site_health_dashboard_widget');
function remove_site_health_dashboard_widget()
{
remove_meta_box('dashboard_site_health', 'dashboard', 'normal');
}
``` |
363,064 | <p>I was thinking this might be done by adding custom CSS to a page template. I have a page template like this: </p>
<pre><code><?php
/*
* Template Name: Grafy Full Width
*/
/*add_filter('materialis_full_width_page', '__return_true');*/
materialis_get_header();
?>
<div <?php echo materialis_page_content_atts(); ?>>
<div class="grafy-full-width-content">
<?php
while (have_posts()) : the_post();
the_content();
endwhile;
?>
</div>
</div>
<?php get_footer(); ?>
</code></pre>
<p>And I thought I might be able to add the CSS like this (basically I have 10 main tags and all I need to do is to change the header background, so I might just add 10 one-lined CSS files and condition them like this): </p>
<pre><code><?php function wpse_enqueue_page_template_styles() {
if (has_tag('Lesy')) {
wp_enqueue_style( 'Lesy', get_template_directory_uri() . '/css/Lesy.css' );
}
}
add_action( 'wp_enqueue_scripts', 'wpse_enqueue_page_template_styles' );?>
</code></pre>
<p>No matter what I do, this just isn't working. What could I be doing wrong?
Many thanks!</p>
| [
{
"answer_id": 363066,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p>If you used the <code>body_class</code> and <code>post_class</code> template tags, you get a CSS class added that contains classes for all the tags and terms a post has which you can use to conditionally style posts without needing to conditionally enqueue stylesheets</p>\n"
},
{
"answer_id": 363069,
"author": "Elex",
"author_id": 113687,
"author_profile": "https://wordpress.stackexchange.com/users/113687",
"pm_score": 0,
"selected": false,
"text": "<p>You are using <code>has_tag</code> outside of the loop. You must add the post ID to <code>has_tag</code>. I also add <code>property_exists</code> to be sure we have a post object and avoid warnings.</p>\n\n<pre><code>function wpse_enqueue_page_template_styles() {\n global $post;\n\n if (property_exists($post, 'ID') === true && has_tag('Lesy', $post->ID)) {\n wp_enqueue_style( 'Lesy', get_template_directory_uri() . '/css/Lesy.css' );\n }\n}\nadd_action( 'wp_enqueue_scripts', 'wpse_enqueue_page_template_styles' );\n</code></pre>\n"
}
] | 2020/04/02 | [
"https://wordpress.stackexchange.com/questions/363064",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/183438/"
] | I was thinking this might be done by adding custom CSS to a page template. I have a page template like this:
```
<?php
/*
* Template Name: Grafy Full Width
*/
/*add_filter('materialis_full_width_page', '__return_true');*/
materialis_get_header();
?>
<div <?php echo materialis_page_content_atts(); ?>>
<div class="grafy-full-width-content">
<?php
while (have_posts()) : the_post();
the_content();
endwhile;
?>
</div>
</div>
<?php get_footer(); ?>
```
And I thought I might be able to add the CSS like this (basically I have 10 main tags and all I need to do is to change the header background, so I might just add 10 one-lined CSS files and condition them like this):
```
<?php function wpse_enqueue_page_template_styles() {
if (has_tag('Lesy')) {
wp_enqueue_style( 'Lesy', get_template_directory_uri() . '/css/Lesy.css' );
}
}
add_action( 'wp_enqueue_scripts', 'wpse_enqueue_page_template_styles' );?>
```
No matter what I do, this just isn't working. What could I be doing wrong?
Many thanks! | If you used the `body_class` and `post_class` template tags, you get a CSS class added that contains classes for all the tags and terms a post has which you can use to conditionally style posts without needing to conditionally enqueue stylesheets |
363,095 | <p>Hopefully, I can explain this well enough, but let me know if not and I'll expand on it.</p>
<p>I've used ACF in conjunction with a Custom Post Type, but when I try to grab the photo that I've uploaded for each product it only shows the photo for the first product each time for all products on the archive-products.php page.</p>
<pre><code><?php
$args = array( 'post_type' => 'products', 'posts_per_page' => 9 );
$the_query = new WP_Query( $args );
$landscape = get_field('main_photo_landscape', $post->ID);
?>
<main class="site-content">
<div class="row">
<?php if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<article class="col-12 col-md-6 col-lg-4 product">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<div class="featured-img" style="background: url('<?php echo $landscape['sizes']['large']; ?>') center center no-repeat; background-size: auto 100%"></div>
<h1 class="title"><?php the_title(); ?></h1>
<button class="btn">More Details</button>
</a>
</article>
<?php endwhile; ?>
<?php the_posts_navigation(); ?>
<?php endif; ?>
</div>
</main>
</code></pre>
| [
{
"answer_id": 363096,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 3,
"selected": true,
"text": "<p>You need to define <code>$landscape</code> in the loop. You're defining out so it is not part of your repeating portion.</p>\n\n<p>Move it down just under the <code>while</code> line so it looks like this:</p>\n\n<pre><code><?php \n$args = array( 'post_type' => 'products', 'posts_per_page' => 9 );\n$the_query = new WP_Query( $args );\n\n\n?>\n\n<main class=\"site-content\">\n<div class=\"row\">\n\n <?php if ( $the_query->have_posts() ) : ?>\n <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>\n\n $landscape = get_field('main_photo_landscape');\n\n <article class=\"col-12 col-md-6 col-lg-4 product\">\n <a href=\"<?php the_permalink(); ?>\" title=\"<?php the_title_attribute(); ?>\">\n <div class=\"featured-img\" style=\"background: url('<?php echo $landscape['sizes']['large']; ?>') center center no-repeat; background-size: auto 100%\"></div>\n <h1 class=\"title\"><?php the_title(); ?></h1>\n <button class=\"btn\">More Details</button>\n </a>\n </article>\n\n <?php endwhile; ?>\n\n <?php the_posts_navigation(); ?>\n\n <?php endif; ?>\n\n</div>\n</code></pre>\n\n<p></p>\n\n<p>Notice I removed <code>, $post->ID</code> as well.</p>\n"
},
{
"answer_id": 363097,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 1,
"selected": false,
"text": "<p>What's happening here is you are setting <code>$landscape</code> before the loop, so it only gets set once. (So it shows up for each item in the loop.)</p>\n\n<p>To fix this, move your 5th line - <code>$landscape</code> - inside the loop.</p>\n\n<pre><code><?php \n $args = array( 'post_type' => 'products', 'posts_per_page' => 9 );\n $the_query = new WP_Query( $args );\n // No longer setting $landscape here, which only sets it once.\n?>\n\n<main class=\"site-content\">\n <div class=\"row\">\n\n <?php if ( $the_query->have_posts() ) : ?>\n <?php while ( $the_query->have_posts() ) : $the_query->the_post();\n // Landscape now pulls for the current post.\n $landscape = get_field('main_photo_landscape', $post->ID);\n ?>\n\n <article class=\"col-12 col-md-6 col-lg-4 product\">\n <a href=\"<?php the_permalink(); ?>\" title=\"<?php the_title_attribute(); ?>\">\n <div class=\"featured-img\" style=\"background: url('<?php echo $landscape['sizes']['large']; ?>') center center no-repeat; background-size: auto 100%\"></div>\n <h1 class=\"title\"><?php the_title(); ?></h1>\n <button class=\"btn\">More Details</button>\n </a>\n </article>\n\n <?php endwhile; ?>\n\n <?php the_posts_navigation(); ?>\n\n <?php endif; ?>\n\n </div>\n</main>\n</code></pre>\n\n<p>This will pull the ACF field for each individual post.</p>\n"
}
] | 2020/04/02 | [
"https://wordpress.stackexchange.com/questions/363095",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/160534/"
] | Hopefully, I can explain this well enough, but let me know if not and I'll expand on it.
I've used ACF in conjunction with a Custom Post Type, but when I try to grab the photo that I've uploaded for each product it only shows the photo for the first product each time for all products on the archive-products.php page.
```
<?php
$args = array( 'post_type' => 'products', 'posts_per_page' => 9 );
$the_query = new WP_Query( $args );
$landscape = get_field('main_photo_landscape', $post->ID);
?>
<main class="site-content">
<div class="row">
<?php if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<article class="col-12 col-md-6 col-lg-4 product">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<div class="featured-img" style="background: url('<?php echo $landscape['sizes']['large']; ?>') center center no-repeat; background-size: auto 100%"></div>
<h1 class="title"><?php the_title(); ?></h1>
<button class="btn">More Details</button>
</a>
</article>
<?php endwhile; ?>
<?php the_posts_navigation(); ?>
<?php endif; ?>
</div>
</main>
``` | You need to define `$landscape` in the loop. You're defining out so it is not part of your repeating portion.
Move it down just under the `while` line so it looks like this:
```
<?php
$args = array( 'post_type' => 'products', 'posts_per_page' => 9 );
$the_query = new WP_Query( $args );
?>
<main class="site-content">
<div class="row">
<?php if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
$landscape = get_field('main_photo_landscape');
<article class="col-12 col-md-6 col-lg-4 product">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<div class="featured-img" style="background: url('<?php echo $landscape['sizes']['large']; ?>') center center no-repeat; background-size: auto 100%"></div>
<h1 class="title"><?php the_title(); ?></h1>
<button class="btn">More Details</button>
</a>
</article>
<?php endwhile; ?>
<?php the_posts_navigation(); ?>
<?php endif; ?>
</div>
```
Notice I removed `, $post->ID` as well. |
363,106 | <p>I am using Stripe Connect to collect a commission for sales on a woocommerce site. </p>
<p>I need to add the following to the payment request JSON. </p>
<pre><code> 'application_fee_amount' => (Gateway Based Fees Amount),
'transfer_data' => [
'destination' => '{{CONNECTED_STRIPE_ACCOUNT_ID}}',
],
</code></pre>
<p>This code I found and modified a little to fit my purpose. EDIT: I have completely rewritten this, I just need to get the extra variable array values added to the request. </p>
<pre><code>//add_filter( 'woocommerce_stripe_request_body', 'add_application_fee', 20, 2 );
add_filter('wc_stripe_generate_payment_request', 'add_application_fee', 20, 3 );
function add_application_fee( $post_data ) {
//$applicationFee = (int)apply_filters('vnm_wc_stripe_connect_application_fee', $order, $request);
$applicationFee = 25; // <- Use this for testing, I
$post_data['application_fee_amount'] = $applicationFee;
$post_data['on_behalf_of'] = 'acct_1GQjzOHenYA2KZ8B';
$post_data['transfer_data']['destination'] = 'acct_1GQjzOHenYA2KZ8B';
return $post_data;
}
</code></pre>
<p>This does not produce any errors, however the information does not get added onto the stripe payment.</p>
<pre><code>{
"amount": "12766",
"currency": "USD",
"description": "Order 35215",
"metadata": {
"instance": "example.com",
"order_id": "35215",
"order_email": "[email protected]",
"cart_hash": ""
},
"setup_future_usage": "off_session",
"capture_method": "automatic",
"confirmation_method": "manual",
"customer": "cus_H1VGhq2aNJWokc"
}
</code></pre>
| [
{
"answer_id": 363096,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 3,
"selected": true,
"text": "<p>You need to define <code>$landscape</code> in the loop. You're defining out so it is not part of your repeating portion.</p>\n\n<p>Move it down just under the <code>while</code> line so it looks like this:</p>\n\n<pre><code><?php \n$args = array( 'post_type' => 'products', 'posts_per_page' => 9 );\n$the_query = new WP_Query( $args );\n\n\n?>\n\n<main class=\"site-content\">\n<div class=\"row\">\n\n <?php if ( $the_query->have_posts() ) : ?>\n <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>\n\n $landscape = get_field('main_photo_landscape');\n\n <article class=\"col-12 col-md-6 col-lg-4 product\">\n <a href=\"<?php the_permalink(); ?>\" title=\"<?php the_title_attribute(); ?>\">\n <div class=\"featured-img\" style=\"background: url('<?php echo $landscape['sizes']['large']; ?>') center center no-repeat; background-size: auto 100%\"></div>\n <h1 class=\"title\"><?php the_title(); ?></h1>\n <button class=\"btn\">More Details</button>\n </a>\n </article>\n\n <?php endwhile; ?>\n\n <?php the_posts_navigation(); ?>\n\n <?php endif; ?>\n\n</div>\n</code></pre>\n\n<p></p>\n\n<p>Notice I removed <code>, $post->ID</code> as well.</p>\n"
},
{
"answer_id": 363097,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 1,
"selected": false,
"text": "<p>What's happening here is you are setting <code>$landscape</code> before the loop, so it only gets set once. (So it shows up for each item in the loop.)</p>\n\n<p>To fix this, move your 5th line - <code>$landscape</code> - inside the loop.</p>\n\n<pre><code><?php \n $args = array( 'post_type' => 'products', 'posts_per_page' => 9 );\n $the_query = new WP_Query( $args );\n // No longer setting $landscape here, which only sets it once.\n?>\n\n<main class=\"site-content\">\n <div class=\"row\">\n\n <?php if ( $the_query->have_posts() ) : ?>\n <?php while ( $the_query->have_posts() ) : $the_query->the_post();\n // Landscape now pulls for the current post.\n $landscape = get_field('main_photo_landscape', $post->ID);\n ?>\n\n <article class=\"col-12 col-md-6 col-lg-4 product\">\n <a href=\"<?php the_permalink(); ?>\" title=\"<?php the_title_attribute(); ?>\">\n <div class=\"featured-img\" style=\"background: url('<?php echo $landscape['sizes']['large']; ?>') center center no-repeat; background-size: auto 100%\"></div>\n <h1 class=\"title\"><?php the_title(); ?></h1>\n <button class=\"btn\">More Details</button>\n </a>\n </article>\n\n <?php endwhile; ?>\n\n <?php the_posts_navigation(); ?>\n\n <?php endif; ?>\n\n </div>\n</main>\n</code></pre>\n\n<p>This will pull the ACF field for each individual post.</p>\n"
}
] | 2020/04/03 | [
"https://wordpress.stackexchange.com/questions/363106",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70863/"
] | I am using Stripe Connect to collect a commission for sales on a woocommerce site.
I need to add the following to the payment request JSON.
```
'application_fee_amount' => (Gateway Based Fees Amount),
'transfer_data' => [
'destination' => '{{CONNECTED_STRIPE_ACCOUNT_ID}}',
],
```
This code I found and modified a little to fit my purpose. EDIT: I have completely rewritten this, I just need to get the extra variable array values added to the request.
```
//add_filter( 'woocommerce_stripe_request_body', 'add_application_fee', 20, 2 );
add_filter('wc_stripe_generate_payment_request', 'add_application_fee', 20, 3 );
function add_application_fee( $post_data ) {
//$applicationFee = (int)apply_filters('vnm_wc_stripe_connect_application_fee', $order, $request);
$applicationFee = 25; // <- Use this for testing, I
$post_data['application_fee_amount'] = $applicationFee;
$post_data['on_behalf_of'] = 'acct_1GQjzOHenYA2KZ8B';
$post_data['transfer_data']['destination'] = 'acct_1GQjzOHenYA2KZ8B';
return $post_data;
}
```
This does not produce any errors, however the information does not get added onto the stripe payment.
```
{
"amount": "12766",
"currency": "USD",
"description": "Order 35215",
"metadata": {
"instance": "example.com",
"order_id": "35215",
"order_email": "[email protected]",
"cart_hash": ""
},
"setup_future_usage": "off_session",
"capture_method": "automatic",
"confirmation_method": "manual",
"customer": "cus_H1VGhq2aNJWokc"
}
``` | You need to define `$landscape` in the loop. You're defining out so it is not part of your repeating portion.
Move it down just under the `while` line so it looks like this:
```
<?php
$args = array( 'post_type' => 'products', 'posts_per_page' => 9 );
$the_query = new WP_Query( $args );
?>
<main class="site-content">
<div class="row">
<?php if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
$landscape = get_field('main_photo_landscape');
<article class="col-12 col-md-6 col-lg-4 product">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<div class="featured-img" style="background: url('<?php echo $landscape['sizes']['large']; ?>') center center no-repeat; background-size: auto 100%"></div>
<h1 class="title"><?php the_title(); ?></h1>
<button class="btn">More Details</button>
</a>
</article>
<?php endwhile; ?>
<?php the_posts_navigation(); ?>
<?php endif; ?>
</div>
```
Notice I removed `, $post->ID` as well. |
363,123 | <p>I'm using WordPress admin to create a page (named <code>get-region-page</code>), in which Pod shortcode is used to retrieve the URL parameter. For example:</p>
<pre><code>[pods name="region" slug="{@get.regionparam}" field="region_name"]
</code></pre>
<p>With a redirection 301 to the URL <code>/get-region-page&regionparam=$region_slug</code>, the Pod shortcode works fine.</p>
<p>The problem arrives when I need to create a rewrite rule for that page in <code>functions.php</code> (with <code>1234</code> is the page ID for <code>get-region-page</code>):</p>
<pre><code>add_rewrite_rule('({some-custom-regex})/?$','index.php?page_id=1234&regionparam=$matches[1]','top');
</code></pre>
<p>...the parameter becomes <code>null</code>. I can no longer retrieve the URL parameter.
But if I try this PHP code in the WordPress template of the page, the parameter is still there:</p>
<pre><code>echo get_query_var('regionparam');
</code></pre>
<p>Remark, this one does not work either in the PHP template:</p>
<pre><code>echo $_GET['regionparam'];
</code></pre>
<p>So I wonder if there is some equivalent Pod shortcode for <code>get_query_var('regionparam')</code> for my first Pod shortcode to work again?</p>
| [
{
"answer_id": 363096,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 3,
"selected": true,
"text": "<p>You need to define <code>$landscape</code> in the loop. You're defining out so it is not part of your repeating portion.</p>\n\n<p>Move it down just under the <code>while</code> line so it looks like this:</p>\n\n<pre><code><?php \n$args = array( 'post_type' => 'products', 'posts_per_page' => 9 );\n$the_query = new WP_Query( $args );\n\n\n?>\n\n<main class=\"site-content\">\n<div class=\"row\">\n\n <?php if ( $the_query->have_posts() ) : ?>\n <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>\n\n $landscape = get_field('main_photo_landscape');\n\n <article class=\"col-12 col-md-6 col-lg-4 product\">\n <a href=\"<?php the_permalink(); ?>\" title=\"<?php the_title_attribute(); ?>\">\n <div class=\"featured-img\" style=\"background: url('<?php echo $landscape['sizes']['large']; ?>') center center no-repeat; background-size: auto 100%\"></div>\n <h1 class=\"title\"><?php the_title(); ?></h1>\n <button class=\"btn\">More Details</button>\n </a>\n </article>\n\n <?php endwhile; ?>\n\n <?php the_posts_navigation(); ?>\n\n <?php endif; ?>\n\n</div>\n</code></pre>\n\n<p></p>\n\n<p>Notice I removed <code>, $post->ID</code> as well.</p>\n"
},
{
"answer_id": 363097,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 1,
"selected": false,
"text": "<p>What's happening here is you are setting <code>$landscape</code> before the loop, so it only gets set once. (So it shows up for each item in the loop.)</p>\n\n<p>To fix this, move your 5th line - <code>$landscape</code> - inside the loop.</p>\n\n<pre><code><?php \n $args = array( 'post_type' => 'products', 'posts_per_page' => 9 );\n $the_query = new WP_Query( $args );\n // No longer setting $landscape here, which only sets it once.\n?>\n\n<main class=\"site-content\">\n <div class=\"row\">\n\n <?php if ( $the_query->have_posts() ) : ?>\n <?php while ( $the_query->have_posts() ) : $the_query->the_post();\n // Landscape now pulls for the current post.\n $landscape = get_field('main_photo_landscape', $post->ID);\n ?>\n\n <article class=\"col-12 col-md-6 col-lg-4 product\">\n <a href=\"<?php the_permalink(); ?>\" title=\"<?php the_title_attribute(); ?>\">\n <div class=\"featured-img\" style=\"background: url('<?php echo $landscape['sizes']['large']; ?>') center center no-repeat; background-size: auto 100%\"></div>\n <h1 class=\"title\"><?php the_title(); ?></h1>\n <button class=\"btn\">More Details</button>\n </a>\n </article>\n\n <?php endwhile; ?>\n\n <?php the_posts_navigation(); ?>\n\n <?php endif; ?>\n\n </div>\n</main>\n</code></pre>\n\n<p>This will pull the ACF field for each individual post.</p>\n"
}
] | 2020/04/03 | [
"https://wordpress.stackexchange.com/questions/363123",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/185342/"
] | I'm using WordPress admin to create a page (named `get-region-page`), in which Pod shortcode is used to retrieve the URL parameter. For example:
```
[pods name="region" slug="{@get.regionparam}" field="region_name"]
```
With a redirection 301 to the URL `/get-region-page®ionparam=$region_slug`, the Pod shortcode works fine.
The problem arrives when I need to create a rewrite rule for that page in `functions.php` (with `1234` is the page ID for `get-region-page`):
```
add_rewrite_rule('({some-custom-regex})/?$','index.php?page_id=1234®ionparam=$matches[1]','top');
```
...the parameter becomes `null`. I can no longer retrieve the URL parameter.
But if I try this PHP code in the WordPress template of the page, the parameter is still there:
```
echo get_query_var('regionparam');
```
Remark, this one does not work either in the PHP template:
```
echo $_GET['regionparam'];
```
So I wonder if there is some equivalent Pod shortcode for `get_query_var('regionparam')` for my first Pod shortcode to work again? | You need to define `$landscape` in the loop. You're defining out so it is not part of your repeating portion.
Move it down just under the `while` line so it looks like this:
```
<?php
$args = array( 'post_type' => 'products', 'posts_per_page' => 9 );
$the_query = new WP_Query( $args );
?>
<main class="site-content">
<div class="row">
<?php if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
$landscape = get_field('main_photo_landscape');
<article class="col-12 col-md-6 col-lg-4 product">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<div class="featured-img" style="background: url('<?php echo $landscape['sizes']['large']; ?>') center center no-repeat; background-size: auto 100%"></div>
<h1 class="title"><?php the_title(); ?></h1>
<button class="btn">More Details</button>
</a>
</article>
<?php endwhile; ?>
<?php the_posts_navigation(); ?>
<?php endif; ?>
</div>
```
Notice I removed `, $post->ID` as well. |
363,139 | <p>So I've tried a few different ways to override a method inside the parent theme and I'm not having much luck at all.</p>
<p>So here is the structure:</p>
<blockquote>
<p>themes/<br>
- wp-starter<br>
-- custom_header.php<br>
- wp-starter-child<br>
-- custom_header.php</p>
</blockquote>
<p>I have a method inside the parent custom_header.php as shown below:</p>
<pre><code>function wp_bootstrap_starter_custom_header_setup() {
add_theme_support( 'custom-header', apply_filters( 'wp_bootstrap_starter_custom_header_args', array(
'default-image' => '',
'default-text-color' => 'fff',
'width' => 1000,
'height' => 250,
'flex-height' => true,
'wp-head-callback' => 'wp_bootstrap_starter_header_style',
) ) );
}
add_action( 'after_setup_theme', 'wp_bootstrap_starter_custom_header_setup' );
</code></pre>
<p>Now.. I want to be able to call that method inside my child <code>custom_header.php</code> and override the width and height.</p>
<p>Here are a few attempts:</p>
<p>Added priority to action (Didn't work):</p>
<pre><code>function wp_bootstrap_starter_custom_header_setup() {
add_theme_support( 'custom-header', apply_filters( 'wp_bootstrap_starter_custom_header_args', array(
'default-image' => '',
'default-text-color' => 'fff',
'width' => 1000,
'height' => 500,
'flex-height' => true,
'wp-head-callback' => 'wp_bootstrap_starter_header_style',
) ) );
}
add_action('after_setup_theme', 'wp_bootstrap_starter_custom_header_setup', 20);
</code></pre>
<p>Renamed the method and added priority (Didn't work):</p>
<pre><code>function wp_bootstrap_starter_custom_header_setup() {
add_theme_support( 'custom-header', apply_filters( 'wp_bootstrap_starter_custom_header_args', array(
'default-image' => '',
'default-text-color' => 'fff',
'width' => 1000,
'height' => 500,
'flex-height' => true,
'wp-head-callback' => 'wp_bootstrap_starter_header_style',
) ) );
}
add_action('after_setup_theme', 'wp_bootstrap_starter_custom_header_setup', 20);
</code></pre>
<p>Added an init action call with priority (Didn't work):</p>
<pre><code>function wp_bootstrap_starter_custom_header_setup() {
add_theme_support( 'custom-header', apply_filters( 'wp_bootstrap_starter_custom_header_args', array(
'default-image' => '',
'default-text-color' => 'fff',
'width' => 1000,
'height' => 500,
'flex-height' => true,
'wp-head-callback' => 'wp_bootstrap_starter_header_style',
) ) );
}
add_action('after_setup_theme', 'wp_bootstrap_starter_custom_header_setup' );
add_action('init', 'wp_bootstrap_starter_custom_header_setup', 15);
</code></pre>
<p>So I've tried doing <code>remove_action('after_setup_theme', 'wp_bootstrap_starter_custom_header_setup');</code> with no results.</p>
| [
{
"answer_id": 363178,
"author": "Himad",
"author_id": 158512,
"author_profile": "https://wordpress.stackexchange.com/users/158512",
"pm_score": 1,
"selected": false,
"text": "<p>Lower numbers have higher priority. Default priority is 10, so if you want an action to be executed before, try with 9.</p>\n\n<p>Also, you should remove the original actions to prevent any unwanted side effects. </p>\n\n<pre><code>function override_wp_bootstrap_starter_custom_header_setup() {\n remove_action('after_setup_theme', 'wp_bootstrap_starter_custom_header_setup', 10);\n\n add_theme_support( 'custom-header', apply_filters( 'wp_bootstrap_starter_custom_header_args', array(\n 'default-image' => '',\n 'default-text-color' => 'fff',\n 'width' => 1000,\n 'height' => 500,\n 'flex-height' => true,\n 'wp-head-callback' => 'wp_bootstrap_starter_header_style',\n ) ) );\n}\n\nadd_action('after_setup_theme', 'override_wp_bootstrap_starter_custom_header_setup', 9);\n\n</code></pre>\n"
},
{
"answer_id": 363208,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p>You can't just redeclare the function in the child theme or call <code>add_action</code> a second time. It doesn't replace it, it adds a second hook. As a result, you haven't overriden it, you've duplicated the original. Child theme overrides only work for templates.</p>\n\n<p>What's more, by adding a second definition of <code>wp_bootstrap_starter_custom_header_setup</code> you've declared the function twice, which would generate a PHP fatal error. You can't have 2 functions with the same name.</p>\n\n<p>So first, we need to rename your function so that there's valid PHP:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function sams_custom_header_setup() {\n</code></pre>\n\n<p>Next, <code>add_action</code> adds an action. It has no concept of <em>replacing</em> an action. If you call <code>add_action</code> 5 times, the function will run 5 times.</p>\n\n<p>So lets add our action for the new setup:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action('after_setup_theme', 'sams_custom_header_setup' );\n</code></pre>\n\n<p>But remember, the original function got added too, so now both will run! So, remove the original:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>remove_action( 'after_setup_theme', 'wp_bootstrap_starter_custom_header_setup' );\n</code></pre>\n\n<p>TLDR:</p>\n\n<ul>\n<li>You can't \"override\" actions.</li>\n<li>But you can remove them and add a new action to replace them.</li>\n<li>Stop making multiple functions with the same name! That's invalid PHP, it'll break things</li>\n<li>Child themes let you override <em>templates</em> loaded via WP, not arbitrary PHP files, functions, hooks, etc</li>\n</ul>\n\n<hr>\n\n<p>Edit:</p>\n\n<p>It seems the function in your parent theme uses <code>apply_filters</code>, you could just filter the parameters on the <code>wp_bootstrap_starter_custom_header_args</code> filter and modify the array itself. You don't need to mess around replacing the function, or calling <code>add_theme_support</code></p>\n"
},
{
"answer_id": 376893,
"author": "Xebozone",
"author_id": 196414,
"author_profile": "https://wordpress.stackexchange.com/users/196414",
"pm_score": 0,
"selected": false,
"text": "<p>I am customizing the same theme. In my child theme functions file, I did the following to override the height:</p>\n<pre><code>/*\n * Customize the header image parameters\n * See parent theme /inc/custom-header.php for reference\n */\nfunction custom_parameters_wp_bootstrap_starter_custom_header_setup() {\n add_theme_support( 'custom-header', apply_filters( 'wp_bootstrap_starter_custom_header_args', array(\n 'height' => 500\n ) ) );\n}\nadd_action( 'after_setup_theme', 'custom_parameters_wp_bootstrap_starter_custom_header_setup', 9 );\n</code></pre>\n<p>The trick was to add a lower priority, which make the changes execute after the original definitions (default priority is 10).</p>\n"
}
] | 2020/04/03 | [
"https://wordpress.stackexchange.com/questions/363139",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/173392/"
] | So I've tried a few different ways to override a method inside the parent theme and I'm not having much luck at all.
So here is the structure:
>
> themes/
>
> - wp-starter
>
> -- custom\_header.php
>
> - wp-starter-child
>
> -- custom\_header.php
>
>
>
I have a method inside the parent custom\_header.php as shown below:
```
function wp_bootstrap_starter_custom_header_setup() {
add_theme_support( 'custom-header', apply_filters( 'wp_bootstrap_starter_custom_header_args', array(
'default-image' => '',
'default-text-color' => 'fff',
'width' => 1000,
'height' => 250,
'flex-height' => true,
'wp-head-callback' => 'wp_bootstrap_starter_header_style',
) ) );
}
add_action( 'after_setup_theme', 'wp_bootstrap_starter_custom_header_setup' );
```
Now.. I want to be able to call that method inside my child `custom_header.php` and override the width and height.
Here are a few attempts:
Added priority to action (Didn't work):
```
function wp_bootstrap_starter_custom_header_setup() {
add_theme_support( 'custom-header', apply_filters( 'wp_bootstrap_starter_custom_header_args', array(
'default-image' => '',
'default-text-color' => 'fff',
'width' => 1000,
'height' => 500,
'flex-height' => true,
'wp-head-callback' => 'wp_bootstrap_starter_header_style',
) ) );
}
add_action('after_setup_theme', 'wp_bootstrap_starter_custom_header_setup', 20);
```
Renamed the method and added priority (Didn't work):
```
function wp_bootstrap_starter_custom_header_setup() {
add_theme_support( 'custom-header', apply_filters( 'wp_bootstrap_starter_custom_header_args', array(
'default-image' => '',
'default-text-color' => 'fff',
'width' => 1000,
'height' => 500,
'flex-height' => true,
'wp-head-callback' => 'wp_bootstrap_starter_header_style',
) ) );
}
add_action('after_setup_theme', 'wp_bootstrap_starter_custom_header_setup', 20);
```
Added an init action call with priority (Didn't work):
```
function wp_bootstrap_starter_custom_header_setup() {
add_theme_support( 'custom-header', apply_filters( 'wp_bootstrap_starter_custom_header_args', array(
'default-image' => '',
'default-text-color' => 'fff',
'width' => 1000,
'height' => 500,
'flex-height' => true,
'wp-head-callback' => 'wp_bootstrap_starter_header_style',
) ) );
}
add_action('after_setup_theme', 'wp_bootstrap_starter_custom_header_setup' );
add_action('init', 'wp_bootstrap_starter_custom_header_setup', 15);
```
So I've tried doing `remove_action('after_setup_theme', 'wp_bootstrap_starter_custom_header_setup');` with no results. | You can't just redeclare the function in the child theme or call `add_action` a second time. It doesn't replace it, it adds a second hook. As a result, you haven't overriden it, you've duplicated the original. Child theme overrides only work for templates.
What's more, by adding a second definition of `wp_bootstrap_starter_custom_header_setup` you've declared the function twice, which would generate a PHP fatal error. You can't have 2 functions with the same name.
So first, we need to rename your function so that there's valid PHP:
```php
function sams_custom_header_setup() {
```
Next, `add_action` adds an action. It has no concept of *replacing* an action. If you call `add_action` 5 times, the function will run 5 times.
So lets add our action for the new setup:
```php
add_action('after_setup_theme', 'sams_custom_header_setup' );
```
But remember, the original function got added too, so now both will run! So, remove the original:
```php
remove_action( 'after_setup_theme', 'wp_bootstrap_starter_custom_header_setup' );
```
TLDR:
* You can't "override" actions.
* But you can remove them and add a new action to replace them.
* Stop making multiple functions with the same name! That's invalid PHP, it'll break things
* Child themes let you override *templates* loaded via WP, not arbitrary PHP files, functions, hooks, etc
---
Edit:
It seems the function in your parent theme uses `apply_filters`, you could just filter the parameters on the `wp_bootstrap_starter_custom_header_args` filter and modify the array itself. You don't need to mess around replacing the function, or calling `add_theme_support` |
363,166 | <p>Im using ACF and trying to show a post type title based on the current time. So I have my post type entry with start_time and end_time and my conditional is showing my div.onAir, but Im getting this Recoverable Fatal Error. Here is my code:</p>
<pre><code><?php
$time_now = date("g:i a");
$shows = get_posts( array(
'post_type' => 'shows',
'meta_query' => array(
array(
'key' => 'start_time',
'compare' => '<=',
'value' => $time_now,
'type' => 'DATETIME',
),
array(
'key' => 'end_time',
'compare' => '<=',
'value' => $time_now,
'type' => 'DATETIME',
)
),
));
if( $shows ) {
foreach( $shows as $show ){ ?>
<div class="onAir">
Currently On Air: <?php echo the_title($show); ?>
</div>
<?php
wp_reset_query();
}
} ?>
</code></pre>
<p>I feel Im close, but I haven't seen this particular error before. Any help would be appreciated! Thanks.</p>
<p><strong>UPDATE:</strong> </p>
<p>Tom changed my code up to use WP_Query. I had an issue with the timestamps in ACF and WP matching up. Once I figured that out, this code renders the correct comparison of show posts that I was going for. Please note that I used <code>date_i18n('g:i a');</code> which fixed my localization timestamp. Thanks Tom and Yuri!</p>
<pre><code><?php
$time = date_i18n('g:i a');
$shows = get_field('station_shows', false, false);
$query = new WP_Query(array(
'post_type' => 'shows',
'posts_per_page' => 1,
'post__in' => $shows,
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'start_time',
'compare' => '<=',
'value' => date_i18n('g:i a', $time),
'type' => 'TIME',
),
array(
'key' => 'end_time',
'compare' => '>=',
'value' => date_i18n('g:i a', $time),
'type' => 'TIME',
)
),
) );
if ( $query->have_posts() ) { while( $query->have_posts() ) {
$query- >the_post();
echo '<div class="onAir"><h3>Currently On Air @ ';
the_title();
if (get_field('dj', $query->ID)) {
$dj = get_field('dj');
echo ' w/ ';
echo $dj;
}
echo '</h3></div>';
} wp_reset_postdata();
}
?>
</code></pre>
| [
{
"answer_id": 363167,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p><code>the_title</code> doesn't work that way:</p>\n<pre class=\"lang-php prettyprint-override\"><code>the_title( $before, $after, $echo );\n</code></pre>\n<p><code>$before</code> is the text that comes before the title, but you didn't give it a string/text, you gave it a post object. Post objects aren't strings, PHP doesn't know what to do so it stops and prints an error instead.</p>\n<p>For <code>the_title</code> to work, you need to setup the current postdata. Normally a standard loop does this by calling <code>the_post</code> on the query, but you've chosen to use <code>get_posts</code> instead.</p>\n<p>This is what a standard post <code>WP_Query</code> post loop should look like:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$query = new WP_Query([ ... ]);\nif ( $query->have_posts() ) {\n while( $query->have_posts() ) {\n $query->the_post();\n //.... display post here\n }\n wp_reset_postdata();\n}\n</code></pre>\n"
},
{
"answer_id": 363168,
"author": "Neolot",
"author_id": 41273,
"author_profile": "https://wordpress.stackexchange.com/users/41273",
"pm_score": 0,
"selected": false,
"text": "<p>You are calling WordPress functions incorrectly. I fixed, try this code.</p>\n\n<pre><code><?php\n $time_now = date( \"g:i a\" );\n $shows = get_posts( array(\n 'post_type' => 'shows',\n 'meta_query' => array(\n array(\n 'key' => 'start_time',\n 'compare' => '<=',\n 'value' => $time_now,\n 'type' => 'DATETIME',\n ),\n array(\n 'key' => 'end_time',\n 'compare' => '<=',\n 'value' => $time_now,\n 'type' => 'DATETIME',\n )\n ),\n ) );\n\n if ( $shows ) :\n foreach ( $shows as $show ) :\n ?>\n\n <div class=\"onAir\">\n Currently On Air: <?php echo get_the_title($show->ID); ?>\n </div>\n\n <?php\n endforeach;\n wp_reset_postdata();\n endif;\n?>\n</code></pre>\n"
}
] | 2020/04/03 | [
"https://wordpress.stackexchange.com/questions/363166",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/185384/"
] | Im using ACF and trying to show a post type title based on the current time. So I have my post type entry with start\_time and end\_time and my conditional is showing my div.onAir, but Im getting this Recoverable Fatal Error. Here is my code:
```
<?php
$time_now = date("g:i a");
$shows = get_posts( array(
'post_type' => 'shows',
'meta_query' => array(
array(
'key' => 'start_time',
'compare' => '<=',
'value' => $time_now,
'type' => 'DATETIME',
),
array(
'key' => 'end_time',
'compare' => '<=',
'value' => $time_now,
'type' => 'DATETIME',
)
),
));
if( $shows ) {
foreach( $shows as $show ){ ?>
<div class="onAir">
Currently On Air: <?php echo the_title($show); ?>
</div>
<?php
wp_reset_query();
}
} ?>
```
I feel Im close, but I haven't seen this particular error before. Any help would be appreciated! Thanks.
**UPDATE:**
Tom changed my code up to use WP\_Query. I had an issue with the timestamps in ACF and WP matching up. Once I figured that out, this code renders the correct comparison of show posts that I was going for. Please note that I used `date_i18n('g:i a');` which fixed my localization timestamp. Thanks Tom and Yuri!
```
<?php
$time = date_i18n('g:i a');
$shows = get_field('station_shows', false, false);
$query = new WP_Query(array(
'post_type' => 'shows',
'posts_per_page' => 1,
'post__in' => $shows,
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'start_time',
'compare' => '<=',
'value' => date_i18n('g:i a', $time),
'type' => 'TIME',
),
array(
'key' => 'end_time',
'compare' => '>=',
'value' => date_i18n('g:i a', $time),
'type' => 'TIME',
)
),
) );
if ( $query->have_posts() ) { while( $query->have_posts() ) {
$query- >the_post();
echo '<div class="onAir"><h3>Currently On Air @ ';
the_title();
if (get_field('dj', $query->ID)) {
$dj = get_field('dj');
echo ' w/ ';
echo $dj;
}
echo '</h3></div>';
} wp_reset_postdata();
}
?>
``` | `the_title` doesn't work that way:
```php
the_title( $before, $after, $echo );
```
`$before` is the text that comes before the title, but you didn't give it a string/text, you gave it a post object. Post objects aren't strings, PHP doesn't know what to do so it stops and prints an error instead.
For `the_title` to work, you need to setup the current postdata. Normally a standard loop does this by calling `the_post` on the query, but you've chosen to use `get_posts` instead.
This is what a standard post `WP_Query` post loop should look like:
```php
$query = new WP_Query([ ... ]);
if ( $query->have_posts() ) {
while( $query->have_posts() ) {
$query->the_post();
//.... display post here
}
wp_reset_postdata();
}
``` |
363,193 | <pre><code> function im_check_term($name,$tax){
$term = get_term_by("name", $name,$tax);
return !is_wp_error($term) ? $term->term_id : false;
}
</code></pre>
<p>Notice: Trying to get property of non-object in /home/pcodecom/demo.p30code.com/multimedia-2/wp-content/plugins/imdb/imdb.php on line 11</p>
| [
{
"answer_id": 363167,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p><code>the_title</code> doesn't work that way:</p>\n<pre class=\"lang-php prettyprint-override\"><code>the_title( $before, $after, $echo );\n</code></pre>\n<p><code>$before</code> is the text that comes before the title, but you didn't give it a string/text, you gave it a post object. Post objects aren't strings, PHP doesn't know what to do so it stops and prints an error instead.</p>\n<p>For <code>the_title</code> to work, you need to setup the current postdata. Normally a standard loop does this by calling <code>the_post</code> on the query, but you've chosen to use <code>get_posts</code> instead.</p>\n<p>This is what a standard post <code>WP_Query</code> post loop should look like:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$query = new WP_Query([ ... ]);\nif ( $query->have_posts() ) {\n while( $query->have_posts() ) {\n $query->the_post();\n //.... display post here\n }\n wp_reset_postdata();\n}\n</code></pre>\n"
},
{
"answer_id": 363168,
"author": "Neolot",
"author_id": 41273,
"author_profile": "https://wordpress.stackexchange.com/users/41273",
"pm_score": 0,
"selected": false,
"text": "<p>You are calling WordPress functions incorrectly. I fixed, try this code.</p>\n\n<pre><code><?php\n $time_now = date( \"g:i a\" );\n $shows = get_posts( array(\n 'post_type' => 'shows',\n 'meta_query' => array(\n array(\n 'key' => 'start_time',\n 'compare' => '<=',\n 'value' => $time_now,\n 'type' => 'DATETIME',\n ),\n array(\n 'key' => 'end_time',\n 'compare' => '<=',\n 'value' => $time_now,\n 'type' => 'DATETIME',\n )\n ),\n ) );\n\n if ( $shows ) :\n foreach ( $shows as $show ) :\n ?>\n\n <div class=\"onAir\">\n Currently On Air: <?php echo get_the_title($show->ID); ?>\n </div>\n\n <?php\n endforeach;\n wp_reset_postdata();\n endif;\n?>\n</code></pre>\n"
}
] | 2020/04/04 | [
"https://wordpress.stackexchange.com/questions/363193",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/185337/"
] | ```
function im_check_term($name,$tax){
$term = get_term_by("name", $name,$tax);
return !is_wp_error($term) ? $term->term_id : false;
}
```
Notice: Trying to get property of non-object in /home/pcodecom/demo.p30code.com/multimedia-2/wp-content/plugins/imdb/imdb.php on line 11 | `the_title` doesn't work that way:
```php
the_title( $before, $after, $echo );
```
`$before` is the text that comes before the title, but you didn't give it a string/text, you gave it a post object. Post objects aren't strings, PHP doesn't know what to do so it stops and prints an error instead.
For `the_title` to work, you need to setup the current postdata. Normally a standard loop does this by calling `the_post` on the query, but you've chosen to use `get_posts` instead.
This is what a standard post `WP_Query` post loop should look like:
```php
$query = new WP_Query([ ... ]);
if ( $query->have_posts() ) {
while( $query->have_posts() ) {
$query->the_post();
//.... display post here
}
wp_reset_postdata();
}
``` |
363,233 | <p>I am PHP newbie. I've got this code, and I want to pass global variable called $sum defined in function <code>post_order</code> to function <code>update_custom_meta</code>. Still no luck. What am I doing wrong?
Thank you in advance!</p>
<pre><code>function post_order() {
$args = array(
'type' => 'shop_order',
'status' => 'processing',//zmienić//zmienić na completed
'return' => 'ids',
'date_created' => ( date("F j, Y", strtotime( '-2 days' ) ) ),
);
$orders_ids = wc_get_orders( $args );
foreach ($orders_ids as $order_id) {
$order = new WC_Order( $order_id );
$items = $order->get_items();
global $sum;
foreach ( $items as $item ) {
$product_id = $item->get_product_id();
if($product_id == $_GET['post']) {
$product_qty = $item->get_quantity();
$sum += $product_qty;
}
}
}
}
add_action('init', 'post_order');
function update_custom_meta() {
global $post_id;
echo $sum;
$custom_value = $_POST['auto_restock_value'] - $sum;
update_post_meta($post_id, 'auto_restock_value', $custom_value);
//get_post_meta($post -> ID, 'daily_restock_amount', true);
update_post_meta($post_id, '_stock', $custom_value);
}
function update_cart_stock() {
global $post_id;
//echo get_post_meta($post_id, 'total_sales', true);
update_post_meta($post_id, '_stock', $custom_value);
}
add_action( 'save_post', 'update_custom_meta' , 10, 2 );
</code></pre>
| [
{
"answer_id": 363167,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p><code>the_title</code> doesn't work that way:</p>\n<pre class=\"lang-php prettyprint-override\"><code>the_title( $before, $after, $echo );\n</code></pre>\n<p><code>$before</code> is the text that comes before the title, but you didn't give it a string/text, you gave it a post object. Post objects aren't strings, PHP doesn't know what to do so it stops and prints an error instead.</p>\n<p>For <code>the_title</code> to work, you need to setup the current postdata. Normally a standard loop does this by calling <code>the_post</code> on the query, but you've chosen to use <code>get_posts</code> instead.</p>\n<p>This is what a standard post <code>WP_Query</code> post loop should look like:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$query = new WP_Query([ ... ]);\nif ( $query->have_posts() ) {\n while( $query->have_posts() ) {\n $query->the_post();\n //.... display post here\n }\n wp_reset_postdata();\n}\n</code></pre>\n"
},
{
"answer_id": 363168,
"author": "Neolot",
"author_id": 41273,
"author_profile": "https://wordpress.stackexchange.com/users/41273",
"pm_score": 0,
"selected": false,
"text": "<p>You are calling WordPress functions incorrectly. I fixed, try this code.</p>\n\n<pre><code><?php\n $time_now = date( \"g:i a\" );\n $shows = get_posts( array(\n 'post_type' => 'shows',\n 'meta_query' => array(\n array(\n 'key' => 'start_time',\n 'compare' => '<=',\n 'value' => $time_now,\n 'type' => 'DATETIME',\n ),\n array(\n 'key' => 'end_time',\n 'compare' => '<=',\n 'value' => $time_now,\n 'type' => 'DATETIME',\n )\n ),\n ) );\n\n if ( $shows ) :\n foreach ( $shows as $show ) :\n ?>\n\n <div class=\"onAir\">\n Currently On Air: <?php echo get_the_title($show->ID); ?>\n </div>\n\n <?php\n endforeach;\n wp_reset_postdata();\n endif;\n?>\n</code></pre>\n"
}
] | 2020/04/04 | [
"https://wordpress.stackexchange.com/questions/363233",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/184176/"
] | I am PHP newbie. I've got this code, and I want to pass global variable called $sum defined in function `post_order` to function `update_custom_meta`. Still no luck. What am I doing wrong?
Thank you in advance!
```
function post_order() {
$args = array(
'type' => 'shop_order',
'status' => 'processing',//zmienić//zmienić na completed
'return' => 'ids',
'date_created' => ( date("F j, Y", strtotime( '-2 days' ) ) ),
);
$orders_ids = wc_get_orders( $args );
foreach ($orders_ids as $order_id) {
$order = new WC_Order( $order_id );
$items = $order->get_items();
global $sum;
foreach ( $items as $item ) {
$product_id = $item->get_product_id();
if($product_id == $_GET['post']) {
$product_qty = $item->get_quantity();
$sum += $product_qty;
}
}
}
}
add_action('init', 'post_order');
function update_custom_meta() {
global $post_id;
echo $sum;
$custom_value = $_POST['auto_restock_value'] - $sum;
update_post_meta($post_id, 'auto_restock_value', $custom_value);
//get_post_meta($post -> ID, 'daily_restock_amount', true);
update_post_meta($post_id, '_stock', $custom_value);
}
function update_cart_stock() {
global $post_id;
//echo get_post_meta($post_id, 'total_sales', true);
update_post_meta($post_id, '_stock', $custom_value);
}
add_action( 'save_post', 'update_custom_meta' , 10, 2 );
``` | `the_title` doesn't work that way:
```php
the_title( $before, $after, $echo );
```
`$before` is the text that comes before the title, but you didn't give it a string/text, you gave it a post object. Post objects aren't strings, PHP doesn't know what to do so it stops and prints an error instead.
For `the_title` to work, you need to setup the current postdata. Normally a standard loop does this by calling `the_post` on the query, but you've chosen to use `get_posts` instead.
This is what a standard post `WP_Query` post loop should look like:
```php
$query = new WP_Query([ ... ]);
if ( $query->have_posts() ) {
while( $query->have_posts() ) {
$query->the_post();
//.... display post here
}
wp_reset_postdata();
}
``` |
363,284 | <h3>Edit:</h3>
<h3>Where are the Woocommerce blocks located in Woocommerce code on Github? Answer:</h3>
<h3>As the answer underneath mentions the Woocommerce Block is a package so it is not shown on Github for the Woocommerce library but is called from: <a href="https://github.com/woocommerce/woocommerce-gutenberg-products-block/tree/master/assets/js/blocks" rel="nofollow noreferrer">https://github.com/woocommerce/woocommerce-gutenberg-products-block/tree/master/assets/js/blocks</a></h3>
<br>
<hr />
<p>If you search for adding custom attributes for Woocommerce Blocks you find a lot of WordPress examples for this.</p>
<p>For example <a href="https://wordpress.stackexchange.com/a/339151/179478">this</a>, where the answer points out, that you can add attributes by using the <code>blocks.registerBlockType</code>. But how to do this for Woocommerce Blocks?</p>
<p>I want to be able to add a data field to the HTML output. The data field should then call a product attribute and show, if it exists.</p>
<p><strong>So when you use the Woocommerce Blocks on your front page - for example the size will be shown underneath the add to cart button - as in the image.</strong></p>
<p><a href="https://i.stack.imgur.com/L3Ncy.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L3Ncy.jpg" alt="enter image description here" /></a></p>
<p>As you might know the functionality of showing/hiding the price, add-to-cart-button, reviews are already there, when you choose a Woocommerce Block on the editing site.</p>
<p>But i havent't found the place where this functionality is created.</p>
<p><em>This would also be a great help actually - if you could show me <a href="https://github.com/woocommerce/woocommerce" rel="nofollow noreferrer">where in the Woocommerce Github library</a> the blocks are beying created. Maybe i can figure out my self how to filter through them and add the funcionality</em></p>
<p>I know - based on a Udemy course - how to create a custom plugin and create a new blog-type, save and edit.</p>
<p>But i need to figure out what Woocommerce namespace is, how they create their blocks, and what their data is called. The Woocommerce developer handbook is not saying anything about this - not what i've found.</p>
<p>I've been searching the internet for three days now, and I just don't understand that i can't seem to find ANYTHING on this. That nobody else wants to customize this functionality in Woocommerce. I know it is a new function (blocks) in the core, but still.</p>
<p>I just need to be pointed in the right direction.</p>
| [
{
"answer_id": 363800,
"author": "Himad",
"author_id": 158512,
"author_profile": "https://wordpress.stackexchange.com/users/158512",
"pm_score": 1,
"selected": false,
"text": "<p>Woocommerce blocks are located at <code>woocommerce/packages/woocommerce-blocks/assets/js/blocks</code>.</p>\n\n<p>An example of how woocommerce registers the best-selling products block:</p>\n\n<pre><code>registerBlockType( 'woocommerce/product-best-sellers', {\n ...\n} );\n</code></pre>\n\n<p>As you can see, the namespace is just <code>woocommerce</code>. </p>\n\n<p>I didn't understand what you want to achieve with the custom data field. Could you explain it better?</p>\n"
},
{
"answer_id": 375764,
"author": "helgatheviking",
"author_id": 6477,
"author_profile": "https://wordpress.stackexchange.com/users/6477",
"pm_score": 2,
"selected": false,
"text": "<p>As the blocks more more and more to front-end rendering... there's only one filter that I've been able to find for modifying the output of the blocks via PHP. <a href=\"https://github.com/woocommerce/woocommerce-gutenberg-products-block/blob/b841c53f7ec0aa01ad4cd7f0f8f1e2d338708d9b/src/BlockTypes/AbstractProductGrid.php#L329\" rel=\"nofollow noreferrer\"><code>woocommerce_blocks_product_grid_item_html</code></a> and I'm not even sure if that will work on the All Products block which may/may not use the same code as the other products list blocks.</p>\n<p>Here's an example that 1. removes the link and 2. adds the product's short description:</p>\n<pre><code>/**\n * Add short descriptions\n *\n * @param string $html\n * @param object $data\n * @param WC_Product $product\n * @return string\n */\nfunction kia_blocks_product_grid_item_html( $html, $data, $product ) {\n $short_description = $product->get_short_description() ? '<div class="wp-block-grid__short-description">' . wc_format_content( $product->get_short_description() ) . ' </div>' : '';\n\n return \n "<li class=\\"wc-block-grid__product\\">\n {$data->image}\n {$data->title}\n {$data->badge}\n {$data->price}\n {$data->rating}" .\n\n $short_description\n\n . "{$data->button}\n </li>";\n}\nadd_filter( 'woocommerce_blocks_product_grid_item_html', 'kia_blocks_product_grid_item_html', 10, 3 );\n</code></pre>\n"
}
] | 2020/04/05 | [
"https://wordpress.stackexchange.com/questions/363284",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/179478/"
] | ### Edit:
### Where are the Woocommerce blocks located in Woocommerce code on Github? Answer:
### As the answer underneath mentions the Woocommerce Block is a package so it is not shown on Github for the Woocommerce library but is called from: <https://github.com/woocommerce/woocommerce-gutenberg-products-block/tree/master/assets/js/blocks>
---
If you search for adding custom attributes for Woocommerce Blocks you find a lot of WordPress examples for this.
For example [this](https://wordpress.stackexchange.com/a/339151/179478), where the answer points out, that you can add attributes by using the `blocks.registerBlockType`. But how to do this for Woocommerce Blocks?
I want to be able to add a data field to the HTML output. The data field should then call a product attribute and show, if it exists.
**So when you use the Woocommerce Blocks on your front page - for example the size will be shown underneath the add to cart button - as in the image.**
[](https://i.stack.imgur.com/L3Ncy.jpg)
As you might know the functionality of showing/hiding the price, add-to-cart-button, reviews are already there, when you choose a Woocommerce Block on the editing site.
But i havent't found the place where this functionality is created.
*This would also be a great help actually - if you could show me [where in the Woocommerce Github library](https://github.com/woocommerce/woocommerce) the blocks are beying created. Maybe i can figure out my self how to filter through them and add the funcionality*
I know - based on a Udemy course - how to create a custom plugin and create a new blog-type, save and edit.
But i need to figure out what Woocommerce namespace is, how they create their blocks, and what their data is called. The Woocommerce developer handbook is not saying anything about this - not what i've found.
I've been searching the internet for three days now, and I just don't understand that i can't seem to find ANYTHING on this. That nobody else wants to customize this functionality in Woocommerce. I know it is a new function (blocks) in the core, but still.
I just need to be pointed in the right direction. | As the blocks more more and more to front-end rendering... there's only one filter that I've been able to find for modifying the output of the blocks via PHP. [`woocommerce_blocks_product_grid_item_html`](https://github.com/woocommerce/woocommerce-gutenberg-products-block/blob/b841c53f7ec0aa01ad4cd7f0f8f1e2d338708d9b/src/BlockTypes/AbstractProductGrid.php#L329) and I'm not even sure if that will work on the All Products block which may/may not use the same code as the other products list blocks.
Here's an example that 1. removes the link and 2. adds the product's short description:
```
/**
* Add short descriptions
*
* @param string $html
* @param object $data
* @param WC_Product $product
* @return string
*/
function kia_blocks_product_grid_item_html( $html, $data, $product ) {
$short_description = $product->get_short_description() ? '<div class="wp-block-grid__short-description">' . wc_format_content( $product->get_short_description() ) . ' </div>' : '';
return
"<li class=\"wc-block-grid__product\">
{$data->image}
{$data->title}
{$data->badge}
{$data->price}
{$data->rating}" .
$short_description
. "{$data->button}
</li>";
}
add_filter( 'woocommerce_blocks_product_grid_item_html', 'kia_blocks_product_grid_item_html', 10, 3 );
``` |
363,310 | <p>I'm writing a function in functions.php. I am working with woocommerce and trying to get posts with the same cat name of product_cat on single product pages. My idea is using the cat name of woocommerce cat and get_cat_ID() to get the category ID, then use WP_query to get the posts. However, get_cat_ID() always returns 0 (I event create a category called 'test', but still). Tried to google the problem but no solution. get_cat_ID() seems to be really straightforward so I am really not sure what went wrong. It would be great if anyone can let me know what would be the possible reason.</p>
<p>To sum up my problem: I have a product_cat named 'test'. Now I want to get the ID of the category with the same name 'test'.</p>
<p>Here's the code:</p>
<pre><code>$cate_object = get_the_terms( $post->ID, 'product_cat' );
foreach( $cate_object as $cate ){
// get cat id by tax name
$thisCatName = $cate->name;
$thisCatID = get_cat_ID($thisCatName);
if($thisCat !== null && $thisCat != 0)
$cat_array[] = $thisCatID;
}
</code></pre>
<p>Thanks!</p>
| [
{
"answer_id": 363316,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p><code>get_cat_ID</code> gets the ID of a <em>category</em> based on the name. \"Category\" is a specific taxonomy named <code>category</code>. You're trying to get the ID of a <em>Product Category</em> (<code>product_cat</code>). You cannot use <code>get_cat_ID()</code> to get the ID of a custom taxonomy.</p>\n\n<p>To do that you need to use <code>get_term_by()</code>:</p>\n\n<pre><code>$product_cat = get_term_by( 'name', $cat_name, 'product_cat' );\n\nif ( $product_cat ) {\n $thisCatID = $product_cat->term_id;\n}\n</code></pre>\n\n<p><em>But</em>, based on your code, you don't need to be finding the ID. You already have it:</p>\n\n<pre><code>$cate_object = get_the_terms( $post->ID, 'product_cat' );\nforeach( $cate_object as $cate ){\n $thisCatID = $cate->term_id; // This is the ID.\n\n $cat_array[] = $thisCatID;\n}\n</code></pre>\n"
},
{
"answer_id": 363803,
"author": "Wei",
"author_id": 185488,
"author_profile": "https://wordpress.stackexchange.com/users/185488",
"pm_score": 2,
"selected": true,
"text": "<p>For people who has the same problem: \nI think the problem is caused by Polylang. I checked my category list on dashboard, and realized that the category I failed to get with get_cat_ID() doesn't belong to any language (which is weird). I created a test category and give assign a language to it, then get_cat_ID() works!</p>\n\n<p>Thanks to people who tried to help out!</p>\n"
}
] | 2020/04/05 | [
"https://wordpress.stackexchange.com/questions/363310",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/185488/"
] | I'm writing a function in functions.php. I am working with woocommerce and trying to get posts with the same cat name of product\_cat on single product pages. My idea is using the cat name of woocommerce cat and get\_cat\_ID() to get the category ID, then use WP\_query to get the posts. However, get\_cat\_ID() always returns 0 (I event create a category called 'test', but still). Tried to google the problem but no solution. get\_cat\_ID() seems to be really straightforward so I am really not sure what went wrong. It would be great if anyone can let me know what would be the possible reason.
To sum up my problem: I have a product\_cat named 'test'. Now I want to get the ID of the category with the same name 'test'.
Here's the code:
```
$cate_object = get_the_terms( $post->ID, 'product_cat' );
foreach( $cate_object as $cate ){
// get cat id by tax name
$thisCatName = $cate->name;
$thisCatID = get_cat_ID($thisCatName);
if($thisCat !== null && $thisCat != 0)
$cat_array[] = $thisCatID;
}
```
Thanks! | For people who has the same problem:
I think the problem is caused by Polylang. I checked my category list on dashboard, and realized that the category I failed to get with get\_cat\_ID() doesn't belong to any language (which is weird). I created a test category and give assign a language to it, then get\_cat\_ID() works!
Thanks to people who tried to help out! |
363,479 | <p>I need an unordered list, but with options selected for each list item. To achieve this I've created a custom block called icon-list which is a <code>ul</code> element with InnerBlocks, which allows only my custom icon-list-item block as a child. My icon-list-item block is just a RichText element with <code>tagName: li</code> and some controls. This all works fine, but currently pressing the enter key adds a line break to the current icon-list-item block - what I'd really like is for the enter key to insert a new icon-list-item block. Similarly pressing the backspace key when at the start of a icon-list-item block should remove that block - the exact same functionality of the core/list block.</p>
<p>I've had a dig through the Gutenberg docs and source and found that I need to implement the onSplit and onReplace properties for my RichText element, but it's not clear to me how I actually do this. So far I have:</p>
<pre><code>el(RichText, {
tagName : 'li',
className : 'icon--' + props.attributes.icon,
value : props.attributes.content,
placeholder : props.attributes.placeholder,
onChange : function(value) {
props.setAttributes({ content: value })
},
onSplit : function(value) {
if (!value) {
return createBlock('tutti/icon-list-item');
}
return createBlock('tutti/icon-list-item', {
...props.attributes,
content: value,
}
},
onReplace : function() {
// something
}
})
</code></pre>
<p>... obviously I'm completely lost when it comes to the onReplace function. Any pointers would be very much appreciated!</p>
| [
{
"answer_id": 363316,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p><code>get_cat_ID</code> gets the ID of a <em>category</em> based on the name. \"Category\" is a specific taxonomy named <code>category</code>. You're trying to get the ID of a <em>Product Category</em> (<code>product_cat</code>). You cannot use <code>get_cat_ID()</code> to get the ID of a custom taxonomy.</p>\n\n<p>To do that you need to use <code>get_term_by()</code>:</p>\n\n<pre><code>$product_cat = get_term_by( 'name', $cat_name, 'product_cat' );\n\nif ( $product_cat ) {\n $thisCatID = $product_cat->term_id;\n}\n</code></pre>\n\n<p><em>But</em>, based on your code, you don't need to be finding the ID. You already have it:</p>\n\n<pre><code>$cate_object = get_the_terms( $post->ID, 'product_cat' );\nforeach( $cate_object as $cate ){\n $thisCatID = $cate->term_id; // This is the ID.\n\n $cat_array[] = $thisCatID;\n}\n</code></pre>\n"
},
{
"answer_id": 363803,
"author": "Wei",
"author_id": 185488,
"author_profile": "https://wordpress.stackexchange.com/users/185488",
"pm_score": 2,
"selected": true,
"text": "<p>For people who has the same problem: \nI think the problem is caused by Polylang. I checked my category list on dashboard, and realized that the category I failed to get with get_cat_ID() doesn't belong to any language (which is weird). I created a test category and give assign a language to it, then get_cat_ID() works!</p>\n\n<p>Thanks to people who tried to help out!</p>\n"
}
] | 2020/04/07 | [
"https://wordpress.stackexchange.com/questions/363479",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/38894/"
] | I need an unordered list, but with options selected for each list item. To achieve this I've created a custom block called icon-list which is a `ul` element with InnerBlocks, which allows only my custom icon-list-item block as a child. My icon-list-item block is just a RichText element with `tagName: li` and some controls. This all works fine, but currently pressing the enter key adds a line break to the current icon-list-item block - what I'd really like is for the enter key to insert a new icon-list-item block. Similarly pressing the backspace key when at the start of a icon-list-item block should remove that block - the exact same functionality of the core/list block.
I've had a dig through the Gutenberg docs and source and found that I need to implement the onSplit and onReplace properties for my RichText element, but it's not clear to me how I actually do this. So far I have:
```
el(RichText, {
tagName : 'li',
className : 'icon--' + props.attributes.icon,
value : props.attributes.content,
placeholder : props.attributes.placeholder,
onChange : function(value) {
props.setAttributes({ content: value })
},
onSplit : function(value) {
if (!value) {
return createBlock('tutti/icon-list-item');
}
return createBlock('tutti/icon-list-item', {
...props.attributes,
content: value,
}
},
onReplace : function() {
// something
}
})
```
... obviously I'm completely lost when it comes to the onReplace function. Any pointers would be very much appreciated! | For people who has the same problem:
I think the problem is caused by Polylang. I checked my category list on dashboard, and realized that the category I failed to get with get\_cat\_ID() doesn't belong to any language (which is weird). I created a test category and give assign a language to it, then get\_cat\_ID() works!
Thanks to people who tried to help out! |
363,641 | <p>I have a custom menu on a wordpress + woocommerce site using the Walker_Nav_Menu class. When hiding posts (products) from the site those posts and category are still included in the custom menu.
I would like to know how to remove either the specific product posts from this menu, for e.g. post ID = 6927 - or to remove the category (and the products therein) from this menu, for e.g. category ID = 41.The category I want to hide is "End of range" in this image:</p>
<p><a href="https://i.stack.imgur.com/5SVm4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5SVm4.png" alt="screengrab of custom menu"></a></p>
<p>I have tried many solutions over the past 2 days without success:</p>
<p>1)</p>
<pre><code>function wpse31748_exclude_menu_items( $items, $menu, $args ) {
// Iterate over the items to search and destroy
foreach ( $items as $key => $item ) {
if ( $item->object_id == 6927 ) unset( $items[$key] );
}
return $items;
}
add_filter( 'wp_get_nav_menu_items', 'wpse31748_exclude_menu_items', null, 3 );
</code></pre>
<p>and different variations of above.</p>
<p>I'm not sure if I'm completely off track but I thought updating the file template-parts/modules/module-category-menu.php to exclude the category may work, here is the contents of that file: </p>
<pre><code><?php
$orderby = 'date';
$order = 'desc';
$hide_empty = true ;
$cat_args = array(
'orderby' => $orderby,
'order' => $order,
'hide_empty' => $hide_empty,
);
$product_categories = get_terms( 'product_cat', $cat_args );
if( !empty($product_categories)) :
?>
<div class="row">
<div class="col-12 sec-menu">
<ul class=" nav nav-justified" id="sec-menu">
<?php
foreach ($product_categories as $key => $category):
?>
<li class="nav-item">
<h2>
<a class="nav-link collapsed top-menu" href="#cat<?php echo $category->term_id; ?>" data-toggle="collapse" data-target="#cat<?php echo $category->term_id; ?>">
<?php echo $category->name; ?>
</a>
</h2>
<?php
$args = array(
'posts_per_page' => '-1',
'post_type' => 'product',
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'asc',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'terms' => array($category->term_id),
'operator' => 'IN'
),
)
);
$products = new WP_Query($args);
if($products->have_posts()):
?>
<div class="collapse sub-menu" id="cat<?php echo $category->term_id; ?>" aria-expanded="false" data-parent="#sec-menu">
<ul class="flex-column nav">
<?php
while($products->have_posts()):
$products->the_post();
?>
<li class="nav-item">
<a class="nav-link sub-link" href="<?php the_permalink();?>" title="<?php the_title(); ?>">
<span><?php the_title(); ?></span>
</a>
</li>
<?php
endwhile;
wp_reset_query();
?>
</ul>
</div>
<?php
endif;
?>
</li>
<?php
endforeach;
?>
</ul>
</div>
</div>
<?php
endif;
?>
</code></pre>
<p>Any help is greatly appreciated.</p>
<p><strong>EDIT</strong>
Here is the Walker_Nav_Menu class from the functions.php file: </p>
<pre><code>class Custom_Foundation_Nav_Menu extends Walker_Nav_Menu
{
private $curItem;
function display_element($element, &$children_elements, $max_depth, $depth = 0, $args, &$output)
{
$element->hasChildren = isset($children_elements[$element->ID]) && !empty($children_elements[$element->ID]);
return parent::display_element($element, $children_elements, $max_depth, $depth, $args, $output);
}
function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0)
{
global $wp_query;
$new_class = array();
$this->curItem = $item;
$indent = ($depth) ? str_repeat("\t", $depth) : '';
$class_names = $value = '';
$classes = empty($item->classes) ? array() : (array) $item->classes;
$new_class[] = 'nav-item';
if (in_array('current-menu-item', $classes) || in_array('current-menu-ancestor', $classes)) {
$new_class[] = 'active';
}
if ($item->hasChildren) {
$add_sub_class = 'nav-link collapsed';
} else {
$add_sub_class = 'nav-link';
}
if ($depth > 0) {
$add_sub_class .= ' sub-link ';
}
$new_class = implode(' ', $new_class);
// echo $new_class;
$class_names = join(' ', apply_filters('nav_menu_css_class', array_filter($classes), $item));
$class_names = ' class="' . $new_class . ' ' . $class_names . '"';
$class_names = trim($class_names);
$output .= $indent . '<li id="menu-item-' . $item->ID . '" ' . $value . $class_names . '>';
$attributes = !empty($item->attr_title) ? ' title="' . esc_attr($item->attr_title) . '" ' : '';
if ($item->hasChildren && !is_page(6927)) {
$attributes .= ' href="#submenu' . $item->ID . '" ';
$attributes .= ' data-toggle="collapse" ';
$attributes .= ' data-target="#submenu' . $item->ID . '" ';
} else {
$attributes .= !empty($item->url) ? ' href="' . esc_attr($item->url) . '" ' : '';
}
$attributes .= !empty($add_sub_class) ? ' class="' . $add_sub_class . '" ' : '';
$item_output = $args->before;
$item_output .= '<a' . $attributes . ' ><span data-hover="' . $args->link_before . apply_filters('the_title', $item->title, $item->ID) . '">';
$item_output .= $args->link_before . apply_filters('the_title', $item->title, $item->ID);
$item_output .= '</span></a>';
$item_output .= $args->after;
$output .= apply_filters('walker_nav_menu_start_el', $item_output, $item, $depth, $args);
}
function start_lvl(&$output, $depth = 0, $args = array())
{
global $wp_query;
$thisItem = $this->curItem;
$indent = str_repeat("\t", $depth);
$output .= "\n$indent<div class='collapse' id='submenu$thisItem->ID' aria-expanded='false'><ul id='submenu-$thisItem->ID' class='flex-column nav sub-nav'>\n";
}
}
</code></pre>
| [
{
"answer_id": 363316,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p><code>get_cat_ID</code> gets the ID of a <em>category</em> based on the name. \"Category\" is a specific taxonomy named <code>category</code>. You're trying to get the ID of a <em>Product Category</em> (<code>product_cat</code>). You cannot use <code>get_cat_ID()</code> to get the ID of a custom taxonomy.</p>\n\n<p>To do that you need to use <code>get_term_by()</code>:</p>\n\n<pre><code>$product_cat = get_term_by( 'name', $cat_name, 'product_cat' );\n\nif ( $product_cat ) {\n $thisCatID = $product_cat->term_id;\n}\n</code></pre>\n\n<p><em>But</em>, based on your code, you don't need to be finding the ID. You already have it:</p>\n\n<pre><code>$cate_object = get_the_terms( $post->ID, 'product_cat' );\nforeach( $cate_object as $cate ){\n $thisCatID = $cate->term_id; // This is the ID.\n\n $cat_array[] = $thisCatID;\n}\n</code></pre>\n"
},
{
"answer_id": 363803,
"author": "Wei",
"author_id": 185488,
"author_profile": "https://wordpress.stackexchange.com/users/185488",
"pm_score": 2,
"selected": true,
"text": "<p>For people who has the same problem: \nI think the problem is caused by Polylang. I checked my category list on dashboard, and realized that the category I failed to get with get_cat_ID() doesn't belong to any language (which is weird). I created a test category and give assign a language to it, then get_cat_ID() works!</p>\n\n<p>Thanks to people who tried to help out!</p>\n"
}
] | 2020/04/09 | [
"https://wordpress.stackexchange.com/questions/363641",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/176497/"
] | I have a custom menu on a wordpress + woocommerce site using the Walker\_Nav\_Menu class. When hiding posts (products) from the site those posts and category are still included in the custom menu.
I would like to know how to remove either the specific product posts from this menu, for e.g. post ID = 6927 - or to remove the category (and the products therein) from this menu, for e.g. category ID = 41.The category I want to hide is "End of range" in this image:
[](https://i.stack.imgur.com/5SVm4.png)
I have tried many solutions over the past 2 days without success:
1)
```
function wpse31748_exclude_menu_items( $items, $menu, $args ) {
// Iterate over the items to search and destroy
foreach ( $items as $key => $item ) {
if ( $item->object_id == 6927 ) unset( $items[$key] );
}
return $items;
}
add_filter( 'wp_get_nav_menu_items', 'wpse31748_exclude_menu_items', null, 3 );
```
and different variations of above.
I'm not sure if I'm completely off track but I thought updating the file template-parts/modules/module-category-menu.php to exclude the category may work, here is the contents of that file:
```
<?php
$orderby = 'date';
$order = 'desc';
$hide_empty = true ;
$cat_args = array(
'orderby' => $orderby,
'order' => $order,
'hide_empty' => $hide_empty,
);
$product_categories = get_terms( 'product_cat', $cat_args );
if( !empty($product_categories)) :
?>
<div class="row">
<div class="col-12 sec-menu">
<ul class=" nav nav-justified" id="sec-menu">
<?php
foreach ($product_categories as $key => $category):
?>
<li class="nav-item">
<h2>
<a class="nav-link collapsed top-menu" href="#cat<?php echo $category->term_id; ?>" data-toggle="collapse" data-target="#cat<?php echo $category->term_id; ?>">
<?php echo $category->name; ?>
</a>
</h2>
<?php
$args = array(
'posts_per_page' => '-1',
'post_type' => 'product',
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'asc',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'terms' => array($category->term_id),
'operator' => 'IN'
),
)
);
$products = new WP_Query($args);
if($products->have_posts()):
?>
<div class="collapse sub-menu" id="cat<?php echo $category->term_id; ?>" aria-expanded="false" data-parent="#sec-menu">
<ul class="flex-column nav">
<?php
while($products->have_posts()):
$products->the_post();
?>
<li class="nav-item">
<a class="nav-link sub-link" href="<?php the_permalink();?>" title="<?php the_title(); ?>">
<span><?php the_title(); ?></span>
</a>
</li>
<?php
endwhile;
wp_reset_query();
?>
</ul>
</div>
<?php
endif;
?>
</li>
<?php
endforeach;
?>
</ul>
</div>
</div>
<?php
endif;
?>
```
Any help is greatly appreciated.
**EDIT**
Here is the Walker\_Nav\_Menu class from the functions.php file:
```
class Custom_Foundation_Nav_Menu extends Walker_Nav_Menu
{
private $curItem;
function display_element($element, &$children_elements, $max_depth, $depth = 0, $args, &$output)
{
$element->hasChildren = isset($children_elements[$element->ID]) && !empty($children_elements[$element->ID]);
return parent::display_element($element, $children_elements, $max_depth, $depth, $args, $output);
}
function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0)
{
global $wp_query;
$new_class = array();
$this->curItem = $item;
$indent = ($depth) ? str_repeat("\t", $depth) : '';
$class_names = $value = '';
$classes = empty($item->classes) ? array() : (array) $item->classes;
$new_class[] = 'nav-item';
if (in_array('current-menu-item', $classes) || in_array('current-menu-ancestor', $classes)) {
$new_class[] = 'active';
}
if ($item->hasChildren) {
$add_sub_class = 'nav-link collapsed';
} else {
$add_sub_class = 'nav-link';
}
if ($depth > 0) {
$add_sub_class .= ' sub-link ';
}
$new_class = implode(' ', $new_class);
// echo $new_class;
$class_names = join(' ', apply_filters('nav_menu_css_class', array_filter($classes), $item));
$class_names = ' class="' . $new_class . ' ' . $class_names . '"';
$class_names = trim($class_names);
$output .= $indent . '<li id="menu-item-' . $item->ID . '" ' . $value . $class_names . '>';
$attributes = !empty($item->attr_title) ? ' title="' . esc_attr($item->attr_title) . '" ' : '';
if ($item->hasChildren && !is_page(6927)) {
$attributes .= ' href="#submenu' . $item->ID . '" ';
$attributes .= ' data-toggle="collapse" ';
$attributes .= ' data-target="#submenu' . $item->ID . '" ';
} else {
$attributes .= !empty($item->url) ? ' href="' . esc_attr($item->url) . '" ' : '';
}
$attributes .= !empty($add_sub_class) ? ' class="' . $add_sub_class . '" ' : '';
$item_output = $args->before;
$item_output .= '<a' . $attributes . ' ><span data-hover="' . $args->link_before . apply_filters('the_title', $item->title, $item->ID) . '">';
$item_output .= $args->link_before . apply_filters('the_title', $item->title, $item->ID);
$item_output .= '</span></a>';
$item_output .= $args->after;
$output .= apply_filters('walker_nav_menu_start_el', $item_output, $item, $depth, $args);
}
function start_lvl(&$output, $depth = 0, $args = array())
{
global $wp_query;
$thisItem = $this->curItem;
$indent = str_repeat("\t", $depth);
$output .= "\n$indent<div class='collapse' id='submenu$thisItem->ID' aria-expanded='false'><ul id='submenu-$thisItem->ID' class='flex-column nav sub-nav'>\n";
}
}
``` | For people who has the same problem:
I think the problem is caused by Polylang. I checked my category list on dashboard, and realized that the category I failed to get with get\_cat\_ID() doesn't belong to any language (which is weird). I created a test category and give assign a language to it, then get\_cat\_ID() works!
Thanks to people who tried to help out! |
363,650 | <p>I am using Code Snippets plugins, that allow create shortcodes from the Wordpress Admin panel. I am using a simple shortcode to print some info and works great. Anyway, I want make this add some info if the parameter 'error' is in the url.</p>
<p>To make this, I am doing this:</p>
<pre><code>add_shortcode( 'my_shortcode', function () {
$out = '';
print_r($_GET); //--> prints Array ( )
if(isset($_GET['error'])){
$out .='<div id="login_error">El usuario o contraseña no es correcto.</div>';
}
$out .='HTML info';
return $out;
} );
</code></pre>
<p>Anyway, my URL is <a href="http://localhost/login/?error=true" rel="nofollow noreferrer">http://localhost/login/?error=true</a> and I think this should be working. Some idea about this problem?</p>
| [
{
"answer_id": 363702,
"author": "user1422434",
"author_id": 52814,
"author_profile": "https://wordpress.stackexchange.com/users/52814",
"pm_score": 2,
"selected": true,
"text": "<p>reading about this type of problems (because my template wasn't the problem) and it's a fresh installation. I read that wordpress recommends the use of <code>$_REQUEST</code> instead <code>$_GET</code> (Anyway I see that other people can use <code>$_GET</code> without problems) and tried with <code>$_REQUEST</code>, now it's working.</p>\n"
},
{
"answer_id": 363712,
"author": "Stoian Delev",
"author_id": 185752,
"author_profile": "https://wordpress.stackexchange.com/users/185752",
"pm_score": 2,
"selected": false,
"text": "<p>$_GET is a glob var. which is triger/created when you're sending html form data og visit a link. When is send from form you can add the needet info in \"action\" atr. But from youre example i see onlu that you return from the function some string...did not see the part of adding it to the $_GET...</p>\n\n<p>as sugested up you can use $_REQUEST[\"GET\"] or $_SERVER['REQUEST_METHOD'] allso</p>\n\n<p>lets roll back a sec. - you need to add some extra data to the get requst if have some specific condition ( 'error )and the what??? for example :</p>\n\n<p>This directly will add data to url and redirect to da location, do proper escaping..this is example</p>\n\n<p>function get_server_info(){</p>\n\n<pre><code>$server = array();\nif(isset($_SERVER['REMOTE_ADDR'])){\n $server[\"ip\"] = $_SERVER['REMOTE_ADDR'];\n}else{ $server[\"ip\"] = false; }\n\nif(isset($_SERVER['HTTP_HOST'])){\n $server[\"host\"] = $_SERVER['HTTP_HOST'];\n}else{ $server[\"host\"] = false; }\n\nif(isset($_SERVER['QUERY_STRING'])){\n $server[\"query\"] = $_SERVER['QUERY_STRING'];\n}else{ $server[\"query\"] = false; }\n\nif(isset($_SERVER['HTTP_REFERER'])){\n $server[\"from\"] = $_SERVER['HTTP_REFERER']; \n}else{ $server[\"from\"] = false; }\n\nif(isset($_SERVER[\"REQUEST_URI\"])){\n $server[\"requested\"] = $_SERVER[\"REQUEST_URI\"];\n}else{ $server[\"requested\"] = false; }\n\nreturn $server;\n</code></pre>\n\n<p>}</p>\n\n<p>function redirect_to($location,$content = \"text/html\"){</p>\n\n<pre><code>header(\"Location: \".$location);\nheader(\"Content-Type: \".$content);\nexit;\n</code></pre>\n\n<p>}</p>\n\n<p>this should redirect you to the original intendet location whit extra url data\n somthing like this</p>\n\n<p>function add_to_url(){</p>\n\n<p>$server = get_server_info();</p>\n\n<p>if( youre condition ){</p>\n\n<pre><code> $to_add ='<div id=\"login_error\">El usuario o contraseña no es correcto. \n </div>';\n\n $redirect_to = $server[\"requested\"].\"&\".$to_add;\n\n redirect_to( $redirect_to);\n</code></pre>\n\n<p>}</p>\n\n<p>} </p>\n"
}
] | 2020/04/09 | [
"https://wordpress.stackexchange.com/questions/363650",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/52814/"
] | I am using Code Snippets plugins, that allow create shortcodes from the Wordpress Admin panel. I am using a simple shortcode to print some info and works great. Anyway, I want make this add some info if the parameter 'error' is in the url.
To make this, I am doing this:
```
add_shortcode( 'my_shortcode', function () {
$out = '';
print_r($_GET); //--> prints Array ( )
if(isset($_GET['error'])){
$out .='<div id="login_error">El usuario o contraseña no es correcto.</div>';
}
$out .='HTML info';
return $out;
} );
```
Anyway, my URL is <http://localhost/login/?error=true> and I think this should be working. Some idea about this problem? | reading about this type of problems (because my template wasn't the problem) and it's a fresh installation. I read that wordpress recommends the use of `$_REQUEST` instead `$_GET` (Anyway I see that other people can use `$_GET` without problems) and tried with `$_REQUEST`, now it's working. |
363,652 | <p>Every page on the admin dashboard is looking like this -- with "dead/empty" notification leftovers we cannot get rid of. NO new plugin was added and no plug-in update was made. Our code doesn't touch any admin page. </p>
<p>Is there any database table I can "zap" or drain to allow us to get rid of this annoying effect.</p>
<p><strong>The admin pages still function</strong> -- we just have to scroll down to get to the actual content. This is an annoyance -- but we'd like to get rid of it. </p>
<p><a href="https://i.stack.imgur.com/mbWMT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mbWMT.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 364176,
"author": "uPrompt",
"author_id": 155077,
"author_profile": "https://wordpress.stackexchange.com/users/155077",
"pm_score": 0,
"selected": false,
"text": "<p>Can't post a comment so here goes.</p>\n\n<p>If you're not into writing or debugging code I'd try this:</p>\n\n<p>Search the WordPress site for a plugin called \"Disable admin notices individually\". Whenever an admin notice pops up, you can disable it. While this plugin doesn't fix the root cause of the problem, it does seem to hide it under a rock so you don't see it.</p>\n\n<p>I do want to point out that if you've updated WordPress but haven't updated plugins, that may be the problem.</p>\n"
},
{
"answer_id": 364207,
"author": "wpnovice",
"author_id": 185893,
"author_profile": "https://wordpress.stackexchange.com/users/185893",
"pm_score": 0,
"selected": false,
"text": "<p>Here's a workaround with jQuery. \nAdd this to your functions.php in the active theme folder</p>\n\n<pre><code>function enqueue_my_scripts_hide_warnings() {\n?>\n<script>\njQuery(document).ready(function(){\n jQuery('.notice-info').each(function(){\n if(!jQuery(this).text()){\n jQuery(this).hide();\n }\n })\n jQuery('.notice-warning').each(function(){\n if(!jQuery(this).text()){\n jQuery(this).hide();\n }\n })\n});\n</script>\n<?php\n\n} \nadd_action( 'admin_footer', 'enqueue_my_scripts_hide_warnings' );\n</code></pre>\n\n<p>If that selector doesn't work, just replace line 5-9 with this below. However the selector may be too wide, so use with caution. May have to tweak the selector depending on how your admin pages work.</p>\n\n<pre><code> jQuery('.notice').each(function(){\n if(!jQuery(this).text()){\n jQuery(this).hide();\n }\n })\n</code></pre>\n"
},
{
"answer_id": 364221,
"author": "Daniel Simmons",
"author_id": 185900,
"author_profile": "https://wordpress.stackexchange.com/users/185900",
"pm_score": 4,
"selected": true,
"text": "<p>Let's take a look at <code>admin_notices</code>, since that's where your output is.</p>\n\n<p><a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/admin-header.php#L281\" rel=\"noreferrer\">https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/admin-header.php#L281</a></p>\n\n<p>So, it's simply just an action-as-an-output-spot, what this means is that if you wish, you can output anything here and most importantly, this all happens in-memory, so, debugging should be pretty straight-forward; this spot is meant to output things. That's it.</p>\n\n<p>Unless you're using a wrapper around this action such as <a href=\"https://github.com/WPTRT/admin-notices\" rel=\"noreferrer\">https://github.com/WPTRT/admin-notices</a> that allows you write your code cleaner (but this still uses the <code>admin_notices</code> action inside), you'll be doing something like <code>add_action( 'admin_notices', function() { echo 'My notification!' } )</code></p>\n\n<p>...and so will any other package that allows you to push these notifications out.</p>\n\n<p>Knowing the following variables: in-memory, actions, we can attempt to see what's going out in there. You can write your own <code>action inspection engine</code> or, you can use someone else's:</p>\n\n<p><a href=\"https://wordpress.org/plugins/query-monitor/\" rel=\"noreferrer\">https://wordpress.org/plugins/query-monitor/</a></p>\n\n<p>Now, if we are to Go to our Dashboard > Open the Query Monitor Panel (it's in the top, sticky WP bar) > Access \"Hooks & Actions\" > Search for <code>admin_notices</code>, we'll be prompted with a screen like this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/lvYzm.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/lvYzm.png\" alt=\"All actions hooking to <code>admin_notices</code>\"></a></p>\n\n<p>In here, we can see exactly what's hooked to this action and their priority, so, let's try to replicate your issue. Let's create some empty notifications and output them:</p>\n\n<pre><code>add_action( 'admin_notices', function() {\n $class = 'notice notice-error';\n\n printf( '<div class=\"%1$s\"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );\n printf( '<div class=\"%1$s\"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );\n printf( '<div class=\"%1$s\"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );\n printf( '<div class=\"%1$s\"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );\n printf( '<div class=\"%1$s\"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );\n}, 15 );\n</code></pre>\n\n<p>Great, and let's see how our dashboard looks now:</p>\n\n<p><a href=\"https://i.stack.imgur.com/yUKV9.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/yUKV9.png\" alt=\"Dashboard with error code in\"></a></p>\n\n<p>Oof. <strong>It's broken, just like yours is</strong>. But what does the image tell us? Well, it says that inside the theme, coming from a closure, within <code>functions.php</code> on line <code>87</code>, there are some notifications that it's trying to output.</p>\n\n<p>Do this for your case and try to see which one is having issues.</p>\n\n<hr>\n\n<p>Although a bit out of scope, or rather, comprising a larger scope, at times, I really wish you could get the <code>return value</code> of a hook. Your case is the prime example of inspecting how the data flows within actions isn't as easy to do, don't get me wrong, it's still possible, but requires quite some work to take care of everything and I gave up mid-way myself. In other words, wouldn't it be cool to say <code>Hey, WordPress, on action 'admin_notices', which one of the hooked functions returns an empty string or an error?</code>. Really saves you a lot of time.</p>\n"
}
] | 2020/04/09 | [
"https://wordpress.stackexchange.com/questions/363652",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/135990/"
] | Every page on the admin dashboard is looking like this -- with "dead/empty" notification leftovers we cannot get rid of. NO new plugin was added and no plug-in update was made. Our code doesn't touch any admin page.
Is there any database table I can "zap" or drain to allow us to get rid of this annoying effect.
**The admin pages still function** -- we just have to scroll down to get to the actual content. This is an annoyance -- but we'd like to get rid of it.
[](https://i.stack.imgur.com/mbWMT.png) | Let's take a look at `admin_notices`, since that's where your output is.
<https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/admin-header.php#L281>
So, it's simply just an action-as-an-output-spot, what this means is that if you wish, you can output anything here and most importantly, this all happens in-memory, so, debugging should be pretty straight-forward; this spot is meant to output things. That's it.
Unless you're using a wrapper around this action such as <https://github.com/WPTRT/admin-notices> that allows you write your code cleaner (but this still uses the `admin_notices` action inside), you'll be doing something like `add_action( 'admin_notices', function() { echo 'My notification!' } )`
...and so will any other package that allows you to push these notifications out.
Knowing the following variables: in-memory, actions, we can attempt to see what's going out in there. You can write your own `action inspection engine` or, you can use someone else's:
<https://wordpress.org/plugins/query-monitor/>
Now, if we are to Go to our Dashboard > Open the Query Monitor Panel (it's in the top, sticky WP bar) > Access "Hooks & Actions" > Search for `admin_notices`, we'll be prompted with a screen like this:
[](https://i.stack.imgur.com/lvYzm.png)
In here, we can see exactly what's hooked to this action and their priority, so, let's try to replicate your issue. Let's create some empty notifications and output them:
```
add_action( 'admin_notices', function() {
$class = 'notice notice-error';
printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );
printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );
printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );
printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );
printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );
}, 15 );
```
Great, and let's see how our dashboard looks now:
[](https://i.stack.imgur.com/yUKV9.png)
Oof. **It's broken, just like yours is**. But what does the image tell us? Well, it says that inside the theme, coming from a closure, within `functions.php` on line `87`, there are some notifications that it's trying to output.
Do this for your case and try to see which one is having issues.
---
Although a bit out of scope, or rather, comprising a larger scope, at times, I really wish you could get the `return value` of a hook. Your case is the prime example of inspecting how the data flows within actions isn't as easy to do, don't get me wrong, it's still possible, but requires quite some work to take care of everything and I gave up mid-way myself. In other words, wouldn't it be cool to say `Hey, WordPress, on action 'admin_notices', which one of the hooked functions returns an empty string or an error?`. Really saves you a lot of time. |
363,680 | <p>I'm currently styling my single.php file and for some reason when compiled the page completely skips the first tag yet prints everything else afterwards, including the <code><h1></code> tag in the first <code><div></code>. The only fix I have produced at the moment is placing a blank <code><div></code> tag before <code><div class="page-header mb-5"></code> in order to print and therefore see the styling however I feel that there is just a bug with my code and don't really want to have to rely on a blank <code><div></code> as a fix. </p>
<p>Any help?</p>
<pre><code><?php get_header();?>
<div class="page-header mb-5">
<h1 class="text-center"><?php the_title();?></h1>
</div>
<div class="container">
<?php if(have_posts()) : while(have_posts()) : the_post();?>
<?php the_content();?>
<?php endwhile; endif;?>
</div>
<?php get_footer();?>
</code></pre>
| [
{
"answer_id": 364176,
"author": "uPrompt",
"author_id": 155077,
"author_profile": "https://wordpress.stackexchange.com/users/155077",
"pm_score": 0,
"selected": false,
"text": "<p>Can't post a comment so here goes.</p>\n\n<p>If you're not into writing or debugging code I'd try this:</p>\n\n<p>Search the WordPress site for a plugin called \"Disable admin notices individually\". Whenever an admin notice pops up, you can disable it. While this plugin doesn't fix the root cause of the problem, it does seem to hide it under a rock so you don't see it.</p>\n\n<p>I do want to point out that if you've updated WordPress but haven't updated plugins, that may be the problem.</p>\n"
},
{
"answer_id": 364207,
"author": "wpnovice",
"author_id": 185893,
"author_profile": "https://wordpress.stackexchange.com/users/185893",
"pm_score": 0,
"selected": false,
"text": "<p>Here's a workaround with jQuery. \nAdd this to your functions.php in the active theme folder</p>\n\n<pre><code>function enqueue_my_scripts_hide_warnings() {\n?>\n<script>\njQuery(document).ready(function(){\n jQuery('.notice-info').each(function(){\n if(!jQuery(this).text()){\n jQuery(this).hide();\n }\n })\n jQuery('.notice-warning').each(function(){\n if(!jQuery(this).text()){\n jQuery(this).hide();\n }\n })\n});\n</script>\n<?php\n\n} \nadd_action( 'admin_footer', 'enqueue_my_scripts_hide_warnings' );\n</code></pre>\n\n<p>If that selector doesn't work, just replace line 5-9 with this below. However the selector may be too wide, so use with caution. May have to tweak the selector depending on how your admin pages work.</p>\n\n<pre><code> jQuery('.notice').each(function(){\n if(!jQuery(this).text()){\n jQuery(this).hide();\n }\n })\n</code></pre>\n"
},
{
"answer_id": 364221,
"author": "Daniel Simmons",
"author_id": 185900,
"author_profile": "https://wordpress.stackexchange.com/users/185900",
"pm_score": 4,
"selected": true,
"text": "<p>Let's take a look at <code>admin_notices</code>, since that's where your output is.</p>\n\n<p><a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/admin-header.php#L281\" rel=\"noreferrer\">https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/admin-header.php#L281</a></p>\n\n<p>So, it's simply just an action-as-an-output-spot, what this means is that if you wish, you can output anything here and most importantly, this all happens in-memory, so, debugging should be pretty straight-forward; this spot is meant to output things. That's it.</p>\n\n<p>Unless you're using a wrapper around this action such as <a href=\"https://github.com/WPTRT/admin-notices\" rel=\"noreferrer\">https://github.com/WPTRT/admin-notices</a> that allows you write your code cleaner (but this still uses the <code>admin_notices</code> action inside), you'll be doing something like <code>add_action( 'admin_notices', function() { echo 'My notification!' } )</code></p>\n\n<p>...and so will any other package that allows you to push these notifications out.</p>\n\n<p>Knowing the following variables: in-memory, actions, we can attempt to see what's going out in there. You can write your own <code>action inspection engine</code> or, you can use someone else's:</p>\n\n<p><a href=\"https://wordpress.org/plugins/query-monitor/\" rel=\"noreferrer\">https://wordpress.org/plugins/query-monitor/</a></p>\n\n<p>Now, if we are to Go to our Dashboard > Open the Query Monitor Panel (it's in the top, sticky WP bar) > Access \"Hooks & Actions\" > Search for <code>admin_notices</code>, we'll be prompted with a screen like this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/lvYzm.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/lvYzm.png\" alt=\"All actions hooking to <code>admin_notices</code>\"></a></p>\n\n<p>In here, we can see exactly what's hooked to this action and their priority, so, let's try to replicate your issue. Let's create some empty notifications and output them:</p>\n\n<pre><code>add_action( 'admin_notices', function() {\n $class = 'notice notice-error';\n\n printf( '<div class=\"%1$s\"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );\n printf( '<div class=\"%1$s\"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );\n printf( '<div class=\"%1$s\"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );\n printf( '<div class=\"%1$s\"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );\n printf( '<div class=\"%1$s\"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );\n}, 15 );\n</code></pre>\n\n<p>Great, and let's see how our dashboard looks now:</p>\n\n<p><a href=\"https://i.stack.imgur.com/yUKV9.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/yUKV9.png\" alt=\"Dashboard with error code in\"></a></p>\n\n<p>Oof. <strong>It's broken, just like yours is</strong>. But what does the image tell us? Well, it says that inside the theme, coming from a closure, within <code>functions.php</code> on line <code>87</code>, there are some notifications that it's trying to output.</p>\n\n<p>Do this for your case and try to see which one is having issues.</p>\n\n<hr>\n\n<p>Although a bit out of scope, or rather, comprising a larger scope, at times, I really wish you could get the <code>return value</code> of a hook. Your case is the prime example of inspecting how the data flows within actions isn't as easy to do, don't get me wrong, it's still possible, but requires quite some work to take care of everything and I gave up mid-way myself. In other words, wouldn't it be cool to say <code>Hey, WordPress, on action 'admin_notices', which one of the hooked functions returns an empty string or an error?</code>. Really saves you a lot of time.</p>\n"
}
] | 2020/04/09 | [
"https://wordpress.stackexchange.com/questions/363680",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/185796/"
] | I'm currently styling my single.php file and for some reason when compiled the page completely skips the first tag yet prints everything else afterwards, including the `<h1>` tag in the first `<div>`. The only fix I have produced at the moment is placing a blank `<div>` tag before `<div class="page-header mb-5">` in order to print and therefore see the styling however I feel that there is just a bug with my code and don't really want to have to rely on a blank `<div>` as a fix.
Any help?
```
<?php get_header();?>
<div class="page-header mb-5">
<h1 class="text-center"><?php the_title();?></h1>
</div>
<div class="container">
<?php if(have_posts()) : while(have_posts()) : the_post();?>
<?php the_content();?>
<?php endwhile; endif;?>
</div>
<?php get_footer();?>
``` | Let's take a look at `admin_notices`, since that's where your output is.
<https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/admin-header.php#L281>
So, it's simply just an action-as-an-output-spot, what this means is that if you wish, you can output anything here and most importantly, this all happens in-memory, so, debugging should be pretty straight-forward; this spot is meant to output things. That's it.
Unless you're using a wrapper around this action such as <https://github.com/WPTRT/admin-notices> that allows you write your code cleaner (but this still uses the `admin_notices` action inside), you'll be doing something like `add_action( 'admin_notices', function() { echo 'My notification!' } )`
...and so will any other package that allows you to push these notifications out.
Knowing the following variables: in-memory, actions, we can attempt to see what's going out in there. You can write your own `action inspection engine` or, you can use someone else's:
<https://wordpress.org/plugins/query-monitor/>
Now, if we are to Go to our Dashboard > Open the Query Monitor Panel (it's in the top, sticky WP bar) > Access "Hooks & Actions" > Search for `admin_notices`, we'll be prompted with a screen like this:
[](https://i.stack.imgur.com/lvYzm.png)
In here, we can see exactly what's hooked to this action and their priority, so, let's try to replicate your issue. Let's create some empty notifications and output them:
```
add_action( 'admin_notices', function() {
$class = 'notice notice-error';
printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );
printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );
printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );
printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );
printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );
}, 15 );
```
Great, and let's see how our dashboard looks now:
[](https://i.stack.imgur.com/yUKV9.png)
Oof. **It's broken, just like yours is**. But what does the image tell us? Well, it says that inside the theme, coming from a closure, within `functions.php` on line `87`, there are some notifications that it's trying to output.
Do this for your case and try to see which one is having issues.
---
Although a bit out of scope, or rather, comprising a larger scope, at times, I really wish you could get the `return value` of a hook. Your case is the prime example of inspecting how the data flows within actions isn't as easy to do, don't get me wrong, it's still possible, but requires quite some work to take care of everything and I gave up mid-way myself. In other words, wouldn't it be cool to say `Hey, WordPress, on action 'admin_notices', which one of the hooked functions returns an empty string or an error?`. Really saves you a lot of time. |
363,703 | <p>I tried to write a very simple block plugin for Gutenberg: A simple TOC generator. I can now place a block in a post and the table of contents is being generated as an unordered list. Great! But in the backend (Gutenberg Editor) there is still my ugly block that just say "SimpleTOC" and is not dynamic. </p>
<p>How can I display the output of my php function "render_callback" in the plugin.php <a href="https://github.com/mtoensing/simpletoc/blob/0.5/plugin.php" rel="nofollow noreferrer">https://github.com/mtoensing/simpletoc/blob/0.5/plugin.php</a> in the "edit" function in the JS code? I read my tutorials and looked at core blocks but I just don't get the server side functions. </p>
<p>This is all of my index.js <a href="https://github.com/mtoensing/simpletoc/blob/0.5/src/index.js" rel="nofollow noreferrer">https://github.com/mtoensing/simpletoc/blob/0.5/src/index.js</a> block code: </p>
<pre><code>const { __, setLocaleData } = wp.i18n;
const { registerBlockType } = wp.blocks;
registerBlockType( 'simpletoc/toc', {
title: __( 'Table of Contents', 'simpletoc' ),
icon: 'list-view',
category: 'layout',
edit( { className } ) {
return <p className={ className }>
<ul>
<li>SimpleTOC</li>
<li>SimpleTOC</li>
<li>SimpleTOC</li>
</ul>
</p>;
},
save: props => {
return null;
},
} );
</code></pre>
<p>My render_callback function looks like this in plugin.php <a href="https://github.com/mtoensing/simpletoc/blob/0.5/plugin.php" rel="nofollow noreferrer">https://github.com/mtoensing/simpletoc/blob/0.5/plugin.php</a>:</p>
<pre><code>function render_callback( $attributes, $content ) {
$blocks = parse_blocks( get_the_content( get_the_ID()));
if ( empty( $blocks ) ) {
return 'No contents.';
}
//add only if block is used in this post.
add_filter( 'render_block', __NAMESPACE__ . '\\filter_block', 10, 2 );
$headings = array_values( array_filter( $blocks, function( $block ){
return $block['blockName'] === 'core/heading';
}) );
if ( empty( $headings ) ) {
return 'No headings.';
}
$heading_contents = array_column( $headings, 'innerHTML');
$output .= '<ul class="toc">';
foreach ( $heading_contents as $heading_content ) {
preg_match( '|<h[^>]+>(.*)</h[^>]+>|iU', $heading_content , $matches );
$link = sanitize_title_with_dashes( $matches[1]);
$output .= '<li><a href="#' . $link . '">' . $matches[1] . '</a></li>';
}
$output .= '</ul>';
return $output;
}
</code></pre>
| [
{
"answer_id": 364176,
"author": "uPrompt",
"author_id": 155077,
"author_profile": "https://wordpress.stackexchange.com/users/155077",
"pm_score": 0,
"selected": false,
"text": "<p>Can't post a comment so here goes.</p>\n\n<p>If you're not into writing or debugging code I'd try this:</p>\n\n<p>Search the WordPress site for a plugin called \"Disable admin notices individually\". Whenever an admin notice pops up, you can disable it. While this plugin doesn't fix the root cause of the problem, it does seem to hide it under a rock so you don't see it.</p>\n\n<p>I do want to point out that if you've updated WordPress but haven't updated plugins, that may be the problem.</p>\n"
},
{
"answer_id": 364207,
"author": "wpnovice",
"author_id": 185893,
"author_profile": "https://wordpress.stackexchange.com/users/185893",
"pm_score": 0,
"selected": false,
"text": "<p>Here's a workaround with jQuery. \nAdd this to your functions.php in the active theme folder</p>\n\n<pre><code>function enqueue_my_scripts_hide_warnings() {\n?>\n<script>\njQuery(document).ready(function(){\n jQuery('.notice-info').each(function(){\n if(!jQuery(this).text()){\n jQuery(this).hide();\n }\n })\n jQuery('.notice-warning').each(function(){\n if(!jQuery(this).text()){\n jQuery(this).hide();\n }\n })\n});\n</script>\n<?php\n\n} \nadd_action( 'admin_footer', 'enqueue_my_scripts_hide_warnings' );\n</code></pre>\n\n<p>If that selector doesn't work, just replace line 5-9 with this below. However the selector may be too wide, so use with caution. May have to tweak the selector depending on how your admin pages work.</p>\n\n<pre><code> jQuery('.notice').each(function(){\n if(!jQuery(this).text()){\n jQuery(this).hide();\n }\n })\n</code></pre>\n"
},
{
"answer_id": 364221,
"author": "Daniel Simmons",
"author_id": 185900,
"author_profile": "https://wordpress.stackexchange.com/users/185900",
"pm_score": 4,
"selected": true,
"text": "<p>Let's take a look at <code>admin_notices</code>, since that's where your output is.</p>\n\n<p><a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/admin-header.php#L281\" rel=\"noreferrer\">https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/admin-header.php#L281</a></p>\n\n<p>So, it's simply just an action-as-an-output-spot, what this means is that if you wish, you can output anything here and most importantly, this all happens in-memory, so, debugging should be pretty straight-forward; this spot is meant to output things. That's it.</p>\n\n<p>Unless you're using a wrapper around this action such as <a href=\"https://github.com/WPTRT/admin-notices\" rel=\"noreferrer\">https://github.com/WPTRT/admin-notices</a> that allows you write your code cleaner (but this still uses the <code>admin_notices</code> action inside), you'll be doing something like <code>add_action( 'admin_notices', function() { echo 'My notification!' } )</code></p>\n\n<p>...and so will any other package that allows you to push these notifications out.</p>\n\n<p>Knowing the following variables: in-memory, actions, we can attempt to see what's going out in there. You can write your own <code>action inspection engine</code> or, you can use someone else's:</p>\n\n<p><a href=\"https://wordpress.org/plugins/query-monitor/\" rel=\"noreferrer\">https://wordpress.org/plugins/query-monitor/</a></p>\n\n<p>Now, if we are to Go to our Dashboard > Open the Query Monitor Panel (it's in the top, sticky WP bar) > Access \"Hooks & Actions\" > Search for <code>admin_notices</code>, we'll be prompted with a screen like this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/lvYzm.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/lvYzm.png\" alt=\"All actions hooking to <code>admin_notices</code>\"></a></p>\n\n<p>In here, we can see exactly what's hooked to this action and their priority, so, let's try to replicate your issue. Let's create some empty notifications and output them:</p>\n\n<pre><code>add_action( 'admin_notices', function() {\n $class = 'notice notice-error';\n\n printf( '<div class=\"%1$s\"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );\n printf( '<div class=\"%1$s\"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );\n printf( '<div class=\"%1$s\"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );\n printf( '<div class=\"%1$s\"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );\n printf( '<div class=\"%1$s\"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );\n}, 15 );\n</code></pre>\n\n<p>Great, and let's see how our dashboard looks now:</p>\n\n<p><a href=\"https://i.stack.imgur.com/yUKV9.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/yUKV9.png\" alt=\"Dashboard with error code in\"></a></p>\n\n<p>Oof. <strong>It's broken, just like yours is</strong>. But what does the image tell us? Well, it says that inside the theme, coming from a closure, within <code>functions.php</code> on line <code>87</code>, there are some notifications that it's trying to output.</p>\n\n<p>Do this for your case and try to see which one is having issues.</p>\n\n<hr>\n\n<p>Although a bit out of scope, or rather, comprising a larger scope, at times, I really wish you could get the <code>return value</code> of a hook. Your case is the prime example of inspecting how the data flows within actions isn't as easy to do, don't get me wrong, it's still possible, but requires quite some work to take care of everything and I gave up mid-way myself. In other words, wouldn't it be cool to say <code>Hey, WordPress, on action 'admin_notices', which one of the hooked functions returns an empty string or an error?</code>. Really saves you a lot of time.</p>\n"
}
] | 2020/04/10 | [
"https://wordpress.stackexchange.com/questions/363703",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/33797/"
] | I tried to write a very simple block plugin for Gutenberg: A simple TOC generator. I can now place a block in a post and the table of contents is being generated as an unordered list. Great! But in the backend (Gutenberg Editor) there is still my ugly block that just say "SimpleTOC" and is not dynamic.
How can I display the output of my php function "render\_callback" in the plugin.php <https://github.com/mtoensing/simpletoc/blob/0.5/plugin.php> in the "edit" function in the JS code? I read my tutorials and looked at core blocks but I just don't get the server side functions.
This is all of my index.js <https://github.com/mtoensing/simpletoc/blob/0.5/src/index.js> block code:
```
const { __, setLocaleData } = wp.i18n;
const { registerBlockType } = wp.blocks;
registerBlockType( 'simpletoc/toc', {
title: __( 'Table of Contents', 'simpletoc' ),
icon: 'list-view',
category: 'layout',
edit( { className } ) {
return <p className={ className }>
<ul>
<li>SimpleTOC</li>
<li>SimpleTOC</li>
<li>SimpleTOC</li>
</ul>
</p>;
},
save: props => {
return null;
},
} );
```
My render\_callback function looks like this in plugin.php <https://github.com/mtoensing/simpletoc/blob/0.5/plugin.php>:
```
function render_callback( $attributes, $content ) {
$blocks = parse_blocks( get_the_content( get_the_ID()));
if ( empty( $blocks ) ) {
return 'No contents.';
}
//add only if block is used in this post.
add_filter( 'render_block', __NAMESPACE__ . '\\filter_block', 10, 2 );
$headings = array_values( array_filter( $blocks, function( $block ){
return $block['blockName'] === 'core/heading';
}) );
if ( empty( $headings ) ) {
return 'No headings.';
}
$heading_contents = array_column( $headings, 'innerHTML');
$output .= '<ul class="toc">';
foreach ( $heading_contents as $heading_content ) {
preg_match( '|<h[^>]+>(.*)</h[^>]+>|iU', $heading_content , $matches );
$link = sanitize_title_with_dashes( $matches[1]);
$output .= '<li><a href="#' . $link . '">' . $matches[1] . '</a></li>';
}
$output .= '</ul>';
return $output;
}
``` | Let's take a look at `admin_notices`, since that's where your output is.
<https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/admin-header.php#L281>
So, it's simply just an action-as-an-output-spot, what this means is that if you wish, you can output anything here and most importantly, this all happens in-memory, so, debugging should be pretty straight-forward; this spot is meant to output things. That's it.
Unless you're using a wrapper around this action such as <https://github.com/WPTRT/admin-notices> that allows you write your code cleaner (but this still uses the `admin_notices` action inside), you'll be doing something like `add_action( 'admin_notices', function() { echo 'My notification!' } )`
...and so will any other package that allows you to push these notifications out.
Knowing the following variables: in-memory, actions, we can attempt to see what's going out in there. You can write your own `action inspection engine` or, you can use someone else's:
<https://wordpress.org/plugins/query-monitor/>
Now, if we are to Go to our Dashboard > Open the Query Monitor Panel (it's in the top, sticky WP bar) > Access "Hooks & Actions" > Search for `admin_notices`, we'll be prompted with a screen like this:
[](https://i.stack.imgur.com/lvYzm.png)
In here, we can see exactly what's hooked to this action and their priority, so, let's try to replicate your issue. Let's create some empty notifications and output them:
```
add_action( 'admin_notices', function() {
$class = 'notice notice-error';
printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );
printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );
printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );
printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );
printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );
}, 15 );
```
Great, and let's see how our dashboard looks now:
[](https://i.stack.imgur.com/yUKV9.png)
Oof. **It's broken, just like yours is**. But what does the image tell us? Well, it says that inside the theme, coming from a closure, within `functions.php` on line `87`, there are some notifications that it's trying to output.
Do this for your case and try to see which one is having issues.
---
Although a bit out of scope, or rather, comprising a larger scope, at times, I really wish you could get the `return value` of a hook. Your case is the prime example of inspecting how the data flows within actions isn't as easy to do, don't get me wrong, it's still possible, but requires quite some work to take care of everything and I gave up mid-way myself. In other words, wouldn't it be cool to say `Hey, WordPress, on action 'admin_notices', which one of the hooked functions returns an empty string or an error?`. Really saves you a lot of time. |
363,731 | <p>Hi so for all my Wordpress 5.4 site’s posts (articles), I'm using Yoast SEO plugin for breadcrumbs across my site.</p>
<p>For all my posts (articles) I just want:</p>
<p>Home > CategoryLink > as breadcrumbs, not the topic of the post. </p>
<p>So I’ve tried the following code in my theme's functions.php:</p>
<pre><code> add_filter( ‘wpseo_breadcrumb_links’, ‘wpseo_breadcrumb_remove_postname’ );
</code></pre>
<p>function wpseo_breadcrumb_remove_postname( $links ) {</p>
<p>if( sizeof($links) > 1 ) {</p>
<p>array_pop($links);
}</p>
<p>return $links;</p>
<p>}</p>
<p>However, what the hack above does is it also removes the previous link (parent link) and publishes only text instead of a link.</p>
<p>So if I have links as follows:</p>
<p>Home> CategoryUrl > Title of Post</p>
<p>Applying the patch into functions.php results in this:</p>
<p>Home > CategoryText</p>
<p>So the Category name is not a link anymore but a text. So breadcrumbs are useless after this hack.</p>
<p>Is there a correct way of not displaying post title in the breadcrumbs using Yoast? Thanks!</p>
| [
{
"answer_id": 364176,
"author": "uPrompt",
"author_id": 155077,
"author_profile": "https://wordpress.stackexchange.com/users/155077",
"pm_score": 0,
"selected": false,
"text": "<p>Can't post a comment so here goes.</p>\n\n<p>If you're not into writing or debugging code I'd try this:</p>\n\n<p>Search the WordPress site for a plugin called \"Disable admin notices individually\". Whenever an admin notice pops up, you can disable it. While this plugin doesn't fix the root cause of the problem, it does seem to hide it under a rock so you don't see it.</p>\n\n<p>I do want to point out that if you've updated WordPress but haven't updated plugins, that may be the problem.</p>\n"
},
{
"answer_id": 364207,
"author": "wpnovice",
"author_id": 185893,
"author_profile": "https://wordpress.stackexchange.com/users/185893",
"pm_score": 0,
"selected": false,
"text": "<p>Here's a workaround with jQuery. \nAdd this to your functions.php in the active theme folder</p>\n\n<pre><code>function enqueue_my_scripts_hide_warnings() {\n?>\n<script>\njQuery(document).ready(function(){\n jQuery('.notice-info').each(function(){\n if(!jQuery(this).text()){\n jQuery(this).hide();\n }\n })\n jQuery('.notice-warning').each(function(){\n if(!jQuery(this).text()){\n jQuery(this).hide();\n }\n })\n});\n</script>\n<?php\n\n} \nadd_action( 'admin_footer', 'enqueue_my_scripts_hide_warnings' );\n</code></pre>\n\n<p>If that selector doesn't work, just replace line 5-9 with this below. However the selector may be too wide, so use with caution. May have to tweak the selector depending on how your admin pages work.</p>\n\n<pre><code> jQuery('.notice').each(function(){\n if(!jQuery(this).text()){\n jQuery(this).hide();\n }\n })\n</code></pre>\n"
},
{
"answer_id": 364221,
"author": "Daniel Simmons",
"author_id": 185900,
"author_profile": "https://wordpress.stackexchange.com/users/185900",
"pm_score": 4,
"selected": true,
"text": "<p>Let's take a look at <code>admin_notices</code>, since that's where your output is.</p>\n\n<p><a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/admin-header.php#L281\" rel=\"noreferrer\">https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/admin-header.php#L281</a></p>\n\n<p>So, it's simply just an action-as-an-output-spot, what this means is that if you wish, you can output anything here and most importantly, this all happens in-memory, so, debugging should be pretty straight-forward; this spot is meant to output things. That's it.</p>\n\n<p>Unless you're using a wrapper around this action such as <a href=\"https://github.com/WPTRT/admin-notices\" rel=\"noreferrer\">https://github.com/WPTRT/admin-notices</a> that allows you write your code cleaner (but this still uses the <code>admin_notices</code> action inside), you'll be doing something like <code>add_action( 'admin_notices', function() { echo 'My notification!' } )</code></p>\n\n<p>...and so will any other package that allows you to push these notifications out.</p>\n\n<p>Knowing the following variables: in-memory, actions, we can attempt to see what's going out in there. You can write your own <code>action inspection engine</code> or, you can use someone else's:</p>\n\n<p><a href=\"https://wordpress.org/plugins/query-monitor/\" rel=\"noreferrer\">https://wordpress.org/plugins/query-monitor/</a></p>\n\n<p>Now, if we are to Go to our Dashboard > Open the Query Monitor Panel (it's in the top, sticky WP bar) > Access \"Hooks & Actions\" > Search for <code>admin_notices</code>, we'll be prompted with a screen like this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/lvYzm.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/lvYzm.png\" alt=\"All actions hooking to <code>admin_notices</code>\"></a></p>\n\n<p>In here, we can see exactly what's hooked to this action and their priority, so, let's try to replicate your issue. Let's create some empty notifications and output them:</p>\n\n<pre><code>add_action( 'admin_notices', function() {\n $class = 'notice notice-error';\n\n printf( '<div class=\"%1$s\"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );\n printf( '<div class=\"%1$s\"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );\n printf( '<div class=\"%1$s\"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );\n printf( '<div class=\"%1$s\"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );\n printf( '<div class=\"%1$s\"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );\n}, 15 );\n</code></pre>\n\n<p>Great, and let's see how our dashboard looks now:</p>\n\n<p><a href=\"https://i.stack.imgur.com/yUKV9.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/yUKV9.png\" alt=\"Dashboard with error code in\"></a></p>\n\n<p>Oof. <strong>It's broken, just like yours is</strong>. But what does the image tell us? Well, it says that inside the theme, coming from a closure, within <code>functions.php</code> on line <code>87</code>, there are some notifications that it's trying to output.</p>\n\n<p>Do this for your case and try to see which one is having issues.</p>\n\n<hr>\n\n<p>Although a bit out of scope, or rather, comprising a larger scope, at times, I really wish you could get the <code>return value</code> of a hook. Your case is the prime example of inspecting how the data flows within actions isn't as easy to do, don't get me wrong, it's still possible, but requires quite some work to take care of everything and I gave up mid-way myself. In other words, wouldn't it be cool to say <code>Hey, WordPress, on action 'admin_notices', which one of the hooked functions returns an empty string or an error?</code>. Really saves you a lot of time.</p>\n"
}
] | 2020/04/10 | [
"https://wordpress.stackexchange.com/questions/363731",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/185836/"
] | Hi so for all my Wordpress 5.4 site’s posts (articles), I'm using Yoast SEO plugin for breadcrumbs across my site.
For all my posts (articles) I just want:
Home > CategoryLink > as breadcrumbs, not the topic of the post.
So I’ve tried the following code in my theme's functions.php:
```
add_filter( ‘wpseo_breadcrumb_links’, ‘wpseo_breadcrumb_remove_postname’ );
```
function wpseo\_breadcrumb\_remove\_postname( $links ) {
if( sizeof($links) > 1 ) {
array\_pop($links);
}
return $links;
}
However, what the hack above does is it also removes the previous link (parent link) and publishes only text instead of a link.
So if I have links as follows:
Home> CategoryUrl > Title of Post
Applying the patch into functions.php results in this:
Home > CategoryText
So the Category name is not a link anymore but a text. So breadcrumbs are useless after this hack.
Is there a correct way of not displaying post title in the breadcrumbs using Yoast? Thanks! | Let's take a look at `admin_notices`, since that's where your output is.
<https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/admin-header.php#L281>
So, it's simply just an action-as-an-output-spot, what this means is that if you wish, you can output anything here and most importantly, this all happens in-memory, so, debugging should be pretty straight-forward; this spot is meant to output things. That's it.
Unless you're using a wrapper around this action such as <https://github.com/WPTRT/admin-notices> that allows you write your code cleaner (but this still uses the `admin_notices` action inside), you'll be doing something like `add_action( 'admin_notices', function() { echo 'My notification!' } )`
...and so will any other package that allows you to push these notifications out.
Knowing the following variables: in-memory, actions, we can attempt to see what's going out in there. You can write your own `action inspection engine` or, you can use someone else's:
<https://wordpress.org/plugins/query-monitor/>
Now, if we are to Go to our Dashboard > Open the Query Monitor Panel (it's in the top, sticky WP bar) > Access "Hooks & Actions" > Search for `admin_notices`, we'll be prompted with a screen like this:
[](https://i.stack.imgur.com/lvYzm.png)
In here, we can see exactly what's hooked to this action and their priority, so, let's try to replicate your issue. Let's create some empty notifications and output them:
```
add_action( 'admin_notices', function() {
$class = 'notice notice-error';
printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );
printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );
printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );
printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );
printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( '' ) );
}, 15 );
```
Great, and let's see how our dashboard looks now:
[](https://i.stack.imgur.com/yUKV9.png)
Oof. **It's broken, just like yours is**. But what does the image tell us? Well, it says that inside the theme, coming from a closure, within `functions.php` on line `87`, there are some notifications that it's trying to output.
Do this for your case and try to see which one is having issues.
---
Although a bit out of scope, or rather, comprising a larger scope, at times, I really wish you could get the `return value` of a hook. Your case is the prime example of inspecting how the data flows within actions isn't as easy to do, don't get me wrong, it's still possible, but requires quite some work to take care of everything and I gave up mid-way myself. In other words, wouldn't it be cool to say `Hey, WordPress, on action 'admin_notices', which one of the hooked functions returns an empty string or an error?`. Really saves you a lot of time. |
363,870 | <p>I have a site that reviews movies (DVD/Blu-ray, etc.)So every review in a particular category will have (Blu-ray) after the title, another will have DVD and so forth. i.e. Avengers: Infinity War (Blu-ray). I want to trim the format of the disc (Blu-ray) from the page title and I have this code, but it's not working. Wasn't sure what the issue was.</p>
<pre><code><span style="color: #ffffff">About <?php if (in_category('5447') ):?>
<?php
echo str_replace("(Blu-ray)","&nbsp;","<?php the_title(); ?>");
?>
</span>
<?php endif; ?>
</code></pre>
<p>So, in essence, I can grab the title and it will read:
Avengers: Infinity War (Blu-ray)</p>
<p>but I want it to read:
Avengers: Infinity War</p>
| [
{
"answer_id": 363895,
"author": "Will",
"author_id": 48698,
"author_profile": "https://wordpress.stackexchange.com/users/48698",
"pm_score": 0,
"selected": false,
"text": "<p>You have a couple options: </p>\n\n<p>You could use the <a href=\"https://wordpress.org/support/article/media-text-block/\" rel=\"nofollow noreferrer\">media and text block</a> which is designed for inserting text next to an image. </p>\n\n<p>Or you could use the columns block, select a layout that only has 2 columns and then on the left column you can insert image and in the right column, insert text. </p>\n"
},
{
"answer_id": 364220,
"author": "buzztone",
"author_id": 27750,
"author_profile": "https://wordpress.stackexchange.com/users/27750",
"pm_score": 1,
"selected": false,
"text": "<p>Using the Align options you found (Align left, Align center, Align right) is often the easiest way to allow text to flow around your images in your WordPress posts.</p>\n\n<ol>\n<li>Add the Image </li>\n<li>Select Align right in Image options</li>\n<li>Add some text (puts Image in Paragraph block)</li>\n<li>Adjust the width of the Image block\nso the text flows around</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/0E0Mp.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/0E0Mp.png\" alt=\"Add image in Paragraph block\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/0oINd.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/0oINd.png\" alt=\"Adjust the width of the Image block\"></a></p>\n"
}
] | 2020/04/12 | [
"https://wordpress.stackexchange.com/questions/363870",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/34872/"
] | I have a site that reviews movies (DVD/Blu-ray, etc.)So every review in a particular category will have (Blu-ray) after the title, another will have DVD and so forth. i.e. Avengers: Infinity War (Blu-ray). I want to trim the format of the disc (Blu-ray) from the page title and I have this code, but it's not working. Wasn't sure what the issue was.
```
<span style="color: #ffffff">About <?php if (in_category('5447') ):?>
<?php
echo str_replace("(Blu-ray)"," ","<?php the_title(); ?>");
?>
</span>
<?php endif; ?>
```
So, in essence, I can grab the title and it will read:
Avengers: Infinity War (Blu-ray)
but I want it to read:
Avengers: Infinity War | Using the Align options you found (Align left, Align center, Align right) is often the easiest way to allow text to flow around your images in your WordPress posts.
1. Add the Image
2. Select Align right in Image options
3. Add some text (puts Image in Paragraph block)
4. Adjust the width of the Image block
so the text flows around
[](https://i.stack.imgur.com/0E0Mp.png)
[](https://i.stack.imgur.com/0oINd.png) |
363,893 | <p>I am using Wordpress 5.4. I created a CPT using the code below:</p>
<pre><code>$args = array(
'labels' => $labels,
'description' => 'Some description',
'public' => true,
'menu_position' => 5,
'supports' => array( 'title', 'editor', 'thumbnail', 'excerpt', 'comments' ),
'has_archive' => true,
);
register_post_type( 'article', $args );
</code></pre>
<p><code>has_archive</code> was set to true and my understanding is that now when I goto <code>/articles</code> I am supposed to see all posts of type <code>article</code>. But that is not the case. When I goto <code>/articles</code> I see my normal posts. I do not have any <code>article-archive.php</code> on my system and understand that is not necessary. I do have a <code>./wp-content/themes/twentynineteen/archive.php</code> and I am using a child theme of <code>twnetynineteen</code> on my site.</p>
<p>How can I fix this?</p>
<p><strong>EDIT</strong>: </p>
<ol>
<li>I have tried <code>/article</code> and it does not fix the problem.</li>
<li>I have tried resaving permalinks (Settings->Permalinks) and it does not fix the problem.</li>
<li>The code above is located in a plugin.</li>
<li>I <strong>can</strong> see my article if I goto <code>/?article=test-article</code> where <code>test-article</code> is slug of my article.</li>
<li>I am using <code>nginx</code> with <a href="https://gist.github.com/md5/d9206eacb5a0ff5d6be0#file-wordpress-fpm-conf" rel="nofollow noreferrer">this</a> configuration. </li>
</ol>
| [
{
"answer_id": 363900,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>has_archive was set to true and my understanding is that now when I goto /articles I am supposed to see all posts of type article. </p>\n</blockquote>\n\n<p>Nowhere in your code is article<em>S</em> mentioned, the slug of the post type is <code>article</code>, so the URL of its archive should be <code>/article/</code>. If you want it to be <code>articles</code> you have to say so.</p>\n\n<p>In this case, it's the classic mistake of registering a post type or taxonomy, but not flushing permalinks to add their rules. Go to the permalinks setting page, and resave.</p>\n\n<p>As for the template <code>archive.php</code>, this is irrelevant to wether the page loads or not. The template hierarchy will fallback to <code>index.php</code> which is required for a theme if no other templats are found. Additionally, <code>archive.php</code> doesn't make the URL an archive. The URL makes it an archive, and the fact it's an archive makes WP load that template. WP has already figured out what posts to fetch before the template is chosen.</p>\n"
},
{
"answer_id": 363969,
"author": "morpheus",
"author_id": 29199,
"author_profile": "https://wordpress.stackexchange.com/users/29199",
"pm_score": 1,
"selected": true,
"text": "<p>The solution to this problem is to use <strong>Post name</strong> in <code>/wp-admin/options-permalink.php</code>. </p>\n\n<p><a href=\"https://i.stack.imgur.com/UqytL.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/UqytL.png\" alt=\"enter image description here\"></a></p>\n"
}
] | 2020/04/12 | [
"https://wordpress.stackexchange.com/questions/363893",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/29199/"
] | I am using Wordpress 5.4. I created a CPT using the code below:
```
$args = array(
'labels' => $labels,
'description' => 'Some description',
'public' => true,
'menu_position' => 5,
'supports' => array( 'title', 'editor', 'thumbnail', 'excerpt', 'comments' ),
'has_archive' => true,
);
register_post_type( 'article', $args );
```
`has_archive` was set to true and my understanding is that now when I goto `/articles` I am supposed to see all posts of type `article`. But that is not the case. When I goto `/articles` I see my normal posts. I do not have any `article-archive.php` on my system and understand that is not necessary. I do have a `./wp-content/themes/twentynineteen/archive.php` and I am using a child theme of `twnetynineteen` on my site.
How can I fix this?
**EDIT**:
1. I have tried `/article` and it does not fix the problem.
2. I have tried resaving permalinks (Settings->Permalinks) and it does not fix the problem.
3. The code above is located in a plugin.
4. I **can** see my article if I goto `/?article=test-article` where `test-article` is slug of my article.
5. I am using `nginx` with [this](https://gist.github.com/md5/d9206eacb5a0ff5d6be0#file-wordpress-fpm-conf) configuration. | The solution to this problem is to use **Post name** in `/wp-admin/options-permalink.php`.
[](https://i.stack.imgur.com/UqytL.png) |
363,912 | <pre><code><img alt="Capital" data-inject-svg src="<?php bloginfo( 'template_url' ); ?>/assets/img/logos/imglogo.svg">
</code></pre>
<pre><code><img alt="Capital" data-inject-svg src="<?php echo get_template_directory_uri(); ?>/assets/img/logos/imglogo.svg">
</code></pre>
<p>i tried both of above code but don't get output</p>
| [
{
"answer_id": 363928,
"author": "Stoian Delev",
"author_id": 185752,
"author_profile": "https://wordpress.stackexchange.com/users/185752",
"pm_score": -1,
"selected": false,
"text": "<p>the answer ;) is : </p>\n\n<pre><code><img alt=\"Capital\" data-inject-svg src=\"<?php bloginfo( 'template_url' ).\"/assets/img/logos/imglogo.svg\"; ?>\"> \n</code></pre>\n"
},
{
"answer_id": 363934,
"author": "Sanjay Gupta",
"author_id": 185502,
"author_profile": "https://wordpress.stackexchange.com/users/185502",
"pm_score": -1,
"selected": false,
"text": "<p>I hope it will your help</p>\n\n<p>Firstly you need to create folder inside the activate theme like this: assets > img > logos > imglogo.svg</p>\n\n<p>If you are working on the child theme can use this:</p>\n\n<pre><code><img alt=\"Capital\" data-inject-svg src=\"<?php echo get_stylesheet_directory_uri(); ?>/assets/img/logos/imglogo.svg\">\n</code></pre>\n\n<p>Otherwise you can use this:</p>\n\n<pre><code><img alt=\"Capital\" data-inject-svg src=\"<?php echo bloginfo( 'template_url' ); ?>/assets/img/logos/imglogo.svg\">\n</code></pre>\n"
},
{
"answer_id": 363938,
"author": "Stoian Delev",
"author_id": 185752,
"author_profile": "https://wordpress.stackexchange.com/users/185752",
"pm_score": 0,
"selected": false,
"text": "<p>remove \"data-inject-svg\" or use data=\"data-inject-svg\" ...work great ...hire a screenshots </p>\n\n<p><a href=\"https://i.stack.imgur.com/jIDT8.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/jIDT8.png\" alt=\"Result img\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/9Mf3P.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9Mf3P.png\" alt=\"Code img\"></a></p>\n"
}
] | 2020/04/13 | [
"https://wordpress.stackexchange.com/questions/363912",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/185964/"
] | ```
<img alt="Capital" data-inject-svg src="<?php bloginfo( 'template_url' ); ?>/assets/img/logos/imglogo.svg">
```
```
<img alt="Capital" data-inject-svg src="<?php echo get_template_directory_uri(); ?>/assets/img/logos/imglogo.svg">
```
i tried both of above code but don't get output | remove "data-inject-svg" or use data="data-inject-svg" ...work great ...hire a screenshots
[](https://i.stack.imgur.com/jIDT8.png)
[](https://i.stack.imgur.com/9Mf3P.png) |
363,971 | <p>I looked at this question:</p>
<p><a href="https://wordpress.stackexchange.com/questions/253504/plugin-css-is-not-being-applied-to-the-page">plugin css is not being applied to the page?</a></p>
<p>but I couldnt solve my problem.</p>
<p>I use below code like the question:</p>
<pre><code> <?php
function libload()
{
wp_register_style( 'foo-styles', plugin_dir_url( __FILE__ ) . 'dahili/bootstrap.min.css' );
wp_enqueue_style( 'foo-styles' );
wp_register_style( 'foo-styles2', plugin_dir_url( __FILE__ ) . 'dahili/style.css' );
wp_enqueue_style( 'foo-styles2' );
wp_register_style( 'foo-styles3', plugin_dir_url( __FILE__ ) . 'dahili/responsive.css' );
wp_enqueue_style( 'foo-styles3' );
}
add_action('wp_enqueue_scripts','libload');
?>
</code></pre>
<p>style files are loading as you can see below link but wp not apply them:</p>
<p><a href="http://www.hekim.deniz-tasarim.site/sample-page/" rel="nofollow noreferrer">http://www.hekim.deniz-tasarim.site/sample-page/</a></p>
<p>How can I solve this problem?</p>
| [
{
"answer_id": 363928,
"author": "Stoian Delev",
"author_id": 185752,
"author_profile": "https://wordpress.stackexchange.com/users/185752",
"pm_score": -1,
"selected": false,
"text": "<p>the answer ;) is : </p>\n\n<pre><code><img alt=\"Capital\" data-inject-svg src=\"<?php bloginfo( 'template_url' ).\"/assets/img/logos/imglogo.svg\"; ?>\"> \n</code></pre>\n"
},
{
"answer_id": 363934,
"author": "Sanjay Gupta",
"author_id": 185502,
"author_profile": "https://wordpress.stackexchange.com/users/185502",
"pm_score": -1,
"selected": false,
"text": "<p>I hope it will your help</p>\n\n<p>Firstly you need to create folder inside the activate theme like this: assets > img > logos > imglogo.svg</p>\n\n<p>If you are working on the child theme can use this:</p>\n\n<pre><code><img alt=\"Capital\" data-inject-svg src=\"<?php echo get_stylesheet_directory_uri(); ?>/assets/img/logos/imglogo.svg\">\n</code></pre>\n\n<p>Otherwise you can use this:</p>\n\n<pre><code><img alt=\"Capital\" data-inject-svg src=\"<?php echo bloginfo( 'template_url' ); ?>/assets/img/logos/imglogo.svg\">\n</code></pre>\n"
},
{
"answer_id": 363938,
"author": "Stoian Delev",
"author_id": 185752,
"author_profile": "https://wordpress.stackexchange.com/users/185752",
"pm_score": 0,
"selected": false,
"text": "<p>remove \"data-inject-svg\" or use data=\"data-inject-svg\" ...work great ...hire a screenshots </p>\n\n<p><a href=\"https://i.stack.imgur.com/jIDT8.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/jIDT8.png\" alt=\"Result img\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/9Mf3P.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9Mf3P.png\" alt=\"Code img\"></a></p>\n"
}
] | 2020/04/13 | [
"https://wordpress.stackexchange.com/questions/363971",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180385/"
] | I looked at this question:
[plugin css is not being applied to the page?](https://wordpress.stackexchange.com/questions/253504/plugin-css-is-not-being-applied-to-the-page)
but I couldnt solve my problem.
I use below code like the question:
```
<?php
function libload()
{
wp_register_style( 'foo-styles', plugin_dir_url( __FILE__ ) . 'dahili/bootstrap.min.css' );
wp_enqueue_style( 'foo-styles' );
wp_register_style( 'foo-styles2', plugin_dir_url( __FILE__ ) . 'dahili/style.css' );
wp_enqueue_style( 'foo-styles2' );
wp_register_style( 'foo-styles3', plugin_dir_url( __FILE__ ) . 'dahili/responsive.css' );
wp_enqueue_style( 'foo-styles3' );
}
add_action('wp_enqueue_scripts','libload');
?>
```
style files are loading as you can see below link but wp not apply them:
<http://www.hekim.deniz-tasarim.site/sample-page/>
How can I solve this problem? | remove "data-inject-svg" or use data="data-inject-svg" ...work great ...hire a screenshots
[](https://i.stack.imgur.com/jIDT8.png)
[](https://i.stack.imgur.com/9Mf3P.png) |
364,025 | <p>I have a wordpress installation where the posts also contain attachments that were not embedded in the content by using the <code>media library -> add</code>.</p>
<p>I would like to find all attachments that are not used in any posts/pages/custom_post_types</p>
<p>It is ok for me if I get results for attachments uploaded for a specific month, for example <strong>january 2017</strong>.</p>
<p>Here is my attempt to write the SQL:</p>
<pre><code>select distinct a.*
from (
select *
from wp_posts
where post_type = 'attachment'
and post_date between '2017-01-01' and '2017-01-31'
) as a,
(
select post_content
from wp_posts
where post_type in ('post', 'page', 'custom_post_type_1', 'custom_post_type_2', 'custom_post_type_n')
and post_status = 'publish'
) as p
where p.post_content not like CONCAT('%/wp-content/uploads/', DATE_FORMAT(a.post_date, '%Y/%m'), '/', a.post_name, '%')
</code></pre>
<p>Since not all attachments were embedded in the content via the media library, I cannot use:</p>
<pre><code>select *
from wp_posts
where post_type = 'attachment'
and post_parent = 0;
</code></pre>
<p>Does anyone know a better way? My SQL query is quite slow.</p>
| [
{
"answer_id": 364046,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": true,
"text": "<p>What you seek isn't truly possible. You can get sort of close, but you cannot definitively say if an attachment is or isn't in use.</p>\n\n<p>We can get somewhere close to a solution, but to do this we will need to process each attachment individually.</p>\n\n<p>So first, get a list of all the IDs of attachments. Use a standard <code>WP_Query</code> to do this, you might even get a speed boost from object cache as a result.</p>\n\n<p>Here's the official date query docs:</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/classes/wp_query/#date-parameters\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/classes/wp_query/#date-parameters</a></p>\n\n<p>For each attachment:</p>\n\n<ul>\n<li>Check all post content and post meta for the attachments URL, with the image size removed</li>\n<li>Check all options and post meta for the attachments ID</li>\n<li>Check if the attachment has a post parent</li>\n<li>If any of these are true, the attachment is probably in use</li>\n</ul>\n\n<p>Doing every attachment in a single go will be problematic, it won't be possible to run the query from a browser due to the PHP execution limit. You'd need to do attachments in batches, or via a CLI command. Preferably in batches of 100. PHP will run out of memory if you try to process all 47k at once.</p>\n\n<p>However, the most effective means of testing if an attachment is in use, is to spider the entire site and save the results locally, then search the folder for the URL. Note that this won't catch things that only show once forms submit, or RSS specific stuff, things that only show to logged in users, etc</p>\n"
},
{
"answer_id": 387580,
"author": "And Finally",
"author_id": 14984,
"author_profile": "https://wordpress.stackexchange.com/users/14984",
"pm_score": 1,
"selected": false,
"text": "<p>I found a useful SQL query <a href=\"https://neliosoftware.com/blog/how-to-remove-unused-images-from-your-media-library-in-wordpress/\" rel=\"nofollow noreferrer\">here</a> which addresses many of the points Tom mentions. I've tweaked it a bit for my purposes.</p>\n<pre class=\"lang-php prettyprint-override\"><code>$ids = $wpdb->get_col(\n "SELECT i.ID FROM $wpdb->posts i\n WHERE i.post_type = 'attachment'\n AND i.post_parent > 0\n AND NOT EXISTS (SELECT * FROM $wpdb->posts p WHERE p.ID = i.post_parent)\n AND NOT EXISTS (SELECT * FROM $wpdb->postmeta pm WHERE pm.meta_key = '_thumbnail_id' AND pm.meta_value = i.ID)\n AND NOT EXISTS (SELECT * FROM $wpdb->postmeta pm WHERE pm.meta_key = '_product_image_gallery' AND pm.meta_value LIKE CONCAT('%', i.ID,'%'))\n AND NOT EXISTS (SELECT * FROM $wpdb->posts p WHERE p.post_type <> 'attachment' AND p.post_content LIKE CONCAT('%', i.guid,'%'))\n AND NOT EXISTS (SELECT * FROM $wpdb->postmeta pm WHERE pm.meta_value LIKE CONCAT('%', i.guid,'%'))"\n);\n</code></pre>\n<p>This should find all attachments</p>\n<ul>\n<li>With <code>post_parent</code> greater than 0.</li>\n<li>Whose <code>post_parent</code> refers to a non-existent post.</li>\n<li>Which isn't used as the featured image (<code>_thumbnail_id</code>) for any post.</li>\n<li>Which isn't used in any WooCommerce product gallery.</li>\n<li>Whose <code>guid</code> (which usually means the attachment's URL) doesn't appear in any post content.</li>\n<li>Whose URL doesn't appear in any postmeta value.</li>\n</ul>\n<p>Once you have the list of IDs you can loop through it and call <code>wp_delete_attachment( $attachment_id, true )</code> to force delete each attachment and its accompanying postmeta, as well as the associated media file.</p>\n<p>The query for product gallery IDs is a bit crude, though it's good enough for me, and the post content search won't work for you if the URLs of your attachments are different from their <code>guid</code>s.</p>\n"
}
] | 2020/04/14 | [
"https://wordpress.stackexchange.com/questions/364025",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/182202/"
] | I have a wordpress installation where the posts also contain attachments that were not embedded in the content by using the `media library -> add`.
I would like to find all attachments that are not used in any posts/pages/custom\_post\_types
It is ok for me if I get results for attachments uploaded for a specific month, for example **january 2017**.
Here is my attempt to write the SQL:
```
select distinct a.*
from (
select *
from wp_posts
where post_type = 'attachment'
and post_date between '2017-01-01' and '2017-01-31'
) as a,
(
select post_content
from wp_posts
where post_type in ('post', 'page', 'custom_post_type_1', 'custom_post_type_2', 'custom_post_type_n')
and post_status = 'publish'
) as p
where p.post_content not like CONCAT('%/wp-content/uploads/', DATE_FORMAT(a.post_date, '%Y/%m'), '/', a.post_name, '%')
```
Since not all attachments were embedded in the content via the media library, I cannot use:
```
select *
from wp_posts
where post_type = 'attachment'
and post_parent = 0;
```
Does anyone know a better way? My SQL query is quite slow. | What you seek isn't truly possible. You can get sort of close, but you cannot definitively say if an attachment is or isn't in use.
We can get somewhere close to a solution, but to do this we will need to process each attachment individually.
So first, get a list of all the IDs of attachments. Use a standard `WP_Query` to do this, you might even get a speed boost from object cache as a result.
Here's the official date query docs:
<https://developer.wordpress.org/reference/classes/wp_query/#date-parameters>
For each attachment:
* Check all post content and post meta for the attachments URL, with the image size removed
* Check all options and post meta for the attachments ID
* Check if the attachment has a post parent
* If any of these are true, the attachment is probably in use
Doing every attachment in a single go will be problematic, it won't be possible to run the query from a browser due to the PHP execution limit. You'd need to do attachments in batches, or via a CLI command. Preferably in batches of 100. PHP will run out of memory if you try to process all 47k at once.
However, the most effective means of testing if an attachment is in use, is to spider the entire site and save the results locally, then search the folder for the URL. Note that this won't catch things that only show once forms submit, or RSS specific stuff, things that only show to logged in users, etc |
364,066 | <p>I have a taxonomy called ORGANIZER.
All the terms of this taxonomy have a name and a description.
I tried to get the description of each term but i don't know how to loop on them.</p>
<p>I suppose i mus begin with:</p>
<pre><code>$terms = get_terms( array(
'taxonomy' => 'organizer',
'hide_empty' => false,
) );
</code></pre>
<p>but could you help me for the loop please ?
thanks</p>
| [
{
"answer_id": 364072,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"nofollow noreferrer\"><code>get_terms()</code></a> returns an array of <a href=\"https://developer.wordpress.org/reference/classes/wp_term/\" rel=\"nofollow noreferrer\"><code>WP_Term</code></a> objects. To get the description, with the usual filters applied, you can pass this object to <a href=\"https://developer.wordpress.org/reference/functions/term_description/\" rel=\"nofollow noreferrer\"><code>term_description()</code></a>:</p>\n\n<pre><code>$terms = get_terms( array(\n 'taxonomy' => 'organizer',\n 'hide_empty' => false,\n) );\n\nif ( ! is_wp_error( $terms ) ) {\n foreach ( $terms as $term ) {\n echo term_description( $term );\n }\n}\n</code></pre>\n"
},
{
"answer_id": 364124,
"author": "pipoulito",
"author_id": 64414,
"author_profile": "https://wordpress.stackexchange.com/users/64414",
"pm_score": 0,
"selected": false,
"text": "<p>@jacob peattie</p>\n\n<p>Sorry I have no rights to add comments so i add another answer, i don't know how do to better...</p>\n\n<p>It seems that <code>get_terms()</code> returns nothing but the organizer taxonomy exists and is not empty.</p>\n"
}
] | 2020/04/14 | [
"https://wordpress.stackexchange.com/questions/364066",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114630/"
] | I have a taxonomy called ORGANIZER.
All the terms of this taxonomy have a name and a description.
I tried to get the description of each term but i don't know how to loop on them.
I suppose i mus begin with:
```
$terms = get_terms( array(
'taxonomy' => 'organizer',
'hide_empty' => false,
) );
```
but could you help me for the loop please ?
thanks | [`get_terms()`](https://developer.wordpress.org/reference/functions/get_terms/) returns an array of [`WP_Term`](https://developer.wordpress.org/reference/classes/wp_term/) objects. To get the description, with the usual filters applied, you can pass this object to [`term_description()`](https://developer.wordpress.org/reference/functions/term_description/):
```
$terms = get_terms( array(
'taxonomy' => 'organizer',
'hide_empty' => false,
) );
if ( ! is_wp_error( $terms ) ) {
foreach ( $terms as $term ) {
echo term_description( $term );
}
}
``` |
364,077 | <p>Okay, so I programmed the following ajax code for my plugin, and I'm wondering why it's not working:</p>
<p>JavaScript:</p>
<pre><code>function myFunction() {
let dataContent = "hello";
let myData = {
// Nonce
_ajax_nonce: "<?php wp_create_nonce( 'nonce-name' );?>",
// Action Hook name for Ajax Call
action: 'my_action',
// Currently typed username
data: dataContent
};
// To send the JavaScript object to the server, convert it into a JSON string
let myDataJSON = JSON.stringify(myData);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
let link = "<?php admin_url( 'admin-ajax.php' );?>";
xhttp.open("POST", link, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("data=" + myDataJSON);
}
</code></pre>
<p>PHP (Callback):</p>
<pre><code>function answer() {
check_ajax_referer( 'nonce-name' );
echo "hello";
}
</code></pre>
<p>PHP (Hook):</p>
<pre><code>add_action( 'wp_ajax_my_action', 'answer' );
</code></pre>
<p>When launching the call, I get "undefined" displayed in the alert window. What's wrong?</p>
| [
{
"answer_id": 364119,
"author": "西門 正 Code Guy",
"author_id": 35701,
"author_profile": "https://wordpress.stackexchange.com/users/35701",
"pm_score": 2,
"selected": true,
"text": "<p>There are 4 filters to work with WordPress ajax.\nAccording to your description, the following conditions are assumed</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/wp_ajax_action/\" rel=\"nofollow noreferrer\"><code>wp_ajax_{$action}</code></a> is for running in frontend and the user is logged in</li>\n<li>if echo something in the php file, it will not reflect in the frontend. Javascript alert will output 'hello'</li>\n<li>your javascript seems to be done in PHP and generate javascript, I suppose you have added proper header</li>\n</ul>\n\n<p>According to WP Codex, the 4 filters for ajax are</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/wp_ajax_action/\" rel=\"nofollow noreferrer\"><code>wp_ajax_{$action}</code></a> Fires authenticated Ajax actions for logged-in users.</li>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/wp_ajax_nopriv__requestaction/\" rel=\"nofollow noreferrer\"><code>wp_ajax_nopriv_{$action}</code></a> Fires non-authenticated Ajax actions for logged-out users.</li>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/admin_post_action/\" rel=\"nofollow noreferrer\"><code>admin_post_{$action}</code></a> Fires on an authenticated admin post request for the given action.</li>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/admin_post_nopriv_action/\" rel=\"nofollow noreferrer\"><code>admin_post_nopriv_{$action}</code></a> Fires on a non-authenticated admin post request for the given action.</li>\n</ul>\n\n<p>Some facts about the code</p>\n\n<ul>\n<li>There are missing <code>echo</code> to output nonce and admin_url</li>\n<li>the script is actually not working (it is according to your shared code, there might be additional code. Anyway, if going to browser inspector, it gives 400 bad request error. It did not send ajax successfully.</li>\n</ul>\n\n<p>There are a few issues in the code, here is the fixed script with missing pieces that I need for doing the test. I put the code into my theme <code>functions.php</code> and javascript code into <code>test.php</code></p>\n\n<p>In the testing, have put in the theme functions.php</p>\n\n<pre><code>// load the javascript\nfunction q364077_enqueue_scripts()\n{\n wp_enqueue_script('test-custom-scripts', get_theme_file_uri('/test.php'), array(), 't' . time(), true);\n}\nadd_action('wp_enqueue_scripts', 'q364077_enqueue_scripts', 101);\n\n// The ajax answer()\nadd_action( 'wp_ajax_my_action', 'answer' );\nfunction answer() {\n // check_ajax_referer( 'nonce-name' );\n echo \"hello\";\n\n wp_die(); // terminate script after any required work, if not, the response text will output 'hello0' because the of function return after finish\n}\n</code></pre>\n\n<p>The test.php is put in the theme folder, same level as functions.php</p>\n\n<pre><code><?php\n// inside the javascript test.php\n/** Load WordPress Bootstrap */\n// for test.php in theme folders\nrequire_once( ( ( dirname( dirname( dirname( dirname( __FILE__ ) ) ) ) ) ) . '/wp-load.php' ); // to use admin_url(), if not, the script will be broken\n\n\n// for output the javascript through php\nheader(\"Content-type: text/javascript\");?>\n\nfunction myFunction() {\n\n let dataContent = \"hello\";\n\n let myData = {\n _ajax_nonce: \"<?php echo wp_create_nonce( 'nonce-name' );?>\", // haven't added echo here, it is actually blank in output.\n // Action Hook name for Ajax Call\n action: 'my_action',\n // Currently typed username\n data: dataContent\n };\n // To send the JavaScript object to the server, convert it into a JSON string\n let myDataJSON = JSON.stringify(myData);\n\n var xhttp = new XMLHttpRequest();\n\n xhttp.onreadystatechange = function() {\n if (this.readyState == 4 && this.status == 200) {\n alert(this.responseText);\n }\n };\n\n let link = \"<?php echo admin_url( 'admin-ajax.php' );?>\"; // require \"echo\" to output, otherwise, it will alert unexpected output\n xhttp.open(\"POST\", link, true);\n xhttp.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded; charset=UTF-8\");\n\n // It is explained in the following, I use static value for illustration purpose\n xhttp.send('_ajax_nonce=efc5e4029d&action=my_action&data=hello');\n</code></pre>\n\n<p>The data need to be serialized, not only string. Your data look likes</p>\n\n<pre><code>{\"_ajax_nonce\":\"efc5e4029d\",\"action\":\"my_action\",\"data\":\"hello\"}\n</code></pre>\n\n<p>Ajax looks for this which jQuery has done for user. For Vanilla JS, it need to be done manually or using any existing vanilla js tools.</p>\n\n<pre><code>_ajax_nonce=efc5e4029d&action=my_action&data=hello\n</code></pre>\n\n<p>You may test the above code by fixing the 'echo' and putting a static value of the data to experience and may also go to the inspector, Chrome as an example.</p>\n\n<p>in the inspector -> Network Tab -> when you fire myFunction() in console log, it return the status to you with request/response header, in that way, it helps bug fixing.</p>\n\n<p>The above code tested and proved working in a fresh WordPress 5.3.2, default twenty twenty theme.</p>\n"
},
{
"answer_id": 364616,
"author": "Joe",
"author_id": 183929,
"author_profile": "https://wordpress.stackexchange.com/users/183929",
"pm_score": 0,
"selected": false,
"text": "<p>You're focusing on the script - side, but the addition of slashes to the json object only happens once the data is sent and received by the server, before being sent back to javascript. Guess I need to find out how to define the datatype in pure javascript in wordpress, with jquery its simply by using dataType:json (tried to serialize in pure js, didn't work, lmk if u get the answer, and thx!) </p>\n"
}
] | 2020/04/14 | [
"https://wordpress.stackexchange.com/questions/364077",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/183929/"
] | Okay, so I programmed the following ajax code for my plugin, and I'm wondering why it's not working:
JavaScript:
```
function myFunction() {
let dataContent = "hello";
let myData = {
// Nonce
_ajax_nonce: "<?php wp_create_nonce( 'nonce-name' );?>",
// Action Hook name for Ajax Call
action: 'my_action',
// Currently typed username
data: dataContent
};
// To send the JavaScript object to the server, convert it into a JSON string
let myDataJSON = JSON.stringify(myData);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
let link = "<?php admin_url( 'admin-ajax.php' );?>";
xhttp.open("POST", link, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("data=" + myDataJSON);
}
```
PHP (Callback):
```
function answer() {
check_ajax_referer( 'nonce-name' );
echo "hello";
}
```
PHP (Hook):
```
add_action( 'wp_ajax_my_action', 'answer' );
```
When launching the call, I get "undefined" displayed in the alert window. What's wrong? | There are 4 filters to work with WordPress ajax.
According to your description, the following conditions are assumed
* [`wp_ajax_{$action}`](https://developer.wordpress.org/reference/hooks/wp_ajax_action/) is for running in frontend and the user is logged in
* if echo something in the php file, it will not reflect in the frontend. Javascript alert will output 'hello'
* your javascript seems to be done in PHP and generate javascript, I suppose you have added proper header
According to WP Codex, the 4 filters for ajax are
* [`wp_ajax_{$action}`](https://developer.wordpress.org/reference/hooks/wp_ajax_action/) Fires authenticated Ajax actions for logged-in users.
* [`wp_ajax_nopriv_{$action}`](https://developer.wordpress.org/reference/hooks/wp_ajax_nopriv__requestaction/) Fires non-authenticated Ajax actions for logged-out users.
* [`admin_post_{$action}`](https://developer.wordpress.org/reference/hooks/admin_post_action/) Fires on an authenticated admin post request for the given action.
* [`admin_post_nopriv_{$action}`](https://developer.wordpress.org/reference/hooks/admin_post_nopriv_action/) Fires on a non-authenticated admin post request for the given action.
Some facts about the code
* There are missing `echo` to output nonce and admin\_url
* the script is actually not working (it is according to your shared code, there might be additional code. Anyway, if going to browser inspector, it gives 400 bad request error. It did not send ajax successfully.
There are a few issues in the code, here is the fixed script with missing pieces that I need for doing the test. I put the code into my theme `functions.php` and javascript code into `test.php`
In the testing, have put in the theme functions.php
```
// load the javascript
function q364077_enqueue_scripts()
{
wp_enqueue_script('test-custom-scripts', get_theme_file_uri('/test.php'), array(), 't' . time(), true);
}
add_action('wp_enqueue_scripts', 'q364077_enqueue_scripts', 101);
// The ajax answer()
add_action( 'wp_ajax_my_action', 'answer' );
function answer() {
// check_ajax_referer( 'nonce-name' );
echo "hello";
wp_die(); // terminate script after any required work, if not, the response text will output 'hello0' because the of function return after finish
}
```
The test.php is put in the theme folder, same level as functions.php
```
<?php
// inside the javascript test.php
/** Load WordPress Bootstrap */
// for test.php in theme folders
require_once( ( ( dirname( dirname( dirname( dirname( __FILE__ ) ) ) ) ) ) . '/wp-load.php' ); // to use admin_url(), if not, the script will be broken
// for output the javascript through php
header("Content-type: text/javascript");?>
function myFunction() {
let dataContent = "hello";
let myData = {
_ajax_nonce: "<?php echo wp_create_nonce( 'nonce-name' );?>", // haven't added echo here, it is actually blank in output.
// Action Hook name for Ajax Call
action: 'my_action',
// Currently typed username
data: dataContent
};
// To send the JavaScript object to the server, convert it into a JSON string
let myDataJSON = JSON.stringify(myData);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
let link = "<?php echo admin_url( 'admin-ajax.php' );?>"; // require "echo" to output, otherwise, it will alert unexpected output
xhttp.open("POST", link, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
// It is explained in the following, I use static value for illustration purpose
xhttp.send('_ajax_nonce=efc5e4029d&action=my_action&data=hello');
```
The data need to be serialized, not only string. Your data look likes
```
{"_ajax_nonce":"efc5e4029d","action":"my_action","data":"hello"}
```
Ajax looks for this which jQuery has done for user. For Vanilla JS, it need to be done manually or using any existing vanilla js tools.
```
_ajax_nonce=efc5e4029d&action=my_action&data=hello
```
You may test the above code by fixing the 'echo' and putting a static value of the data to experience and may also go to the inspector, Chrome as an example.
in the inspector -> Network Tab -> when you fire myFunction() in console log, it return the status to you with request/response header, in that way, it helps bug fixing.
The above code tested and proved working in a fresh WordPress 5.3.2, default twenty twenty theme. |
364,083 | <p>I'm having an issue processing a form.
The project was standalone PHP and I'm integrating it into Wordpress using this:</p>
<pre><code>require_once("../../../wp-load.php");
</code></pre>
<p>The form element is defined as:</p>
<pre><code><form id="new_post" name="new_post" class="form-horizontal" method="post" enctype="multipart/form-data">
</code></pre>
<p>Now, I'm satisfied with the testing, I'm trying to move this in to a wordpress plugin and embed the form on the front end into a particular page using <code>is_page()</code> </p>
<p>Now, the form appears ok but when I submit the form, I get the theme's 404 page showing up instead of the desired output that I was getting in the test version.</p>
<p>I've tried changing the form element to:</p>
<pre><code><form action="<?php echo esc_url( admin_url('admin-post.php') ); ?> id="new_post" name="new_post" class="form-horizontal" method="post" enctype="multipart/form-data">
</code></pre>
<p>but then I just get a white screen.
No errors are showing up in my logs.</p>
<p>Any suggestions on what I'm doing wrong?</p>
| [
{
"answer_id": 364119,
"author": "西門 正 Code Guy",
"author_id": 35701,
"author_profile": "https://wordpress.stackexchange.com/users/35701",
"pm_score": 2,
"selected": true,
"text": "<p>There are 4 filters to work with WordPress ajax.\nAccording to your description, the following conditions are assumed</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/wp_ajax_action/\" rel=\"nofollow noreferrer\"><code>wp_ajax_{$action}</code></a> is for running in frontend and the user is logged in</li>\n<li>if echo something in the php file, it will not reflect in the frontend. Javascript alert will output 'hello'</li>\n<li>your javascript seems to be done in PHP and generate javascript, I suppose you have added proper header</li>\n</ul>\n\n<p>According to WP Codex, the 4 filters for ajax are</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/wp_ajax_action/\" rel=\"nofollow noreferrer\"><code>wp_ajax_{$action}</code></a> Fires authenticated Ajax actions for logged-in users.</li>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/wp_ajax_nopriv__requestaction/\" rel=\"nofollow noreferrer\"><code>wp_ajax_nopriv_{$action}</code></a> Fires non-authenticated Ajax actions for logged-out users.</li>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/admin_post_action/\" rel=\"nofollow noreferrer\"><code>admin_post_{$action}</code></a> Fires on an authenticated admin post request for the given action.</li>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/admin_post_nopriv_action/\" rel=\"nofollow noreferrer\"><code>admin_post_nopriv_{$action}</code></a> Fires on a non-authenticated admin post request for the given action.</li>\n</ul>\n\n<p>Some facts about the code</p>\n\n<ul>\n<li>There are missing <code>echo</code> to output nonce and admin_url</li>\n<li>the script is actually not working (it is according to your shared code, there might be additional code. Anyway, if going to browser inspector, it gives 400 bad request error. It did not send ajax successfully.</li>\n</ul>\n\n<p>There are a few issues in the code, here is the fixed script with missing pieces that I need for doing the test. I put the code into my theme <code>functions.php</code> and javascript code into <code>test.php</code></p>\n\n<p>In the testing, have put in the theme functions.php</p>\n\n<pre><code>// load the javascript\nfunction q364077_enqueue_scripts()\n{\n wp_enqueue_script('test-custom-scripts', get_theme_file_uri('/test.php'), array(), 't' . time(), true);\n}\nadd_action('wp_enqueue_scripts', 'q364077_enqueue_scripts', 101);\n\n// The ajax answer()\nadd_action( 'wp_ajax_my_action', 'answer' );\nfunction answer() {\n // check_ajax_referer( 'nonce-name' );\n echo \"hello\";\n\n wp_die(); // terminate script after any required work, if not, the response text will output 'hello0' because the of function return after finish\n}\n</code></pre>\n\n<p>The test.php is put in the theme folder, same level as functions.php</p>\n\n<pre><code><?php\n// inside the javascript test.php\n/** Load WordPress Bootstrap */\n// for test.php in theme folders\nrequire_once( ( ( dirname( dirname( dirname( dirname( __FILE__ ) ) ) ) ) ) . '/wp-load.php' ); // to use admin_url(), if not, the script will be broken\n\n\n// for output the javascript through php\nheader(\"Content-type: text/javascript\");?>\n\nfunction myFunction() {\n\n let dataContent = \"hello\";\n\n let myData = {\n _ajax_nonce: \"<?php echo wp_create_nonce( 'nonce-name' );?>\", // haven't added echo here, it is actually blank in output.\n // Action Hook name for Ajax Call\n action: 'my_action',\n // Currently typed username\n data: dataContent\n };\n // To send the JavaScript object to the server, convert it into a JSON string\n let myDataJSON = JSON.stringify(myData);\n\n var xhttp = new XMLHttpRequest();\n\n xhttp.onreadystatechange = function() {\n if (this.readyState == 4 && this.status == 200) {\n alert(this.responseText);\n }\n };\n\n let link = \"<?php echo admin_url( 'admin-ajax.php' );?>\"; // require \"echo\" to output, otherwise, it will alert unexpected output\n xhttp.open(\"POST\", link, true);\n xhttp.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded; charset=UTF-8\");\n\n // It is explained in the following, I use static value for illustration purpose\n xhttp.send('_ajax_nonce=efc5e4029d&action=my_action&data=hello');\n</code></pre>\n\n<p>The data need to be serialized, not only string. Your data look likes</p>\n\n<pre><code>{\"_ajax_nonce\":\"efc5e4029d\",\"action\":\"my_action\",\"data\":\"hello\"}\n</code></pre>\n\n<p>Ajax looks for this which jQuery has done for user. For Vanilla JS, it need to be done manually or using any existing vanilla js tools.</p>\n\n<pre><code>_ajax_nonce=efc5e4029d&action=my_action&data=hello\n</code></pre>\n\n<p>You may test the above code by fixing the 'echo' and putting a static value of the data to experience and may also go to the inspector, Chrome as an example.</p>\n\n<p>in the inspector -> Network Tab -> when you fire myFunction() in console log, it return the status to you with request/response header, in that way, it helps bug fixing.</p>\n\n<p>The above code tested and proved working in a fresh WordPress 5.3.2, default twenty twenty theme.</p>\n"
},
{
"answer_id": 364616,
"author": "Joe",
"author_id": 183929,
"author_profile": "https://wordpress.stackexchange.com/users/183929",
"pm_score": 0,
"selected": false,
"text": "<p>You're focusing on the script - side, but the addition of slashes to the json object only happens once the data is sent and received by the server, before being sent back to javascript. Guess I need to find out how to define the datatype in pure javascript in wordpress, with jquery its simply by using dataType:json (tried to serialize in pure js, didn't work, lmk if u get the answer, and thx!) </p>\n"
}
] | 2020/04/14 | [
"https://wordpress.stackexchange.com/questions/364083",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/36980/"
] | I'm having an issue processing a form.
The project was standalone PHP and I'm integrating it into Wordpress using this:
```
require_once("../../../wp-load.php");
```
The form element is defined as:
```
<form id="new_post" name="new_post" class="form-horizontal" method="post" enctype="multipart/form-data">
```
Now, I'm satisfied with the testing, I'm trying to move this in to a wordpress plugin and embed the form on the front end into a particular page using `is_page()`
Now, the form appears ok but when I submit the form, I get the theme's 404 page showing up instead of the desired output that I was getting in the test version.
I've tried changing the form element to:
```
<form action="<?php echo esc_url( admin_url('admin-post.php') ); ?> id="new_post" name="new_post" class="form-horizontal" method="post" enctype="multipart/form-data">
```
but then I just get a white screen.
No errors are showing up in my logs.
Any suggestions on what I'm doing wrong? | There are 4 filters to work with WordPress ajax.
According to your description, the following conditions are assumed
* [`wp_ajax_{$action}`](https://developer.wordpress.org/reference/hooks/wp_ajax_action/) is for running in frontend and the user is logged in
* if echo something in the php file, it will not reflect in the frontend. Javascript alert will output 'hello'
* your javascript seems to be done in PHP and generate javascript, I suppose you have added proper header
According to WP Codex, the 4 filters for ajax are
* [`wp_ajax_{$action}`](https://developer.wordpress.org/reference/hooks/wp_ajax_action/) Fires authenticated Ajax actions for logged-in users.
* [`wp_ajax_nopriv_{$action}`](https://developer.wordpress.org/reference/hooks/wp_ajax_nopriv__requestaction/) Fires non-authenticated Ajax actions for logged-out users.
* [`admin_post_{$action}`](https://developer.wordpress.org/reference/hooks/admin_post_action/) Fires on an authenticated admin post request for the given action.
* [`admin_post_nopriv_{$action}`](https://developer.wordpress.org/reference/hooks/admin_post_nopriv_action/) Fires on a non-authenticated admin post request for the given action.
Some facts about the code
* There are missing `echo` to output nonce and admin\_url
* the script is actually not working (it is according to your shared code, there might be additional code. Anyway, if going to browser inspector, it gives 400 bad request error. It did not send ajax successfully.
There are a few issues in the code, here is the fixed script with missing pieces that I need for doing the test. I put the code into my theme `functions.php` and javascript code into `test.php`
In the testing, have put in the theme functions.php
```
// load the javascript
function q364077_enqueue_scripts()
{
wp_enqueue_script('test-custom-scripts', get_theme_file_uri('/test.php'), array(), 't' . time(), true);
}
add_action('wp_enqueue_scripts', 'q364077_enqueue_scripts', 101);
// The ajax answer()
add_action( 'wp_ajax_my_action', 'answer' );
function answer() {
// check_ajax_referer( 'nonce-name' );
echo "hello";
wp_die(); // terminate script after any required work, if not, the response text will output 'hello0' because the of function return after finish
}
```
The test.php is put in the theme folder, same level as functions.php
```
<?php
// inside the javascript test.php
/** Load WordPress Bootstrap */
// for test.php in theme folders
require_once( ( ( dirname( dirname( dirname( dirname( __FILE__ ) ) ) ) ) ) . '/wp-load.php' ); // to use admin_url(), if not, the script will be broken
// for output the javascript through php
header("Content-type: text/javascript");?>
function myFunction() {
let dataContent = "hello";
let myData = {
_ajax_nonce: "<?php echo wp_create_nonce( 'nonce-name' );?>", // haven't added echo here, it is actually blank in output.
// Action Hook name for Ajax Call
action: 'my_action',
// Currently typed username
data: dataContent
};
// To send the JavaScript object to the server, convert it into a JSON string
let myDataJSON = JSON.stringify(myData);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
let link = "<?php echo admin_url( 'admin-ajax.php' );?>"; // require "echo" to output, otherwise, it will alert unexpected output
xhttp.open("POST", link, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
// It is explained in the following, I use static value for illustration purpose
xhttp.send('_ajax_nonce=efc5e4029d&action=my_action&data=hello');
```
The data need to be serialized, not only string. Your data look likes
```
{"_ajax_nonce":"efc5e4029d","action":"my_action","data":"hello"}
```
Ajax looks for this which jQuery has done for user. For Vanilla JS, it need to be done manually or using any existing vanilla js tools.
```
_ajax_nonce=efc5e4029d&action=my_action&data=hello
```
You may test the above code by fixing the 'echo' and putting a static value of the data to experience and may also go to the inspector, Chrome as an example.
in the inspector -> Network Tab -> when you fire myFunction() in console log, it return the status to you with request/response header, in that way, it helps bug fixing.
The above code tested and proved working in a fresh WordPress 5.3.2, default twenty twenty theme. |
364,095 | <p>I managed to finally get the ServerSideRender to work. But how do I reload the ServerSideRender when the post is saved? </p>
<pre><code> save: props => {
return null;
},
</code></pre>
<p>I think here I need something like a trigger to load the data again from my plugin.php Can somebody please tell me where to look? The serversiderender lists the headings structure and needs to display new data when the post is updated. Here is the whole index.js for the block.</p>
<pre><code>const { __, setLocaleData } = wp.i18n;
const { registerBlockType } = wp.blocks;
const listul = wp.element.createElement('svg',
{
width: 20,
height: 20
},
wp.element.createElement( 'path',
{
d: "M5.5 7C4.67 7 4 6.33 4 5.5 4 4.68 4.67 4 5.5 4 6.32 4 7 4.68 7 5.5 7 6.33 6.32 7 5.5 7zM8 5h9v1H8V5zm-2.5 7c-.83 0-1.5-.67-1.5-1.5C4 9.68 4.67 9 5.5 9c.82 0 1.5.68 1.5 1.5 0 .83-.68 1.5-1.5 1.5zM8 10h9v1H8v-1zm-2.5 7c-.83 0-1.5-.67-1.5-1.5 0-.82.67-1.5 1.5-1.5.82 0 1.5.68 1.5 1.5 0 .83-.68 1.5-1.5 1.5zM8 15h9v1H8v-1z"
}
)
);
import ServerSideRender from '@wordpress/server-side-render';
registerBlockType( 'simpletoc/toc', {
title: __( 'SimpleTOC', 'simpletoc' ),
icon: listul,
category: 'layout',
edit: function( props ) {
return (
<p className={ props.className }>
<ServerSideRender
block="simpletoc/toc"
attributes={ props.attributes }
/>
</p>
);
},
save: props => {
return null;
},
} );
</code></pre>
| [
{
"answer_id": 364805,
"author": "Marc",
"author_id": 33797,
"author_profile": "https://wordpress.stackexchange.com/users/33797",
"pm_score": 2,
"selected": true,
"text": "<p>I solved it with an \"update\" button in the block. It is a bit weird because I need to send \"fake\" attributes to re-render it. But it works.</p>\n\n<pre><code>var el = wp.element.createElement;\nvar registerBlockType = wp.blocks.registerBlockType;\nvar BlockControls = wp.blockEditor.BlockControls;\nvar ServerSideRender = wp.serverSideRender;\nvar Toolbar = wp.components.Toolbar;\nvar IconButton = wp.components.Button;\n\nfunction sendfakeAttribute(props) {\n // this actually triggers the ServerSideRender again ¯\\_(ツ)_/¯\n props.setAttributes({ updated: Date.now() });\n}\n\nregisterBlockType( 'simpletoc/toc', {\n title: __( 'SimpleTOC', 'simpletoc' ),\n icon: listul,\n category: 'layout',\n edit: function( props ) {\n\n return [\n el(\n BlockControls,\n { key: 'controls' },\n el(\n Toolbar,\n null,\n el(\n IconButton,\n {\n className: 'components-icon-button components-toolbar__control',\n label: 'update',\n onClick: function() { sendfakeAttribute(props) },\n icon: 'update'\n }\n )\n )\n ),\n el(\n ServerSideRender,\n {\n block: props.name,\n attributes: props.attributes\n }\n )\n ];\n\n\n },\n save: props => {\n return null;\n },\n} );\n</code></pre>\n"
},
{
"answer_id": 409914,
"author": "kitchin",
"author_id": 34438,
"author_profile": "https://wordpress.stackexchange.com/users/34438",
"pm_score": 0,
"selected": false,
"text": "<p>Another workaround I found, <code>urlQueryArgs</code> always triggers <code>ServerSideRender</code>:</p>\n<pre><code>ServerSideRender,\n{\n block: props.name,\n attributes: props.attributes,\n urlQueryArgs: { foo: 1 }\n}\n</code></pre>\n<p>even though <code>foo</code> never changes. But this workaround is undocumented, as far as I know, so not a good idea in case WP decides to code more change checks.</p>\n<p>So your own answer is better, Marc.</p>\n<p>I found out the hard way that you are very right to use</p>\n<pre><code>props.setAttributes({ updated: Date.now() });\n</code></pre>\n<p>instead of</p>\n<pre><code>props.updated = Date.now();\n</code></pre>\n<p>Two things were news to me:</p>\n<ol>\n<li><code>setAttributes()</code> merges existing properties instead of setting all properties.</li>\n<li><code>setAttributes()</code> flags <code>wp.element</code> (or <code>wp</code>) to run <code>ServerSideRender</code>.</li>\n</ol>\n<p>By inspection, <code>function ServerSideRender()</code> in 'wp-includes/js/dist/server-side-render.js' checks if the properties have changed before fetching. But if you debug the script you see <code>ServerSideRender</code> does not even get called again unless <code>setAttributes()</code> is used.</p>\n"
}
] | 2020/04/14 | [
"https://wordpress.stackexchange.com/questions/364095",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/33797/"
] | I managed to finally get the ServerSideRender to work. But how do I reload the ServerSideRender when the post is saved?
```
save: props => {
return null;
},
```
I think here I need something like a trigger to load the data again from my plugin.php Can somebody please tell me where to look? The serversiderender lists the headings structure and needs to display new data when the post is updated. Here is the whole index.js for the block.
```
const { __, setLocaleData } = wp.i18n;
const { registerBlockType } = wp.blocks;
const listul = wp.element.createElement('svg',
{
width: 20,
height: 20
},
wp.element.createElement( 'path',
{
d: "M5.5 7C4.67 7 4 6.33 4 5.5 4 4.68 4.67 4 5.5 4 6.32 4 7 4.68 7 5.5 7 6.33 6.32 7 5.5 7zM8 5h9v1H8V5zm-2.5 7c-.83 0-1.5-.67-1.5-1.5C4 9.68 4.67 9 5.5 9c.82 0 1.5.68 1.5 1.5 0 .83-.68 1.5-1.5 1.5zM8 10h9v1H8v-1zm-2.5 7c-.83 0-1.5-.67-1.5-1.5 0-.82.67-1.5 1.5-1.5.82 0 1.5.68 1.5 1.5 0 .83-.68 1.5-1.5 1.5zM8 15h9v1H8v-1z"
}
)
);
import ServerSideRender from '@wordpress/server-side-render';
registerBlockType( 'simpletoc/toc', {
title: __( 'SimpleTOC', 'simpletoc' ),
icon: listul,
category: 'layout',
edit: function( props ) {
return (
<p className={ props.className }>
<ServerSideRender
block="simpletoc/toc"
attributes={ props.attributes }
/>
</p>
);
},
save: props => {
return null;
},
} );
``` | I solved it with an "update" button in the block. It is a bit weird because I need to send "fake" attributes to re-render it. But it works.
```
var el = wp.element.createElement;
var registerBlockType = wp.blocks.registerBlockType;
var BlockControls = wp.blockEditor.BlockControls;
var ServerSideRender = wp.serverSideRender;
var Toolbar = wp.components.Toolbar;
var IconButton = wp.components.Button;
function sendfakeAttribute(props) {
// this actually triggers the ServerSideRender again ¯\_(ツ)_/¯
props.setAttributes({ updated: Date.now() });
}
registerBlockType( 'simpletoc/toc', {
title: __( 'SimpleTOC', 'simpletoc' ),
icon: listul,
category: 'layout',
edit: function( props ) {
return [
el(
BlockControls,
{ key: 'controls' },
el(
Toolbar,
null,
el(
IconButton,
{
className: 'components-icon-button components-toolbar__control',
label: 'update',
onClick: function() { sendfakeAttribute(props) },
icon: 'update'
}
)
)
),
el(
ServerSideRender,
{
block: props.name,
attributes: props.attributes
}
)
];
},
save: props => {
return null;
},
} );
``` |
364,107 | <p>I found this code to functions.php</p>
<pre><code>add_filter( 'wp_default_editor', create_function('', 'return "html";') );
</code></pre>
<p>but I need to limit it to a specific set of roles (such as Editor or Author).</p>
<p>How do I do that?</p>
<p>Thanks!</p>
| [
{
"answer_id": 364112,
"author": "Tony Djukic",
"author_id": 60844,
"author_profile": "https://wordpress.stackexchange.com/users/60844",
"pm_score": 0,
"selected": false,
"text": "<p>This should do it for you.</p>\n\n<pre><code>if ( current_user_can( 'editor' ) || current_user_can( 'author' ) ) {\n add_filter( 'wp_default_editor', create_function( '', 'return \"html\";' ) );\n}\n</code></pre>\n\n<p>Basically what you're doing is asking if the current user is an <em>editor</em> or an <em>author</em> before you add the filter.</p>\n\n<p>As you mentioned, you essentially put this code into your <em>functions.php</em> file. </p>\n"
},
{
"answer_id": 364116,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p><code>create_function()</code> is deprecated as of PHP 7.2.0, so you should avoid using it. Instead, use an <a href=\"https://www.php.net/manual/en/functions.anonymous.php\" rel=\"nofollow noreferrer\">anonymous function</a>. </p>\n\n<p>Additionally, it's better the check the current user role <em>inside</em> the callback function, so that the current user role is checked when the filter is applied, not when the hook is added, which could be before the current user role can be determined.</p>\n\n<pre><code>add_filter(\n 'wp_default_editor',\n function( $default_editor ) {\n if ( current_user_can( 'editor' ) || current_user_can( 'author' ) ) {\n $default_editor = 'html';\n }\n\n return $default_editor;\n }\n);\n</code></pre>\n"
}
] | 2020/04/14 | [
"https://wordpress.stackexchange.com/questions/364107",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/186114/"
] | I found this code to functions.php
```
add_filter( 'wp_default_editor', create_function('', 'return "html";') );
```
but I need to limit it to a specific set of roles (such as Editor or Author).
How do I do that?
Thanks! | `create_function()` is deprecated as of PHP 7.2.0, so you should avoid using it. Instead, use an [anonymous function](https://www.php.net/manual/en/functions.anonymous.php).
Additionally, it's better the check the current user role *inside* the callback function, so that the current user role is checked when the filter is applied, not when the hook is added, which could be before the current user role can be determined.
```
add_filter(
'wp_default_editor',
function( $default_editor ) {
if ( current_user_can( 'editor' ) || current_user_can( 'author' ) ) {
$default_editor = 'html';
}
return $default_editor;
}
);
``` |
364,177 | <p>I have a form that redirects to a payment platform and sends data in $_POST.</p>
<pre><code><form method="POST" action="https://www.paiementgateway.com/paiement/order1.pl" accept-charset="UTF8" id="knp-form" target="_top">
<table border="0" cellpadding="2" cellspacing="0" width="20%">
<meta charset="UTF-8">
<tr>
<td width="50%">Nom:</td>
<td width="50%"><input type="text" name="NOM" size="24" value=""></td>
</tr>
<tr>
<td width="50%">Prenom:</td>
<td width="50%"><input type="text" name="PRENOM" size="24" value=""></td>
</tr>
<tr>
<td width="50%">Adresse:</td>
<td width="50%"><input type="text" name="ADRESSE" size="24" value=""></td>
</tr>
<tr>
<td width="50%">Code Postal:</td>
<td width="50%"><input type="text" name="CODEPOSTAL" size="24" value=""></td>
</tr>
<tr>
<td width="50%">Ville:</td>
<td width="50%"><input type="text" name="VILLE" size="24" value=""></td>
</tr>
<tr>
<td width="50%">Pays:</td>
<td width="50%"><select size="1" name="PAYS">
<option value="CH" selected="selected">Suisse </option>
<option value="FR">France</option>
</select>
</td>
</tr>
<tr>
<td width="50%">Tel:</font></td>
<td width="50%"><input type="text" name="TEL" size="24" value=""></td>
</tr>
<tr>
<td width="50%">E-mail:</font></td>
<td width="50%"><input type="text" name="EMAIL" size="24" value=""></td>
</tr>
<input type="hidden" name="ID" value="1234567890">
<input type="hidden" name="ABONNEMENT" value="123ABC465DEF7890">
<tr>
<td width="100%" colspan="2">
<p align="center"><input type="submit" value="Envoyer" name="B1"></p></td>
</tr>
</table>
</code></pre>
<p>I wanted to create an action like a user registration but unfortunately the action doesn't seem to work.</p>
<p>The user is redirected to the payment platform without the user being created on WP.</p>
<pre><code>function traitement_formulaire_inscription() {
if (isset($_POST['B1'])) {
$user_login = sanitize_text_field( $_POST['EMAIL'] );
$user_email = sanitize_email( $_POST['EMAIL'] );
$user = register_new_user( $user_login, $user_email );
}
}
add_action('template_redirect', 'traitement_formulaire_inscription', 5);
</code></pre>
| [
{
"answer_id": 364112,
"author": "Tony Djukic",
"author_id": 60844,
"author_profile": "https://wordpress.stackexchange.com/users/60844",
"pm_score": 0,
"selected": false,
"text": "<p>This should do it for you.</p>\n\n<pre><code>if ( current_user_can( 'editor' ) || current_user_can( 'author' ) ) {\n add_filter( 'wp_default_editor', create_function( '', 'return \"html\";' ) );\n}\n</code></pre>\n\n<p>Basically what you're doing is asking if the current user is an <em>editor</em> or an <em>author</em> before you add the filter.</p>\n\n<p>As you mentioned, you essentially put this code into your <em>functions.php</em> file. </p>\n"
},
{
"answer_id": 364116,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p><code>create_function()</code> is deprecated as of PHP 7.2.0, so you should avoid using it. Instead, use an <a href=\"https://www.php.net/manual/en/functions.anonymous.php\" rel=\"nofollow noreferrer\">anonymous function</a>. </p>\n\n<p>Additionally, it's better the check the current user role <em>inside</em> the callback function, so that the current user role is checked when the filter is applied, not when the hook is added, which could be before the current user role can be determined.</p>\n\n<pre><code>add_filter(\n 'wp_default_editor',\n function( $default_editor ) {\n if ( current_user_can( 'editor' ) || current_user_can( 'author' ) ) {\n $default_editor = 'html';\n }\n\n return $default_editor;\n }\n);\n</code></pre>\n"
}
] | 2020/04/15 | [
"https://wordpress.stackexchange.com/questions/364177",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/186169/"
] | I have a form that redirects to a payment platform and sends data in $\_POST.
```
<form method="POST" action="https://www.paiementgateway.com/paiement/order1.pl" accept-charset="UTF8" id="knp-form" target="_top">
<table border="0" cellpadding="2" cellspacing="0" width="20%">
<meta charset="UTF-8">
<tr>
<td width="50%">Nom:</td>
<td width="50%"><input type="text" name="NOM" size="24" value=""></td>
</tr>
<tr>
<td width="50%">Prenom:</td>
<td width="50%"><input type="text" name="PRENOM" size="24" value=""></td>
</tr>
<tr>
<td width="50%">Adresse:</td>
<td width="50%"><input type="text" name="ADRESSE" size="24" value=""></td>
</tr>
<tr>
<td width="50%">Code Postal:</td>
<td width="50%"><input type="text" name="CODEPOSTAL" size="24" value=""></td>
</tr>
<tr>
<td width="50%">Ville:</td>
<td width="50%"><input type="text" name="VILLE" size="24" value=""></td>
</tr>
<tr>
<td width="50%">Pays:</td>
<td width="50%"><select size="1" name="PAYS">
<option value="CH" selected="selected">Suisse </option>
<option value="FR">France</option>
</select>
</td>
</tr>
<tr>
<td width="50%">Tel:</font></td>
<td width="50%"><input type="text" name="TEL" size="24" value=""></td>
</tr>
<tr>
<td width="50%">E-mail:</font></td>
<td width="50%"><input type="text" name="EMAIL" size="24" value=""></td>
</tr>
<input type="hidden" name="ID" value="1234567890">
<input type="hidden" name="ABONNEMENT" value="123ABC465DEF7890">
<tr>
<td width="100%" colspan="2">
<p align="center"><input type="submit" value="Envoyer" name="B1"></p></td>
</tr>
</table>
```
I wanted to create an action like a user registration but unfortunately the action doesn't seem to work.
The user is redirected to the payment platform without the user being created on WP.
```
function traitement_formulaire_inscription() {
if (isset($_POST['B1'])) {
$user_login = sanitize_text_field( $_POST['EMAIL'] );
$user_email = sanitize_email( $_POST['EMAIL'] );
$user = register_new_user( $user_login, $user_email );
}
}
add_action('template_redirect', 'traitement_formulaire_inscription', 5);
``` | `create_function()` is deprecated as of PHP 7.2.0, so you should avoid using it. Instead, use an [anonymous function](https://www.php.net/manual/en/functions.anonymous.php).
Additionally, it's better the check the current user role *inside* the callback function, so that the current user role is checked when the filter is applied, not when the hook is added, which could be before the current user role can be determined.
```
add_filter(
'wp_default_editor',
function( $default_editor ) {
if ( current_user_can( 'editor' ) || current_user_can( 'author' ) ) {
$default_editor = 'html';
}
return $default_editor;
}
);
``` |
364,211 | <p>i'm adding a function in my child theme's functions.php file that will only work on a specific page. </p>
<p>i can successfully Enqueue a 3rd-party jquery script.</p>
<p>and i can successfully add my own bit of jquery/js.</p>
<p>but i'm wondering if i can add these two things within the same function wrapper.</p>
<p>so here's the part for adding the external script:</p>
<pre><code>function custom_thing () {
if(is_page( 2138 )){
wp_enqueue_script('external-script', 'http://domain.com/external/script.js', array('jquery'), 0, true);
}}
add_action( 'wp_enqueue_scripts', 'custom_thing' );
</code></pre>
<p>and here's the extra bit of code i need that goes with the external script:</p>
<pre><code>function custom_thing_addition () {
if(is_page( 2138 )){
?>
<script>
jQuery(document).ready(function($) {
$("div.specific").on('click', 'div.thing1', function () {
//do somethiing
});
});
</script>
<?php
}}
add_action( 'wp_footer', 'custom_thing_addition' );
</code></pre>
<p>can i combine these? perhaps something like this (tho this does NOT work)...</p>
<pre><code>function custom_thing () {
if(is_page( 2138 )){
wp_enqueue_script('external-script', 'http://domain.com/external/script.js', array('jquery'), 0, true);
?>
<script>
jQuery(document).ready(function($) {
$("div.specific").on('click', 'div.thing1', function () {
//do somethiing
});
});
</script>
<?php
}}
add_action( 'wp_enqueue_scripts', 'custom_thing' );
</code></pre>
<p>thanks.</p>
| [
{
"answer_id": 364214,
"author": "Tony Djukic",
"author_id": 60844,
"author_profile": "https://wordpress.stackexchange.com/users/60844",
"pm_score": 1,
"selected": false,
"text": "<p>The correct way to do this and make things easier for yourself is to put your secondary code into it's own file. Let's call it <code>custom_thing.js</code> and lets just put it in the main child theme folder:</p>\n\n<p>Then you'd simply do this:</p>\n\n<pre><code>function custom_thing() {\n if( is_page( 2138 ) ) {\n wp_enqueue_script( 'external-script', 'http://domain.com/external/script.js', array( 'jquery' ), 0, true );\n wp_enqueue_script( 'custom_thing-script', get_stylesheet_directory_uri() . '/custom_thing.js', array( 'jquery' ), 0, true );\n }\n}\nadd_action( 'wp_enqueue_scripts', 'custom_thing' );\n</code></pre>\n\n<p>Sometimes, if the code library/jQuery plugin I'm including in the theme is something that I can host locally rather than a CDN, I just append my instantiation JS to the bottom of the code library file so that I'm including less scripts. However, if I'm working off a CDN hosted library I do it this way.</p>\n\n<p><strong>Edited</strong></p>\n\n<p>As Jacob Pettie pointed out in the comment, I forgot the correct function to call the child theme's directory and instead was attempting to include the JS from the parent theme, where it doesn't exist. Have edited answer to use <code>get_stylesheet_directory_uri()</code> instead.</p>\n"
},
{
"answer_id": 364218,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>The <a href=\"https://developer.wordpress.org/reference/functions/wp_add_inline_script/\" rel=\"nofollow noreferrer\"><code>wp_add_inline_script()</code></a> is designed for this purpose. It lets you add some inline JavaScript above or below an enqueued script. You just need to pass the contents of the script, <em>without</em> <code><script></code> tags:</p>\n\n<pre><code>function custom_thing () {\n if ( is_page( 2138 ) ) {\n wp_enqueue_script( 'external-script', 'http://domain.com/external/script.js', array( 'jquery' ), 0, true );\n wp_add_inline_script(\n 'external-script',\n 'jQuery( document ).ready( function( $ ) {\n $( \"div.specific\" ).on( \"click\", \"div.thing\", function () {\n //do somethiing\n } );\n } );',\n 'after'\n );\n );\n}\nadd_action( 'wp_enqueue_scripts', 'custom_thing' );\n</code></pre>\n\n<p>The JavaScript itself is passed as a string, so just be careful about quotes. If the script is long enough that this becomes unwieldy, you'd be better off putting your JavaScript into its own file, and setting the external script as a dependency:</p>\n\n<pre><code>function custom_thing() {\n if ( is_page( 2138 ) ) {\n wp_enqueue_script( 'external-script', 'http://domain.com/external/script.js', array( 'jquery' ), 0, true );\n wp_enqueue_script( 'custom-script', get_theme_file_uri( 'path/to/custom-script.js' ), array( 'jquery', 'external-script' ), 0, true );\n }\n}\nadd_action( 'wp_enqueue_scripts', 'custom_thing' );\n</code></pre>\n"
}
] | 2020/04/16 | [
"https://wordpress.stackexchange.com/questions/364211",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58663/"
] | i'm adding a function in my child theme's functions.php file that will only work on a specific page.
i can successfully Enqueue a 3rd-party jquery script.
and i can successfully add my own bit of jquery/js.
but i'm wondering if i can add these two things within the same function wrapper.
so here's the part for adding the external script:
```
function custom_thing () {
if(is_page( 2138 )){
wp_enqueue_script('external-script', 'http://domain.com/external/script.js', array('jquery'), 0, true);
}}
add_action( 'wp_enqueue_scripts', 'custom_thing' );
```
and here's the extra bit of code i need that goes with the external script:
```
function custom_thing_addition () {
if(is_page( 2138 )){
?>
<script>
jQuery(document).ready(function($) {
$("div.specific").on('click', 'div.thing1', function () {
//do somethiing
});
});
</script>
<?php
}}
add_action( 'wp_footer', 'custom_thing_addition' );
```
can i combine these? perhaps something like this (tho this does NOT work)...
```
function custom_thing () {
if(is_page( 2138 )){
wp_enqueue_script('external-script', 'http://domain.com/external/script.js', array('jquery'), 0, true);
?>
<script>
jQuery(document).ready(function($) {
$("div.specific").on('click', 'div.thing1', function () {
//do somethiing
});
});
</script>
<?php
}}
add_action( 'wp_enqueue_scripts', 'custom_thing' );
```
thanks. | The [`wp_add_inline_script()`](https://developer.wordpress.org/reference/functions/wp_add_inline_script/) is designed for this purpose. It lets you add some inline JavaScript above or below an enqueued script. You just need to pass the contents of the script, *without* `<script>` tags:
```
function custom_thing () {
if ( is_page( 2138 ) ) {
wp_enqueue_script( 'external-script', 'http://domain.com/external/script.js', array( 'jquery' ), 0, true );
wp_add_inline_script(
'external-script',
'jQuery( document ).ready( function( $ ) {
$( "div.specific" ).on( "click", "div.thing", function () {
//do somethiing
} );
} );',
'after'
);
);
}
add_action( 'wp_enqueue_scripts', 'custom_thing' );
```
The JavaScript itself is passed as a string, so just be careful about quotes. If the script is long enough that this becomes unwieldy, you'd be better off putting your JavaScript into its own file, and setting the external script as a dependency:
```
function custom_thing() {
if ( is_page( 2138 ) ) {
wp_enqueue_script( 'external-script', 'http://domain.com/external/script.js', array( 'jquery' ), 0, true );
wp_enqueue_script( 'custom-script', get_theme_file_uri( 'path/to/custom-script.js' ), array( 'jquery', 'external-script' ), 0, true );
}
}
add_action( 'wp_enqueue_scripts', 'custom_thing' );
``` |
364,406 | <p>I would like specific users to only see the WooCommerce -> Settings -> Shipping menu. I've managed to remove other tabs e.g. Products, Payments, etc, but stuck on the following 2 things that I want to to accomplish:</p>
<ol>
<li>Remove the "GENERAL" Tab in WooCommerce Settings.</li>
<li>Remove the "ORDER STATUSES" Tab from a plugin. (Note: this isn't a tab exactly, the slug is
'edit.php?post_type=wc_order_status')</li>
</ol>
<p><a href="https://i.stack.imgur.com/XI6lc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XI6lc.png" alt="enter image description here"></a></p>
<p>When I try to remove the GENERAL tab, it eliminates the entire Settings menu. As for the 'Order Statuses', my code just doesn't work.</p>
<pre><code>add_filter( 'woocommerce_settings_tabs_array', 'remove_woocommerce_setting_tabs', 200, 1 );
function remove_woocommerce_setting_tabs( $array ) {
global $current_user;
//Declare the tabs we want to hide
$tabs_to_hide = array(
'general' => 'General', //this one removes the entire Settings menu
'wc_order_status' => 'Order Statuses'// this doesn't work, maybe bc it's a post_type
);
// Remove tab if user role is shipping_manager
if ( in_array("shipping_manager", $$current_user->roles) ) {
$array = array_diff_key($array, $tabs_to_hide);
}
}
</code></pre>
<p>I had also tried the below code to remove the ORDER STATUSES tab, but still no luck:</p>
<pre><code> add_action( 'admin_menu', 'remove_order_statuses_tab', 999);
function remove_order_statuses_tab()
{
global $current_user;
if ( in_array("shipping_manager", $current_user->roles) ) {
remove_menu_page( 'edit.php?post_type=wc_order_status' ); //not working either
}
}
</code></pre>
| [
{
"answer_id": 364300,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p><strong>Terms/Tags aren't ordered</strong>.</p>\n\n<p>To help make the terms easier to read, the editor will list them alphabetically, but that isn't because they're ordered alphabetically in the database. It's because a piece of javascript sorted the terms in the UI control.</p>\n\n<p>There is no order, only the order you give them. Fundamentally terms have no order. Any order you see in the editor is purely circumstantial, there is no order mechanism in the database for terms.</p>\n\n<p>If you want to give special meaning to a term, you need to do so explicitly, e.g. store the term ID of the significant term in post meta. You cannot rely on order, as terms do not have order.</p>\n"
},
{
"answer_id": 376736,
"author": "giorgos",
"author_id": 80294,
"author_profile": "https://wordpress.stackexchange.com/users/80294",
"pm_score": 0,
"selected": false,
"text": "<p>I faced the same issue and saw that while there is the <code>wp_term_relationships</code> table, it doesn't get properly updated with the tags' order on post update. As a workaround, I hooked into the <code>rest_after_insert_this-post_type</code> to update the order myself. Here is <a href=\"https://www.gsarigiannidis.gr/wordpress-post-tags-order/\" rel=\"nofollow noreferrer\">a more detailed explanation</a> of what I did, along with some code that seems to work fine so far.</p>\n"
}
] | 2020/04/17 | [
"https://wordpress.stackexchange.com/questions/364406",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/186344/"
] | I would like specific users to only see the WooCommerce -> Settings -> Shipping menu. I've managed to remove other tabs e.g. Products, Payments, etc, but stuck on the following 2 things that I want to to accomplish:
1. Remove the "GENERAL" Tab in WooCommerce Settings.
2. Remove the "ORDER STATUSES" Tab from a plugin. (Note: this isn't a tab exactly, the slug is
'edit.php?post\_type=wc\_order\_status')
[](https://i.stack.imgur.com/XI6lc.png)
When I try to remove the GENERAL tab, it eliminates the entire Settings menu. As for the 'Order Statuses', my code just doesn't work.
```
add_filter( 'woocommerce_settings_tabs_array', 'remove_woocommerce_setting_tabs', 200, 1 );
function remove_woocommerce_setting_tabs( $array ) {
global $current_user;
//Declare the tabs we want to hide
$tabs_to_hide = array(
'general' => 'General', //this one removes the entire Settings menu
'wc_order_status' => 'Order Statuses'// this doesn't work, maybe bc it's a post_type
);
// Remove tab if user role is shipping_manager
if ( in_array("shipping_manager", $$current_user->roles) ) {
$array = array_diff_key($array, $tabs_to_hide);
}
}
```
I had also tried the below code to remove the ORDER STATUSES tab, but still no luck:
```
add_action( 'admin_menu', 'remove_order_statuses_tab', 999);
function remove_order_statuses_tab()
{
global $current_user;
if ( in_array("shipping_manager", $current_user->roles) ) {
remove_menu_page( 'edit.php?post_type=wc_order_status' ); //not working either
}
}
``` | **Terms/Tags aren't ordered**.
To help make the terms easier to read, the editor will list them alphabetically, but that isn't because they're ordered alphabetically in the database. It's because a piece of javascript sorted the terms in the UI control.
There is no order, only the order you give them. Fundamentally terms have no order. Any order you see in the editor is purely circumstantial, there is no order mechanism in the database for terms.
If you want to give special meaning to a term, you need to do so explicitly, e.g. store the term ID of the significant term in post meta. You cannot rely on order, as terms do not have order. |
364,417 | <p>I'm entirely new to OOP, but trying to dip my toe in by creating a simple Recipes plugin. I have added a Recipes custom post type and a few meta fields to go along with it, and now I am trying to create a few template files for displaying the recipe meta and content. To do this, I am thinking it would be useful to create a class to get all the meta for a particular post.</p>
<p>To test, I created a template file that is meant to echo one sentence with a single meta value after the post content:</p>
<pre><code>$recipe = new Wp_Recipes_Recipe;
echo '<p>The prep time for this recipe is ' . $recipe->$recipeprep . '</p>';
</code></pre>
<p>And I created a new file in plugin-dir > public called "class-wp-recipes-recipe.php" that contains the following:</p>
<pre><code>class Wp_Recipes_Recipe {
public function __construct( $post_id ) {
$this->$recipemeta = get_post_custom($post_id);
$this->$recipeprep = $this->$recipemeta['_rcp-prep-time'][0];
}
}
</code></pre>
<p>I think I need to add some code to specify to include my new file, but I am just not sure where to put it. I have tried putting a "require_once" for the file in the load_dependencies() function in the includes folder. No matter what I try, the meta value I am trying to display does not display, and the only noticeable effect from my efforts is that the wp admin bar no longer displays.</p>
<p>I may be going about this completely the wrong way, but any guidance would be greatly appreciated! Thanks!</p>
| [
{
"answer_id": 364420,
"author": "cameronjonesweb",
"author_id": 65582,
"author_profile": "https://wordpress.stackexchange.com/users/65582",
"pm_score": 2,
"selected": true,
"text": "<p>Your constructor requires the post ID to be passed to the class when it's instatiated, try this</p>\n\n<p><code>$recipe = new Wp_Recipes_Recipe( get_the_ID() );</code></p>\n"
},
{
"answer_id": 364424,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p>When WordPress loads your plugin it only automatically loads the main plugin file. The one with this at the top:</p>\n\n<pre><code><?php\n/**\n * Plugin Name: YOUR PLUGIN NAME\n */\n</code></pre>\n\n<p>If you have function or class definitions in other files that you want to use, then you need to include them into this file. If your class file is <code>public/class-wp-recipes-recipe.php</code>, then you would include it like this, using <a href=\"https://developer.wordpress.org/reference/functions/plugin_dir_path/\" rel=\"nofollow noreferrer\"><code>plugin_dir_path()</code></a>:</p>\n\n<pre><code><?php\n/**\n * Plugin Name: YOUR PLUGIN NAME\n */\n\nrequire_once plugin_dir_path( __FILE__ ) . 'public/class-wp-recipes-recipe.php';\n</code></pre>\n\n<p>Now your class will be available to use anywhere in WordPress after your plugin has loaded.</p>\n\n<p>You might want to put your includes into a function, only include it when needed, or even experiment with an autoloader, but this is the minimum required to load PHP files into a plugin.</p>\n\n<p>Lastly, you should not use the <code>Wp_</code> prefix for your own classes and functions. The purpose of a prefix is to namespace them to avoid conflicts with other themes, plugins, <em>and WordPress itself</em>. While it's highly unlikely WordPress will ever include a class named <code>Wp_Recipes_Recipe</code>, you should treat <code>Wp_</code> as reserved and use your own unique prefix (or even <a href=\"https://www.php.net/manual/en/language.namespaces.php\" rel=\"nofollow noreferrer\">namespaces</a>, not that WordPress requires PHP 5.6). </p>\n"
}
] | 2020/04/18 | [
"https://wordpress.stackexchange.com/questions/364417",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/155285/"
] | I'm entirely new to OOP, but trying to dip my toe in by creating a simple Recipes plugin. I have added a Recipes custom post type and a few meta fields to go along with it, and now I am trying to create a few template files for displaying the recipe meta and content. To do this, I am thinking it would be useful to create a class to get all the meta for a particular post.
To test, I created a template file that is meant to echo one sentence with a single meta value after the post content:
```
$recipe = new Wp_Recipes_Recipe;
echo '<p>The prep time for this recipe is ' . $recipe->$recipeprep . '</p>';
```
And I created a new file in plugin-dir > public called "class-wp-recipes-recipe.php" that contains the following:
```
class Wp_Recipes_Recipe {
public function __construct( $post_id ) {
$this->$recipemeta = get_post_custom($post_id);
$this->$recipeprep = $this->$recipemeta['_rcp-prep-time'][0];
}
}
```
I think I need to add some code to specify to include my new file, but I am just not sure where to put it. I have tried putting a "require\_once" for the file in the load\_dependencies() function in the includes folder. No matter what I try, the meta value I am trying to display does not display, and the only noticeable effect from my efforts is that the wp admin bar no longer displays.
I may be going about this completely the wrong way, but any guidance would be greatly appreciated! Thanks! | Your constructor requires the post ID to be passed to the class when it's instatiated, try this
`$recipe = new Wp_Recipes_Recipe( get_the_ID() );` |
364,448 | <p>When visiting wp-admin at the link <a href="http://ec2-3-16-54-250.us-east-2.compute.amazonaws.com/wp-admin" rel="nofollow noreferrer">http://ec2-3-16-54-250.us-east-2.compute.amazonaws.com/wp-admin</a>, I get the below URL</p>
<p><a href="http://ec2-3-16-54-250.us-east-2.compute.amazonaws.com/wp-admin/ec2-3-16-54-250.us-east-2.compute.amazonaws.com/wp-login.php?redirect_to=http%3A%2F%2Fec2-3-16-54-250.us-east-2.compute.amazonaws.com%2Fwp-admin%2F&reauth=1" rel="nofollow noreferrer">http://ec2-3-16-54-250.us-east-2.compute.amazonaws.com/wp-admin/ec2-3-16-54-250.us-east-2.compute.amazonaws.com/wp-login.php?redirect_to=http%3A%2F%2Fec2-3-16-54-250.us-east-2.compute.amazonaws.com%2Fwp-admin%2F&reauth=1</a></p>
<p>I am coming from a direct database transfer from localhost to server.</p>
<p>I went into wp-options and changed the option_value in wp_options to reflect that of the current live. See below.</p>
<pre><code> option_id: 1
option_name: siteurl
option_value: ec2-3-16-54-250.us-east-2.compute.amazonaws.com
autoload: yes
*************************** 2. row ***************************
option_id: 2
option_name: home
option_value: ec2-3-16-54-250.us-east-2.compute.amazonaws.com
autoload: yes
</code></pre>
<p>I just replaced the localhost values, though it seems I've done something incorrectly. I have not installed any url altering plugins or htaccess files, it is a relatively fresh AWS EC2 instance.</p>
<p>I see a lot of issues out there of people failing to reach the wp-admin link, but not this on specifically.</p>
<p>Can you please help?</p>
| [
{
"answer_id": 364420,
"author": "cameronjonesweb",
"author_id": 65582,
"author_profile": "https://wordpress.stackexchange.com/users/65582",
"pm_score": 2,
"selected": true,
"text": "<p>Your constructor requires the post ID to be passed to the class when it's instatiated, try this</p>\n\n<p><code>$recipe = new Wp_Recipes_Recipe( get_the_ID() );</code></p>\n"
},
{
"answer_id": 364424,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p>When WordPress loads your plugin it only automatically loads the main plugin file. The one with this at the top:</p>\n\n<pre><code><?php\n/**\n * Plugin Name: YOUR PLUGIN NAME\n */\n</code></pre>\n\n<p>If you have function or class definitions in other files that you want to use, then you need to include them into this file. If your class file is <code>public/class-wp-recipes-recipe.php</code>, then you would include it like this, using <a href=\"https://developer.wordpress.org/reference/functions/plugin_dir_path/\" rel=\"nofollow noreferrer\"><code>plugin_dir_path()</code></a>:</p>\n\n<pre><code><?php\n/**\n * Plugin Name: YOUR PLUGIN NAME\n */\n\nrequire_once plugin_dir_path( __FILE__ ) . 'public/class-wp-recipes-recipe.php';\n</code></pre>\n\n<p>Now your class will be available to use anywhere in WordPress after your plugin has loaded.</p>\n\n<p>You might want to put your includes into a function, only include it when needed, or even experiment with an autoloader, but this is the minimum required to load PHP files into a plugin.</p>\n\n<p>Lastly, you should not use the <code>Wp_</code> prefix for your own classes and functions. The purpose of a prefix is to namespace them to avoid conflicts with other themes, plugins, <em>and WordPress itself</em>. While it's highly unlikely WordPress will ever include a class named <code>Wp_Recipes_Recipe</code>, you should treat <code>Wp_</code> as reserved and use your own unique prefix (or even <a href=\"https://www.php.net/manual/en/language.namespaces.php\" rel=\"nofollow noreferrer\">namespaces</a>, not that WordPress requires PHP 5.6). </p>\n"
}
] | 2020/04/18 | [
"https://wordpress.stackexchange.com/questions/364448",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111544/"
] | When visiting wp-admin at the link <http://ec2-3-16-54-250.us-east-2.compute.amazonaws.com/wp-admin>, I get the below URL
<http://ec2-3-16-54-250.us-east-2.compute.amazonaws.com/wp-admin/ec2-3-16-54-250.us-east-2.compute.amazonaws.com/wp-login.php?redirect_to=http%3A%2F%2Fec2-3-16-54-250.us-east-2.compute.amazonaws.com%2Fwp-admin%2F&reauth=1>
I am coming from a direct database transfer from localhost to server.
I went into wp-options and changed the option\_value in wp\_options to reflect that of the current live. See below.
```
option_id: 1
option_name: siteurl
option_value: ec2-3-16-54-250.us-east-2.compute.amazonaws.com
autoload: yes
*************************** 2. row ***************************
option_id: 2
option_name: home
option_value: ec2-3-16-54-250.us-east-2.compute.amazonaws.com
autoload: yes
```
I just replaced the localhost values, though it seems I've done something incorrectly. I have not installed any url altering plugins or htaccess files, it is a relatively fresh AWS EC2 instance.
I see a lot of issues out there of people failing to reach the wp-admin link, but not this on specifically.
Can you please help? | Your constructor requires the post ID to be passed to the class when it's instatiated, try this
`$recipe = new Wp_Recipes_Recipe( get_the_ID() );` |
364,453 | <p>Recently I met the below code</p>
<pre><code>did_action( 'init' ) && $scripts->add_inline_script( 'lodash', 'window.lodash = _.noConflict();' );
</code></pre>
<p>inside the file \wp-includes\script-loader.php</p>
<p>Does anyone knows what does it mean? Especially double ampersand between two commands. I 've never met this syntax in PHP before and I cannot find documentation about this.</p>
| [
{
"answer_id": 364454,
"author": "NextGenThemes",
"author_id": 38602,
"author_profile": "https://wordpress.stackexchange.com/users/38602",
"pm_score": 2,
"selected": false,
"text": "<p>I think its actually not allowed or discouraged in WP coding standards.</p>\n\n<p>Its is basically saying \"If true go ahead\".</p>\n\n<p>It's a short form of this:</p>\n\n<pre><code>if ( did_action( 'init' ) ) {\n $scripts->add_inline_script( 'lodash', 'window.lodash = _.noConflict();' );\n}\n</code></pre>\n\n<p>You can also think of this as if it's inside brackets of an if statement like this.</p>\n\n<pre><code>$var = false;\n\nif ( $var && $scripts->add_inline_script( '...' ) ) { // As long as $var is false PHP won't execute or check what comes after the `&&`\n\n}\n</code></pre>\n\n<p>The line itself could be refactored to use <code>AND</code> instead of <code>&&</code> as well. This technique is sometimes used to make code \"speak\" English. Example:</p>\n\n<pre><code>$if_my_value_is_TRUE = TRUE;\n$if_my_value_is_TRUE AND print \"This get's printed to the screen.\";\n\n// The exact same thing with `OR` or `||`\n$my_value_is_TRUE = FALSE;\n$my_value_is_TRUE OR print \"This get's printed to the screen.\";\n</code></pre>\n"
},
{
"answer_id": 364458,
"author": "Nomikos Strigkos",
"author_id": 134516,
"author_profile": "https://wordpress.stackexchange.com/users/134516",
"pm_score": -1,
"selected": false,
"text": "<p>It must be something like : </p>\n\n<blockquote>\n <p>Do both simultaneously or do nothing</p>\n</blockquote>\n\n<p>because i find out that if the first command cannot be executed neither the second does</p>\n"
}
] | 2020/04/18 | [
"https://wordpress.stackexchange.com/questions/364453",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/134516/"
] | Recently I met the below code
```
did_action( 'init' ) && $scripts->add_inline_script( 'lodash', 'window.lodash = _.noConflict();' );
```
inside the file \wp-includes\script-loader.php
Does anyone knows what does it mean? Especially double ampersand between two commands. I 've never met this syntax in PHP before and I cannot find documentation about this. | I think its actually not allowed or discouraged in WP coding standards.
Its is basically saying "If true go ahead".
It's a short form of this:
```
if ( did_action( 'init' ) ) {
$scripts->add_inline_script( 'lodash', 'window.lodash = _.noConflict();' );
}
```
You can also think of this as if it's inside brackets of an if statement like this.
```
$var = false;
if ( $var && $scripts->add_inline_script( '...' ) ) { // As long as $var is false PHP won't execute or check what comes after the `&&`
}
```
The line itself could be refactored to use `AND` instead of `&&` as well. This technique is sometimes used to make code "speak" English. Example:
```
$if_my_value_is_TRUE = TRUE;
$if_my_value_is_TRUE AND print "This get's printed to the screen.";
// The exact same thing with `OR` or `||`
$my_value_is_TRUE = FALSE;
$my_value_is_TRUE OR print "This get's printed to the screen.";
``` |
364,562 | <p>I have a simple piece of "hello world" code I'm trying to execute on a page. I'm adding it using a PHP snippet:</p>
<pre><code>add_action( 'wp_head', function () { ?>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
jQuery(document).ready(() => {
jQuery('div#tm-extra-product-options').click(() => {
console.log("it's working!")
});
});
</script>
<?php } );
</code></pre>
<p>I can get it to show up in the page source and if I paste that directly into the console it works fine, however when I load the page and try it, I get nothing. I know that jQuery is loading because it is defined in the console without my intervention (previously this was not the case), however the code itself appears to not work at all. </p>
| [
{
"answer_id": 364565,
"author": "K H",
"author_id": 137894,
"author_profile": "https://wordpress.stackexchange.com/users/137894",
"pm_score": -1,
"selected": false,
"text": "<p>It is always an headache working with jQuery in Wordpress.\nJust try replace second jQuery with $ sign. \nI guess once you opened jQuery tag you need to continue with $ sign inside:\nLike this</p>\n\n<pre><code>add_action( 'wp_head', function () { ?>\n<script type=\"text/javascript\" src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\">\n\njQuery(document).ready(() => {\n $('div#tm-extra-product-options').click(() => {\n console.log(\"it's working!\")\n });\n});\n</script>\n<?php } );\n</code></pre>\n"
},
{
"answer_id": 364583,
"author": "Sanjay Gupta",
"author_id": 185502,
"author_profile": "https://wordpress.stackexchange.com/users/185502",
"pm_score": 1,
"selected": true,
"text": "<p>Try this.</p>\n\n<pre><code>add_action ( 'wp_head', 'custom_script_hook');\nfunction custom_script_hook() {\n\n?>\n<script type=\"text/javascript\" src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n<?php \n\n $output='<script>\n jQuery(document).ready(() => {\n $(\"div#tm-extra-product-options\").click(() => {\n console.log(\"it working!\")\n });\n });\n </script>';\n echo $output;\n}\n</code></pre>\n"
}
] | 2020/04/20 | [
"https://wordpress.stackexchange.com/questions/364562",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/182134/"
] | I have a simple piece of "hello world" code I'm trying to execute on a page. I'm adding it using a PHP snippet:
```
add_action( 'wp_head', function () { ?>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
jQuery(document).ready(() => {
jQuery('div#tm-extra-product-options').click(() => {
console.log("it's working!")
});
});
</script>
<?php } );
```
I can get it to show up in the page source and if I paste that directly into the console it works fine, however when I load the page and try it, I get nothing. I know that jQuery is loading because it is defined in the console without my intervention (previously this was not the case), however the code itself appears to not work at all. | Try this.
```
add_action ( 'wp_head', 'custom_script_hook');
function custom_script_hook() {
?>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<?php
$output='<script>
jQuery(document).ready(() => {
$("div#tm-extra-product-options").click(() => {
console.log("it working!")
});
});
</script>';
echo $output;
}
``` |
364,595 | <p>I am creating a post within <code>gform_after_submission</code> action, which sets a post ID variable when the post is successfully created.</p>
<p><a href="https://docs.gravityforms.com/gform_after_submission/" rel="nofollow noreferrer">https://docs.gravityforms.com/gform_after_submission/</a></p>
<pre><code>add_action('gform_after_submission_1', [ $this, 'create_order' ], 10, 2 );
public function create_order( $entry, $form ) {
// get the current cart data array
$data = self::data();
// user id
$user_id = get_current_user_id();
// create an order array
$order = [
'post_author' => $user_id,
'post_content' => json_encode($data,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),
'post_type' => 'purchase-order',
'post_status' => 'publish'
];
// create order post using an array and return the post id
$result = wp_insert_post($order);
// if post id and is not a wp error then
if($result && !is_wp_error($result)) {
// get the id
$post_id = $result;
// my order custom field updates go here...
}
}
</code></pre>
<p><br/>
Because my form is submitting via ajax, I can't invoke a header php redirect above because the redirect will just happen within the ajax request.</p>
<p>I need to somehow pass my <code>$post_id</code> to the gravity forms <code>gform_confirmation</code> filter. But I'm really struggling to see how this can be done.</p>
<p><a href="https://docs.gravityforms.com/gform_confirmation/" rel="nofollow noreferrer">https://docs.gravityforms.com/gform_confirmation/</a></p>
<pre><code>add_filter('gform_confirmation_1', [ $this, 'order_confirmation' ], 10, 4 );
public function order_confirmation( $confirmation, $form, $entry, $ajax ) {
// update redirect to order
$confirmation = array( 'redirect' => get_permalink($post_id) );
// return confirmation
return $confirmation;
}
</code></pre>
<p><br/>
If anyone has any ideas that would be great thanks.</p>
| [
{
"answer_id": 364565,
"author": "K H",
"author_id": 137894,
"author_profile": "https://wordpress.stackexchange.com/users/137894",
"pm_score": -1,
"selected": false,
"text": "<p>It is always an headache working with jQuery in Wordpress.\nJust try replace second jQuery with $ sign. \nI guess once you opened jQuery tag you need to continue with $ sign inside:\nLike this</p>\n\n<pre><code>add_action( 'wp_head', function () { ?>\n<script type=\"text/javascript\" src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\">\n\njQuery(document).ready(() => {\n $('div#tm-extra-product-options').click(() => {\n console.log(\"it's working!\")\n });\n});\n</script>\n<?php } );\n</code></pre>\n"
},
{
"answer_id": 364583,
"author": "Sanjay Gupta",
"author_id": 185502,
"author_profile": "https://wordpress.stackexchange.com/users/185502",
"pm_score": 1,
"selected": true,
"text": "<p>Try this.</p>\n\n<pre><code>add_action ( 'wp_head', 'custom_script_hook');\nfunction custom_script_hook() {\n\n?>\n<script type=\"text/javascript\" src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n<?php \n\n $output='<script>\n jQuery(document).ready(() => {\n $(\"div#tm-extra-product-options\").click(() => {\n console.log(\"it working!\")\n });\n });\n </script>';\n echo $output;\n}\n</code></pre>\n"
}
] | 2020/04/20 | [
"https://wordpress.stackexchange.com/questions/364595",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111152/"
] | I am creating a post within `gform_after_submission` action, which sets a post ID variable when the post is successfully created.
<https://docs.gravityforms.com/gform_after_submission/>
```
add_action('gform_after_submission_1', [ $this, 'create_order' ], 10, 2 );
public function create_order( $entry, $form ) {
// get the current cart data array
$data = self::data();
// user id
$user_id = get_current_user_id();
// create an order array
$order = [
'post_author' => $user_id,
'post_content' => json_encode($data,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),
'post_type' => 'purchase-order',
'post_status' => 'publish'
];
// create order post using an array and return the post id
$result = wp_insert_post($order);
// if post id and is not a wp error then
if($result && !is_wp_error($result)) {
// get the id
$post_id = $result;
// my order custom field updates go here...
}
}
```
Because my form is submitting via ajax, I can't invoke a header php redirect above because the redirect will just happen within the ajax request.
I need to somehow pass my `$post_id` to the gravity forms `gform_confirmation` filter. But I'm really struggling to see how this can be done.
<https://docs.gravityforms.com/gform_confirmation/>
```
add_filter('gform_confirmation_1', [ $this, 'order_confirmation' ], 10, 4 );
public function order_confirmation( $confirmation, $form, $entry, $ajax ) {
// update redirect to order
$confirmation = array( 'redirect' => get_permalink($post_id) );
// return confirmation
return $confirmation;
}
```
If anyone has any ideas that would be great thanks. | Try this.
```
add_action ( 'wp_head', 'custom_script_hook');
function custom_script_hook() {
?>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<?php
$output='<script>
jQuery(document).ready(() => {
$("div#tm-extra-product-options").click(() => {
console.log("it working!")
});
});
</script>';
echo $output;
}
``` |
364,598 | <p>Each user has a user meta called profile_url chosen during registration.
After user creation, a page with that slug is created and made private (the author of the page is the admin).
The user in his front-end dashboard has the possibility to make this page public or private.
When the page is private, the owner user cannot see it.</p>
<p>I would like to make the private page visible to the owner user.</p>
<p>The only way that came to mind is to add capabilities, like:</p>
<pre><code>$ user = new WP_User ($ user_id);
$ user-> add_cap ('read_private_pages');
</code></pre>
<p>but I'd like to specify the page id, and I don't know if it's possible.</p>
<p>Thank you</p>
| [
{
"answer_id": 364565,
"author": "K H",
"author_id": 137894,
"author_profile": "https://wordpress.stackexchange.com/users/137894",
"pm_score": -1,
"selected": false,
"text": "<p>It is always an headache working with jQuery in Wordpress.\nJust try replace second jQuery with $ sign. \nI guess once you opened jQuery tag you need to continue with $ sign inside:\nLike this</p>\n\n<pre><code>add_action( 'wp_head', function () { ?>\n<script type=\"text/javascript\" src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\">\n\njQuery(document).ready(() => {\n $('div#tm-extra-product-options').click(() => {\n console.log(\"it's working!\")\n });\n});\n</script>\n<?php } );\n</code></pre>\n"
},
{
"answer_id": 364583,
"author": "Sanjay Gupta",
"author_id": 185502,
"author_profile": "https://wordpress.stackexchange.com/users/185502",
"pm_score": 1,
"selected": true,
"text": "<p>Try this.</p>\n\n<pre><code>add_action ( 'wp_head', 'custom_script_hook');\nfunction custom_script_hook() {\n\n?>\n<script type=\"text/javascript\" src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n<?php \n\n $output='<script>\n jQuery(document).ready(() => {\n $(\"div#tm-extra-product-options\").click(() => {\n console.log(\"it working!\")\n });\n });\n </script>';\n echo $output;\n}\n</code></pre>\n"
}
] | 2020/04/20 | [
"https://wordpress.stackexchange.com/questions/364598",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/186515/"
] | Each user has a user meta called profile\_url chosen during registration.
After user creation, a page with that slug is created and made private (the author of the page is the admin).
The user in his front-end dashboard has the possibility to make this page public or private.
When the page is private, the owner user cannot see it.
I would like to make the private page visible to the owner user.
The only way that came to mind is to add capabilities, like:
```
$ user = new WP_User ($ user_id);
$ user-> add_cap ('read_private_pages');
```
but I'd like to specify the page id, and I don't know if it's possible.
Thank you | Try this.
```
add_action ( 'wp_head', 'custom_script_hook');
function custom_script_hook() {
?>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<?php
$output='<script>
jQuery(document).ready(() => {
$("div#tm-extra-product-options").click(() => {
console.log("it working!")
});
});
</script>';
echo $output;
}
``` |
364,676 | <p>We display event dates/times via Wordpress <a href="https://wordpress.org/support/article/formatting-date-and-time/" rel="nofollow noreferrer">date and time</a> functions in am/pm time (12 hour, not 24 hour). For any times that are noon - i.e. "12:00 pm" - we'd like to display "12:00 noon" instead. </p>
<p>And we'd also like to display "12:00 midnight" instead of "12:00 am".</p>
<p>This is to avoid confusion (we run online events around the world at different times so there is room for this type of confusion). </p>
<p>All other times of the day can keep their am/pm, it's just these two exact times that we're seeking to change.</p>
| [
{
"answer_id": 364685,
"author": "Sam",
"author_id": 186246,
"author_profile": "https://wordpress.stackexchange.com/users/186246",
"pm_score": 0,
"selected": false,
"text": "<p>I think you can Do it with Translation loops! Simply find the \"12:00 pm\" and put 12:00 Noon. Maybe It works! try it :D. </p>\n"
},
{
"answer_id": 364690,
"author": "Tony Djukic",
"author_id": 60844,
"author_profile": "https://wordpress.stackexchange.com/users/60844",
"pm_score": 3,
"selected": true,
"text": "<p>So what you need to do is make your life easier and instead of searching everything within every instance of <code>.pp-post-content</code> or <code>.pp-post-content p</code>, let's wrap the times or the times in question with a span tag. Like you suggested in your comments <code><span class=\"tas-event-time\"></code> is sufficient enough.</p>\n\n<p>Now, in your .js file, you want to add the following:</p>\n\n<pre><code>jQuery( document ).ready( function($) {\n $( '.tas-event-time' ).html( $( '.tas-event-time' ).html().replace( '12:00 pm','12:00 noon') );\n} );\n</code></pre>\n\n<p>That will, once the document is ready, change the instances of <em>'12:00 pm'</em> to <em>'12:00 noon'</em>.</p>\n"
}
] | 2020/04/21 | [
"https://wordpress.stackexchange.com/questions/364676",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/2495/"
] | We display event dates/times via Wordpress [date and time](https://wordpress.org/support/article/formatting-date-and-time/) functions in am/pm time (12 hour, not 24 hour). For any times that are noon - i.e. "12:00 pm" - we'd like to display "12:00 noon" instead.
And we'd also like to display "12:00 midnight" instead of "12:00 am".
This is to avoid confusion (we run online events around the world at different times so there is room for this type of confusion).
All other times of the day can keep their am/pm, it's just these two exact times that we're seeking to change. | So what you need to do is make your life easier and instead of searching everything within every instance of `.pp-post-content` or `.pp-post-content p`, let's wrap the times or the times in question with a span tag. Like you suggested in your comments `<span class="tas-event-time">` is sufficient enough.
Now, in your .js file, you want to add the following:
```
jQuery( document ).ready( function($) {
$( '.tas-event-time' ).html( $( '.tas-event-time' ).html().replace( '12:00 pm','12:00 noon') );
} );
```
That will, once the document is ready, change the instances of *'12:00 pm'* to *'12:00 noon'*. |
364,679 | <p>All guest comments are <code>user_id = 0</code>, while registered users have their unique <code>user_id</code> attach to the comment. How to edit comment <code>user_id</code> from the comment edit screen.</p>
<p>I think I need to use edit_comment and add_meta_boxes_comment hooks.</p>
| [
{
"answer_id": 364950,
"author": "Chetan Vaghela",
"author_id": 169856,
"author_profile": "https://wordpress.stackexchange.com/users/169856",
"pm_score": 2,
"selected": false,
"text": "<p>You can take reference from below code. It will provide an option to update user id of comment (<a href=\"https://prnt.sc/s57q4f\" rel=\"nofollow noreferrer\">https://prnt.sc/s57q4f</a>). paste below code in active theme's functions.php file.I have tested and it is working for me. let me know if it works for you. </p>\n\n<pre><code># comment user id update metabox\nfunction action_add_meta_boxes_comment( $comment ) {\n ?>\n <div id=\"commnet-user-id\" class=\"stuffbox\">\n <div class=\"inside\">\n <h2 class=\"edit-comment-userid\"><?php _e( 'Commment User ID' ); ?></h2>\n <fieldset>\n <legend class=\"screen-reader-text\"><?php _e( 'Comment User ID' ); ?></legend>\n <table class=\"form-table editcomment\" role=\"presentation\">\n <tbody>\n <tr>\n <td class=\"first\"><label for=\"name\"><?php _e( 'User ID' ); ?></label></td>\n <td><input type=\"text\" name=\"newcomment_userid\" size=\"30\" value=\"<?php echo esc_attr( $comment->user_id ); ?>\" id=\"user_id\" /></td>\n </tr>\n\n </tbody>\n </table>\n </fieldset>\n </div>\n </div>\n <?php\n}; \n// add the action \nadd_action( 'add_meta_boxes_comment', 'action_add_meta_boxes_comment', 10, 1 ); \n\nadd_filter( 'comment_edit_redirect', 'save_edit_comment_data', 10, 2 );\nfunction save_edit_comment_data( $location, $comment_id )\n{\n $_POST['user_id'] = (int) $_POST['newcomment_userid'];\n wp_update_comment( $_POST );\n return $location;\n}\n</code></pre>\n"
},
{
"answer_id": 364952,
"author": "西門 正 Code Guy",
"author_id": 35701,
"author_profile": "https://wordpress.stackexchange.com/users/35701",
"pm_score": 2,
"selected": false,
"text": "<p>As an alternative option, you may use <a href=\"https://developer.wordpress.org/reference/hooks/wp_update_comment_data/\" rel=\"nofollow noreferrer\"><code>wp_update_comment_data</code></a> filter which is right before default update to database.</p>\n\n<p>Pros</p>\n\n<ul>\n<li>don't need to do any saving mechanism and focus of data preparation</li>\n<li>have full control of all data before saving</li>\n</ul>\n\n<p>This example used <code>add_meta_boxes</code> while @Chetan Vaghela is using add_meta_boxes_comment.\nTheir calling location in edit-form-comment.php is just side by side, so result should be the same.\nYou may also combine both method by using @Chetan Vaghela meta box with the comment data filter <code>wp_update_comment_data</code> to further simplify the solution</p>\n\n<p>If using <a href=\"https://developer.wordpress.org/reference/functions/add_meta_box/\" rel=\"nofollow noreferrer\"><code>add_meta_box function</code></a>, could only use position <code>normal</code>. It will not be rendered in other locations.</p>\n\n<pre><code>add_action( 'add_meta_boxes', 'ws364679_register_meta_boxes', 10, 2 );\nadd_filter( 'wp_update_comment_data', 'ws364679_save_comment' );\nfunction ws364679_register_meta_boxes( $post_type, $comment )\n{\n // this example use an add_meta_box + a metabox callback or just use your own html here and use the $comment variable as reference\n add_meta_box('user_id_box', 'User ID:', 'ws364679_metabox_callback', 'comment', 'normal', 'default', $comment );\n}\n\nfunction ws364679_metabox_callback( $comment )\n {\n// if using id ane name 'user_id' rather than comment_user_id, you don't need even need to use 'wp_update_comment_data' filter because by default 'user_id' will be prepared as the variable for putting into database. You may optionally use the filter for final checking.\n ?>\n <div class=\"custom-meta-box-container\">\n <div class=\"form-row\">\n <input type=\"text\" id=\"comment_user_id\" name=\"comment_user_id\" value=\"<?php echo $comment->user_id; ?>\"/>\n\n </div>\n </div>\n <?php\n }\n\nfunction ws364679_save_comment( $data ) {\n // because user id is prepared somewhere before it is saved, so it is suitable to add any changes to `wp_update_comment_data` filter\n // in this filter $_REQUEST has been processed and prepared in $data\n\n // because username and email could be manually updated in the ui, you may add an automatic logic here to match your new user id by fetching it from data base\n\n // if the input box id and name is 'user_id', no need to do this manipulation\n $data['user_id'] = $data['comment_user_id'];\n\n // any checking if you need before return\n\n return $data;\n}\n</code></pre>\n\n<p>I tested the above code in a default theme and proved to work. While it update user id, you may also consider update the user information automatically by fetching user information by the id during the data manipulation.</p>\n"
},
{
"answer_id": 364967,
"author": "Bikram",
"author_id": 145504,
"author_profile": "https://wordpress.stackexchange.com/users/145504",
"pm_score": 2,
"selected": true,
"text": "<p>Thanks, everyone for the answers. I already solved it. This is my code. I was trying <code>edit_comment</code> at the time of questioning. </p>\n\n<pre><code>function wp_review_id_metabox_full() {\n\n if (get_comment_type($comment->comment_ID) == 'wp_review_comment') {\n\n add_meta_box('some_meta_box_name', __( 'ID: ' ), 'wp_review_id_metabox', 'comment', 'normal', 'high' );\n\n}}\nadd_action( 'add_meta_boxes_comment', 'wp_review_id_metabox_full' );\n\n\nfunction wp_review_id_metabox( $comment ) { ?>\n\n <input type=\"text\" name=\"new_user_id\" value=\"<?php echo $comment->user_id; ?>\"/>\n<?php }\n\n\nfunction wp_review_id_save_comment( $comment ) {\n\n $comment['user_id'] = $comment['new_user_id'];\n\n return $comment;\n}\nadd_filter( 'wp_update_comment_data', 'wp_review_id_save_comment' );\n</code></pre>\n"
}
] | 2020/04/21 | [
"https://wordpress.stackexchange.com/questions/364679",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145504/"
] | All guest comments are `user_id = 0`, while registered users have their unique `user_id` attach to the comment. How to edit comment `user_id` from the comment edit screen.
I think I need to use edit\_comment and add\_meta\_boxes\_comment hooks. | Thanks, everyone for the answers. I already solved it. This is my code. I was trying `edit_comment` at the time of questioning.
```
function wp_review_id_metabox_full() {
if (get_comment_type($comment->comment_ID) == 'wp_review_comment') {
add_meta_box('some_meta_box_name', __( 'ID: ' ), 'wp_review_id_metabox', 'comment', 'normal', 'high' );
}}
add_action( 'add_meta_boxes_comment', 'wp_review_id_metabox_full' );
function wp_review_id_metabox( $comment ) { ?>
<input type="text" name="new_user_id" value="<?php echo $comment->user_id; ?>"/>
<?php }
function wp_review_id_save_comment( $comment ) {
$comment['user_id'] = $comment['new_user_id'];
return $comment;
}
add_filter( 'wp_update_comment_data', 'wp_review_id_save_comment' );
``` |
364,680 | <p>I'm trying to embed this code: <a href="https://codepen.io/jme11/pen/zMVJVX" rel="nofollow noreferrer">https://codepen.io/jme11/pen/zMVJVX</a></p>
<p>into my Wordpress about fitness, but I don't know why it's not working correctly - </p>
<p>I've downloaded the export of the code, which works perfectly in the standalone HTML (+ js and css) file (specifically the completed form will display in the results div.</p>
<p>I've then embedded the HTML in my Wordpress template page - it appears on the front end fine,
I've properly linked in the css and js in the same order as in the HTML - and checking them in (View Source shows they are connected)</p>
<p>Completing the form and hitting calculate DOES do something (it shows amounts the protein / fat / carb field) - however, the results div (with calories per day) does not appear.</p>
<p>I think it might have something to do with jquery as I get this error in the console (but don't understand):</p>
<pre><code>Uncaught TypeError: $(...).fadeOut is not a function
at calcDailyCals (script.js?ver=1.0:51)
at HTMLFormElement.<anonymous> (script.js:3)
at HTMLFormElement.dispatch (jquery-3.4.1.slim.min.js:2)
at HTMLFormElement.v.handle (jquery-3.4.1.slim.min.js:2)
</code></pre>
<p>Can anyone help? Just not sure why it would work in the standalone HTML file and not on a Wordpress page.</p>
<p>Thanks</p>
| [
{
"answer_id": 364950,
"author": "Chetan Vaghela",
"author_id": 169856,
"author_profile": "https://wordpress.stackexchange.com/users/169856",
"pm_score": 2,
"selected": false,
"text": "<p>You can take reference from below code. It will provide an option to update user id of comment (<a href=\"https://prnt.sc/s57q4f\" rel=\"nofollow noreferrer\">https://prnt.sc/s57q4f</a>). paste below code in active theme's functions.php file.I have tested and it is working for me. let me know if it works for you. </p>\n\n<pre><code># comment user id update metabox\nfunction action_add_meta_boxes_comment( $comment ) {\n ?>\n <div id=\"commnet-user-id\" class=\"stuffbox\">\n <div class=\"inside\">\n <h2 class=\"edit-comment-userid\"><?php _e( 'Commment User ID' ); ?></h2>\n <fieldset>\n <legend class=\"screen-reader-text\"><?php _e( 'Comment User ID' ); ?></legend>\n <table class=\"form-table editcomment\" role=\"presentation\">\n <tbody>\n <tr>\n <td class=\"first\"><label for=\"name\"><?php _e( 'User ID' ); ?></label></td>\n <td><input type=\"text\" name=\"newcomment_userid\" size=\"30\" value=\"<?php echo esc_attr( $comment->user_id ); ?>\" id=\"user_id\" /></td>\n </tr>\n\n </tbody>\n </table>\n </fieldset>\n </div>\n </div>\n <?php\n}; \n// add the action \nadd_action( 'add_meta_boxes_comment', 'action_add_meta_boxes_comment', 10, 1 ); \n\nadd_filter( 'comment_edit_redirect', 'save_edit_comment_data', 10, 2 );\nfunction save_edit_comment_data( $location, $comment_id )\n{\n $_POST['user_id'] = (int) $_POST['newcomment_userid'];\n wp_update_comment( $_POST );\n return $location;\n}\n</code></pre>\n"
},
{
"answer_id": 364952,
"author": "西門 正 Code Guy",
"author_id": 35701,
"author_profile": "https://wordpress.stackexchange.com/users/35701",
"pm_score": 2,
"selected": false,
"text": "<p>As an alternative option, you may use <a href=\"https://developer.wordpress.org/reference/hooks/wp_update_comment_data/\" rel=\"nofollow noreferrer\"><code>wp_update_comment_data</code></a> filter which is right before default update to database.</p>\n\n<p>Pros</p>\n\n<ul>\n<li>don't need to do any saving mechanism and focus of data preparation</li>\n<li>have full control of all data before saving</li>\n</ul>\n\n<p>This example used <code>add_meta_boxes</code> while @Chetan Vaghela is using add_meta_boxes_comment.\nTheir calling location in edit-form-comment.php is just side by side, so result should be the same.\nYou may also combine both method by using @Chetan Vaghela meta box with the comment data filter <code>wp_update_comment_data</code> to further simplify the solution</p>\n\n<p>If using <a href=\"https://developer.wordpress.org/reference/functions/add_meta_box/\" rel=\"nofollow noreferrer\"><code>add_meta_box function</code></a>, could only use position <code>normal</code>. It will not be rendered in other locations.</p>\n\n<pre><code>add_action( 'add_meta_boxes', 'ws364679_register_meta_boxes', 10, 2 );\nadd_filter( 'wp_update_comment_data', 'ws364679_save_comment' );\nfunction ws364679_register_meta_boxes( $post_type, $comment )\n{\n // this example use an add_meta_box + a metabox callback or just use your own html here and use the $comment variable as reference\n add_meta_box('user_id_box', 'User ID:', 'ws364679_metabox_callback', 'comment', 'normal', 'default', $comment );\n}\n\nfunction ws364679_metabox_callback( $comment )\n {\n// if using id ane name 'user_id' rather than comment_user_id, you don't need even need to use 'wp_update_comment_data' filter because by default 'user_id' will be prepared as the variable for putting into database. You may optionally use the filter for final checking.\n ?>\n <div class=\"custom-meta-box-container\">\n <div class=\"form-row\">\n <input type=\"text\" id=\"comment_user_id\" name=\"comment_user_id\" value=\"<?php echo $comment->user_id; ?>\"/>\n\n </div>\n </div>\n <?php\n }\n\nfunction ws364679_save_comment( $data ) {\n // because user id is prepared somewhere before it is saved, so it is suitable to add any changes to `wp_update_comment_data` filter\n // in this filter $_REQUEST has been processed and prepared in $data\n\n // because username and email could be manually updated in the ui, you may add an automatic logic here to match your new user id by fetching it from data base\n\n // if the input box id and name is 'user_id', no need to do this manipulation\n $data['user_id'] = $data['comment_user_id'];\n\n // any checking if you need before return\n\n return $data;\n}\n</code></pre>\n\n<p>I tested the above code in a default theme and proved to work. While it update user id, you may also consider update the user information automatically by fetching user information by the id during the data manipulation.</p>\n"
},
{
"answer_id": 364967,
"author": "Bikram",
"author_id": 145504,
"author_profile": "https://wordpress.stackexchange.com/users/145504",
"pm_score": 2,
"selected": true,
"text": "<p>Thanks, everyone for the answers. I already solved it. This is my code. I was trying <code>edit_comment</code> at the time of questioning. </p>\n\n<pre><code>function wp_review_id_metabox_full() {\n\n if (get_comment_type($comment->comment_ID) == 'wp_review_comment') {\n\n add_meta_box('some_meta_box_name', __( 'ID: ' ), 'wp_review_id_metabox', 'comment', 'normal', 'high' );\n\n}}\nadd_action( 'add_meta_boxes_comment', 'wp_review_id_metabox_full' );\n\n\nfunction wp_review_id_metabox( $comment ) { ?>\n\n <input type=\"text\" name=\"new_user_id\" value=\"<?php echo $comment->user_id; ?>\"/>\n<?php }\n\n\nfunction wp_review_id_save_comment( $comment ) {\n\n $comment['user_id'] = $comment['new_user_id'];\n\n return $comment;\n}\nadd_filter( 'wp_update_comment_data', 'wp_review_id_save_comment' );\n</code></pre>\n"
}
] | 2020/04/21 | [
"https://wordpress.stackexchange.com/questions/364680",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/174612/"
] | I'm trying to embed this code: <https://codepen.io/jme11/pen/zMVJVX>
into my Wordpress about fitness, but I don't know why it's not working correctly -
I've downloaded the export of the code, which works perfectly in the standalone HTML (+ js and css) file (specifically the completed form will display in the results div.
I've then embedded the HTML in my Wordpress template page - it appears on the front end fine,
I've properly linked in the css and js in the same order as in the HTML - and checking them in (View Source shows they are connected)
Completing the form and hitting calculate DOES do something (it shows amounts the protein / fat / carb field) - however, the results div (with calories per day) does not appear.
I think it might have something to do with jquery as I get this error in the console (but don't understand):
```
Uncaught TypeError: $(...).fadeOut is not a function
at calcDailyCals (script.js?ver=1.0:51)
at HTMLFormElement.<anonymous> (script.js:3)
at HTMLFormElement.dispatch (jquery-3.4.1.slim.min.js:2)
at HTMLFormElement.v.handle (jquery-3.4.1.slim.min.js:2)
```
Can anyone help? Just not sure why it would work in the standalone HTML file and not on a Wordpress page.
Thanks | Thanks, everyone for the answers. I already solved it. This is my code. I was trying `edit_comment` at the time of questioning.
```
function wp_review_id_metabox_full() {
if (get_comment_type($comment->comment_ID) == 'wp_review_comment') {
add_meta_box('some_meta_box_name', __( 'ID: ' ), 'wp_review_id_metabox', 'comment', 'normal', 'high' );
}}
add_action( 'add_meta_boxes_comment', 'wp_review_id_metabox_full' );
function wp_review_id_metabox( $comment ) { ?>
<input type="text" name="new_user_id" value="<?php echo $comment->user_id; ?>"/>
<?php }
function wp_review_id_save_comment( $comment ) {
$comment['user_id'] = $comment['new_user_id'];
return $comment;
}
add_filter( 'wp_update_comment_data', 'wp_review_id_save_comment' );
``` |
364,681 | <p>I wanna know, what are the <strong>hooks</strong> in wp themes, like before_header_hook, after_header_hook?
What are the uses and benefits of these hooks in theme development?</p>
| [
{
"answer_id": 364696,
"author": "Amir",
"author_id": 80135,
"author_profile": "https://wordpress.stackexchange.com/users/80135",
"pm_score": 1,
"selected": false,
"text": "<p>Whenever you want to do something or customize something in WordPress, then there is very likely a hook you can use.</p>\n\n<p>The “do” hook is called an “action.” Wherever an action is defined, you can execute your own code. Here are some examples:</p>\n\n<ul>\n<li>send an email to the author once a post is published;</li>\n<li>load a custom script file in the footer of the page;</li>\n<li>add instructions above the login form.</li>\n</ul>\n\n<p>A hook is a place in WordPress’s code that can get functions added to it. When you create a hook, you give yourself and other developers the opportunity to add in additional functionality at that location.</p>\n\n<p>Hooked functions are custom PHP functions that we can “hook into” WordPress, at the locations specified by its hooks.</p>\n"
},
{
"answer_id": 364703,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 2,
"selected": false,
"text": "<p>WordPress is a whole package of different code components working together to provide a functional Content Management System. WordPress Core, Plugins, and Themes are all part of this package. Since some of these components update separately you do not want to edit the code directly, otherwise your changes will be overwritten whenever these components update. Thus, WordPress implemented a <a href=\"https://developer.wordpress.org/plugins/hooks/\" rel=\"nofollow noreferrer\">system of Hooks</a>.</p>\n\n<hr>\n\n<p><a href=\"https://developer.wordpress.org/plugins/hooks/actions/\" rel=\"nofollow noreferrer\">Action hooks</a> allow you to inject functionality into a specific point of runtime. You can create your own plugin or theme with these action hooks so that they do not get overwritten whenever a component updates. For example, <code>plugins_loaded</code> is an action hook that runs after all plugins have been loaded during runtime. If you wanted to run specific functionality after all the plugins have been loaded during a page request you could say:</p>\n\n<pre><code>function example_plugins_loaded_callback() {\n\n // Print a message then stop page request load.\n print( 'All plugins have been loaded successfully!' );\n exit();\n\n}\nadd_action( 'plugins_loaded', 'example_plugins_loaded_callback' );\n</code></pre>\n\n<p>Once all plugins are loaded the above message gets printed to the screen and the page request stops loading additional files. This is a simple example usage but that's the gist of how action hooks work. You could call an API or write to the database at this point if you wanted to.</p>\n\n<p>Without Action Hooks, if you wanted to print the above you would need edit the <a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-settings.php#L409\" rel=\"nofollow noreferrer\"><code>wp-settings.php</code></a> file directly which would eventually be overwritten whenever WordPress updates. This would break whatever functionality you would need in place when the <code>plugins_loaded</code> hook runs.</p>\n\n<hr>\n\n<p><a href=\"https://developer.wordpress.org/plugins/hooks/filters/\" rel=\"nofollow noreferrer\">Filter Hooks</a> allow you to modify specific values generated by functions. Unlike action hooks they expect a returned value. A good example for this is the filter hook <a href=\"https://developer.wordpress.org/reference/hooks/the_title/\" rel=\"nofollow noreferrer\"><code>the_title</code></a> which allows you to modify <code>the_title()</code> and <code>get_the_title()</code> values before they're printed to the screen. You can view the code directly by <a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-includes/post-template.php#L117\" rel=\"nofollow noreferrer\">viewing the function on trac</a>. The function and callback is similar to action hooks:</p>\n\n<pre><code>function example_the_title_callback() {\n\n return 'Example Title';\n\n}\nadd_filter( 'the_title', 'example_the_title_callback' );\n</code></pre>\n\n<p>Using the above filter hook, anywhere that <code>the_title()</code> is called will now print <code>Example Title</code> instead.</p>\n\n<hr>\n\n<p>Hooks also come with priorities and number of args. You will need to look up each hook to figure out what args are passed to the hook but it goes like this:</p>\n\n<pre><code>add_filter(\n 'the_title', // Hook Name\n 'example_the_title_callback', // Callback Function Name\n 10, // Priority\n 2 // Number of arguments\n);\n</code></pre>\n\n<ul>\n<li><strong>Hook Name</strong> - Not every function has available hooks. You will need to look this up on a per-need basis using the <a href=\"https://developer.wordpress.org/reference/\" rel=\"nofollow noreferrer\">Developer Docs</a>.</li>\n<li><strong>Callback Function</strong> - The name of the function you want to trigger.</li>\n<li><strong>Priority</strong> - When you want the hook to run. Hooks can have multiple functions attached to them, some may not be yours ( plugins or themes ). Lower priority will run before higher priority hooks.</li>\n<li><strong>Number of Arguments</strong> - The arguments passed to the callback function.</li>\n</ul>\n\n<p>Hooks that pass more than 1 argument need to be told to give your callback function those arguments. <code>the_title</code> hook passes <code>$title</code> and <code>$post_id</code>. If we want to use the <code>$post_id</code> argument we need to tell the <code>add_filter()</code> function to pass those to our callback function:</p>\n\n<pre><code>/**\n * One Argument Hook\n */\nfunction example_the_title_callback( $title ) {\n\n /**\n * - By default we always get 1 argument if possible.\n * - We do not have access to $post_id at this point.\n */\n $new_title = $title . '!!!';\n\n return $new_title;\n}\nadd_filter( 'the_title', 'example_the_title_callback' );\n\n/**\n * Two Arguments Hook\n */\nfunction example_the_title_callback( $title, $post_id ) {\n\n /**\n * Since we specified 2 arguments, we receive the 2 arguments that the hook provides\n */\n $post = get_post( $post_id );\n $new_title = $title . ' - ' . $post->ID;\n\n return $new_title;\n}\nadd_filter( 'the_title', 'example_the_title_callback', 10, 2 );\n</code></pre>\n\n<p>Again, you'll need into the Developer Docs to see what arguments the hook passes.</p>\n\n<hr>\n\n<p>Finally, you as a theme or plugin developer can add in your own custom hooks which will allow other developers to add any or modify specific functionality.</p>\n\n<p>Let's say you've written a plugin that wraps the Post Title on the frontend in <code><span></code> HTML tags for specific styling. You can add a hook to allow other developers to add custom classes to your span like so:</p>\n\n<pre><code>/**\n * My super cool plugin\n * Add HTML span tags around titles\n * Our plugin CSS can style them cool later\n */\nfunction supercool_title( $title ) {\n\n // Allow theme developers or plugin developers to add classes to our span tag.\n $classes = apply_filters(\n 'supercool_title_classes', // Our custom filter name\n array(), // Array of classes to pass to the filter, empty in this scenario\n );\n\n // Filters always return\n return sprintf( '<span class=\"%s\">%s</span>', esc_attr( implode( ' ', $classes ) ), $title );\n\n}\nadd_filter( 'the_title', 'supercool_title' );\n</code></pre>\n\n<p>As a theme developer I can use that plugins hook to add in my own classes if I wanted to.</p>\n\n<pre><code>/**\n * Theme Devloper modifies plugin functionality\n * Adds specific class to the super cool plugin title wrapper\n */\nfunction my_theme_supercool_title_classes( $classe ) {\n\n $classes[] = 'special-title';\n return $classes;\n\n}\nadd_filter( 'supercool_title_classes', 'my_theme_supercool_title_classes' );\n\n// Output\n<span class=\"special-title\">Post Title</span>\n</code></pre>\n\n<p>You could do the same thing with action hooks when creating your theme or plugin. WooCommerce utilizes a lot of action hooks in their templating system allowing other plugins and specific themes to add in output. Something like:</p>\n\n<pre><code>do_action( 'before_header_hook' ); // A custom action hook created by the developer.\n</code></pre>\n\n<p>Simply allows you, if you want to, to inject specific code at that point. Maybe an Analytics script or an entire HTML wrapper for a utility nav that the theme previously didn't support. The possibilities are endless!</p>\n"
}
] | 2020/04/21 | [
"https://wordpress.stackexchange.com/questions/364681",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/186599/"
] | I wanna know, what are the **hooks** in wp themes, like before\_header\_hook, after\_header\_hook?
What are the uses and benefits of these hooks in theme development? | WordPress is a whole package of different code components working together to provide a functional Content Management System. WordPress Core, Plugins, and Themes are all part of this package. Since some of these components update separately you do not want to edit the code directly, otherwise your changes will be overwritten whenever these components update. Thus, WordPress implemented a [system of Hooks](https://developer.wordpress.org/plugins/hooks/).
---
[Action hooks](https://developer.wordpress.org/plugins/hooks/actions/) allow you to inject functionality into a specific point of runtime. You can create your own plugin or theme with these action hooks so that they do not get overwritten whenever a component updates. For example, `plugins_loaded` is an action hook that runs after all plugins have been loaded during runtime. If you wanted to run specific functionality after all the plugins have been loaded during a page request you could say:
```
function example_plugins_loaded_callback() {
// Print a message then stop page request load.
print( 'All plugins have been loaded successfully!' );
exit();
}
add_action( 'plugins_loaded', 'example_plugins_loaded_callback' );
```
Once all plugins are loaded the above message gets printed to the screen and the page request stops loading additional files. This is a simple example usage but that's the gist of how action hooks work. You could call an API or write to the database at this point if you wanted to.
Without Action Hooks, if you wanted to print the above you would need edit the [`wp-settings.php`](https://core.trac.wordpress.org/browser/tags/5.4/src/wp-settings.php#L409) file directly which would eventually be overwritten whenever WordPress updates. This would break whatever functionality you would need in place when the `plugins_loaded` hook runs.
---
[Filter Hooks](https://developer.wordpress.org/plugins/hooks/filters/) allow you to modify specific values generated by functions. Unlike action hooks they expect a returned value. A good example for this is the filter hook [`the_title`](https://developer.wordpress.org/reference/hooks/the_title/) which allows you to modify `the_title()` and `get_the_title()` values before they're printed to the screen. You can view the code directly by [viewing the function on trac](https://core.trac.wordpress.org/browser/tags/5.4/src/wp-includes/post-template.php#L117). The function and callback is similar to action hooks:
```
function example_the_title_callback() {
return 'Example Title';
}
add_filter( 'the_title', 'example_the_title_callback' );
```
Using the above filter hook, anywhere that `the_title()` is called will now print `Example Title` instead.
---
Hooks also come with priorities and number of args. You will need to look up each hook to figure out what args are passed to the hook but it goes like this:
```
add_filter(
'the_title', // Hook Name
'example_the_title_callback', // Callback Function Name
10, // Priority
2 // Number of arguments
);
```
* **Hook Name** - Not every function has available hooks. You will need to look this up on a per-need basis using the [Developer Docs](https://developer.wordpress.org/reference/).
* **Callback Function** - The name of the function you want to trigger.
* **Priority** - When you want the hook to run. Hooks can have multiple functions attached to them, some may not be yours ( plugins or themes ). Lower priority will run before higher priority hooks.
* **Number of Arguments** - The arguments passed to the callback function.
Hooks that pass more than 1 argument need to be told to give your callback function those arguments. `the_title` hook passes `$title` and `$post_id`. If we want to use the `$post_id` argument we need to tell the `add_filter()` function to pass those to our callback function:
```
/**
* One Argument Hook
*/
function example_the_title_callback( $title ) {
/**
* - By default we always get 1 argument if possible.
* - We do not have access to $post_id at this point.
*/
$new_title = $title . '!!!';
return $new_title;
}
add_filter( 'the_title', 'example_the_title_callback' );
/**
* Two Arguments Hook
*/
function example_the_title_callback( $title, $post_id ) {
/**
* Since we specified 2 arguments, we receive the 2 arguments that the hook provides
*/
$post = get_post( $post_id );
$new_title = $title . ' - ' . $post->ID;
return $new_title;
}
add_filter( 'the_title', 'example_the_title_callback', 10, 2 );
```
Again, you'll need into the Developer Docs to see what arguments the hook passes.
---
Finally, you as a theme or plugin developer can add in your own custom hooks which will allow other developers to add any or modify specific functionality.
Let's say you've written a plugin that wraps the Post Title on the frontend in `<span>` HTML tags for specific styling. You can add a hook to allow other developers to add custom classes to your span like so:
```
/**
* My super cool plugin
* Add HTML span tags around titles
* Our plugin CSS can style them cool later
*/
function supercool_title( $title ) {
// Allow theme developers or plugin developers to add classes to our span tag.
$classes = apply_filters(
'supercool_title_classes', // Our custom filter name
array(), // Array of classes to pass to the filter, empty in this scenario
);
// Filters always return
return sprintf( '<span class="%s">%s</span>', esc_attr( implode( ' ', $classes ) ), $title );
}
add_filter( 'the_title', 'supercool_title' );
```
As a theme developer I can use that plugins hook to add in my own classes if I wanted to.
```
/**
* Theme Devloper modifies plugin functionality
* Adds specific class to the super cool plugin title wrapper
*/
function my_theme_supercool_title_classes( $classe ) {
$classes[] = 'special-title';
return $classes;
}
add_filter( 'supercool_title_classes', 'my_theme_supercool_title_classes' );
// Output
<span class="special-title">Post Title</span>
```
You could do the same thing with action hooks when creating your theme or plugin. WooCommerce utilizes a lot of action hooks in their templating system allowing other plugins and specific themes to add in output. Something like:
```
do_action( 'before_header_hook' ); // A custom action hook created by the developer.
```
Simply allows you, if you want to, to inject specific code at that point. Maybe an Analytics script or an entire HTML wrapper for a utility nav that the theme previously didn't support. The possibilities are endless! |
364,791 | <p>I started getting international visits but how do I make my site multi-language? Is there a good plugin or what do I have to do?</p>
| [
{
"answer_id": 364696,
"author": "Amir",
"author_id": 80135,
"author_profile": "https://wordpress.stackexchange.com/users/80135",
"pm_score": 1,
"selected": false,
"text": "<p>Whenever you want to do something or customize something in WordPress, then there is very likely a hook you can use.</p>\n\n<p>The “do” hook is called an “action.” Wherever an action is defined, you can execute your own code. Here are some examples:</p>\n\n<ul>\n<li>send an email to the author once a post is published;</li>\n<li>load a custom script file in the footer of the page;</li>\n<li>add instructions above the login form.</li>\n</ul>\n\n<p>A hook is a place in WordPress’s code that can get functions added to it. When you create a hook, you give yourself and other developers the opportunity to add in additional functionality at that location.</p>\n\n<p>Hooked functions are custom PHP functions that we can “hook into” WordPress, at the locations specified by its hooks.</p>\n"
},
{
"answer_id": 364703,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 2,
"selected": false,
"text": "<p>WordPress is a whole package of different code components working together to provide a functional Content Management System. WordPress Core, Plugins, and Themes are all part of this package. Since some of these components update separately you do not want to edit the code directly, otherwise your changes will be overwritten whenever these components update. Thus, WordPress implemented a <a href=\"https://developer.wordpress.org/plugins/hooks/\" rel=\"nofollow noreferrer\">system of Hooks</a>.</p>\n\n<hr>\n\n<p><a href=\"https://developer.wordpress.org/plugins/hooks/actions/\" rel=\"nofollow noreferrer\">Action hooks</a> allow you to inject functionality into a specific point of runtime. You can create your own plugin or theme with these action hooks so that they do not get overwritten whenever a component updates. For example, <code>plugins_loaded</code> is an action hook that runs after all plugins have been loaded during runtime. If you wanted to run specific functionality after all the plugins have been loaded during a page request you could say:</p>\n\n<pre><code>function example_plugins_loaded_callback() {\n\n // Print a message then stop page request load.\n print( 'All plugins have been loaded successfully!' );\n exit();\n\n}\nadd_action( 'plugins_loaded', 'example_plugins_loaded_callback' );\n</code></pre>\n\n<p>Once all plugins are loaded the above message gets printed to the screen and the page request stops loading additional files. This is a simple example usage but that's the gist of how action hooks work. You could call an API or write to the database at this point if you wanted to.</p>\n\n<p>Without Action Hooks, if you wanted to print the above you would need edit the <a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-settings.php#L409\" rel=\"nofollow noreferrer\"><code>wp-settings.php</code></a> file directly which would eventually be overwritten whenever WordPress updates. This would break whatever functionality you would need in place when the <code>plugins_loaded</code> hook runs.</p>\n\n<hr>\n\n<p><a href=\"https://developer.wordpress.org/plugins/hooks/filters/\" rel=\"nofollow noreferrer\">Filter Hooks</a> allow you to modify specific values generated by functions. Unlike action hooks they expect a returned value. A good example for this is the filter hook <a href=\"https://developer.wordpress.org/reference/hooks/the_title/\" rel=\"nofollow noreferrer\"><code>the_title</code></a> which allows you to modify <code>the_title()</code> and <code>get_the_title()</code> values before they're printed to the screen. You can view the code directly by <a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-includes/post-template.php#L117\" rel=\"nofollow noreferrer\">viewing the function on trac</a>. The function and callback is similar to action hooks:</p>\n\n<pre><code>function example_the_title_callback() {\n\n return 'Example Title';\n\n}\nadd_filter( 'the_title', 'example_the_title_callback' );\n</code></pre>\n\n<p>Using the above filter hook, anywhere that <code>the_title()</code> is called will now print <code>Example Title</code> instead.</p>\n\n<hr>\n\n<p>Hooks also come with priorities and number of args. You will need to look up each hook to figure out what args are passed to the hook but it goes like this:</p>\n\n<pre><code>add_filter(\n 'the_title', // Hook Name\n 'example_the_title_callback', // Callback Function Name\n 10, // Priority\n 2 // Number of arguments\n);\n</code></pre>\n\n<ul>\n<li><strong>Hook Name</strong> - Not every function has available hooks. You will need to look this up on a per-need basis using the <a href=\"https://developer.wordpress.org/reference/\" rel=\"nofollow noreferrer\">Developer Docs</a>.</li>\n<li><strong>Callback Function</strong> - The name of the function you want to trigger.</li>\n<li><strong>Priority</strong> - When you want the hook to run. Hooks can have multiple functions attached to them, some may not be yours ( plugins or themes ). Lower priority will run before higher priority hooks.</li>\n<li><strong>Number of Arguments</strong> - The arguments passed to the callback function.</li>\n</ul>\n\n<p>Hooks that pass more than 1 argument need to be told to give your callback function those arguments. <code>the_title</code> hook passes <code>$title</code> and <code>$post_id</code>. If we want to use the <code>$post_id</code> argument we need to tell the <code>add_filter()</code> function to pass those to our callback function:</p>\n\n<pre><code>/**\n * One Argument Hook\n */\nfunction example_the_title_callback( $title ) {\n\n /**\n * - By default we always get 1 argument if possible.\n * - We do not have access to $post_id at this point.\n */\n $new_title = $title . '!!!';\n\n return $new_title;\n}\nadd_filter( 'the_title', 'example_the_title_callback' );\n\n/**\n * Two Arguments Hook\n */\nfunction example_the_title_callback( $title, $post_id ) {\n\n /**\n * Since we specified 2 arguments, we receive the 2 arguments that the hook provides\n */\n $post = get_post( $post_id );\n $new_title = $title . ' - ' . $post->ID;\n\n return $new_title;\n}\nadd_filter( 'the_title', 'example_the_title_callback', 10, 2 );\n</code></pre>\n\n<p>Again, you'll need into the Developer Docs to see what arguments the hook passes.</p>\n\n<hr>\n\n<p>Finally, you as a theme or plugin developer can add in your own custom hooks which will allow other developers to add any or modify specific functionality.</p>\n\n<p>Let's say you've written a plugin that wraps the Post Title on the frontend in <code><span></code> HTML tags for specific styling. You can add a hook to allow other developers to add custom classes to your span like so:</p>\n\n<pre><code>/**\n * My super cool plugin\n * Add HTML span tags around titles\n * Our plugin CSS can style them cool later\n */\nfunction supercool_title( $title ) {\n\n // Allow theme developers or plugin developers to add classes to our span tag.\n $classes = apply_filters(\n 'supercool_title_classes', // Our custom filter name\n array(), // Array of classes to pass to the filter, empty in this scenario\n );\n\n // Filters always return\n return sprintf( '<span class=\"%s\">%s</span>', esc_attr( implode( ' ', $classes ) ), $title );\n\n}\nadd_filter( 'the_title', 'supercool_title' );\n</code></pre>\n\n<p>As a theme developer I can use that plugins hook to add in my own classes if I wanted to.</p>\n\n<pre><code>/**\n * Theme Devloper modifies plugin functionality\n * Adds specific class to the super cool plugin title wrapper\n */\nfunction my_theme_supercool_title_classes( $classe ) {\n\n $classes[] = 'special-title';\n return $classes;\n\n}\nadd_filter( 'supercool_title_classes', 'my_theme_supercool_title_classes' );\n\n// Output\n<span class=\"special-title\">Post Title</span>\n</code></pre>\n\n<p>You could do the same thing with action hooks when creating your theme or plugin. WooCommerce utilizes a lot of action hooks in their templating system allowing other plugins and specific themes to add in output. Something like:</p>\n\n<pre><code>do_action( 'before_header_hook' ); // A custom action hook created by the developer.\n</code></pre>\n\n<p>Simply allows you, if you want to, to inject specific code at that point. Maybe an Analytics script or an entire HTML wrapper for a utility nav that the theme previously didn't support. The possibilities are endless!</p>\n"
}
] | 2020/04/22 | [
"https://wordpress.stackexchange.com/questions/364791",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/186686/"
] | I started getting international visits but how do I make my site multi-language? Is there a good plugin or what do I have to do? | WordPress is a whole package of different code components working together to provide a functional Content Management System. WordPress Core, Plugins, and Themes are all part of this package. Since some of these components update separately you do not want to edit the code directly, otherwise your changes will be overwritten whenever these components update. Thus, WordPress implemented a [system of Hooks](https://developer.wordpress.org/plugins/hooks/).
---
[Action hooks](https://developer.wordpress.org/plugins/hooks/actions/) allow you to inject functionality into a specific point of runtime. You can create your own plugin or theme with these action hooks so that they do not get overwritten whenever a component updates. For example, `plugins_loaded` is an action hook that runs after all plugins have been loaded during runtime. If you wanted to run specific functionality after all the plugins have been loaded during a page request you could say:
```
function example_plugins_loaded_callback() {
// Print a message then stop page request load.
print( 'All plugins have been loaded successfully!' );
exit();
}
add_action( 'plugins_loaded', 'example_plugins_loaded_callback' );
```
Once all plugins are loaded the above message gets printed to the screen and the page request stops loading additional files. This is a simple example usage but that's the gist of how action hooks work. You could call an API or write to the database at this point if you wanted to.
Without Action Hooks, if you wanted to print the above you would need edit the [`wp-settings.php`](https://core.trac.wordpress.org/browser/tags/5.4/src/wp-settings.php#L409) file directly which would eventually be overwritten whenever WordPress updates. This would break whatever functionality you would need in place when the `plugins_loaded` hook runs.
---
[Filter Hooks](https://developer.wordpress.org/plugins/hooks/filters/) allow you to modify specific values generated by functions. Unlike action hooks they expect a returned value. A good example for this is the filter hook [`the_title`](https://developer.wordpress.org/reference/hooks/the_title/) which allows you to modify `the_title()` and `get_the_title()` values before they're printed to the screen. You can view the code directly by [viewing the function on trac](https://core.trac.wordpress.org/browser/tags/5.4/src/wp-includes/post-template.php#L117). The function and callback is similar to action hooks:
```
function example_the_title_callback() {
return 'Example Title';
}
add_filter( 'the_title', 'example_the_title_callback' );
```
Using the above filter hook, anywhere that `the_title()` is called will now print `Example Title` instead.
---
Hooks also come with priorities and number of args. You will need to look up each hook to figure out what args are passed to the hook but it goes like this:
```
add_filter(
'the_title', // Hook Name
'example_the_title_callback', // Callback Function Name
10, // Priority
2 // Number of arguments
);
```
* **Hook Name** - Not every function has available hooks. You will need to look this up on a per-need basis using the [Developer Docs](https://developer.wordpress.org/reference/).
* **Callback Function** - The name of the function you want to trigger.
* **Priority** - When you want the hook to run. Hooks can have multiple functions attached to them, some may not be yours ( plugins or themes ). Lower priority will run before higher priority hooks.
* **Number of Arguments** - The arguments passed to the callback function.
Hooks that pass more than 1 argument need to be told to give your callback function those arguments. `the_title` hook passes `$title` and `$post_id`. If we want to use the `$post_id` argument we need to tell the `add_filter()` function to pass those to our callback function:
```
/**
* One Argument Hook
*/
function example_the_title_callback( $title ) {
/**
* - By default we always get 1 argument if possible.
* - We do not have access to $post_id at this point.
*/
$new_title = $title . '!!!';
return $new_title;
}
add_filter( 'the_title', 'example_the_title_callback' );
/**
* Two Arguments Hook
*/
function example_the_title_callback( $title, $post_id ) {
/**
* Since we specified 2 arguments, we receive the 2 arguments that the hook provides
*/
$post = get_post( $post_id );
$new_title = $title . ' - ' . $post->ID;
return $new_title;
}
add_filter( 'the_title', 'example_the_title_callback', 10, 2 );
```
Again, you'll need into the Developer Docs to see what arguments the hook passes.
---
Finally, you as a theme or plugin developer can add in your own custom hooks which will allow other developers to add any or modify specific functionality.
Let's say you've written a plugin that wraps the Post Title on the frontend in `<span>` HTML tags for specific styling. You can add a hook to allow other developers to add custom classes to your span like so:
```
/**
* My super cool plugin
* Add HTML span tags around titles
* Our plugin CSS can style them cool later
*/
function supercool_title( $title ) {
// Allow theme developers or plugin developers to add classes to our span tag.
$classes = apply_filters(
'supercool_title_classes', // Our custom filter name
array(), // Array of classes to pass to the filter, empty in this scenario
);
// Filters always return
return sprintf( '<span class="%s">%s</span>', esc_attr( implode( ' ', $classes ) ), $title );
}
add_filter( 'the_title', 'supercool_title' );
```
As a theme developer I can use that plugins hook to add in my own classes if I wanted to.
```
/**
* Theme Devloper modifies plugin functionality
* Adds specific class to the super cool plugin title wrapper
*/
function my_theme_supercool_title_classes( $classe ) {
$classes[] = 'special-title';
return $classes;
}
add_filter( 'supercool_title_classes', 'my_theme_supercool_title_classes' );
// Output
<span class="special-title">Post Title</span>
```
You could do the same thing with action hooks when creating your theme or plugin. WooCommerce utilizes a lot of action hooks in their templating system allowing other plugins and specific themes to add in output. Something like:
```
do_action( 'before_header_hook' ); // A custom action hook created by the developer.
```
Simply allows you, if you want to, to inject specific code at that point. Maybe an Analytics script or an entire HTML wrapper for a utility nav that the theme previously didn't support. The possibilities are endless! |
364,807 | <p>I am trying to add some PHP code before my WooCommerce product page sidebar content and can't for the life of me find where to do that. I have tried editing sidebar.php, using the 'woocommerce_sidebar' hook but cannot make this work.</p>
<p>I simply want some PHP code to be visible above the widget content in <code><div class="sidebar-content"</code></p>
<p>Anybody have a simple solution for this? <code>get_sidebar( 'shop' );</code> shop is being called, but how do I get some extra code in there?</p>
| [
{
"answer_id": 364696,
"author": "Amir",
"author_id": 80135,
"author_profile": "https://wordpress.stackexchange.com/users/80135",
"pm_score": 1,
"selected": false,
"text": "<p>Whenever you want to do something or customize something in WordPress, then there is very likely a hook you can use.</p>\n\n<p>The “do” hook is called an “action.” Wherever an action is defined, you can execute your own code. Here are some examples:</p>\n\n<ul>\n<li>send an email to the author once a post is published;</li>\n<li>load a custom script file in the footer of the page;</li>\n<li>add instructions above the login form.</li>\n</ul>\n\n<p>A hook is a place in WordPress’s code that can get functions added to it. When you create a hook, you give yourself and other developers the opportunity to add in additional functionality at that location.</p>\n\n<p>Hooked functions are custom PHP functions that we can “hook into” WordPress, at the locations specified by its hooks.</p>\n"
},
{
"answer_id": 364703,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 2,
"selected": false,
"text": "<p>WordPress is a whole package of different code components working together to provide a functional Content Management System. WordPress Core, Plugins, and Themes are all part of this package. Since some of these components update separately you do not want to edit the code directly, otherwise your changes will be overwritten whenever these components update. Thus, WordPress implemented a <a href=\"https://developer.wordpress.org/plugins/hooks/\" rel=\"nofollow noreferrer\">system of Hooks</a>.</p>\n\n<hr>\n\n<p><a href=\"https://developer.wordpress.org/plugins/hooks/actions/\" rel=\"nofollow noreferrer\">Action hooks</a> allow you to inject functionality into a specific point of runtime. You can create your own plugin or theme with these action hooks so that they do not get overwritten whenever a component updates. For example, <code>plugins_loaded</code> is an action hook that runs after all plugins have been loaded during runtime. If you wanted to run specific functionality after all the plugins have been loaded during a page request you could say:</p>\n\n<pre><code>function example_plugins_loaded_callback() {\n\n // Print a message then stop page request load.\n print( 'All plugins have been loaded successfully!' );\n exit();\n\n}\nadd_action( 'plugins_loaded', 'example_plugins_loaded_callback' );\n</code></pre>\n\n<p>Once all plugins are loaded the above message gets printed to the screen and the page request stops loading additional files. This is a simple example usage but that's the gist of how action hooks work. You could call an API or write to the database at this point if you wanted to.</p>\n\n<p>Without Action Hooks, if you wanted to print the above you would need edit the <a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-settings.php#L409\" rel=\"nofollow noreferrer\"><code>wp-settings.php</code></a> file directly which would eventually be overwritten whenever WordPress updates. This would break whatever functionality you would need in place when the <code>plugins_loaded</code> hook runs.</p>\n\n<hr>\n\n<p><a href=\"https://developer.wordpress.org/plugins/hooks/filters/\" rel=\"nofollow noreferrer\">Filter Hooks</a> allow you to modify specific values generated by functions. Unlike action hooks they expect a returned value. A good example for this is the filter hook <a href=\"https://developer.wordpress.org/reference/hooks/the_title/\" rel=\"nofollow noreferrer\"><code>the_title</code></a> which allows you to modify <code>the_title()</code> and <code>get_the_title()</code> values before they're printed to the screen. You can view the code directly by <a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-includes/post-template.php#L117\" rel=\"nofollow noreferrer\">viewing the function on trac</a>. The function and callback is similar to action hooks:</p>\n\n<pre><code>function example_the_title_callback() {\n\n return 'Example Title';\n\n}\nadd_filter( 'the_title', 'example_the_title_callback' );\n</code></pre>\n\n<p>Using the above filter hook, anywhere that <code>the_title()</code> is called will now print <code>Example Title</code> instead.</p>\n\n<hr>\n\n<p>Hooks also come with priorities and number of args. You will need to look up each hook to figure out what args are passed to the hook but it goes like this:</p>\n\n<pre><code>add_filter(\n 'the_title', // Hook Name\n 'example_the_title_callback', // Callback Function Name\n 10, // Priority\n 2 // Number of arguments\n);\n</code></pre>\n\n<ul>\n<li><strong>Hook Name</strong> - Not every function has available hooks. You will need to look this up on a per-need basis using the <a href=\"https://developer.wordpress.org/reference/\" rel=\"nofollow noreferrer\">Developer Docs</a>.</li>\n<li><strong>Callback Function</strong> - The name of the function you want to trigger.</li>\n<li><strong>Priority</strong> - When you want the hook to run. Hooks can have multiple functions attached to them, some may not be yours ( plugins or themes ). Lower priority will run before higher priority hooks.</li>\n<li><strong>Number of Arguments</strong> - The arguments passed to the callback function.</li>\n</ul>\n\n<p>Hooks that pass more than 1 argument need to be told to give your callback function those arguments. <code>the_title</code> hook passes <code>$title</code> and <code>$post_id</code>. If we want to use the <code>$post_id</code> argument we need to tell the <code>add_filter()</code> function to pass those to our callback function:</p>\n\n<pre><code>/**\n * One Argument Hook\n */\nfunction example_the_title_callback( $title ) {\n\n /**\n * - By default we always get 1 argument if possible.\n * - We do not have access to $post_id at this point.\n */\n $new_title = $title . '!!!';\n\n return $new_title;\n}\nadd_filter( 'the_title', 'example_the_title_callback' );\n\n/**\n * Two Arguments Hook\n */\nfunction example_the_title_callback( $title, $post_id ) {\n\n /**\n * Since we specified 2 arguments, we receive the 2 arguments that the hook provides\n */\n $post = get_post( $post_id );\n $new_title = $title . ' - ' . $post->ID;\n\n return $new_title;\n}\nadd_filter( 'the_title', 'example_the_title_callback', 10, 2 );\n</code></pre>\n\n<p>Again, you'll need into the Developer Docs to see what arguments the hook passes.</p>\n\n<hr>\n\n<p>Finally, you as a theme or plugin developer can add in your own custom hooks which will allow other developers to add any or modify specific functionality.</p>\n\n<p>Let's say you've written a plugin that wraps the Post Title on the frontend in <code><span></code> HTML tags for specific styling. You can add a hook to allow other developers to add custom classes to your span like so:</p>\n\n<pre><code>/**\n * My super cool plugin\n * Add HTML span tags around titles\n * Our plugin CSS can style them cool later\n */\nfunction supercool_title( $title ) {\n\n // Allow theme developers or plugin developers to add classes to our span tag.\n $classes = apply_filters(\n 'supercool_title_classes', // Our custom filter name\n array(), // Array of classes to pass to the filter, empty in this scenario\n );\n\n // Filters always return\n return sprintf( '<span class=\"%s\">%s</span>', esc_attr( implode( ' ', $classes ) ), $title );\n\n}\nadd_filter( 'the_title', 'supercool_title' );\n</code></pre>\n\n<p>As a theme developer I can use that plugins hook to add in my own classes if I wanted to.</p>\n\n<pre><code>/**\n * Theme Devloper modifies plugin functionality\n * Adds specific class to the super cool plugin title wrapper\n */\nfunction my_theme_supercool_title_classes( $classe ) {\n\n $classes[] = 'special-title';\n return $classes;\n\n}\nadd_filter( 'supercool_title_classes', 'my_theme_supercool_title_classes' );\n\n// Output\n<span class=\"special-title\">Post Title</span>\n</code></pre>\n\n<p>You could do the same thing with action hooks when creating your theme or plugin. WooCommerce utilizes a lot of action hooks in their templating system allowing other plugins and specific themes to add in output. Something like:</p>\n\n<pre><code>do_action( 'before_header_hook' ); // A custom action hook created by the developer.\n</code></pre>\n\n<p>Simply allows you, if you want to, to inject specific code at that point. Maybe an Analytics script or an entire HTML wrapper for a utility nav that the theme previously didn't support. The possibilities are endless!</p>\n"
}
] | 2020/04/22 | [
"https://wordpress.stackexchange.com/questions/364807",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/186573/"
] | I am trying to add some PHP code before my WooCommerce product page sidebar content and can't for the life of me find where to do that. I have tried editing sidebar.php, using the 'woocommerce\_sidebar' hook but cannot make this work.
I simply want some PHP code to be visible above the widget content in `<div class="sidebar-content"`
Anybody have a simple solution for this? `get_sidebar( 'shop' );` shop is being called, but how do I get some extra code in there? | WordPress is a whole package of different code components working together to provide a functional Content Management System. WordPress Core, Plugins, and Themes are all part of this package. Since some of these components update separately you do not want to edit the code directly, otherwise your changes will be overwritten whenever these components update. Thus, WordPress implemented a [system of Hooks](https://developer.wordpress.org/plugins/hooks/).
---
[Action hooks](https://developer.wordpress.org/plugins/hooks/actions/) allow you to inject functionality into a specific point of runtime. You can create your own plugin or theme with these action hooks so that they do not get overwritten whenever a component updates. For example, `plugins_loaded` is an action hook that runs after all plugins have been loaded during runtime. If you wanted to run specific functionality after all the plugins have been loaded during a page request you could say:
```
function example_plugins_loaded_callback() {
// Print a message then stop page request load.
print( 'All plugins have been loaded successfully!' );
exit();
}
add_action( 'plugins_loaded', 'example_plugins_loaded_callback' );
```
Once all plugins are loaded the above message gets printed to the screen and the page request stops loading additional files. This is a simple example usage but that's the gist of how action hooks work. You could call an API or write to the database at this point if you wanted to.
Without Action Hooks, if you wanted to print the above you would need edit the [`wp-settings.php`](https://core.trac.wordpress.org/browser/tags/5.4/src/wp-settings.php#L409) file directly which would eventually be overwritten whenever WordPress updates. This would break whatever functionality you would need in place when the `plugins_loaded` hook runs.
---
[Filter Hooks](https://developer.wordpress.org/plugins/hooks/filters/) allow you to modify specific values generated by functions. Unlike action hooks they expect a returned value. A good example for this is the filter hook [`the_title`](https://developer.wordpress.org/reference/hooks/the_title/) which allows you to modify `the_title()` and `get_the_title()` values before they're printed to the screen. You can view the code directly by [viewing the function on trac](https://core.trac.wordpress.org/browser/tags/5.4/src/wp-includes/post-template.php#L117). The function and callback is similar to action hooks:
```
function example_the_title_callback() {
return 'Example Title';
}
add_filter( 'the_title', 'example_the_title_callback' );
```
Using the above filter hook, anywhere that `the_title()` is called will now print `Example Title` instead.
---
Hooks also come with priorities and number of args. You will need to look up each hook to figure out what args are passed to the hook but it goes like this:
```
add_filter(
'the_title', // Hook Name
'example_the_title_callback', // Callback Function Name
10, // Priority
2 // Number of arguments
);
```
* **Hook Name** - Not every function has available hooks. You will need to look this up on a per-need basis using the [Developer Docs](https://developer.wordpress.org/reference/).
* **Callback Function** - The name of the function you want to trigger.
* **Priority** - When you want the hook to run. Hooks can have multiple functions attached to them, some may not be yours ( plugins or themes ). Lower priority will run before higher priority hooks.
* **Number of Arguments** - The arguments passed to the callback function.
Hooks that pass more than 1 argument need to be told to give your callback function those arguments. `the_title` hook passes `$title` and `$post_id`. If we want to use the `$post_id` argument we need to tell the `add_filter()` function to pass those to our callback function:
```
/**
* One Argument Hook
*/
function example_the_title_callback( $title ) {
/**
* - By default we always get 1 argument if possible.
* - We do not have access to $post_id at this point.
*/
$new_title = $title . '!!!';
return $new_title;
}
add_filter( 'the_title', 'example_the_title_callback' );
/**
* Two Arguments Hook
*/
function example_the_title_callback( $title, $post_id ) {
/**
* Since we specified 2 arguments, we receive the 2 arguments that the hook provides
*/
$post = get_post( $post_id );
$new_title = $title . ' - ' . $post->ID;
return $new_title;
}
add_filter( 'the_title', 'example_the_title_callback', 10, 2 );
```
Again, you'll need into the Developer Docs to see what arguments the hook passes.
---
Finally, you as a theme or plugin developer can add in your own custom hooks which will allow other developers to add any or modify specific functionality.
Let's say you've written a plugin that wraps the Post Title on the frontend in `<span>` HTML tags for specific styling. You can add a hook to allow other developers to add custom classes to your span like so:
```
/**
* My super cool plugin
* Add HTML span tags around titles
* Our plugin CSS can style them cool later
*/
function supercool_title( $title ) {
// Allow theme developers or plugin developers to add classes to our span tag.
$classes = apply_filters(
'supercool_title_classes', // Our custom filter name
array(), // Array of classes to pass to the filter, empty in this scenario
);
// Filters always return
return sprintf( '<span class="%s">%s</span>', esc_attr( implode( ' ', $classes ) ), $title );
}
add_filter( 'the_title', 'supercool_title' );
```
As a theme developer I can use that plugins hook to add in my own classes if I wanted to.
```
/**
* Theme Devloper modifies plugin functionality
* Adds specific class to the super cool plugin title wrapper
*/
function my_theme_supercool_title_classes( $classe ) {
$classes[] = 'special-title';
return $classes;
}
add_filter( 'supercool_title_classes', 'my_theme_supercool_title_classes' );
// Output
<span class="special-title">Post Title</span>
```
You could do the same thing with action hooks when creating your theme or plugin. WooCommerce utilizes a lot of action hooks in their templating system allowing other plugins and specific themes to add in output. Something like:
```
do_action( 'before_header_hook' ); // A custom action hook created by the developer.
```
Simply allows you, if you want to, to inject specific code at that point. Maybe an Analytics script or an entire HTML wrapper for a utility nav that the theme previously didn't support. The possibilities are endless! |
364,875 | <p>I have this custom structure set for my permalinks: /archive/%postname%</p>
<p>With this, my URLs show as example.com/parent/child, which is the desired behavior. However, I'm adding a custom post type and this permalink structure is causing undesired URLs for the CPT. I want the permalink to be example.com/news/headline, but I'm getting example.com/archive/news/headline.</p>
<p>Here's my CPT:</p>
<pre><code> register_post_type('news', array(
...
'public' => true,
'rewrite' => array('slug' => 'news'),
'supports' => array( 'title', 'page-attributes', 'editor', 'custom-fields')
));
</code></pre>
<p>Is there a better permalink structure I could use to achieve the URLs I require? Or is there something missing/wrong in my CPT that would fix this issue?</p>
| [
{
"answer_id": 364879,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 0,
"selected": false,
"text": "<p>You can just use the \"Post name\" permalink structure, which is the same as <code>/%postname%/</code>. Pages will use the <code>/parent/child/</code> structure, and your CPT - as-is - will use <code>/news/%postname%/</code>.</p>\n"
},
{
"answer_id": 364881,
"author": "Bikram",
"author_id": 145504,
"author_profile": "https://wordpress.stackexchange.com/users/145504",
"pm_score": 2,
"selected": true,
"text": "<p>Disable the <code>with_front</code> on <code>rewrite</code> while <code>register_post_type</code>.</p>\n\n<p>In your case:</p>\n\n<pre><code>register_post_type('news', array(\n ...\n 'public' => true,\n 'rewrite' => array('slug' => 'news', 'with_front'=> false),\n 'supports' => array( 'title', 'page-attributes', 'editor', 'custom-fields')\n));\n</code></pre>\n"
}
] | 2020/04/23 | [
"https://wordpress.stackexchange.com/questions/364875",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/183146/"
] | I have this custom structure set for my permalinks: /archive/%postname%
With this, my URLs show as example.com/parent/child, which is the desired behavior. However, I'm adding a custom post type and this permalink structure is causing undesired URLs for the CPT. I want the permalink to be example.com/news/headline, but I'm getting example.com/archive/news/headline.
Here's my CPT:
```
register_post_type('news', array(
...
'public' => true,
'rewrite' => array('slug' => 'news'),
'supports' => array( 'title', 'page-attributes', 'editor', 'custom-fields')
));
```
Is there a better permalink structure I could use to achieve the URLs I require? Or is there something missing/wrong in my CPT that would fix this issue? | Disable the `with_front` on `rewrite` while `register_post_type`.
In your case:
```
register_post_type('news', array(
...
'public' => true,
'rewrite' => array('slug' => 'news', 'with_front'=> false),
'supports' => array( 'title', 'page-attributes', 'editor', 'custom-fields')
));
``` |
364,920 | <p>I was wondering how can I load parent theme template parts through child theme after customization. I have created three custom template for my theme and they are working fine. But now I want to load parent theme template parts layout. For example if I want edit profile page the location of the PHP file in parent theme is template_parts/layouts/profile/profile-modern.php In that folder there are other parts profile-header.php and other files. I tried to edit the profile-mordern.php directly in the parent theme and it works. But after theme update, it will be gone so I want to load that file from my child theme. I tried to search the solution but didn't get any specifically. Please can anyone help me regarding this issue? And I am learning PHP programming and WordPress theme customization so please guide me step by step if possible. And also resource link to learn. </p>
| [
{
"answer_id": 364922,
"author": "Amir",
"author_id": 80135,
"author_profile": "https://wordpress.stackexchange.com/users/80135",
"pm_score": -1,
"selected": false,
"text": "<p>For every theme file present in the parent directory, WordPress will check whether a corresponding file is present in the child theme and, if so, use that one instead. This means that a profile-modern.php file in the child theme will override its equivalent in the parent folder.</p>\n\n<p>So, if you don’t like something about a page’s layout, just copy the respective file, implement your changes, and upload it to the child theme’s folder. The modifications will then appear in the child theme, while the original file will remain untouched.</p>\n"
},
{
"answer_id": 400348,
"author": "g0h",
"author_id": 194275,
"author_profile": "https://wordpress.stackexchange.com/users/194275",
"pm_score": 2,
"selected": false,
"text": "<p>From the <a href=\"https://developer.wordpress.org/themes/advanced-topics/child-themes/#referencing-or-including-other-files\" rel=\"nofollow noreferrer\">WordPress documentation on child themes (Referencing or Including Other Files)</a>:</p>\n<blockquote>\n<p>To reference the parent theme directory, you would use\nget_template_directory() instead.</p>\n</blockquote>\n<p>Therefore, in your child theme, you could include your parent template file like this:</p>\n<pre><code><?php\ninclude get_template_directory() . '/template_parts/layouts/profile/profile-modern.php';\n?>\n</code></pre>\n"
}
] | 2020/04/24 | [
"https://wordpress.stackexchange.com/questions/364920",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105528/"
] | I was wondering how can I load parent theme template parts through child theme after customization. I have created three custom template for my theme and they are working fine. But now I want to load parent theme template parts layout. For example if I want edit profile page the location of the PHP file in parent theme is template\_parts/layouts/profile/profile-modern.php In that folder there are other parts profile-header.php and other files. I tried to edit the profile-mordern.php directly in the parent theme and it works. But after theme update, it will be gone so I want to load that file from my child theme. I tried to search the solution but didn't get any specifically. Please can anyone help me regarding this issue? And I am learning PHP programming and WordPress theme customization so please guide me step by step if possible. And also resource link to learn. | From the [WordPress documentation on child themes (Referencing or Including Other Files)](https://developer.wordpress.org/themes/advanced-topics/child-themes/#referencing-or-including-other-files):
>
> To reference the parent theme directory, you would use
> get\_template\_directory() instead.
>
>
>
Therefore, in your child theme, you could include your parent template file like this:
```
<?php
include get_template_directory() . '/template_parts/layouts/profile/profile-modern.php';
?>
``` |
364,929 | <p>I'm following <a href="https://make.wordpress.org/cli/handbook/plugin-unit-tests/" rel="nofollow noreferrer">https://make.wordpress.org/cli/handbook/plugin-unit-tests/</a> to run unit tests for plugins.</p>
<p>I create a new plugin.</p>
<pre><code>$ wp scaffold plugin hello-plugin-1
Success: Created plugin files.
Success: Created test files.
</code></pre>
<p>Run <code>install-wp-tests.sh</code>.</p>
<pre><code>$ cd wp-content/plugins/hello-plugin-1
$ ./bin/install-wp-tests.sh wordpress_test_1 root root localhost latest
+ install_wp
+ '[' -d /var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress/ ']'
+ return
+ install_test_suite
++ uname -s
+ [[ Darwin == \D\a\r\w\i\n ]]
+ local ioption=-i.bak
+ '[' '!' -d /var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress-tests-lib ']'
+ '[' '!' -f wp-tests-config.php ']'
+ download https://develop.svn.wordpress.org/tags/5.4/wp-tests-config-sample.php /var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress-tests-lib/wp-tests-config.php
++ which curl
+ '[' /usr/bin/curl ']'
+ curl -s https://develop.svn.wordpress.org/tags/5.4/wp-tests-config-sample.php
++ echo /var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress/
++ sed 's:/\+$::'
+ WP_CORE_DIR=/var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress/
+ sed -i.bak 's:dirname( __FILE__ ) . '\''/src/'\'':'\''/var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress//'\'':' /var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress-tests-lib/wp-tests-config.php
+ sed -i.bak s/youremptytestdbnamehere/wordpress_test_1/ /var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress-tests-lib/wp-tests-config.php
+ sed -i.bak s/yourusernamehere/root/ /var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress-tests-lib/wp-tests-config.php
+ sed -i.bak s/yourpasswordhere/root/ /var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress-tests-lib/wp-tests-config.php
+ sed -i.bak 's|localhost|localhost|' /var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress-tests-lib/wp-tests-config.php
+ install_db
+ '[' false = true ']'
+ PARTS=(${DB_HOST//\:/ })
+ local PARTS
+ local DB_HOSTNAME=localhost
+ local DB_SOCK_OR_PORT=
+ local EXTRA=
+ '[' -z localhost ']'
++ echo
++ grep -e '^[0-9]\{1,\}$'
+ '[' ']'
+ '[' -z ']'
+ '[' -z localhost ']'
+ EXTRA=' --host=localhost --protocol=tcp'
+ mysqladmin create wordpress_test_1 --user=root --password=root --host=localhost --protocol=tcp
mysqladmin: [Warning] Using a password on the command line interface can be insecure.
</code></pre>
<p>Run <code>phpunit</code> and got this DB connection error. </p>
<pre><code>$ phpunit
PHP Warning: mysqli_real_connect(): (HY000/2002): No such file or directory in /private/var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress/wp-includes/wp-db.php on line 1626
PHP Stack trace:
PHP 1. {main}() /private/var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress-tests-lib/includes/install.php:0
PHP 2. require_once() /private/var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress-tests-lib/includes/install.php:29
PHP 3. require_wp_db() /private/var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress/wp-settings.php:126
PHP 4. wpdb->__construct() /private/var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress/wp-includes/load.php:426
PHP 5. wpdb->db_connect() /private/var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress/wp-includes/wp-db.php:631
PHP 6. mysqli_real_connect() /private/var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress/wp-includes/wp-db.php:1626
wp_die called
Message : <p><code>No such file or directory</code></p>
<h1>Error establishing a database connection</h1>
<p>This either means that the username and password information in your <code>wp-config.php</code> file is incorrect or we can&#8217;t contact the database server at <code>localhost</code>. This could mean your host&#8217;s database server is down.</p>
<ul>
<li>Are you sure you have the correct username and password?</li>
<li>Are you sure you have typed the correct hostname?</li>
<li>Are you sure the database server is running?</li>
</ul>
<p>If you&#8217;re unsure what these terms mean you should probably contact your host. If you still need help you can always visit the <a href="https://wordpress.org/support/forums/">WordPress Support Forums</a>.</p>
Title :
</code></pre>
<p>Do we need to set up the DB in <code>wp-config.php</code> in <code>/var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress</code> before I run phpunit? I tried it and it did not work. Any idea what went wrong?</p>
<p>I'm running <code>WP-CLI 2.4.0</code> and <code>PHPUnit 7.5.9</code>.</p>
| [
{
"answer_id": 364922,
"author": "Amir",
"author_id": 80135,
"author_profile": "https://wordpress.stackexchange.com/users/80135",
"pm_score": -1,
"selected": false,
"text": "<p>For every theme file present in the parent directory, WordPress will check whether a corresponding file is present in the child theme and, if so, use that one instead. This means that a profile-modern.php file in the child theme will override its equivalent in the parent folder.</p>\n\n<p>So, if you don’t like something about a page’s layout, just copy the respective file, implement your changes, and upload it to the child theme’s folder. The modifications will then appear in the child theme, while the original file will remain untouched.</p>\n"
},
{
"answer_id": 400348,
"author": "g0h",
"author_id": 194275,
"author_profile": "https://wordpress.stackexchange.com/users/194275",
"pm_score": 2,
"selected": false,
"text": "<p>From the <a href=\"https://developer.wordpress.org/themes/advanced-topics/child-themes/#referencing-or-including-other-files\" rel=\"nofollow noreferrer\">WordPress documentation on child themes (Referencing or Including Other Files)</a>:</p>\n<blockquote>\n<p>To reference the parent theme directory, you would use\nget_template_directory() instead.</p>\n</blockquote>\n<p>Therefore, in your child theme, you could include your parent template file like this:</p>\n<pre><code><?php\ninclude get_template_directory() . '/template_parts/layouts/profile/profile-modern.php';\n?>\n</code></pre>\n"
}
] | 2020/04/24 | [
"https://wordpress.stackexchange.com/questions/364929",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/185727/"
] | I'm following <https://make.wordpress.org/cli/handbook/plugin-unit-tests/> to run unit tests for plugins.
I create a new plugin.
```
$ wp scaffold plugin hello-plugin-1
Success: Created plugin files.
Success: Created test files.
```
Run `install-wp-tests.sh`.
```
$ cd wp-content/plugins/hello-plugin-1
$ ./bin/install-wp-tests.sh wordpress_test_1 root root localhost latest
+ install_wp
+ '[' -d /var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress/ ']'
+ return
+ install_test_suite
++ uname -s
+ [[ Darwin == \D\a\r\w\i\n ]]
+ local ioption=-i.bak
+ '[' '!' -d /var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress-tests-lib ']'
+ '[' '!' -f wp-tests-config.php ']'
+ download https://develop.svn.wordpress.org/tags/5.4/wp-tests-config-sample.php /var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress-tests-lib/wp-tests-config.php
++ which curl
+ '[' /usr/bin/curl ']'
+ curl -s https://develop.svn.wordpress.org/tags/5.4/wp-tests-config-sample.php
++ echo /var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress/
++ sed 's:/\+$::'
+ WP_CORE_DIR=/var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress/
+ sed -i.bak 's:dirname( __FILE__ ) . '\''/src/'\'':'\''/var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress//'\'':' /var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress-tests-lib/wp-tests-config.php
+ sed -i.bak s/youremptytestdbnamehere/wordpress_test_1/ /var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress-tests-lib/wp-tests-config.php
+ sed -i.bak s/yourusernamehere/root/ /var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress-tests-lib/wp-tests-config.php
+ sed -i.bak s/yourpasswordhere/root/ /var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress-tests-lib/wp-tests-config.php
+ sed -i.bak 's|localhost|localhost|' /var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress-tests-lib/wp-tests-config.php
+ install_db
+ '[' false = true ']'
+ PARTS=(${DB_HOST//\:/ })
+ local PARTS
+ local DB_HOSTNAME=localhost
+ local DB_SOCK_OR_PORT=
+ local EXTRA=
+ '[' -z localhost ']'
++ echo
++ grep -e '^[0-9]\{1,\}$'
+ '[' ']'
+ '[' -z ']'
+ '[' -z localhost ']'
+ EXTRA=' --host=localhost --protocol=tcp'
+ mysqladmin create wordpress_test_1 --user=root --password=root --host=localhost --protocol=tcp
mysqladmin: [Warning] Using a password on the command line interface can be insecure.
```
Run `phpunit` and got this DB connection error.
```
$ phpunit
PHP Warning: mysqli_real_connect(): (HY000/2002): No such file or directory in /private/var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress/wp-includes/wp-db.php on line 1626
PHP Stack trace:
PHP 1. {main}() /private/var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress-tests-lib/includes/install.php:0
PHP 2. require_once() /private/var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress-tests-lib/includes/install.php:29
PHP 3. require_wp_db() /private/var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress/wp-settings.php:126
PHP 4. wpdb->__construct() /private/var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress/wp-includes/load.php:426
PHP 5. wpdb->db_connect() /private/var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress/wp-includes/wp-db.php:631
PHP 6. mysqli_real_connect() /private/var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress/wp-includes/wp-db.php:1626
wp_die called
Message : <p><code>No such file or directory</code></p>
<h1>Error establishing a database connection</h1>
<p>This either means that the username and password information in your <code>wp-config.php</code> file is incorrect or we can’t contact the database server at <code>localhost</code>. This could mean your host’s database server is down.</p>
<ul>
<li>Are you sure you have the correct username and password?</li>
<li>Are you sure you have typed the correct hostname?</li>
<li>Are you sure the database server is running?</li>
</ul>
<p>If you’re unsure what these terms mean you should probably contact your host. If you still need help you can always visit the <a href="https://wordpress.org/support/forums/">WordPress Support Forums</a>.</p>
Title :
```
Do we need to set up the DB in `wp-config.php` in `/var/folders/qd/y3hp2mb90gx36d5swtxcndhh0000gn/T/wordpress` before I run phpunit? I tried it and it did not work. Any idea what went wrong?
I'm running `WP-CLI 2.4.0` and `PHPUnit 7.5.9`. | From the [WordPress documentation on child themes (Referencing or Including Other Files)](https://developer.wordpress.org/themes/advanced-topics/child-themes/#referencing-or-including-other-files):
>
> To reference the parent theme directory, you would use
> get\_template\_directory() instead.
>
>
>
Therefore, in your child theme, you could include your parent template file like this:
```
<?php
include get_template_directory() . '/template_parts/layouts/profile/profile-modern.php';
?>
``` |
Subsets and Splits