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
|
---|---|---|---|---|---|---|
326,534 | <p>You have used the code of this question (<a href="https://wordpress.stackexchange.com/questions/74235/show-content-after-the-first-and-second-paragraph">Show content after the first and second paragraph</a>) and it works correctly for me. </p>
<pre><code> <?php
$paragraphAfter[1] = '<div>AFTER FIRST</div>'; //display after the first paragraph
$paragraphAfter[3] = '<div>AFTER THIRD</div>'; //display after the third paragraph
$paragraphAfter[5] = '<div>AFTER FIFtH</div>'; //display after the fifth paragraph
$content = apply_filters( 'the_content', get_the_content() );
$content = explode("</p>", $content);
$count = count($content);
for ($i = 0; $i < $count; $i++ ) {
if ( array_key_exists($i, $paragraphAfter) ) {
echo $paragraphAfter[$i];
}
echo $content[$i] . "</p>";
} ?>
</code></pre>
<p>I've been watching and remixing. But I have not found the way to add a call type "get_template_part". I do not recognize the part of get_template_part. Where is the error, or can not be done?</p>
<p>Change this:</p>
<pre><code>$paragraphAfter[1] = '<div>AFTER FIRST</div>';
</code></pre>
<p>For this:</p>
<pre><code>$paragraphAfter[1] = '<div> get_template_part( 'ad-first' );</div>';
</code></pre>
<p>I have tried to make a simple echo, but there is something that I fail</p>
<pre><code>$paragraphAfter[1] = '<div> echo "Hello world!"; </div>';
</code></pre>
<p>I can not get it to work :-(
Any help or guidance is welcome, thanks</p>
| [
{
"answer_id": 332375,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 3,
"selected": false,
"text": "<p>The closest I can find in <a href=\"https://wordpress.org/gutenberg/handbook/designers-developers/developers/themes/theme-support/\" rel=\"noreferrer\">the documentation</a> is disabling custom font size (the text input) and forcing the dropdown font size to only contain \"Normal\".</p>\n\n<pre><code>add_action('after_setup_theme', 'wpse_remove_custom_colors');\nfunction wpse_remove_custom_colors() {\n // removes the text box where users can enter custom pixel sizes\n add_theme_support('disable-custom-font-sizes');\n // forces the dropdown for font sizes to only contain \"normal\"\n add_theme_support('editor-font-sizes', array(\n array(\n 'name' => 'Normal',\n 'size' => 16,\n 'slug' => 'normal'\n )\n ) );\n}\n</code></pre>\n\n<p>Note this may not work for non-Core blocks - they may have their own way of registering font size etc. that isn't affected by theme_support. Hoping someone else from the community knows how to disable the drop caps as well.</p>\n\n<p><strong>Update: a way to remove Drop Caps</strong></p>\n\n<p>This wouldn't be my preferred method, because you can still add a Drop Cap in the editor and it just doesn't render in the front end, but it's all I have been able to achieve so far:</p>\n\n<p>There is a <code>render_block()</code> hook where you can change what renders on the front end without changing what shows in the editor or gets saved to the database.</p>\n\n<pre><code>add_filter('render_block', function($block_content, $block) {\n // only affect the Core Paragraph block\n if('core/paragraph' === $block['blockName']) {\n // remove the class that creates the drop cap\n $block_content = str_replace('class=\"has-drop-cap\"', '', $block_content);\n }\n // always return the content, whether we changed it or not\n return $block_content;\n}, 10, 2);\n</code></pre>\n\n<p>This method changes the outer appearance rather than the actual content, so that if you ever wanted to allow drop caps, you could just remove the filter and all the ones that people had added in the editor would suddenly appear.</p>\n"
},
{
"answer_id": 386595,
"author": "jg314",
"author_id": 26202,
"author_profile": "https://wordpress.stackexchange.com/users/26202",
"pm_score": 0,
"selected": false,
"text": "<p>As <a href=\"https://wordpress.stackexchange.com/users/172662/jim-rhoades\">Jim Rhoades</a> noted in one of the comments, you can declare support for custom font sizes, but leave out the array of font size options. This removes the "Typography" section entirely so there is no way to choose a font size. The code looks like this:</p>\n<pre><code>add_theme_support( 'editor-font-sizes' );\n</code></pre>\n<p>For those looking for all the code needed to make it work, you would call this from the <code>after_setup_theme</code> hook inside the functions.php file within your theme:</p>\n<pre><code>function theme_setup() {\n add_theme_support( 'editor-font-sizes' );\n}\nadd_action( 'after_setup_theme', 'theme_setup' );\n</code></pre>\n<p>I've tested this in WordPress 5.7, but it's possible it's supported before this version.</p>\n"
},
{
"answer_id": 387087,
"author": "fairport",
"author_id": 202135,
"author_profile": "https://wordpress.stackexchange.com/users/202135",
"pm_score": 3,
"selected": false,
"text": "<p>There's good answers about disabling the font styles but not about disabling the drop cap.</p>\n<p>In WordPress 5.8, you can you the new <code>theme.json</code> feature to disable drop caps in your theme. You need to add a file with name <code>theme.json</code> in the root of your theme. It should have the following content:</p>\n<pre class=\"lang-json prettyprint-override\"><code>{\n "version": 1,\n "settings": {\n "typography": {\n "dropCap": false\n }\n }\n}\n</code></pre>\n<p>If you want to use a filter instead, you can use the following code in WordPress 5.8:</p>\n<pre><code>function disable_drop_cap_ editor_settings_5_8(array $editor_settings): array {\n $editor_settings['__experimentalFeatures']['typography']['dropCap'] = false;\n return $editor_settings;\n}\nadd_filter('block_editor_settings', 'disable_drop_cap_ editor_settings_5_8');\n</code></pre>\n<p>In WordPress 5.7, the drop cap can be disabled with the following code:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function disable_drop_cap_editor_settings_5_7(array $editor_settings): array {\n $editor_settings['__experimentalFeatures']['defaults']['typography']['dropCap'] = false;\n return $editor_settings;\n}\nadd_filter('block_editor_settings', 'disable_drop_cap_editor_settings_5_7');\n</code></pre>\n<p>In WordPress 5.6, the following code works:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function disable_drop_cap_editor_settings_5_6(array $editor_settings): array {\n $editor_settings['__experimentalFeatures']['global']['typography']['dropCap'] = false;\n return $editor_settings;\n}\nadd_filter('block_editor_settings', 'disable_drop_cap_editor_settings_5_6');\n</code></pre>\n<p>In WordPress 5.5, you will have to use JavaScript to accomplish the same thing:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function disable_drop_cap_admin_footer() {\n echo <<<HTML\n<script>\ndocument.addEventListener("DOMContentLoaded", function () {\n var removeDropCap = function(settings, name) {\n \n if (name !== "core/paragraph") {\n return settings;\n }\n var newSettings = Object.assign({}, settings);\n if (\n newSettings.supports &&\n newSettings.supports.__experimentalFeatures &&\n newSettings.supports.__experimentalFeatures.typography &&\n newSettings.supports.__experimentalFeatures.typography.dropCap\n ) {\n newSettings.supports.__experimentalFeatures.typography.dropCap = false;\n }\n return newSettings;\n };\n wp.hooks.addFilter(\n "blocks.registerBlockType",\n "sc/gb/remove-drop-cap",\n removeDropCap,\n );\n});\n</script>\nHTML;\n}\nadd_action('admin_footer', 'disable_drop_cap_admin_footer');\n</code></pre>\n<p>If you want the functionality as a plugin, you can use the <a href=\"https://wordpress.org/plugins/disable-drop-cap/\" rel=\"nofollow noreferrer\">Disable Drop Cap</a> plugin. Full disclosure, I'm the author of the said plugin.</p>\n"
},
{
"answer_id": 395438,
"author": "Kevinleary.net",
"author_id": 1495,
"author_profile": "https://wordpress.stackexchange.com/users/1495",
"pm_score": 1,
"selected": false,
"text": "<p>This was the true, final answer that solved for the exact scenario described in the original question:</p>\n<pre><code>/**\n * Disable Native Gutenberg Features\n */\nfunction gutenberg_removals()\n{\n add_theme_support('disable-custom-font-sizes');\n add_theme_support('editor-font-sizes', []);\n}\nadd_action('after_setup_theme', 'gutenberg_removals');\n</code></pre>\n<p>Passing an empty array to the <code>editor-font-sizes</code> avoid a PHP notice for an invalid argument.</p>\n"
}
] | 2019/01/24 | [
"https://wordpress.stackexchange.com/questions/326534",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159674/"
] | You have used the code of this question ([Show content after the first and second paragraph](https://wordpress.stackexchange.com/questions/74235/show-content-after-the-first-and-second-paragraph)) and it works correctly for me.
```
<?php
$paragraphAfter[1] = '<div>AFTER FIRST</div>'; //display after the first paragraph
$paragraphAfter[3] = '<div>AFTER THIRD</div>'; //display after the third paragraph
$paragraphAfter[5] = '<div>AFTER FIFtH</div>'; //display after the fifth paragraph
$content = apply_filters( 'the_content', get_the_content() );
$content = explode("</p>", $content);
$count = count($content);
for ($i = 0; $i < $count; $i++ ) {
if ( array_key_exists($i, $paragraphAfter) ) {
echo $paragraphAfter[$i];
}
echo $content[$i] . "</p>";
} ?>
```
I've been watching and remixing. But I have not found the way to add a call type "get\_template\_part". I do not recognize the part of get\_template\_part. Where is the error, or can not be done?
Change this:
```
$paragraphAfter[1] = '<div>AFTER FIRST</div>';
```
For this:
```
$paragraphAfter[1] = '<div> get_template_part( 'ad-first' );</div>';
```
I have tried to make a simple echo, but there is something that I fail
```
$paragraphAfter[1] = '<div> echo "Hello world!"; </div>';
```
I can not get it to work :-(
Any help or guidance is welcome, thanks | The closest I can find in [the documentation](https://wordpress.org/gutenberg/handbook/designers-developers/developers/themes/theme-support/) is disabling custom font size (the text input) and forcing the dropdown font size to only contain "Normal".
```
add_action('after_setup_theme', 'wpse_remove_custom_colors');
function wpse_remove_custom_colors() {
// removes the text box where users can enter custom pixel sizes
add_theme_support('disable-custom-font-sizes');
// forces the dropdown for font sizes to only contain "normal"
add_theme_support('editor-font-sizes', array(
array(
'name' => 'Normal',
'size' => 16,
'slug' => 'normal'
)
) );
}
```
Note this may not work for non-Core blocks - they may have their own way of registering font size etc. that isn't affected by theme\_support. Hoping someone else from the community knows how to disable the drop caps as well.
**Update: a way to remove Drop Caps**
This wouldn't be my preferred method, because you can still add a Drop Cap in the editor and it just doesn't render in the front end, but it's all I have been able to achieve so far:
There is a `render_block()` hook where you can change what renders on the front end without changing what shows in the editor or gets saved to the database.
```
add_filter('render_block', function($block_content, $block) {
// only affect the Core Paragraph block
if('core/paragraph' === $block['blockName']) {
// remove the class that creates the drop cap
$block_content = str_replace('class="has-drop-cap"', '', $block_content);
}
// always return the content, whether we changed it or not
return $block_content;
}, 10, 2);
```
This method changes the outer appearance rather than the actual content, so that if you ever wanted to allow drop caps, you could just remove the filter and all the ones that people had added in the editor would suddenly appear. |
326,536 | <p>I migrated my website from one hosting to another by importing the DB and reinstalling the old exported DB on the new hosting. I have also re-installed the wordpress template. The result is the following: </p>
<p><a href="https://www.sea-dobbiaco.bz.it/" rel="nofollow noreferrer">https://www.sea-dobbiaco.bz.it/</a></p>
<p>The original home page is as follows, and on the old hosting it worked well.
<a href="https://goodnews.xplodedthemes.com/news-flash/?xt-preview" rel="nofollow noreferrer">https://goodnews.xplodedthemes.com/news-flash/?xt-preview</a></p>
<p>Please help me!</p>
| [
{
"answer_id": 332375,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 3,
"selected": false,
"text": "<p>The closest I can find in <a href=\"https://wordpress.org/gutenberg/handbook/designers-developers/developers/themes/theme-support/\" rel=\"noreferrer\">the documentation</a> is disabling custom font size (the text input) and forcing the dropdown font size to only contain \"Normal\".</p>\n\n<pre><code>add_action('after_setup_theme', 'wpse_remove_custom_colors');\nfunction wpse_remove_custom_colors() {\n // removes the text box where users can enter custom pixel sizes\n add_theme_support('disable-custom-font-sizes');\n // forces the dropdown for font sizes to only contain \"normal\"\n add_theme_support('editor-font-sizes', array(\n array(\n 'name' => 'Normal',\n 'size' => 16,\n 'slug' => 'normal'\n )\n ) );\n}\n</code></pre>\n\n<p>Note this may not work for non-Core blocks - they may have their own way of registering font size etc. that isn't affected by theme_support. Hoping someone else from the community knows how to disable the drop caps as well.</p>\n\n<p><strong>Update: a way to remove Drop Caps</strong></p>\n\n<p>This wouldn't be my preferred method, because you can still add a Drop Cap in the editor and it just doesn't render in the front end, but it's all I have been able to achieve so far:</p>\n\n<p>There is a <code>render_block()</code> hook where you can change what renders on the front end without changing what shows in the editor or gets saved to the database.</p>\n\n<pre><code>add_filter('render_block', function($block_content, $block) {\n // only affect the Core Paragraph block\n if('core/paragraph' === $block['blockName']) {\n // remove the class that creates the drop cap\n $block_content = str_replace('class=\"has-drop-cap\"', '', $block_content);\n }\n // always return the content, whether we changed it or not\n return $block_content;\n}, 10, 2);\n</code></pre>\n\n<p>This method changes the outer appearance rather than the actual content, so that if you ever wanted to allow drop caps, you could just remove the filter and all the ones that people had added in the editor would suddenly appear.</p>\n"
},
{
"answer_id": 386595,
"author": "jg314",
"author_id": 26202,
"author_profile": "https://wordpress.stackexchange.com/users/26202",
"pm_score": 0,
"selected": false,
"text": "<p>As <a href=\"https://wordpress.stackexchange.com/users/172662/jim-rhoades\">Jim Rhoades</a> noted in one of the comments, you can declare support for custom font sizes, but leave out the array of font size options. This removes the "Typography" section entirely so there is no way to choose a font size. The code looks like this:</p>\n<pre><code>add_theme_support( 'editor-font-sizes' );\n</code></pre>\n<p>For those looking for all the code needed to make it work, you would call this from the <code>after_setup_theme</code> hook inside the functions.php file within your theme:</p>\n<pre><code>function theme_setup() {\n add_theme_support( 'editor-font-sizes' );\n}\nadd_action( 'after_setup_theme', 'theme_setup' );\n</code></pre>\n<p>I've tested this in WordPress 5.7, but it's possible it's supported before this version.</p>\n"
},
{
"answer_id": 387087,
"author": "fairport",
"author_id": 202135,
"author_profile": "https://wordpress.stackexchange.com/users/202135",
"pm_score": 3,
"selected": false,
"text": "<p>There's good answers about disabling the font styles but not about disabling the drop cap.</p>\n<p>In WordPress 5.8, you can you the new <code>theme.json</code> feature to disable drop caps in your theme. You need to add a file with name <code>theme.json</code> in the root of your theme. It should have the following content:</p>\n<pre class=\"lang-json prettyprint-override\"><code>{\n "version": 1,\n "settings": {\n "typography": {\n "dropCap": false\n }\n }\n}\n</code></pre>\n<p>If you want to use a filter instead, you can use the following code in WordPress 5.8:</p>\n<pre><code>function disable_drop_cap_ editor_settings_5_8(array $editor_settings): array {\n $editor_settings['__experimentalFeatures']['typography']['dropCap'] = false;\n return $editor_settings;\n}\nadd_filter('block_editor_settings', 'disable_drop_cap_ editor_settings_5_8');\n</code></pre>\n<p>In WordPress 5.7, the drop cap can be disabled with the following code:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function disable_drop_cap_editor_settings_5_7(array $editor_settings): array {\n $editor_settings['__experimentalFeatures']['defaults']['typography']['dropCap'] = false;\n return $editor_settings;\n}\nadd_filter('block_editor_settings', 'disable_drop_cap_editor_settings_5_7');\n</code></pre>\n<p>In WordPress 5.6, the following code works:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function disable_drop_cap_editor_settings_5_6(array $editor_settings): array {\n $editor_settings['__experimentalFeatures']['global']['typography']['dropCap'] = false;\n return $editor_settings;\n}\nadd_filter('block_editor_settings', 'disable_drop_cap_editor_settings_5_6');\n</code></pre>\n<p>In WordPress 5.5, you will have to use JavaScript to accomplish the same thing:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function disable_drop_cap_admin_footer() {\n echo <<<HTML\n<script>\ndocument.addEventListener("DOMContentLoaded", function () {\n var removeDropCap = function(settings, name) {\n \n if (name !== "core/paragraph") {\n return settings;\n }\n var newSettings = Object.assign({}, settings);\n if (\n newSettings.supports &&\n newSettings.supports.__experimentalFeatures &&\n newSettings.supports.__experimentalFeatures.typography &&\n newSettings.supports.__experimentalFeatures.typography.dropCap\n ) {\n newSettings.supports.__experimentalFeatures.typography.dropCap = false;\n }\n return newSettings;\n };\n wp.hooks.addFilter(\n "blocks.registerBlockType",\n "sc/gb/remove-drop-cap",\n removeDropCap,\n );\n});\n</script>\nHTML;\n}\nadd_action('admin_footer', 'disable_drop_cap_admin_footer');\n</code></pre>\n<p>If you want the functionality as a plugin, you can use the <a href=\"https://wordpress.org/plugins/disable-drop-cap/\" rel=\"nofollow noreferrer\">Disable Drop Cap</a> plugin. Full disclosure, I'm the author of the said plugin.</p>\n"
},
{
"answer_id": 395438,
"author": "Kevinleary.net",
"author_id": 1495,
"author_profile": "https://wordpress.stackexchange.com/users/1495",
"pm_score": 1,
"selected": false,
"text": "<p>This was the true, final answer that solved for the exact scenario described in the original question:</p>\n<pre><code>/**\n * Disable Native Gutenberg Features\n */\nfunction gutenberg_removals()\n{\n add_theme_support('disable-custom-font-sizes');\n add_theme_support('editor-font-sizes', []);\n}\nadd_action('after_setup_theme', 'gutenberg_removals');\n</code></pre>\n<p>Passing an empty array to the <code>editor-font-sizes</code> avoid a PHP notice for an invalid argument.</p>\n"
}
] | 2019/01/24 | [
"https://wordpress.stackexchange.com/questions/326536",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159752/"
] | I migrated my website from one hosting to another by importing the DB and reinstalling the old exported DB on the new hosting. I have also re-installed the wordpress template. The result is the following:
<https://www.sea-dobbiaco.bz.it/>
The original home page is as follows, and on the old hosting it worked well.
<https://goodnews.xplodedthemes.com/news-flash/?xt-preview>
Please help me! | The closest I can find in [the documentation](https://wordpress.org/gutenberg/handbook/designers-developers/developers/themes/theme-support/) is disabling custom font size (the text input) and forcing the dropdown font size to only contain "Normal".
```
add_action('after_setup_theme', 'wpse_remove_custom_colors');
function wpse_remove_custom_colors() {
// removes the text box where users can enter custom pixel sizes
add_theme_support('disable-custom-font-sizes');
// forces the dropdown for font sizes to only contain "normal"
add_theme_support('editor-font-sizes', array(
array(
'name' => 'Normal',
'size' => 16,
'slug' => 'normal'
)
) );
}
```
Note this may not work for non-Core blocks - they may have their own way of registering font size etc. that isn't affected by theme\_support. Hoping someone else from the community knows how to disable the drop caps as well.
**Update: a way to remove Drop Caps**
This wouldn't be my preferred method, because you can still add a Drop Cap in the editor and it just doesn't render in the front end, but it's all I have been able to achieve so far:
There is a `render_block()` hook where you can change what renders on the front end without changing what shows in the editor or gets saved to the database.
```
add_filter('render_block', function($block_content, $block) {
// only affect the Core Paragraph block
if('core/paragraph' === $block['blockName']) {
// remove the class that creates the drop cap
$block_content = str_replace('class="has-drop-cap"', '', $block_content);
}
// always return the content, whether we changed it or not
return $block_content;
}, 10, 2);
```
This method changes the outer appearance rather than the actual content, so that if you ever wanted to allow drop caps, you could just remove the filter and all the ones that people had added in the editor would suddenly appear. |
326,540 | <p>For a menu which has only top-level links to custom post type archive pages, how can I add the <code>.active</code> class to the top-level item when viewing that post type's single?</p>
<p>There's lots of similar questions on WPSE (like <a href="https://stackoverflow.com/questions/26789438/how-to-add-active-class-to-wp-nav-menu-current-menu-item-simple-way">this</a> or <a href="https://wordpress.stackexchange.com/questions/310629/add-class-to-active-top-level-grandparent-menu-item">this</a>), but none seem to address my specific question and make use of <code>.current-menu-item</code> or <code>.current-menu-ancestor</code> (and associated) classes, which don't appear on my menu (as I assume because the single posts aren't part of the menu list structure).</p>
<p>The only way I can think to do this is check the current post type against the slug, but it feels a bit hacky (and doesn't allow for url rewrites, etc).</p>
| [
{
"answer_id": 332375,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 3,
"selected": false,
"text": "<p>The closest I can find in <a href=\"https://wordpress.org/gutenberg/handbook/designers-developers/developers/themes/theme-support/\" rel=\"noreferrer\">the documentation</a> is disabling custom font size (the text input) and forcing the dropdown font size to only contain \"Normal\".</p>\n\n<pre><code>add_action('after_setup_theme', 'wpse_remove_custom_colors');\nfunction wpse_remove_custom_colors() {\n // removes the text box where users can enter custom pixel sizes\n add_theme_support('disable-custom-font-sizes');\n // forces the dropdown for font sizes to only contain \"normal\"\n add_theme_support('editor-font-sizes', array(\n array(\n 'name' => 'Normal',\n 'size' => 16,\n 'slug' => 'normal'\n )\n ) );\n}\n</code></pre>\n\n<p>Note this may not work for non-Core blocks - they may have their own way of registering font size etc. that isn't affected by theme_support. Hoping someone else from the community knows how to disable the drop caps as well.</p>\n\n<p><strong>Update: a way to remove Drop Caps</strong></p>\n\n<p>This wouldn't be my preferred method, because you can still add a Drop Cap in the editor and it just doesn't render in the front end, but it's all I have been able to achieve so far:</p>\n\n<p>There is a <code>render_block()</code> hook where you can change what renders on the front end without changing what shows in the editor or gets saved to the database.</p>\n\n<pre><code>add_filter('render_block', function($block_content, $block) {\n // only affect the Core Paragraph block\n if('core/paragraph' === $block['blockName']) {\n // remove the class that creates the drop cap\n $block_content = str_replace('class=\"has-drop-cap\"', '', $block_content);\n }\n // always return the content, whether we changed it or not\n return $block_content;\n}, 10, 2);\n</code></pre>\n\n<p>This method changes the outer appearance rather than the actual content, so that if you ever wanted to allow drop caps, you could just remove the filter and all the ones that people had added in the editor would suddenly appear.</p>\n"
},
{
"answer_id": 386595,
"author": "jg314",
"author_id": 26202,
"author_profile": "https://wordpress.stackexchange.com/users/26202",
"pm_score": 0,
"selected": false,
"text": "<p>As <a href=\"https://wordpress.stackexchange.com/users/172662/jim-rhoades\">Jim Rhoades</a> noted in one of the comments, you can declare support for custom font sizes, but leave out the array of font size options. This removes the "Typography" section entirely so there is no way to choose a font size. The code looks like this:</p>\n<pre><code>add_theme_support( 'editor-font-sizes' );\n</code></pre>\n<p>For those looking for all the code needed to make it work, you would call this from the <code>after_setup_theme</code> hook inside the functions.php file within your theme:</p>\n<pre><code>function theme_setup() {\n add_theme_support( 'editor-font-sizes' );\n}\nadd_action( 'after_setup_theme', 'theme_setup' );\n</code></pre>\n<p>I've tested this in WordPress 5.7, but it's possible it's supported before this version.</p>\n"
},
{
"answer_id": 387087,
"author": "fairport",
"author_id": 202135,
"author_profile": "https://wordpress.stackexchange.com/users/202135",
"pm_score": 3,
"selected": false,
"text": "<p>There's good answers about disabling the font styles but not about disabling the drop cap.</p>\n<p>In WordPress 5.8, you can you the new <code>theme.json</code> feature to disable drop caps in your theme. You need to add a file with name <code>theme.json</code> in the root of your theme. It should have the following content:</p>\n<pre class=\"lang-json prettyprint-override\"><code>{\n "version": 1,\n "settings": {\n "typography": {\n "dropCap": false\n }\n }\n}\n</code></pre>\n<p>If you want to use a filter instead, you can use the following code in WordPress 5.8:</p>\n<pre><code>function disable_drop_cap_ editor_settings_5_8(array $editor_settings): array {\n $editor_settings['__experimentalFeatures']['typography']['dropCap'] = false;\n return $editor_settings;\n}\nadd_filter('block_editor_settings', 'disable_drop_cap_ editor_settings_5_8');\n</code></pre>\n<p>In WordPress 5.7, the drop cap can be disabled with the following code:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function disable_drop_cap_editor_settings_5_7(array $editor_settings): array {\n $editor_settings['__experimentalFeatures']['defaults']['typography']['dropCap'] = false;\n return $editor_settings;\n}\nadd_filter('block_editor_settings', 'disable_drop_cap_editor_settings_5_7');\n</code></pre>\n<p>In WordPress 5.6, the following code works:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function disable_drop_cap_editor_settings_5_6(array $editor_settings): array {\n $editor_settings['__experimentalFeatures']['global']['typography']['dropCap'] = false;\n return $editor_settings;\n}\nadd_filter('block_editor_settings', 'disable_drop_cap_editor_settings_5_6');\n</code></pre>\n<p>In WordPress 5.5, you will have to use JavaScript to accomplish the same thing:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function disable_drop_cap_admin_footer() {\n echo <<<HTML\n<script>\ndocument.addEventListener("DOMContentLoaded", function () {\n var removeDropCap = function(settings, name) {\n \n if (name !== "core/paragraph") {\n return settings;\n }\n var newSettings = Object.assign({}, settings);\n if (\n newSettings.supports &&\n newSettings.supports.__experimentalFeatures &&\n newSettings.supports.__experimentalFeatures.typography &&\n newSettings.supports.__experimentalFeatures.typography.dropCap\n ) {\n newSettings.supports.__experimentalFeatures.typography.dropCap = false;\n }\n return newSettings;\n };\n wp.hooks.addFilter(\n "blocks.registerBlockType",\n "sc/gb/remove-drop-cap",\n removeDropCap,\n );\n});\n</script>\nHTML;\n}\nadd_action('admin_footer', 'disable_drop_cap_admin_footer');\n</code></pre>\n<p>If you want the functionality as a plugin, you can use the <a href=\"https://wordpress.org/plugins/disable-drop-cap/\" rel=\"nofollow noreferrer\">Disable Drop Cap</a> plugin. Full disclosure, I'm the author of the said plugin.</p>\n"
},
{
"answer_id": 395438,
"author": "Kevinleary.net",
"author_id": 1495,
"author_profile": "https://wordpress.stackexchange.com/users/1495",
"pm_score": 1,
"selected": false,
"text": "<p>This was the true, final answer that solved for the exact scenario described in the original question:</p>\n<pre><code>/**\n * Disable Native Gutenberg Features\n */\nfunction gutenberg_removals()\n{\n add_theme_support('disable-custom-font-sizes');\n add_theme_support('editor-font-sizes', []);\n}\nadd_action('after_setup_theme', 'gutenberg_removals');\n</code></pre>\n<p>Passing an empty array to the <code>editor-font-sizes</code> avoid a PHP notice for an invalid argument.</p>\n"
}
] | 2019/01/24 | [
"https://wordpress.stackexchange.com/questions/326540",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/64117/"
] | For a menu which has only top-level links to custom post type archive pages, how can I add the `.active` class to the top-level item when viewing that post type's single?
There's lots of similar questions on WPSE (like [this](https://stackoverflow.com/questions/26789438/how-to-add-active-class-to-wp-nav-menu-current-menu-item-simple-way) or [this](https://wordpress.stackexchange.com/questions/310629/add-class-to-active-top-level-grandparent-menu-item)), but none seem to address my specific question and make use of `.current-menu-item` or `.current-menu-ancestor` (and associated) classes, which don't appear on my menu (as I assume because the single posts aren't part of the menu list structure).
The only way I can think to do this is check the current post type against the slug, but it feels a bit hacky (and doesn't allow for url rewrites, etc). | The closest I can find in [the documentation](https://wordpress.org/gutenberg/handbook/designers-developers/developers/themes/theme-support/) is disabling custom font size (the text input) and forcing the dropdown font size to only contain "Normal".
```
add_action('after_setup_theme', 'wpse_remove_custom_colors');
function wpse_remove_custom_colors() {
// removes the text box where users can enter custom pixel sizes
add_theme_support('disable-custom-font-sizes');
// forces the dropdown for font sizes to only contain "normal"
add_theme_support('editor-font-sizes', array(
array(
'name' => 'Normal',
'size' => 16,
'slug' => 'normal'
)
) );
}
```
Note this may not work for non-Core blocks - they may have their own way of registering font size etc. that isn't affected by theme\_support. Hoping someone else from the community knows how to disable the drop caps as well.
**Update: a way to remove Drop Caps**
This wouldn't be my preferred method, because you can still add a Drop Cap in the editor and it just doesn't render in the front end, but it's all I have been able to achieve so far:
There is a `render_block()` hook where you can change what renders on the front end without changing what shows in the editor or gets saved to the database.
```
add_filter('render_block', function($block_content, $block) {
// only affect the Core Paragraph block
if('core/paragraph' === $block['blockName']) {
// remove the class that creates the drop cap
$block_content = str_replace('class="has-drop-cap"', '', $block_content);
}
// always return the content, whether we changed it or not
return $block_content;
}, 10, 2);
```
This method changes the outer appearance rather than the actual content, so that if you ever wanted to allow drop caps, you could just remove the filter and all the ones that people had added in the editor would suddenly appear. |
326,575 | <p>The Codex disagrees with itself, so I'm stumped.</p>
<p>On <code>single.php</code> I am trying to use <code>next_post_link()</code> to display a link to the next post, with custom link text, within the same category as the current post.</p>
<p>The <a href="https://codex.wordpress.org/Function_Reference/next_post_link" rel="nofollow noreferrer">Codex article on <code>next_post_link()</code></a> says the parameters are $format, $link, $in_same_term, $excluded_terms, and $taxonomy. Its specific example for my scenario is</p>
<pre><code><?php next_post_link( '%link', 'Next post in category', TRUE ); ?>
</code></pre>
<p>But when I use that exact code, no link is output at all. The rest of the Post fully renders, it's just missing the next post link HTML completely.</p>
<p>If I take out just the "TRUE" it outputs a link almost as desired:</p>
<pre><code><?php next_post_link( '%link', 'Next post in category' ); ?>
</code></pre>
<p>But it links to the next Post in any category, and I need to restrict it to the current category.</p>
<p>The <a href="https://codex.wordpress.org/Next_and_Previous_Links" rel="nofollow noreferrer">Codex article on Next and Previous Links</a> contradicts the article specifically on <code>next_post_link()</code>. It says the parameters are $format, $text, and $title. That would mean that you can't restrict the link to posts within the current category. Since the <a href="https://developer.wordpress.org/reference/functions/next_post_link/" rel="nofollow noreferrer">Code Reference on <code>next_post_link()</code></a> matches the Codex on <code>next_post_link()</code> that seems likely to be the most accurate.</p>
| [
{
"answer_id": 326577,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 0,
"selected": false,
"text": "<p>Ok, this seems silly, but for some reason lowercasing the \"true\" solved the problem.</p>\n\n<p><code><?php next_post_link( '%link', 'Next post in category', true ); ?></code></p>\n"
},
{
"answer_id": 326601,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>OK, so there's a problem with Codes in this part, I guess.</p>\n\n<blockquote>\n <p>The Codex article on Next and Previous Links contradicts the article\n specifically on next_post_link()</p>\n</blockquote>\n\n<p>In that article you can clearly see, that it looked a little bit different. In the part describing <code>next_post_link</code> there is a note:</p>\n\n<blockquote>\n <p>Deprecated: previous_post() and next_post(). Use: -->\n previous_post_link() and next_post_link() instead.</p>\n</blockquote>\n\n<p>So most probably it is describing some old params...</p>\n\n<h1>On the other hand, from PHP point of view...</h1>\n\n<p>The <a href=\"http://php.net/manual/en/language.types.boolean.php\" rel=\"nofollow noreferrer\">official PHP manual says</a>:</p>\n\n<blockquote>\n <p>To specify a boolean literal, use the keywords TRUE or FALSE. Both are\n case-insensitive.</p>\n</blockquote>\n\n<p>So <code>true === TRUE</code> and <code>false === FALSE</code>.</p>\n\n<p>On the <a href=\"https://www.php-fig.org/psr/psr-2/\" rel=\"nofollow noreferrer\">PSR-2</a> standard requires true, false and null to be in lower case.</p>\n"
}
] | 2019/01/24 | [
"https://wordpress.stackexchange.com/questions/326575",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102815/"
] | The Codex disagrees with itself, so I'm stumped.
On `single.php` I am trying to use `next_post_link()` to display a link to the next post, with custom link text, within the same category as the current post.
The [Codex article on `next_post_link()`](https://codex.wordpress.org/Function_Reference/next_post_link) says the parameters are $format, $link, $in\_same\_term, $excluded\_terms, and $taxonomy. Its specific example for my scenario is
```
<?php next_post_link( '%link', 'Next post in category', TRUE ); ?>
```
But when I use that exact code, no link is output at all. The rest of the Post fully renders, it's just missing the next post link HTML completely.
If I take out just the "TRUE" it outputs a link almost as desired:
```
<?php next_post_link( '%link', 'Next post in category' ); ?>
```
But it links to the next Post in any category, and I need to restrict it to the current category.
The [Codex article on Next and Previous Links](https://codex.wordpress.org/Next_and_Previous_Links) contradicts the article specifically on `next_post_link()`. It says the parameters are $format, $text, and $title. That would mean that you can't restrict the link to posts within the current category. Since the [Code Reference on `next_post_link()`](https://developer.wordpress.org/reference/functions/next_post_link/) matches the Codex on `next_post_link()` that seems likely to be the most accurate. | OK, so there's a problem with Codes in this part, I guess.
>
> The Codex article on Next and Previous Links contradicts the article
> specifically on next\_post\_link()
>
>
>
In that article you can clearly see, that it looked a little bit different. In the part describing `next_post_link` there is a note:
>
> Deprecated: previous\_post() and next\_post(). Use: -->
> previous\_post\_link() and next\_post\_link() instead.
>
>
>
So most probably it is describing some old params...
On the other hand, from PHP point of view...
============================================
The [official PHP manual says](http://php.net/manual/en/language.types.boolean.php):
>
> To specify a boolean literal, use the keywords TRUE or FALSE. Both are
> case-insensitive.
>
>
>
So `true === TRUE` and `false === FALSE`.
On the [PSR-2](https://www.php-fig.org/psr/psr-2/) standard requires true, false and null to be in lower case. |
326,580 | <p>I need a WordPress menu item to link to a custom url like the following:</p>
<pre><code>http://www.example.com/my-page#my-anchor
</code></pre>
<p>Yet, WordPress adds a slash before the hash sign and reformats the custom link to</p>
<pre><code>http://www.example.com/my-page/#my-anchor
</code></pre>
<p>thus invalidating the jQuery call I need. </p>
| [
{
"answer_id": 326597,
"author": "admcfajn",
"author_id": 123674,
"author_profile": "https://wordpress.stackexchange.com/users/123674",
"pm_score": 1,
"selected": false,
"text": "<p>You can likely change that by removing the slash from the end of the permalink structure on <code>wp-admin/options-permalink.php</code> & you should be good to go.</p>\n\n<p><a href=\"https://i.stack.imgur.com/9e9cW.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9e9cW.png\" alt=\"enter image description here\"></a></p>\n\n<p>But as <a href=\"https://wordpress.stackexchange.com/users/34172/krzysiek-dr%c3%b3%c5%bcd%c5%bc\">Krzysiek Dróżdż</a> has said: It shouldn't make a difference in the execution of javaScript & trailing slashes are a best-practaice.</p>\n"
},
{
"answer_id": 326600,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 0,
"selected": false,
"text": "<p>It's a good practice to end URLs with slashes. It also shouldn't be any problem at all.</p>\n\n<p>It makes no difference for JS. With or without that slash, the <code>window.location.hash</code> will have the same value.</p>\n\n<p>So if only the JS library you use is written correctly, then the slash won't change anything. And if it does - you should report it as a bug to the author of that library.</p>\n"
}
] | 2019/01/24 | [
"https://wordpress.stackexchange.com/questions/326580",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159782/"
] | I need a WordPress menu item to link to a custom url like the following:
```
http://www.example.com/my-page#my-anchor
```
Yet, WordPress adds a slash before the hash sign and reformats the custom link to
```
http://www.example.com/my-page/#my-anchor
```
thus invalidating the jQuery call I need. | You can likely change that by removing the slash from the end of the permalink structure on `wp-admin/options-permalink.php` & you should be good to go.
[](https://i.stack.imgur.com/9e9cW.png)
But as [Krzysiek Dróżdż](https://wordpress.stackexchange.com/users/34172/krzysiek-dr%c3%b3%c5%bcd%c5%bc) has said: It shouldn't make a difference in the execution of javaScript & trailing slashes are a best-practaice. |
326,613 | <p>I'm building a theme using Gutenberg for the first time. In the past, I've built custom post types like this:</p>
<pre><code>// Register Custom Post Type
function custom_post_type() {
$labels = array(
'name' => _x( 'Post Types', 'Post Type General Name', 'text_domain' ),
'singular_name' => _x( 'Post Type', 'Post Type Singular Name', 'text_domain' ),
'menu_name' => __( 'Post Types', 'text_domain' ),
'name_admin_bar' => __( 'Post Type', 'text_domain' ),
'archives' => __( 'Item Archives', 'text_domain' ),
'attributes' => __( 'Item Attributes', 'text_domain' ),
'parent_item_colon' => __( 'Parent Item:', 'text_domain' ),
'all_items' => __( 'All Items', 'text_domain' ),
'add_new_item' => __( 'Add New Item', 'text_domain' ),
'add_new' => __( 'Add New', 'text_domain' ),
'new_item' => __( 'New Item', 'text_domain' ),
'edit_item' => __( 'Edit Item', 'text_domain' ),
'update_item' => __( 'Update Item', 'text_domain' ),
'view_item' => __( 'View Item', 'text_domain' ),
'view_items' => __( 'View Items', 'text_domain' ),
'search_items' => __( 'Search Item', 'text_domain' ),
'not_found' => __( 'Not found', 'text_domain' ),
'not_found_in_trash' => __( 'Not found in Trash', 'text_domain' ),
'featured_image' => __( 'Featured Image', 'text_domain' ),
'set_featured_image' => __( 'Set featured image', 'text_domain' ),
'remove_featured_image' => __( 'Remove featured image', 'text_domain' ),
'use_featured_image' => __( 'Use as featured image', 'text_domain' ),
'insert_into_item' => __( 'Insert into item', 'text_domain' ),
'uploaded_to_this_item' => __( 'Uploaded to this item', 'text_domain' ),
'items_list' => __( 'Items list', 'text_domain' ),
'items_list_navigation' => __( 'Items list navigation', 'text_domain' ),
'filter_items_list' => __( 'Filter items list', 'text_domain' ),
);
$args = array(
'label' => __( 'Post Type', 'text_domain' ),
'description' => __( 'Post Type Description', 'text_domain' ),
'labels' => $labels,
'supports' => false,
'taxonomies' => array( 'category', 'post_tag' ),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'page',
);
register_post_type( 'post_type', $args );
}
add_action( 'init', 'custom_post_type', 0 );
</code></pre>
<p>When this is added to functions.php, the classic editor appears when creating a post.</p>
<p>I assume I need to enable the post type in REST?</p>
| [
{
"answer_id": 326614,
"author": "Sam",
"author_id": 37548,
"author_profile": "https://wordpress.stackexchange.com/users/37548",
"pm_score": 4,
"selected": true,
"text": "<p>Yep, you just need to add <code>'show_in_rest' => true</code></p>\n\n<p>Here's the full snippet:</p>\n\n<pre><code>// Register Custom Post Type\nfunction custom_post_type() {\n\n $labels = array(\n 'name' => _x( 'Post Types', 'Post Type General Name', 'text_domain' ),\n 'singular_name' => _x( 'Post Type', 'Post Type Singular Name', 'text_domain' ),\n 'menu_name' => __( 'Post Types', 'text_domain' ),\n 'name_admin_bar' => __( 'Post Type', 'text_domain' ),\n 'archives' => __( 'Item Archives', 'text_domain' ),\n 'attributes' => __( 'Item Attributes', 'text_domain' ),\n 'parent_item_colon' => __( 'Parent Item:', 'text_domain' ),\n 'all_items' => __( 'All Items', 'text_domain' ),\n 'add_new_item' => __( 'Add New Item', 'text_domain' ),\n 'add_new' => __( 'Add New', 'text_domain' ),\n 'new_item' => __( 'New Item', 'text_domain' ),\n 'edit_item' => __( 'Edit Item', 'text_domain' ),\n 'update_item' => __( 'Update Item', 'text_domain' ),\n 'view_item' => __( 'View Item', 'text_domain' ),\n 'view_items' => __( 'View Items', 'text_domain' ),\n 'search_items' => __( 'Search Item', 'text_domain' ),\n 'not_found' => __( 'Not found', 'text_domain' ),\n 'not_found_in_trash' => __( 'Not found in Trash', 'text_domain' ),\n 'featured_image' => __( 'Featured Image', 'text_domain' ),\n 'set_featured_image' => __( 'Set featured image', 'text_domain' ),\n 'remove_featured_image' => __( 'Remove featured image', 'text_domain' ),\n 'use_featured_image' => __( 'Use as featured image', 'text_domain' ),\n 'insert_into_item' => __( 'Insert into item', 'text_domain' ),\n 'uploaded_to_this_item' => __( 'Uploaded to this item', 'text_domain' ),\n 'items_list' => __( 'Items list', 'text_domain' ),\n 'items_list_navigation' => __( 'Items list navigation', 'text_domain' ),\n 'filter_items_list' => __( 'Filter items list', 'text_domain' ),\n );\n $args = array(\n 'label' => __( 'Post Type', 'text_domain' ),\n 'description' => __( 'Post Type Description', 'text_domain' ),\n 'labels' => $labels,\n 'supports' => false,\n 'taxonomies' => array( 'category', 'post_tag' ),\n 'hierarchical' => false,\n 'public' => true,\n 'show_ui' => true,\n 'show_in_menu' => true,\n 'menu_position' => 5,\n 'show_in_admin_bar' => true,\n 'show_in_nav_menus' => true,\n 'can_export' => true,\n 'has_archive' => true,\n 'exclude_from_search' => false,\n 'publicly_queryable' => true,\n 'capability_type' => 'page',\n 'show_in_rest' => true,\n );\n register_post_type( 'post_type', $args );\n\n}\nadd_action( 'init', 'custom_post_type', 0 );\n</code></pre>\n"
},
{
"answer_id": 333997,
"author": "Owais Alam",
"author_id": 91939,
"author_profile": "https://wordpress.stackexchange.com/users/91939",
"pm_score": 0,
"selected": false,
"text": "<p>With the current version of WordPress ( 5.1 RC), Gutenberg is only visible for the default pages and post types. Since WordPress custom post types are almost everywhere, the unavailability of Gutenberg editor is something that the community has been talking about since the release of WordPress 5.0.\nFirst you have to Register Gutenberg WordPress Custom Post Type</p>\n\n<pre><code>/*Register WordPress Gutenberg CPT */\nfunction cw_post_type() {\n\n register_post_type( 'portfolio',\n // WordPress CPT Options Start\n array(\n 'labels' => array(\n 'name' => __( 'Portfolio' ),\n 'singular_name' => __( 'Portfolio' )\n ),\n 'has_archive' => true,\n 'public' => true,\n 'rewrite' => array('slug' => 'portfolio'),\n\n )\n );\n}\n\nadd_action( 'init', 'cw_post_type' );\n</code></pre>\n\n<p>Now Add Gutenberg Support to WordPress Custom Post Types</p>\n\n<pre><code>'show_in_rest' => true,\n 'supports' => array('editor')\n</code></pre>\n\n<p>Here is the complete details about <a href=\"https://www.cloudways.com/blog/gutenberg-wordpress-custom-post-type/\" rel=\"nofollow noreferrer\">Use Gutenberg with WordPress Custom Post Types</a></p>\n"
}
] | 2019/01/24 | [
"https://wordpress.stackexchange.com/questions/326613",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37548/"
] | I'm building a theme using Gutenberg for the first time. In the past, I've built custom post types like this:
```
// Register Custom Post Type
function custom_post_type() {
$labels = array(
'name' => _x( 'Post Types', 'Post Type General Name', 'text_domain' ),
'singular_name' => _x( 'Post Type', 'Post Type Singular Name', 'text_domain' ),
'menu_name' => __( 'Post Types', 'text_domain' ),
'name_admin_bar' => __( 'Post Type', 'text_domain' ),
'archives' => __( 'Item Archives', 'text_domain' ),
'attributes' => __( 'Item Attributes', 'text_domain' ),
'parent_item_colon' => __( 'Parent Item:', 'text_domain' ),
'all_items' => __( 'All Items', 'text_domain' ),
'add_new_item' => __( 'Add New Item', 'text_domain' ),
'add_new' => __( 'Add New', 'text_domain' ),
'new_item' => __( 'New Item', 'text_domain' ),
'edit_item' => __( 'Edit Item', 'text_domain' ),
'update_item' => __( 'Update Item', 'text_domain' ),
'view_item' => __( 'View Item', 'text_domain' ),
'view_items' => __( 'View Items', 'text_domain' ),
'search_items' => __( 'Search Item', 'text_domain' ),
'not_found' => __( 'Not found', 'text_domain' ),
'not_found_in_trash' => __( 'Not found in Trash', 'text_domain' ),
'featured_image' => __( 'Featured Image', 'text_domain' ),
'set_featured_image' => __( 'Set featured image', 'text_domain' ),
'remove_featured_image' => __( 'Remove featured image', 'text_domain' ),
'use_featured_image' => __( 'Use as featured image', 'text_domain' ),
'insert_into_item' => __( 'Insert into item', 'text_domain' ),
'uploaded_to_this_item' => __( 'Uploaded to this item', 'text_domain' ),
'items_list' => __( 'Items list', 'text_domain' ),
'items_list_navigation' => __( 'Items list navigation', 'text_domain' ),
'filter_items_list' => __( 'Filter items list', 'text_domain' ),
);
$args = array(
'label' => __( 'Post Type', 'text_domain' ),
'description' => __( 'Post Type Description', 'text_domain' ),
'labels' => $labels,
'supports' => false,
'taxonomies' => array( 'category', 'post_tag' ),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'page',
);
register_post_type( 'post_type', $args );
}
add_action( 'init', 'custom_post_type', 0 );
```
When this is added to functions.php, the classic editor appears when creating a post.
I assume I need to enable the post type in REST? | Yep, you just need to add `'show_in_rest' => true`
Here's the full snippet:
```
// Register Custom Post Type
function custom_post_type() {
$labels = array(
'name' => _x( 'Post Types', 'Post Type General Name', 'text_domain' ),
'singular_name' => _x( 'Post Type', 'Post Type Singular Name', 'text_domain' ),
'menu_name' => __( 'Post Types', 'text_domain' ),
'name_admin_bar' => __( 'Post Type', 'text_domain' ),
'archives' => __( 'Item Archives', 'text_domain' ),
'attributes' => __( 'Item Attributes', 'text_domain' ),
'parent_item_colon' => __( 'Parent Item:', 'text_domain' ),
'all_items' => __( 'All Items', 'text_domain' ),
'add_new_item' => __( 'Add New Item', 'text_domain' ),
'add_new' => __( 'Add New', 'text_domain' ),
'new_item' => __( 'New Item', 'text_domain' ),
'edit_item' => __( 'Edit Item', 'text_domain' ),
'update_item' => __( 'Update Item', 'text_domain' ),
'view_item' => __( 'View Item', 'text_domain' ),
'view_items' => __( 'View Items', 'text_domain' ),
'search_items' => __( 'Search Item', 'text_domain' ),
'not_found' => __( 'Not found', 'text_domain' ),
'not_found_in_trash' => __( 'Not found in Trash', 'text_domain' ),
'featured_image' => __( 'Featured Image', 'text_domain' ),
'set_featured_image' => __( 'Set featured image', 'text_domain' ),
'remove_featured_image' => __( 'Remove featured image', 'text_domain' ),
'use_featured_image' => __( 'Use as featured image', 'text_domain' ),
'insert_into_item' => __( 'Insert into item', 'text_domain' ),
'uploaded_to_this_item' => __( 'Uploaded to this item', 'text_domain' ),
'items_list' => __( 'Items list', 'text_domain' ),
'items_list_navigation' => __( 'Items list navigation', 'text_domain' ),
'filter_items_list' => __( 'Filter items list', 'text_domain' ),
);
$args = array(
'label' => __( 'Post Type', 'text_domain' ),
'description' => __( 'Post Type Description', 'text_domain' ),
'labels' => $labels,
'supports' => false,
'taxonomies' => array( 'category', 'post_tag' ),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'page',
'show_in_rest' => true,
);
register_post_type( 'post_type', $args );
}
add_action( 'init', 'custom_post_type', 0 );
``` |
326,617 | <p>I want to remove bulk action for non admin user (shop manager to be specific),
so I got this code that let me to remove the bulk action for all users.</p>
<pre><code>add_filter( 'bulk_actions-edit-shop_order', '__return_empty_array', 100 );
</code></pre>
<p>How can I make it working only for the shop manager role users?</p>
<p>I also tried <a href="https://wordpress.stackexchange.com/questions/53371/remove-bulk-actions-based-on-user-role-or-capabilities">this</a>, but it didn't work.</p>
<p>Thanks.</p>
| [
{
"answer_id": 326614,
"author": "Sam",
"author_id": 37548,
"author_profile": "https://wordpress.stackexchange.com/users/37548",
"pm_score": 4,
"selected": true,
"text": "<p>Yep, you just need to add <code>'show_in_rest' => true</code></p>\n\n<p>Here's the full snippet:</p>\n\n<pre><code>// Register Custom Post Type\nfunction custom_post_type() {\n\n $labels = array(\n 'name' => _x( 'Post Types', 'Post Type General Name', 'text_domain' ),\n 'singular_name' => _x( 'Post Type', 'Post Type Singular Name', 'text_domain' ),\n 'menu_name' => __( 'Post Types', 'text_domain' ),\n 'name_admin_bar' => __( 'Post Type', 'text_domain' ),\n 'archives' => __( 'Item Archives', 'text_domain' ),\n 'attributes' => __( 'Item Attributes', 'text_domain' ),\n 'parent_item_colon' => __( 'Parent Item:', 'text_domain' ),\n 'all_items' => __( 'All Items', 'text_domain' ),\n 'add_new_item' => __( 'Add New Item', 'text_domain' ),\n 'add_new' => __( 'Add New', 'text_domain' ),\n 'new_item' => __( 'New Item', 'text_domain' ),\n 'edit_item' => __( 'Edit Item', 'text_domain' ),\n 'update_item' => __( 'Update Item', 'text_domain' ),\n 'view_item' => __( 'View Item', 'text_domain' ),\n 'view_items' => __( 'View Items', 'text_domain' ),\n 'search_items' => __( 'Search Item', 'text_domain' ),\n 'not_found' => __( 'Not found', 'text_domain' ),\n 'not_found_in_trash' => __( 'Not found in Trash', 'text_domain' ),\n 'featured_image' => __( 'Featured Image', 'text_domain' ),\n 'set_featured_image' => __( 'Set featured image', 'text_domain' ),\n 'remove_featured_image' => __( 'Remove featured image', 'text_domain' ),\n 'use_featured_image' => __( 'Use as featured image', 'text_domain' ),\n 'insert_into_item' => __( 'Insert into item', 'text_domain' ),\n 'uploaded_to_this_item' => __( 'Uploaded to this item', 'text_domain' ),\n 'items_list' => __( 'Items list', 'text_domain' ),\n 'items_list_navigation' => __( 'Items list navigation', 'text_domain' ),\n 'filter_items_list' => __( 'Filter items list', 'text_domain' ),\n );\n $args = array(\n 'label' => __( 'Post Type', 'text_domain' ),\n 'description' => __( 'Post Type Description', 'text_domain' ),\n 'labels' => $labels,\n 'supports' => false,\n 'taxonomies' => array( 'category', 'post_tag' ),\n 'hierarchical' => false,\n 'public' => true,\n 'show_ui' => true,\n 'show_in_menu' => true,\n 'menu_position' => 5,\n 'show_in_admin_bar' => true,\n 'show_in_nav_menus' => true,\n 'can_export' => true,\n 'has_archive' => true,\n 'exclude_from_search' => false,\n 'publicly_queryable' => true,\n 'capability_type' => 'page',\n 'show_in_rest' => true,\n );\n register_post_type( 'post_type', $args );\n\n}\nadd_action( 'init', 'custom_post_type', 0 );\n</code></pre>\n"
},
{
"answer_id": 333997,
"author": "Owais Alam",
"author_id": 91939,
"author_profile": "https://wordpress.stackexchange.com/users/91939",
"pm_score": 0,
"selected": false,
"text": "<p>With the current version of WordPress ( 5.1 RC), Gutenberg is only visible for the default pages and post types. Since WordPress custom post types are almost everywhere, the unavailability of Gutenberg editor is something that the community has been talking about since the release of WordPress 5.0.\nFirst you have to Register Gutenberg WordPress Custom Post Type</p>\n\n<pre><code>/*Register WordPress Gutenberg CPT */\nfunction cw_post_type() {\n\n register_post_type( 'portfolio',\n // WordPress CPT Options Start\n array(\n 'labels' => array(\n 'name' => __( 'Portfolio' ),\n 'singular_name' => __( 'Portfolio' )\n ),\n 'has_archive' => true,\n 'public' => true,\n 'rewrite' => array('slug' => 'portfolio'),\n\n )\n );\n}\n\nadd_action( 'init', 'cw_post_type' );\n</code></pre>\n\n<p>Now Add Gutenberg Support to WordPress Custom Post Types</p>\n\n<pre><code>'show_in_rest' => true,\n 'supports' => array('editor')\n</code></pre>\n\n<p>Here is the complete details about <a href=\"https://www.cloudways.com/blog/gutenberg-wordpress-custom-post-type/\" rel=\"nofollow noreferrer\">Use Gutenberg with WordPress Custom Post Types</a></p>\n"
}
] | 2019/01/24 | [
"https://wordpress.stackexchange.com/questions/326617",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159814/"
] | I want to remove bulk action for non admin user (shop manager to be specific),
so I got this code that let me to remove the bulk action for all users.
```
add_filter( 'bulk_actions-edit-shop_order', '__return_empty_array', 100 );
```
How can I make it working only for the shop manager role users?
I also tried [this](https://wordpress.stackexchange.com/questions/53371/remove-bulk-actions-based-on-user-role-or-capabilities), but it didn't work.
Thanks. | Yep, you just need to add `'show_in_rest' => true`
Here's the full snippet:
```
// Register Custom Post Type
function custom_post_type() {
$labels = array(
'name' => _x( 'Post Types', 'Post Type General Name', 'text_domain' ),
'singular_name' => _x( 'Post Type', 'Post Type Singular Name', 'text_domain' ),
'menu_name' => __( 'Post Types', 'text_domain' ),
'name_admin_bar' => __( 'Post Type', 'text_domain' ),
'archives' => __( 'Item Archives', 'text_domain' ),
'attributes' => __( 'Item Attributes', 'text_domain' ),
'parent_item_colon' => __( 'Parent Item:', 'text_domain' ),
'all_items' => __( 'All Items', 'text_domain' ),
'add_new_item' => __( 'Add New Item', 'text_domain' ),
'add_new' => __( 'Add New', 'text_domain' ),
'new_item' => __( 'New Item', 'text_domain' ),
'edit_item' => __( 'Edit Item', 'text_domain' ),
'update_item' => __( 'Update Item', 'text_domain' ),
'view_item' => __( 'View Item', 'text_domain' ),
'view_items' => __( 'View Items', 'text_domain' ),
'search_items' => __( 'Search Item', 'text_domain' ),
'not_found' => __( 'Not found', 'text_domain' ),
'not_found_in_trash' => __( 'Not found in Trash', 'text_domain' ),
'featured_image' => __( 'Featured Image', 'text_domain' ),
'set_featured_image' => __( 'Set featured image', 'text_domain' ),
'remove_featured_image' => __( 'Remove featured image', 'text_domain' ),
'use_featured_image' => __( 'Use as featured image', 'text_domain' ),
'insert_into_item' => __( 'Insert into item', 'text_domain' ),
'uploaded_to_this_item' => __( 'Uploaded to this item', 'text_domain' ),
'items_list' => __( 'Items list', 'text_domain' ),
'items_list_navigation' => __( 'Items list navigation', 'text_domain' ),
'filter_items_list' => __( 'Filter items list', 'text_domain' ),
);
$args = array(
'label' => __( 'Post Type', 'text_domain' ),
'description' => __( 'Post Type Description', 'text_domain' ),
'labels' => $labels,
'supports' => false,
'taxonomies' => array( 'category', 'post_tag' ),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'page',
'show_in_rest' => true,
);
register_post_type( 'post_type', $args );
}
add_action( 'init', 'custom_post_type', 0 );
``` |
326,658 | <p>I have a custom post type "projets" that is using the category taxonomy (so it is sharing categories with regular posts).</p>
<p>When I call WP_Query like this:</p>
<pre><code>$args = array(
'post_type' => 'projets',
'posts_per_page' => 6,
'paged' => (get_query_var('paged')) ? get_query_var('paged') : 1,
);
$projects = new WP_Query($args);
</code></pre>
<p>It works perfectly fine.
But when I add a category to the arguments like this:</p>
<pre><code>$args = array(
'post_type' => 'projets',
'posts_per_page' => 6,
'paged' => (get_query_var('paged')) ? get_query_var('paged') : 1,
'cat' => 39
);
$projects = new WP_Query($args);
</code></pre>
<p>It does not returns only projets custom post_type but also regular posts that share the category 39...
Is there a way to make sure <strong>only</strong> the custom post type will be returned?</p>
<p>For info I use the <a href="https://fr.wordpress.org/plugins/custom-post-type-ui/" rel="nofollow noreferrer">Custom Post Type UI</a> extension to declare the post type, I did not declare them myself.</p>
<hr>
<p><strong>Edit:</strong> </p>
<p>To clarify after the first comments, I did not register a custom taxonomy. </p>
<p>I only registered a custom post type called "projets" using the CPT UI plugin, with which I linked the Categories (WP Core) built-in taxonomy.</p>
<p>You can have a look at <a href="https://ibb.co/37vDvPn" rel="nofollow noreferrer">this</a> and <a href="https://ibb.co/zrKQcG7" rel="nofollow noreferrer">this</a> screenshots to see how I configured everything.</p>
<p>The post type name I am using with WP_Query is correct, since it does return the "projets" posts. The problem is that when I add a category to the $args, then regular posts (posts with the "post" type) are being returned.</p>
<hr>
<p><strong>Edit 2 and solution:</strong> </p>
<p>As pointed out by <a href="https://wordpress.stackexchange.com/users/34172/krzysiek-dr%C3%B3%C5%BCd%C5%BC">@krzysiek-dróżdż</a> and <a href="https://wordpress.stackexchange.com/users/57436/chinmoy-kumar-paul">@chinmoy-kumar-paul</a> , in my theme file I am using the pre_get_posts filter :</p>
<pre><code>//Add projets custom posts within the loop
function namespace_add_custom_types( $query ) {
if( (is_category() || is_tag()) && $query->is_archive() && empty( $query->query_vars['suppress_filters'] ) ) {
$query->set( 'post_type', array(
'post', 'projets'
));
}
return $query;
}
add_filter( 'pre_get_posts', 'namespace_add_custom_types' );
</code></pre>
<p>If I comment it out, the problem is gone... So the problem is found out!</p>
<p>But isn't it a WordPress bug? I mean I still do want this custom post type to be included in the loop, so my problem is not completely solved.</p>
<p><strong>In the end, one solution is to add <code>$args['suppress_filters'] = true;</code> before doing the query, allowing to avoid this filter and fix the problem.</strong></p>
| [
{
"answer_id": 326674,
"author": "Jaydip Nimavat",
"author_id": 123295,
"author_profile": "https://wordpress.stackexchange.com/users/123295",
"pm_score": 0,
"selected": false,
"text": "<p>You can not pass CAT parameter for the custom taxonomy. you have to use tax_query. </p>\n\n<p>Reference WordPress codex URL: <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters</a></p>\n"
},
{
"answer_id": 327041,
"author": "Chinmoy Kumar Paul",
"author_id": 57436,
"author_profile": "https://wordpress.stackexchange.com/users/57436",
"pm_score": 2,
"selected": false,
"text": "<p>You will use the tax_query option for custom post type. So your query will be look like this</p>\n\n<pre><code>$args = array(\n 'post_type' => 'projets',\n 'posts_per_page' => 6,\n 'paged' => (get_query_var('paged')) ? get_query_var('paged') : 1,\n 'tax_query' => array(\n array(\n 'taxonomy' => 'category',\n 'field' => 'term_id',\n 'terms' => array( 39 )\n )\n ),\n);\n$projects = new WP_Query($args);\n</code></pre>\n"
},
{
"answer_id": 327070,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 2,
"selected": true,
"text": "<p>Assuming that you have a CPT with slug <code>projets</code> and you've registered built-in categories for that CPT, it all looks correct.</p>\n\n<p>So there are two possibilities, that I would check:</p>\n\n<ol>\n<li>Typos - maybe you misstyped your CPT name somewhere in your code.</li>\n<li><code>pre_get_posts</code> filter is modifying your query and changing its behavior (it's pretty common if you write <code>pre_get_posts</code> and don't pay enough attention to conditions inside of it).</li>\n</ol>\n"
}
] | 2019/01/25 | [
"https://wordpress.stackexchange.com/questions/326658",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/16762/"
] | I have a custom post type "projets" that is using the category taxonomy (so it is sharing categories with regular posts).
When I call WP\_Query like this:
```
$args = array(
'post_type' => 'projets',
'posts_per_page' => 6,
'paged' => (get_query_var('paged')) ? get_query_var('paged') : 1,
);
$projects = new WP_Query($args);
```
It works perfectly fine.
But when I add a category to the arguments like this:
```
$args = array(
'post_type' => 'projets',
'posts_per_page' => 6,
'paged' => (get_query_var('paged')) ? get_query_var('paged') : 1,
'cat' => 39
);
$projects = new WP_Query($args);
```
It does not returns only projets custom post\_type but also regular posts that share the category 39...
Is there a way to make sure **only** the custom post type will be returned?
For info I use the [Custom Post Type UI](https://fr.wordpress.org/plugins/custom-post-type-ui/) extension to declare the post type, I did not declare them myself.
---
**Edit:**
To clarify after the first comments, I did not register a custom taxonomy.
I only registered a custom post type called "projets" using the CPT UI plugin, with which I linked the Categories (WP Core) built-in taxonomy.
You can have a look at [this](https://ibb.co/37vDvPn) and [this](https://ibb.co/zrKQcG7) screenshots to see how I configured everything.
The post type name I am using with WP\_Query is correct, since it does return the "projets" posts. The problem is that when I add a category to the $args, then regular posts (posts with the "post" type) are being returned.
---
**Edit 2 and solution:**
As pointed out by [@krzysiek-dróżdż](https://wordpress.stackexchange.com/users/34172/krzysiek-dr%C3%B3%C5%BCd%C5%BC) and [@chinmoy-kumar-paul](https://wordpress.stackexchange.com/users/57436/chinmoy-kumar-paul) , in my theme file I am using the pre\_get\_posts filter :
```
//Add projets custom posts within the loop
function namespace_add_custom_types( $query ) {
if( (is_category() || is_tag()) && $query->is_archive() && empty( $query->query_vars['suppress_filters'] ) ) {
$query->set( 'post_type', array(
'post', 'projets'
));
}
return $query;
}
add_filter( 'pre_get_posts', 'namespace_add_custom_types' );
```
If I comment it out, the problem is gone... So the problem is found out!
But isn't it a WordPress bug? I mean I still do want this custom post type to be included in the loop, so my problem is not completely solved.
**In the end, one solution is to add `$args['suppress_filters'] = true;` before doing the query, allowing to avoid this filter and fix the problem.** | Assuming that you have a CPT with slug `projets` and you've registered built-in categories for that CPT, it all looks correct.
So there are two possibilities, that I would check:
1. Typos - maybe you misstyped your CPT name somewhere in your code.
2. `pre_get_posts` filter is modifying your query and changing its behavior (it's pretty common if you write `pre_get_posts` and don't pay enough attention to conditions inside of it). |
326,688 | <p>When I add a filter to custom get_all_posts API callback, API works, but the admin page for each page is blank. Why?</p>
<pre><code>function get_all_posts( $data, $post, $context ) {
return [
'id' => $data->data['id'],
'date' => $data->data['date'],
'date_gmt' => $data->data['date_gmt'],
'modified' => $data->data['modified'],
'title' => $data->data['title']['rendered'],
'content' => $data->data['content']['rendered'],
'main_text' => $data->data['main_text'],
'featured_media_url' => $data->data['jetpack_featured_media_url'],
'category' => get_the_category_by_ID( $data->data['categories'][0] ),
'link' => $data->data['link']
];
}
add_filter( 'rest_prepare_post', 'get_all_posts', 10, 3 );
</code></pre>
<p><strong>EDIT:</strong>
Got this error on the webpage <code>Unhandled Promise Rejection: TypeError: undefined is not an object (evaluating 'e.length')</code></p>
<p><a href="https://i.stack.imgur.com/arHmy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/arHmy.png" alt="enter image description here"></a></p>
<p>FYI: I added a meta box on the post admin page, the meta box works perfectly without the code above.</p>
<p>My entire code:</p>
<pre><code>function main_text_meta_box() {
add_meta_box(
'main-text',
__( 'Main text', 'sitepoint' ),
'main_text_meta_box_callback',
'post'
);
}
function main_text_meta_box_callback( $post ) {
// Add a nonce field so we can check for it later.
wp_nonce_field( 'main_text_nonce', 'main_text_nonce' );
$value = get_post_meta( $post->ID, '_main_text', true );
echo '<textarea style="width:100%; height:300px;" id="main_text" name="main_text">' . esc_attr( $value ) . '</textarea>';
}
add_action( 'add_meta_boxes', 'main_text_meta_box' );
function save_main_text_meta_box_data( $post_id ) {
// Check if our nonce is set.
if ( ! isset( $_POST['main_text_nonce'] ) ) {
return;
}
// Verify that the nonce is valid.
if ( ! wp_verify_nonce( $_POST['main_text_nonce'], 'main_text_nonce' ) ) {
return;
}
// If this is an autosave, our form has not been submitted, so we don't want to do anything.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
// Check the user's permissions.
if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] ) {
if ( ! current_user_can( 'edit_page', $post_id ) ) {
return;
}
}
else {
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
}
/* OK, it's safe for us to save the data now. */
// Make sure that it is set.
if ( ! isset( $_POST['main_text'] ) ) {
return;
}
// Sanitize user input.
$my_data = sanitize_text_field( $_POST['main_text'] );
// Update the meta field in the database.
update_post_meta( $post_id, '_main_text', $my_data );
}
add_action( 'save_post', 'save_main_text_meta_box_data' );
function add_custom_fields() {
register_rest_field(
'post',
'main_text', //New Field Name in JSON RESPONSEs
array(
'get_callback' => 'get_main_text', // custom function name
'update_callback' => null,
'schema' => null,
)
);
}
add_action( 'rest_api_init', 'add_custom_fields' );
function get_main_text ( $post, $field_name, $request ){
return get_post_meta($post['id'], '_main_text', true);
}
</code></pre>
| [
{
"answer_id": 326674,
"author": "Jaydip Nimavat",
"author_id": 123295,
"author_profile": "https://wordpress.stackexchange.com/users/123295",
"pm_score": 0,
"selected": false,
"text": "<p>You can not pass CAT parameter for the custom taxonomy. you have to use tax_query. </p>\n\n<p>Reference WordPress codex URL: <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters</a></p>\n"
},
{
"answer_id": 327041,
"author": "Chinmoy Kumar Paul",
"author_id": 57436,
"author_profile": "https://wordpress.stackexchange.com/users/57436",
"pm_score": 2,
"selected": false,
"text": "<p>You will use the tax_query option for custom post type. So your query will be look like this</p>\n\n<pre><code>$args = array(\n 'post_type' => 'projets',\n 'posts_per_page' => 6,\n 'paged' => (get_query_var('paged')) ? get_query_var('paged') : 1,\n 'tax_query' => array(\n array(\n 'taxonomy' => 'category',\n 'field' => 'term_id',\n 'terms' => array( 39 )\n )\n ),\n);\n$projects = new WP_Query($args);\n</code></pre>\n"
},
{
"answer_id": 327070,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 2,
"selected": true,
"text": "<p>Assuming that you have a CPT with slug <code>projets</code> and you've registered built-in categories for that CPT, it all looks correct.</p>\n\n<p>So there are two possibilities, that I would check:</p>\n\n<ol>\n<li>Typos - maybe you misstyped your CPT name somewhere in your code.</li>\n<li><code>pre_get_posts</code> filter is modifying your query and changing its behavior (it's pretty common if you write <code>pre_get_posts</code> and don't pay enough attention to conditions inside of it).</li>\n</ol>\n"
}
] | 2019/01/25 | [
"https://wordpress.stackexchange.com/questions/326688",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159869/"
] | When I add a filter to custom get\_all\_posts API callback, API works, but the admin page for each page is blank. Why?
```
function get_all_posts( $data, $post, $context ) {
return [
'id' => $data->data['id'],
'date' => $data->data['date'],
'date_gmt' => $data->data['date_gmt'],
'modified' => $data->data['modified'],
'title' => $data->data['title']['rendered'],
'content' => $data->data['content']['rendered'],
'main_text' => $data->data['main_text'],
'featured_media_url' => $data->data['jetpack_featured_media_url'],
'category' => get_the_category_by_ID( $data->data['categories'][0] ),
'link' => $data->data['link']
];
}
add_filter( 'rest_prepare_post', 'get_all_posts', 10, 3 );
```
**EDIT:**
Got this error on the webpage `Unhandled Promise Rejection: TypeError: undefined is not an object (evaluating 'e.length')`
[](https://i.stack.imgur.com/arHmy.png)
FYI: I added a meta box on the post admin page, the meta box works perfectly without the code above.
My entire code:
```
function main_text_meta_box() {
add_meta_box(
'main-text',
__( 'Main text', 'sitepoint' ),
'main_text_meta_box_callback',
'post'
);
}
function main_text_meta_box_callback( $post ) {
// Add a nonce field so we can check for it later.
wp_nonce_field( 'main_text_nonce', 'main_text_nonce' );
$value = get_post_meta( $post->ID, '_main_text', true );
echo '<textarea style="width:100%; height:300px;" id="main_text" name="main_text">' . esc_attr( $value ) . '</textarea>';
}
add_action( 'add_meta_boxes', 'main_text_meta_box' );
function save_main_text_meta_box_data( $post_id ) {
// Check if our nonce is set.
if ( ! isset( $_POST['main_text_nonce'] ) ) {
return;
}
// Verify that the nonce is valid.
if ( ! wp_verify_nonce( $_POST['main_text_nonce'], 'main_text_nonce' ) ) {
return;
}
// If this is an autosave, our form has not been submitted, so we don't want to do anything.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
// Check the user's permissions.
if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] ) {
if ( ! current_user_can( 'edit_page', $post_id ) ) {
return;
}
}
else {
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
}
/* OK, it's safe for us to save the data now. */
// Make sure that it is set.
if ( ! isset( $_POST['main_text'] ) ) {
return;
}
// Sanitize user input.
$my_data = sanitize_text_field( $_POST['main_text'] );
// Update the meta field in the database.
update_post_meta( $post_id, '_main_text', $my_data );
}
add_action( 'save_post', 'save_main_text_meta_box_data' );
function add_custom_fields() {
register_rest_field(
'post',
'main_text', //New Field Name in JSON RESPONSEs
array(
'get_callback' => 'get_main_text', // custom function name
'update_callback' => null,
'schema' => null,
)
);
}
add_action( 'rest_api_init', 'add_custom_fields' );
function get_main_text ( $post, $field_name, $request ){
return get_post_meta($post['id'], '_main_text', true);
}
``` | Assuming that you have a CPT with slug `projets` and you've registered built-in categories for that CPT, it all looks correct.
So there are two possibilities, that I would check:
1. Typos - maybe you misstyped your CPT name somewhere in your code.
2. `pre_get_posts` filter is modifying your query and changing its behavior (it's pretty common if you write `pre_get_posts` and don't pay enough attention to conditions inside of it). |
326,708 | <p>So, I'm in the process of writing a plugin for a specific site.</p>
<p>I understand WordPress picks the page template from the theme, with php script names according to the chart below. However, I'd like to write a script for my plugin and have WordPress include my script when it searches for the page template.</p>
<p>I know this is typically the job of the theme. I also know child themes are used to override this behavior. Is this something plugins can do as well?</p>
<p><a href="https://i.stack.imgur.com/zS5PN.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zS5PN.jpg" alt="WordPress Template Page Hierarchy"></a></p>
| [
{
"answer_id": 326714,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 4,
"selected": true,
"text": "<p>WordPress has a <code>template_include</code> filter which you can use.</p>\n\n<pre><code>// Add a filter to 'template_include' hook\nadd_filter( 'template_include', 'wpse_force_template' );\nfunction wpse_force_template( $template ) {\n // If the current url is an archive of any kind\n if( is_archive() ) {\n // Set this to the template file inside your plugin folder\n $template = WP_PLUGIN_DIR .'/'. plugin_basename( dirname(__FILE__) ) .'/archive.php';\n }\n // Always return, even if we didn't change anything\n return $template;\n}\n</code></pre>\n\n<p>It would be wise to allow your users to decide which archives are affected. Many sites have custom post types and may not want those archives affected like other post types. You can add an options page that dynamically pulls all post types on the current site and allows them to toggle your plugin on or off for each. Once you have that, you'll need to again dynamically pull all post types, and then dynamically build \"if\" statements for each one. For example, <code>if(is_archive('event') && $eventtoggle == true</code> - if it's an archive of this specific type and the user toggled the plugin on for this specific type.</p>\n"
},
{
"answer_id": 327075,
"author": "user3135691",
"author_id": 59755,
"author_profile": "https://wordpress.stackexchange.com/users/59755",
"pm_score": 1,
"selected": false,
"text": "<p>In addition to the correct answer above, let's say you have a custom post type called \"links\".</p>\n\n<p>WordPress automatically requests an archive called \"archive-links.php\". Either in your plugin or in your theme, plus the page for the single instance of an CPT entry.</p>\n\n<pre><code><?php\n// Template Logic\nfunction cc_links_init_template_logic($original_template) {\n // Check Theme Template or Plugin Template for archive-links.php\n\n $file = trailingslashit(get_template_directory()) . 'archive-links.php';\n\n if(is_post_type_archive('links')) {\n // some additional logic goes here^.\n if(file_exists($file)) {\n return trailingslashit(get_template_directory()).'archive-links.php';\n } else {\n return plugin_dir_path(__DIR__) . 'templates/archive-links.php';\n }\n } elseif(is_singular('links')) {\n if(file_exists(get_template_directory_uri() . '/single-links.php')) {\n return get_template_directory_uri() . '/single-links.php';\n } else {\n return plugin_dir_path(__DIR__) . 'templates/single-links.php';\n }\n }\n\n return $original_template;\n}\nadd_action('template_include', 'cc_links_init_template_logic');\n</code></pre>\n"
},
{
"answer_id": 358546,
"author": "Asha",
"author_id": 92824,
"author_profile": "https://wordpress.stackexchange.com/users/92824",
"pm_score": 0,
"selected": false,
"text": "<pre><code>//add_filter( 'archive_template', 'get_custom_post_type_template' ) ;\nadd_filter('archive_template', 'yourplugin_get_custom_archive_template');\nfunction yourplugin_get_custom_archive_template($template) {\n global $wp_query;\n if (is_post_type_archive('articles')) {\n $templates[] = 'archive-articles.php';\n $template = yourplugin_locate_plugin_template($templates);\n }\n return $template;\n}\nfunction yourplugin_locate_plugin_template($template_names, $load = false, $require_once = true) {\n if (!is_array($template_names)) {\n return '';\n }\n $located = '';\n $this_plugin_dir = WP_PLUGIN_DIR . '/' . str_replace(basename(__FILE__), \"\", plugin_basename(__FILE__));\n foreach ($template_names as $template_name) {\n if (!$template_name) continue;\n if (file_exists(STYLESHEETPATH . '/' . $template_name)) {\n $located = STYLESHEETPATH . '/' . $template_name;\n break;\n } elseif (file_exists(TEMPLATEPATH . '/' . $template_name)) {\n $located = TEMPLATEPATH . '/' . $template_name;\n break;\n } elseif (file_exists($this_plugin_dir . '/templates/' . $template_name)) {\n $located = $this_plugin_dir . '/templates/' . $template_name;\n break;\n }\n }\n if ($load && $located != '') {\n load_template($located, $require_once);\n }\n return $located;\n}\n</code></pre>\n"
}
] | 2019/01/25 | [
"https://wordpress.stackexchange.com/questions/326708",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80614/"
] | So, I'm in the process of writing a plugin for a specific site.
I understand WordPress picks the page template from the theme, with php script names according to the chart below. However, I'd like to write a script for my plugin and have WordPress include my script when it searches for the page template.
I know this is typically the job of the theme. I also know child themes are used to override this behavior. Is this something plugins can do as well?
[](https://i.stack.imgur.com/zS5PN.jpg) | WordPress has a `template_include` filter which you can use.
```
// Add a filter to 'template_include' hook
add_filter( 'template_include', 'wpse_force_template' );
function wpse_force_template( $template ) {
// If the current url is an archive of any kind
if( is_archive() ) {
// Set this to the template file inside your plugin folder
$template = WP_PLUGIN_DIR .'/'. plugin_basename( dirname(__FILE__) ) .'/archive.php';
}
// Always return, even if we didn't change anything
return $template;
}
```
It would be wise to allow your users to decide which archives are affected. Many sites have custom post types and may not want those archives affected like other post types. You can add an options page that dynamically pulls all post types on the current site and allows them to toggle your plugin on or off for each. Once you have that, you'll need to again dynamically pull all post types, and then dynamically build "if" statements for each one. For example, `if(is_archive('event') && $eventtoggle == true` - if it's an archive of this specific type and the user toggled the plugin on for this specific type. |
326,742 | <p>I want to add some content, in the top or bottom of the wordpress edit.php page for a custom post type. What is the right filter or way to do this ? </p>
| [
{
"answer_id": 326754,
"author": "Md. Ehsanul Haque Kanan",
"author_id": 75705,
"author_profile": "https://wordpress.stackexchange.com/users/75705",
"pm_score": -1,
"selected": false,
"text": "<p>Try following these lines to add html content to <strong>edit.php</strong>:</p>\n<pre><code><?php\n# Called only in /wp-admin/edit.php pages\nadd_action( 'load-edit.php', function() {\n add_filter( 'views_edit-talk', 'talk_tabs' ); // talk is my custom post type\n});\n\n# echo the tabs\nfunction talk_tabs() {\n echo '\n <h2 class="nav-tab-wrapper">\n <a class="nav-tab" href="admin.php?page=guests">Profiles</a>\n <a class="nav-tab nav-tab-active" href="edit.php?post_type=talk">Talks</a>\n <a class="nav-tab" href="edit.php?post_type=offer">Offers</a>\n </h2>\n ';\n}\n?>\n</code></pre>\n<p><em>Source: <a href=\"https://stackoverflow.com/a/32895321\">Stack Overflow - Add content to edit.php</a></em></p>\n"
},
{
"answer_id": 382794,
"author": "brasofilo",
"author_id": 12615,
"author_profile": "https://wordpress.stackexchange.com/users/12615",
"pm_score": 1,
"selected": false,
"text": "<p>The action <code>load-edit.php</code> is not needed. The answer on Stack Overflow is based on this WPSE answer: <a href=\"https://wordpress.stackexchange.com/a/115164/12615\">How do you create a custom edit.php / edit pages page</a> that uses <code>pre_get_posts</code>, that's why it was encapsulated inside <code>load-PAGE</code> action.</p>\n<p>On the screen <code>edit.php</code> we don't have any action hooks to insert content. We can only use the filter <code>views_edit-POST_TYPE</code> to do something there. With jQuery we can adjust the position on screen.</p>\n<pre><code>add_filter( 'views_edit-POST_TYPE', function($views){\n echo '<h2 style="display:none;" id="my-element">My Custom HTML</h2>';\n echo "<script>\n jQuery(document).ready(function($){\n $('#my-element').detach().insertBefore('#ajax-response').fadeIn();\n });\n </script>";\n return $views;\n});\n</code></pre>\n<p>Without jQuery it prints on position 1, and on position 2 using it.</p>\n<p><img src=\"https://i.stack.imgur.com/NutFH.png\" alt=\"\" /></p>\n"
}
] | 2019/01/26 | [
"https://wordpress.stackexchange.com/questions/326742",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/136480/"
] | I want to add some content, in the top or bottom of the wordpress edit.php page for a custom post type. What is the right filter or way to do this ? | The action `load-edit.php` is not needed. The answer on Stack Overflow is based on this WPSE answer: [How do you create a custom edit.php / edit pages page](https://wordpress.stackexchange.com/a/115164/12615) that uses `pre_get_posts`, that's why it was encapsulated inside `load-PAGE` action.
On the screen `edit.php` we don't have any action hooks to insert content. We can only use the filter `views_edit-POST_TYPE` to do something there. With jQuery we can adjust the position on screen.
```
add_filter( 'views_edit-POST_TYPE', function($views){
echo '<h2 style="display:none;" id="my-element">My Custom HTML</h2>';
echo "<script>
jQuery(document).ready(function($){
$('#my-element').detach().insertBefore('#ajax-response').fadeIn();
});
</script>";
return $views;
});
```
Without jQuery it prints on position 1, and on position 2 using it.
 |
326,781 | <p>I have a piece of code that outputs my post title but how can I output it as an H4?</p>
<p>Here is the code I have: <code><?php echo get_the_title( $post_id ); ?></code>
Thanks</p>
| [
{
"answer_id": 326782,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 1,
"selected": true,
"text": "<p>Using your example, you could...</p>\n\n<pre><code><h4><?php echo get_the_title( $post_id ); ?></h4>\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>$h4 = get_the_title();\necho '<h4>' . $h4 . '</h4>';\n</code></pre>\n\n<p>More on <a href=\"https://developer.wordpress.org/reference/functions/get_the_title/\" rel=\"nofollow noreferrer\">get_the_title()</a>.</p>\n\n<p>Or you could use <a href=\"https://codex.wordpress.org/Function_Reference/the_title\" rel=\"nofollow noreferrer\">the_title()</a>.</p>\n\n<pre><code>the_title( '<h4>', '</h4>' );\n</code></pre>\n"
},
{
"answer_id": 326783,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 2,
"selected": false,
"text": "<p>The most simple way is:</p>\n\n<pre><code><h4><?php echo get_the_title( $post_id ); ?></h4>\n</code></pre>\n\n<p>However, if you want check first if that post <em>has</em> a title and avoid an empty <code><h4></code> if it doesn't, you write:</p>\n\n<pre><code>$title = get_the_title( $post_id );\n\nif ( $title )\n echo \"<h4>$title</h4>\";\n</code></pre>\n"
}
] | 2019/01/26 | [
"https://wordpress.stackexchange.com/questions/326781",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/146090/"
] | I have a piece of code that outputs my post title but how can I output it as an H4?
Here is the code I have: `<?php echo get_the_title( $post_id ); ?>`
Thanks | Using your example, you could...
```
<h4><?php echo get_the_title( $post_id ); ?></h4>
```
Or
```
$h4 = get_the_title();
echo '<h4>' . $h4 . '</h4>';
```
More on [get\_the\_title()](https://developer.wordpress.org/reference/functions/get_the_title/).
Or you could use [the\_title()](https://codex.wordpress.org/Function_Reference/the_title).
```
the_title( '<h4>', '</h4>' );
``` |
326,795 | <p>How to add custom settings in the side panel that shows when a block is active? For example Paragraph block has "Text Settings" and "Custom Size" options, how can I add options to my custom block?</p>
<p>This tutorial: <a href="https://wordpress.org/gutenberg/handbook/designers-developers/developers/tutorials/block-tutorial/block-controls-toolbars-and-inspector/" rel="nofollow noreferrer">https://wordpress.org/gutenberg/handbook/designers-developers/developers/tutorials/block-tutorial/block-controls-toolbars-and-inspector/</a>, says to use <code>InspectorControls</code> however that appears to be deprecated and does not work.</p>
<p>Here's what I have so far:</p>
<pre><code>( function( blocks, i18n, element ) {
var el = element.createElement;
var __ = i18n.__;
var ServerSideRender = window.wp.components.ServerSideRender;
blocks.registerBlockType( 'my-block/block', {
title: __( 'My Block', 'my-block' ),
icon: 'welcome-widgets-menus',
category: 'widgets',
attributes : {},
edit: function( props ) {
return [
el( ServerSideRender, {
block: "my-block/block",
attributes: props.attributes
} )
];
},
save: function() {
return null;
},
} );
}(
window.wp.blocks,
window.wp.i18n,
window.wp.element
) );
</code></pre>
<p>Thank you!</p>
| [
{
"answer_id": 326823,
"author": "obiPlabon",
"author_id": 135737,
"author_profile": "https://wordpress.stackexchange.com/users/135737",
"pm_score": 4,
"selected": true,
"text": "<p>Actually <code>InspectorControls</code> is not deprecated. It's been moved to another namespace or under a different object, which is <code>wp.editor</code>. So the latest way of adding controls in side panel is the following (in JSX) -</p>\n\n<pre><code>// Destruct components\n// Place at the top of the block file\nconst { InspectorControls } = wp.editor;\nconst { PanelBody } = wp.components;\n\n// in edit() method\n<InspectorControls>\n <PanelBody\n title={__('Panel Title')}\n initialOpen={true}\n >\n {/* Panel items goes here */}\n </PanelBody>\n</InspectorControls>\n</code></pre>\n\n<p>Update (example in pure JS):</p>\n\n<pre><code>var InspectorControls = wp.editor.InspectorControls;\nvar PanelBody = wp.components.PanelBody;\n\n// in edit() method\nwp.element.createElement(\n InspectorControls,\n null,\n wp.element.createElement(PanelBody, {\n title: __('Panel Title'),\n initialOpen: true\n })\n);\n</code></pre>\n"
},
{
"answer_id": 326826,
"author": "Ashiquzzaman Kiron",
"author_id": 78505,
"author_profile": "https://wordpress.stackexchange.com/users/78505",
"pm_score": 2,
"selected": false,
"text": "<p>First you need to import the components </p>\n\n<pre><code>const { InspectorControls } = wp.editor;\nconst { PanelBody } = wp.components;\n</code></pre>\n\n<p>and then inside the edit function you need to place the InspectorControls like this - </p>\n\n<pre><code><InspectorControls>\n\n <PanelBody title={ __( 'Settings One' ) }>\n </PanelBody>\n\n <PanelBody title={ __( 'Settings Two' ) }>\n </PanelBody>\n\n <PanelBody title={ __( 'Settings Three' ) >\n </PanelBody>\n\n</InspectorControls>\n</code></pre>\n\n<p>And you have three setting panel. Here's another example - </p>\n\n<pre><code> isSelected && (\n <InspectorControls key= { 'inspector' } >\n <PanelBody>\n <RangeControl \n label= { __('Title Size', 'tar') }\n value= { textSize }\n min= '25'\n max= '50'\n onChange={ (set) => setAttributes({ textSize : set }) }\n />\n\n <PanelColorSettings \n title={ __('Title Color', 'tar') }\n colorSettings= { [ \n {\n value: textColor,\n onChange: (colorValue) => setAttributes ( { textColor: colorValue } ),\n label: __('Color', 'tar'),\n },\n ] }\n />\n\n <PanelColorSettings \n title={ __('Background Color', 'tar') }\n colorSettings= { [ \n {\n value: bgColor,\n onChange: (colorValue) => setAttributes ( { bgColor: colorValue } ),\n label: __('Color', 'tar'),\n },\n ] }\n />\n\n </PanelBody>\n </InspectorControls>\n ),\n</code></pre>\n\n<p>Noticed the isSelected props? This means the block sidebar settings will shown ONLY when you click on the block. I hope this helps.</p>\n"
}
] | 2019/01/26 | [
"https://wordpress.stackexchange.com/questions/326795",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/85390/"
] | How to add custom settings in the side panel that shows when a block is active? For example Paragraph block has "Text Settings" and "Custom Size" options, how can I add options to my custom block?
This tutorial: <https://wordpress.org/gutenberg/handbook/designers-developers/developers/tutorials/block-tutorial/block-controls-toolbars-and-inspector/>, says to use `InspectorControls` however that appears to be deprecated and does not work.
Here's what I have so far:
```
( function( blocks, i18n, element ) {
var el = element.createElement;
var __ = i18n.__;
var ServerSideRender = window.wp.components.ServerSideRender;
blocks.registerBlockType( 'my-block/block', {
title: __( 'My Block', 'my-block' ),
icon: 'welcome-widgets-menus',
category: 'widgets',
attributes : {},
edit: function( props ) {
return [
el( ServerSideRender, {
block: "my-block/block",
attributes: props.attributes
} )
];
},
save: function() {
return null;
},
} );
}(
window.wp.blocks,
window.wp.i18n,
window.wp.element
) );
```
Thank you! | Actually `InspectorControls` is not deprecated. It's been moved to another namespace or under a different object, which is `wp.editor`. So the latest way of adding controls in side panel is the following (in JSX) -
```
// Destruct components
// Place at the top of the block file
const { InspectorControls } = wp.editor;
const { PanelBody } = wp.components;
// in edit() method
<InspectorControls>
<PanelBody
title={__('Panel Title')}
initialOpen={true}
>
{/* Panel items goes here */}
</PanelBody>
</InspectorControls>
```
Update (example in pure JS):
```
var InspectorControls = wp.editor.InspectorControls;
var PanelBody = wp.components.PanelBody;
// in edit() method
wp.element.createElement(
InspectorControls,
null,
wp.element.createElement(PanelBody, {
title: __('Panel Title'),
initialOpen: true
})
);
``` |
326,849 | <p>I use a plugin (<a href="https://wordpress.org/plugins/companion-auto-update/" rel="nofollow noreferrer">Companion Auto Update</a>) for auto-update plugins.
<a href="https://wordpress.org/support/topic/updraftplus-backup-restore-is-not-autoupdating/page/2/#post-11129722" rel="nofollow noreferrer">This is using the core function of Wordpress</a> where you can force auto-update for plugins. </p>
<p>All the plugins is updated when an update is available except <a href="https://it.wordpress.org/plugins/updraftplus/" rel="nofollow noreferrer">UpdraftPlus WordPress Backup Plugin</a></p>
<p>This has been tested by me but also by the plugin author of (<a href="https://wordpress.org/plugins/companion-auto-update/" rel="nofollow noreferrer">Companion Auto Update</a>) <a href="https://wordpress.org/support/topic/updraftplus-backup-restore-is-not-autoupdating/page/2/#post-11017962" rel="nofollow noreferrer">see here</a>.</p>
<p>I am on a VPS. I tried different server settings but seems this is not solving the issue.</p>
<p>I am asking why if i update manually all is done very fast (less than 2 minutes) and the auto-update of Wordpress seems to be unable to update automatically UpdraftPlus WordPress Backup. When Wordpress update his version i suppose is more bigger than 7 MB who is the size of UpdraftPlus WordPress Backup.</p>
<p>PHP error has to say:</p>
<pre><code>wp-cron.php' (request: "POST /wordpress/wp-cron.php?doing_wp_cron=***7500") execution timed out (120.770567 sec), terminating
</code></pre>
<p><a href="https://wordpress.org/support/topic/unable-to-auto-update-this-plugin/#post-11133224" rel="nofollow noreferrer">I tried some server settings changes</a> but this doesn't help.
Any idea why there is this issue and how can be solved? Can be a Wordpress auto-update process issue?</p>
| [
{
"answer_id": 326823,
"author": "obiPlabon",
"author_id": 135737,
"author_profile": "https://wordpress.stackexchange.com/users/135737",
"pm_score": 4,
"selected": true,
"text": "<p>Actually <code>InspectorControls</code> is not deprecated. It's been moved to another namespace or under a different object, which is <code>wp.editor</code>. So the latest way of adding controls in side panel is the following (in JSX) -</p>\n\n<pre><code>// Destruct components\n// Place at the top of the block file\nconst { InspectorControls } = wp.editor;\nconst { PanelBody } = wp.components;\n\n// in edit() method\n<InspectorControls>\n <PanelBody\n title={__('Panel Title')}\n initialOpen={true}\n >\n {/* Panel items goes here */}\n </PanelBody>\n</InspectorControls>\n</code></pre>\n\n<p>Update (example in pure JS):</p>\n\n<pre><code>var InspectorControls = wp.editor.InspectorControls;\nvar PanelBody = wp.components.PanelBody;\n\n// in edit() method\nwp.element.createElement(\n InspectorControls,\n null,\n wp.element.createElement(PanelBody, {\n title: __('Panel Title'),\n initialOpen: true\n })\n);\n</code></pre>\n"
},
{
"answer_id": 326826,
"author": "Ashiquzzaman Kiron",
"author_id": 78505,
"author_profile": "https://wordpress.stackexchange.com/users/78505",
"pm_score": 2,
"selected": false,
"text": "<p>First you need to import the components </p>\n\n<pre><code>const { InspectorControls } = wp.editor;\nconst { PanelBody } = wp.components;\n</code></pre>\n\n<p>and then inside the edit function you need to place the InspectorControls like this - </p>\n\n<pre><code><InspectorControls>\n\n <PanelBody title={ __( 'Settings One' ) }>\n </PanelBody>\n\n <PanelBody title={ __( 'Settings Two' ) }>\n </PanelBody>\n\n <PanelBody title={ __( 'Settings Three' ) >\n </PanelBody>\n\n</InspectorControls>\n</code></pre>\n\n<p>And you have three setting panel. Here's another example - </p>\n\n<pre><code> isSelected && (\n <InspectorControls key= { 'inspector' } >\n <PanelBody>\n <RangeControl \n label= { __('Title Size', 'tar') }\n value= { textSize }\n min= '25'\n max= '50'\n onChange={ (set) => setAttributes({ textSize : set }) }\n />\n\n <PanelColorSettings \n title={ __('Title Color', 'tar') }\n colorSettings= { [ \n {\n value: textColor,\n onChange: (colorValue) => setAttributes ( { textColor: colorValue } ),\n label: __('Color', 'tar'),\n },\n ] }\n />\n\n <PanelColorSettings \n title={ __('Background Color', 'tar') }\n colorSettings= { [ \n {\n value: bgColor,\n onChange: (colorValue) => setAttributes ( { bgColor: colorValue } ),\n label: __('Color', 'tar'),\n },\n ] }\n />\n\n </PanelBody>\n </InspectorControls>\n ),\n</code></pre>\n\n<p>Noticed the isSelected props? This means the block sidebar settings will shown ONLY when you click on the block. I hope this helps.</p>\n"
}
] | 2019/01/27 | [
"https://wordpress.stackexchange.com/questions/326849",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159987/"
] | I use a plugin ([Companion Auto Update](https://wordpress.org/plugins/companion-auto-update/)) for auto-update plugins.
[This is using the core function of Wordpress](https://wordpress.org/support/topic/updraftplus-backup-restore-is-not-autoupdating/page/2/#post-11129722) where you can force auto-update for plugins.
All the plugins is updated when an update is available except [UpdraftPlus WordPress Backup Plugin](https://it.wordpress.org/plugins/updraftplus/)
This has been tested by me but also by the plugin author of ([Companion Auto Update](https://wordpress.org/plugins/companion-auto-update/)) [see here](https://wordpress.org/support/topic/updraftplus-backup-restore-is-not-autoupdating/page/2/#post-11017962).
I am on a VPS. I tried different server settings but seems this is not solving the issue.
I am asking why if i update manually all is done very fast (less than 2 minutes) and the auto-update of Wordpress seems to be unable to update automatically UpdraftPlus WordPress Backup. When Wordpress update his version i suppose is more bigger than 7 MB who is the size of UpdraftPlus WordPress Backup.
PHP error has to say:
```
wp-cron.php' (request: "POST /wordpress/wp-cron.php?doing_wp_cron=***7500") execution timed out (120.770567 sec), terminating
```
[I tried some server settings changes](https://wordpress.org/support/topic/unable-to-auto-update-this-plugin/#post-11133224) but this doesn't help.
Any idea why there is this issue and how can be solved? Can be a Wordpress auto-update process issue? | Actually `InspectorControls` is not deprecated. It's been moved to another namespace or under a different object, which is `wp.editor`. So the latest way of adding controls in side panel is the following (in JSX) -
```
// Destruct components
// Place at the top of the block file
const { InspectorControls } = wp.editor;
const { PanelBody } = wp.components;
// in edit() method
<InspectorControls>
<PanelBody
title={__('Panel Title')}
initialOpen={true}
>
{/* Panel items goes here */}
</PanelBody>
</InspectorControls>
```
Update (example in pure JS):
```
var InspectorControls = wp.editor.InspectorControls;
var PanelBody = wp.components.PanelBody;
// in edit() method
wp.element.createElement(
InspectorControls,
null,
wp.element.createElement(PanelBody, {
title: __('Panel Title'),
initialOpen: true
})
);
``` |
326,854 | <p>First off let me explain what I mean.
I work on a company that got a WP page with a theme installed and a load of plugins, like YOAST, WooCommerce, more plugins for woo commerce etc etc.
Those plugins and the theme itself, generate javascript code for our main webpage.
Obviously, that is far from optimized and that's confirmed by:
<a href="https://gtmetrix.com/" rel="nofollow noreferrer">https://gtmetrix.com/</a> and google insights.</p>
<p>Here comes the question.
Is there a way to override some of the js code, by making another "version" of them in the footer? I actually plan to make footer load a js file instead, including overrides, but since I barely know how it will behave, I thought I should ask if I think this right.</p>
<p>It might add to the amount of download plaintext that way. It isn't elegant, since it turns things a little spaghetti, but I plan in the future to make any js call, a call to a js file thus no footer override will be needed and no double code will be downloaded whatsoever, I just need a fast solution for the meantime.
I asssume if I add to the amount of download plaintext, I will still might get parallel loading of scripts in compensation, thus loading time will get improved.</p>
<p>Pictures are small jpgs and they don't contribute on loading time in a significant way.</p>
<p>PageSpeed Score is 74% so there is a lot room for improvement.
CSS and JS are the major factors.</p>
<p>Do I think this right? Any guides will be appreciated.</p>
| [
{
"answer_id": 326823,
"author": "obiPlabon",
"author_id": 135737,
"author_profile": "https://wordpress.stackexchange.com/users/135737",
"pm_score": 4,
"selected": true,
"text": "<p>Actually <code>InspectorControls</code> is not deprecated. It's been moved to another namespace or under a different object, which is <code>wp.editor</code>. So the latest way of adding controls in side panel is the following (in JSX) -</p>\n\n<pre><code>// Destruct components\n// Place at the top of the block file\nconst { InspectorControls } = wp.editor;\nconst { PanelBody } = wp.components;\n\n// in edit() method\n<InspectorControls>\n <PanelBody\n title={__('Panel Title')}\n initialOpen={true}\n >\n {/* Panel items goes here */}\n </PanelBody>\n</InspectorControls>\n</code></pre>\n\n<p>Update (example in pure JS):</p>\n\n<pre><code>var InspectorControls = wp.editor.InspectorControls;\nvar PanelBody = wp.components.PanelBody;\n\n// in edit() method\nwp.element.createElement(\n InspectorControls,\n null,\n wp.element.createElement(PanelBody, {\n title: __('Panel Title'),\n initialOpen: true\n })\n);\n</code></pre>\n"
},
{
"answer_id": 326826,
"author": "Ashiquzzaman Kiron",
"author_id": 78505,
"author_profile": "https://wordpress.stackexchange.com/users/78505",
"pm_score": 2,
"selected": false,
"text": "<p>First you need to import the components </p>\n\n<pre><code>const { InspectorControls } = wp.editor;\nconst { PanelBody } = wp.components;\n</code></pre>\n\n<p>and then inside the edit function you need to place the InspectorControls like this - </p>\n\n<pre><code><InspectorControls>\n\n <PanelBody title={ __( 'Settings One' ) }>\n </PanelBody>\n\n <PanelBody title={ __( 'Settings Two' ) }>\n </PanelBody>\n\n <PanelBody title={ __( 'Settings Three' ) >\n </PanelBody>\n\n</InspectorControls>\n</code></pre>\n\n<p>And you have three setting panel. Here's another example - </p>\n\n<pre><code> isSelected && (\n <InspectorControls key= { 'inspector' } >\n <PanelBody>\n <RangeControl \n label= { __('Title Size', 'tar') }\n value= { textSize }\n min= '25'\n max= '50'\n onChange={ (set) => setAttributes({ textSize : set }) }\n />\n\n <PanelColorSettings \n title={ __('Title Color', 'tar') }\n colorSettings= { [ \n {\n value: textColor,\n onChange: (colorValue) => setAttributes ( { textColor: colorValue } ),\n label: __('Color', 'tar'),\n },\n ] }\n />\n\n <PanelColorSettings \n title={ __('Background Color', 'tar') }\n colorSettings= { [ \n {\n value: bgColor,\n onChange: (colorValue) => setAttributes ( { bgColor: colorValue } ),\n label: __('Color', 'tar'),\n },\n ] }\n />\n\n </PanelBody>\n </InspectorControls>\n ),\n</code></pre>\n\n<p>Noticed the isSelected props? This means the block sidebar settings will shown ONLY when you click on the block. I hope this helps.</p>\n"
}
] | 2019/01/27 | [
"https://wordpress.stackexchange.com/questions/326854",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159988/"
] | First off let me explain what I mean.
I work on a company that got a WP page with a theme installed and a load of plugins, like YOAST, WooCommerce, more plugins for woo commerce etc etc.
Those plugins and the theme itself, generate javascript code for our main webpage.
Obviously, that is far from optimized and that's confirmed by:
<https://gtmetrix.com/> and google insights.
Here comes the question.
Is there a way to override some of the js code, by making another "version" of them in the footer? I actually plan to make footer load a js file instead, including overrides, but since I barely know how it will behave, I thought I should ask if I think this right.
It might add to the amount of download plaintext that way. It isn't elegant, since it turns things a little spaghetti, but I plan in the future to make any js call, a call to a js file thus no footer override will be needed and no double code will be downloaded whatsoever, I just need a fast solution for the meantime.
I asssume if I add to the amount of download plaintext, I will still might get parallel loading of scripts in compensation, thus loading time will get improved.
Pictures are small jpgs and they don't contribute on loading time in a significant way.
PageSpeed Score is 74% so there is a lot room for improvement.
CSS and JS are the major factors.
Do I think this right? Any guides will be appreciated. | Actually `InspectorControls` is not deprecated. It's been moved to another namespace or under a different object, which is `wp.editor`. So the latest way of adding controls in side panel is the following (in JSX) -
```
// Destruct components
// Place at the top of the block file
const { InspectorControls } = wp.editor;
const { PanelBody } = wp.components;
// in edit() method
<InspectorControls>
<PanelBody
title={__('Panel Title')}
initialOpen={true}
>
{/* Panel items goes here */}
</PanelBody>
</InspectorControls>
```
Update (example in pure JS):
```
var InspectorControls = wp.editor.InspectorControls;
var PanelBody = wp.components.PanelBody;
// in edit() method
wp.element.createElement(
InspectorControls,
null,
wp.element.createElement(PanelBody, {
title: __('Panel Title'),
initialOpen: true
})
);
``` |
326,865 | <p>My website is in English Language and using WordPress.</p>
<p>Html Code contains <b>lang="en-US" </b>only. </p>
<p>But I want some of the page in other language like Spanish, Arabic and German.</p>
<p>When I create new page it is by default lang="en-US".</p>
<p>How can I set this lang="es" or specific language attribute?</p>
<p>I have tried many plugins but all are converting every pages to selected languages that I don't want.</p>
| [
{
"answer_id": 326823,
"author": "obiPlabon",
"author_id": 135737,
"author_profile": "https://wordpress.stackexchange.com/users/135737",
"pm_score": 4,
"selected": true,
"text": "<p>Actually <code>InspectorControls</code> is not deprecated. It's been moved to another namespace or under a different object, which is <code>wp.editor</code>. So the latest way of adding controls in side panel is the following (in JSX) -</p>\n\n<pre><code>// Destruct components\n// Place at the top of the block file\nconst { InspectorControls } = wp.editor;\nconst { PanelBody } = wp.components;\n\n// in edit() method\n<InspectorControls>\n <PanelBody\n title={__('Panel Title')}\n initialOpen={true}\n >\n {/* Panel items goes here */}\n </PanelBody>\n</InspectorControls>\n</code></pre>\n\n<p>Update (example in pure JS):</p>\n\n<pre><code>var InspectorControls = wp.editor.InspectorControls;\nvar PanelBody = wp.components.PanelBody;\n\n// in edit() method\nwp.element.createElement(\n InspectorControls,\n null,\n wp.element.createElement(PanelBody, {\n title: __('Panel Title'),\n initialOpen: true\n })\n);\n</code></pre>\n"
},
{
"answer_id": 326826,
"author": "Ashiquzzaman Kiron",
"author_id": 78505,
"author_profile": "https://wordpress.stackexchange.com/users/78505",
"pm_score": 2,
"selected": false,
"text": "<p>First you need to import the components </p>\n\n<pre><code>const { InspectorControls } = wp.editor;\nconst { PanelBody } = wp.components;\n</code></pre>\n\n<p>and then inside the edit function you need to place the InspectorControls like this - </p>\n\n<pre><code><InspectorControls>\n\n <PanelBody title={ __( 'Settings One' ) }>\n </PanelBody>\n\n <PanelBody title={ __( 'Settings Two' ) }>\n </PanelBody>\n\n <PanelBody title={ __( 'Settings Three' ) >\n </PanelBody>\n\n</InspectorControls>\n</code></pre>\n\n<p>And you have three setting panel. Here's another example - </p>\n\n<pre><code> isSelected && (\n <InspectorControls key= { 'inspector' } >\n <PanelBody>\n <RangeControl \n label= { __('Title Size', 'tar') }\n value= { textSize }\n min= '25'\n max= '50'\n onChange={ (set) => setAttributes({ textSize : set }) }\n />\n\n <PanelColorSettings \n title={ __('Title Color', 'tar') }\n colorSettings= { [ \n {\n value: textColor,\n onChange: (colorValue) => setAttributes ( { textColor: colorValue } ),\n label: __('Color', 'tar'),\n },\n ] }\n />\n\n <PanelColorSettings \n title={ __('Background Color', 'tar') }\n colorSettings= { [ \n {\n value: bgColor,\n onChange: (colorValue) => setAttributes ( { bgColor: colorValue } ),\n label: __('Color', 'tar'),\n },\n ] }\n />\n\n </PanelBody>\n </InspectorControls>\n ),\n</code></pre>\n\n<p>Noticed the isSelected props? This means the block sidebar settings will shown ONLY when you click on the block. I hope this helps.</p>\n"
}
] | 2019/01/27 | [
"https://wordpress.stackexchange.com/questions/326865",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/155491/"
] | My website is in English Language and using WordPress.
Html Code contains **lang="en-US"** only.
But I want some of the page in other language like Spanish, Arabic and German.
When I create new page it is by default lang="en-US".
How can I set this lang="es" or specific language attribute?
I have tried many plugins but all are converting every pages to selected languages that I don't want. | Actually `InspectorControls` is not deprecated. It's been moved to another namespace or under a different object, which is `wp.editor`. So the latest way of adding controls in side panel is the following (in JSX) -
```
// Destruct components
// Place at the top of the block file
const { InspectorControls } = wp.editor;
const { PanelBody } = wp.components;
// in edit() method
<InspectorControls>
<PanelBody
title={__('Panel Title')}
initialOpen={true}
>
{/* Panel items goes here */}
</PanelBody>
</InspectorControls>
```
Update (example in pure JS):
```
var InspectorControls = wp.editor.InspectorControls;
var PanelBody = wp.components.PanelBody;
// in edit() method
wp.element.createElement(
InspectorControls,
null,
wp.element.createElement(PanelBody, {
title: __('Panel Title'),
initialOpen: true
})
);
``` |
326,869 | <p>When adding the "Latest Posts" block within Gutenberg, is it possible to filter by custom post type?</p>
<p>Here are the options I can see: </p>
<p><a href="https://i.stack.imgur.com/B9GzP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/B9GzP.png" alt="enter image description here"></a></p>
<p>Would I need to create a custom block for this type of functionality?</p>
<p>I've found a good discussion <a href="https://github.com/WordPress/gutenberg/issues/2685" rel="nofollow noreferrer">here</a>, but I've ended up down a bit of GitHub rabbit hole.</p>
| [
{
"answer_id": 339376,
"author": "hozefa Saleh",
"author_id": 113641,
"author_profile": "https://wordpress.stackexchange.com/users/113641",
"pm_score": 2,
"selected": false,
"text": "<p>Why not create your own custom post display block using this easy to use plugin lazyblock <a href=\"https://wordpress.org/plugins/lazy-blocks/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/lazy-blocks/</a> ?</p>\n\n<ol>\n<li><p>Simple steps are here, first create your custom loop using wp_query, you can take help of <a href=\"https://generatewp.com/wp_query/\" rel=\"nofollow noreferrer\">https://generatewp.com/wp_query/</a>\nhere is my custom loop for portfolio post type I had created</p>\n\n<pre><code>// WP_Query arguments\n$args = array(\n 'post_type' => array( 'uni_portfolio' ),\n);\n\n// The Query\n$query = new WP_Query( $args );\n// The Loop\nif ( $query->have_posts() ) {\n while ( $query->have_posts() ) {\n $query->the_post();\n // do something\n }\n} else {\n // no posts found\n}\n// Restore original Post Data\nwp_reset_postdata();\n</code></pre></li>\n<li><p>Then create a new blank block in lazy block plugin, its very simple and you can look at documentation here <a href=\"https://lazyblocks.com/documentation/blocks-creation/\" rel=\"nofollow noreferrer\">https://lazyblocks.com/documentation/blocks-creation/</a> , you can add few fields as per your need to, for example how many post to display etc.</p></li>\n<li><p>Then add just this function utilizing your above wp_query to create output of your block, I have used one field number of post to control post count in the block</p></li>\n</ol>\n\n<pre><code>add_filter( 'lazyblock/custom-post-loop/frontend_callback', 'uni_block_output_custompostloop', 10, 2 );\nif ( ! function_exists( 'uni_block_output_custompostloop' ) ) :\n function uni_block_output_custompostloop( $output, $attributes ) {\n ob_start();\n // your query start from here\n $args = array( 'post_type' => array( 'uni_portfolio' ), 'posts_per_page' => esc_html( $attributes['uni_number_of_post'] ), );\n $query = new WP_Query( $args );\n if ( $query->have_posts() ) {\n while ( $query->have_posts() ) {\n $query->the_post();\n if ( has_post_thumbnail()) : // Check if thumbnail exists\n the_post_thumbnail();\n endif;\n ?>\n <?php the_terms($post->ID, 'portfolio_category') ?>\n <h3><a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a></h3>\n <?php\n }\n } else {\n echo \"<div>no posts found</div>\";\n }\n wp_reset_postdata();\n // your query code end here\n return ob_get_clean();\n }\nendif;\n</code></pre>\n\n<p>Notice lazyblock/custom-post-loop is the slug of the block you created using lazyblock plugin</p>\n"
},
{
"answer_id": 390647,
"author": "bosco",
"author_id": 25324,
"author_profile": "https://wordpress.stackexchange.com/users/25324",
"pm_score": 3,
"selected": true,
"text": "<h1>It's Not (Reasonably) Possible (Yet) :(</h1>\n<p>This was such an interesting question to dig into. In short, we can get really, really close to accomplishing this using <a href=\"https://developer.wordpress.org/block-editor/reference-guides/filters/block-filters/\" rel=\"nofollow noreferrer\">Block Filters</a> and some hackish duct-tape on the PHP side. But it falls apart in the home stretch.</p>\n<p>It's worth noting that the crux of the complication is specific to the Latest Posts block's implementation - doing something similar to other core blocks is totally possible, depending on the block and modification.</p>\n<p><strong>To get this working properly in the editor without weird side-effects requires a degree of hackery that goes so far beyond an acceptable compromise - I strongly discourage doing so</strong>. I've detailed the specific point of failure in the last section of this answer.</p>\n<p>There's also a chance that a change in core might result in this solution automagically becoming fully-functional as-is at a later date, or adding the necessary extension points to complete the solution otherwise.</p>\n<p>The best solution would be to deregister <code>core/latest-posts</code> in favor of a custom block, perhaps even using the Gutenberg repo as upstream in order to pull in new developments to the core block.</p>\n<hr />\n<h1>(But We Can Get Suuuuper Close)</h1>\n<p><a href=\"https://i.stack.imgur.com/h3quY.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/h3quY.png\" alt=\"Functional post types input control added to Latest Posts block\" /></a></p>\n<p>In short, it's possible to add post-type filtering to the latest posts block in a manner that's fully functional on the front-end and with working controls in the Block Editor. What we can't do is get the block in the editor to display posts of the appropriate type.</p>\n<p>Despite falling short of a stable solution, much of what went into this attempt has a lot of merit for other customizations and modifications - particularly on the JS side. There's a lot that can be learned here to apply elsewhere, so I think it's still worth examining the attempt and where it breaks down.</p>\n<h2>Register Additional Block Attributes</h2>\n<p>We can add a new <code>postTypes</code> array attribute to the Latest Posts block in order to store the selected post types using a <a href=\"https://developer.wordpress.org/block-editor/reference-guides/filters/block-filters/#blocks-registerblocktype\" rel=\"nofollow noreferrer\"><code>blocks.registerBlockType</code> filter</a>:</p>\n<pre class=\"lang-js prettyprint-override\"><code>import { addFilter } from '@wordpress/hooks';\n\nfunction addPostTypesAttribute( settings, name ) {\n if( name !== 'core/latest-posts' )\n return settings;\n\n settings.attributes = {\n ...settings.attributes,\n postTypes: {\n type: 'array',\n default: [ 'post' ]\n }\n };\n\n return settings;\n}\n\naddFilter(\n 'blocks.registerBlockType',\n 'wpse326869/latest-posts-post-types/add-attribute',\n addPostTypesAttribute\n);\n</code></pre>\n<h2>Add Controls to Interact with New Attributes</h2>\n<h3>Filter the Edit Component</h3>\n<p><a href=\"https://developer.wordpress.org/block-editor/reference-guides/filters/block-filters/#editor-blockedit\" rel=\"nofollow noreferrer\">The <code>editor.BlockEdit</code> filter</a> allows us to interact with/modify the component returned from the block's <code>edit()</code> function.</p>\n<h3>Shim Components and Functionality with a HOC</h3>\n<p><a href=\"https://www.npmjs.com/package/@wordpress/compose\" rel=\"nofollow noreferrer\">The <code>@wordpress/compose</code> package</a> provides a handy utility for "wrapping" a component in a <a href=\"https://reactjs.org/docs/higher-order-components.html\" rel=\"nofollow noreferrer\">Higher-Order Component/"HOC"</a> (a function which takes a component as an argument and returns an augmented or wrapped version of it), effectively allowing us to shim our own components and functionality into a pre-existing component.</p>\n<h3>Place Sidebar Controls with the SlotFills System</h3>\n<p>To <a href=\"https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/block-controls-toolbar-and-sidebar/\" rel=\"nofollow noreferrer\">add control components for a block to the sidebar</a>, we simply add them as children of an <code><InspectorControls></code> component, and <a href=\"https://developer.wordpress.org/block-editor/reference-guides/slotfills/\" rel=\"nofollow noreferrer\">Gutenberg's nifty <code>SlotFills</code> system</a> will render them outside of the block in the appropriate location.</p>\n<h3>Select a Control</h3>\n<p>In my opinion, <a href=\"https://wordpress.github.io/gutenberg/?path=/story/components-formtokenfield--default\" rel=\"nofollow noreferrer\"><code>FormTokenField</code></a> is the perfect component to allow the user to enter a number of different post types. But a <a href=\"https://wordpress.github.io/gutenberg/?path=/story/components-selectcontrol--default\" rel=\"nofollow noreferrer\"><code>SelectControl</code></a> or <a href=\"https://wordpress.github.io/gutenberg/?path=/story/components-comboboxcontrol--default\" rel=\"nofollow noreferrer\"><code>ComboboxControl</code></a> might be more appropriate for your use-case.</p>\n<p>Some amount of documentation for most controls can be found in <a href=\"https://developer.wordpress.org/block-editor/reference-guides/components/form-token-field/\" rel=\"nofollow noreferrer\">The Block Editor Handboox</a>, but often times you might find that you need to scour <a href=\"https://github.com/WordPress/gutenberg/tree/trunk/packages/components/src/form-token-field\" rel=\"nofollow noreferrer\">the sources on GitHub</a> to make sense of everything.</p>\n<h3>Implementation</h3>\n<p>All the above in mind, we can add controls to interact with our new <code>postTypes</code> attribute as such:</p>\n<pre class=\"lang-js prettyprint-override\"><code>import { createHigherOrderComponent } from '@wordpress/compose';\nimport { Fragment } from '@wordpress/element';\nimport { InspectorControls } from '@wordpress/block-editor';\nimport { FormTokenField } from '@wordpress/components'\nimport { useSelect } from '@wordpress/data';\n\n// A multiple Post-Type selection control implemented on top of FormTokenField.\nconst PostTypesControl = ( props ) => {\n const { value = [], onChange } = props;\n\n const types = useSelect(\n ( select ) => ( select( 'core' ).getPostTypes() ?? [] ).map( ( { slug, name } ) => ( { value: slug, title: name } ) ),\n []\n );\n\n const tokenIsValid = ( title ) => types.some( type => type.title === title );\n const titleToValue = ( title ) => title ? types.find( type => type.title === title )?.value || '' : '';\n\n return (\n <FormTokenField\n value={ value }\n onChange={ onChange }\n suggestions={ types.map( type => type.title ) }\n saveTransform={ titleToValue }\n __experimentalValidateInput={ tokenIsValid }\n />\n );\n};\n\n// A HOC which adds a PostTypesControl to a block which has a `postTypes` attribute.\nconst withPostTypesControl = createHigherOrderComponent(\n ( BlockEdit ) => ( props ) => {\n const {\n name,\n attributes: { postTypes = [ 'post' ] },\n setAttributes,\n } = props;\n\n if( name !== 'core/latest-posts' )\n return <BlockEdit {...props} />;\n\n const setPostTypes = ( postTypes ) => setAttributes( { postTypes } );\n\n return (\n <Fragment>\n <BlockEdit {...props} />\n <InspectorControls>\n <PanelBody title="Post Types" initialOpen={false}>\n <PanelRow>\n <PostTypesControl\n value={ postTypes }\n onChange={ setPostTypes }\n />\n </PanelRow>\n </PanelBody>\n </InspectorControls>\n </Fragment>\n );\n },\n 'wpse326869withPostTypesControl'\n);\n\naddFilter(\n 'editor.BlockEdit',\n 'wpse326869/latest-posts-post-types/add-controls',\n withPostTypesControl\n);\n</code></pre>\n<h2>Use the Attribute to Filter Posts Query</h2>\n<p>Were Latest Posts a static block type which rendered it's content directly to HTML stored in the <code>post_content</code>, we'd probably use a <code>blocks.getSaveElement</code> filter here to use the attribute and modify the markup.</p>\n<p>But Latest Posts is a dynamic block, meaning that when WordPress renders the block on the front-end it executes a PHP function in order to produce the content per page-load, just like a shortcode.</p>\n<p>Unfortunately, looking at <a href=\"https://github.com/WordPress/gutenberg/blob/dbba2600e2dbe0a118d492b6681d9f33d1abd30a/packages/block-library/src/latest-posts/index.php#L36\" rel=\"nofollow noreferrer\">the source for the PHP function responsible for rendering the block</a>, there's no useful filter to modify the arguments which are sent to <code>get_posts()</code>...</p>\n<p>What we can do, however, is get a little hacky and use a <a href=\"https://developer.wordpress.org/reference/hooks/block_type_metadata_settings/\" rel=\"nofollow noreferrer\"><code>block_type_metadata_settings</code> filter</a> to hijack the Latest Post block's PHP render callback - <strong>this generally seems inadvisable; I probably wouldn't distribute code leveraging such a hack.</strong> In our custom render callback, we can add a <code>pre_get_posts</code> filter to add our <code>postTypes</code> attribute to the query, execute the original render callback, and then remove the filter once more.</p>\n<p>For ease of state management between these functions, I've chosen to use a singleton class to implement the above.</p>\n<pre class=\"lang-php prettyprint-override\"><code>class WPSE326869_LatestPostsPostTypes {\n protected static $instance = null;\n protected $original_render_callback;\n protected $block_attributes;\n\n protected function __construct() {\n add_filter( 'block_type_metadata_settings', [ $this, 'filter_block_settings' ], 10, 2 );\n }\n\n public static function get_instance() {\n if( is_null( self::$instance ) )\n self::$instance = new self();\n\n return self::$instance;\n }\n\n public function filter_block_settings( $args, $data ) {\n if( $data['name'] !== 'core/latest-posts' )\n return $args;\n\n $this->original_render_callback = $args['render_callback'];\n $args['render_callback'] = [ $this, 'render_block' ];\n\n return $args;\n }\n\n public function latest_posts_query_types( $query ) {\n if( empty( $this->block_attributes['postTypes'] ) )\n return;\n\n $public_types = get_post_types(\n [\n 'show_in_rest' => true,\n ]\n );\n\n $types = array_intersect( $public_types, $this->block_attributes['postTypes'] );\n\n $query->set( 'post_type', $types );\n }\n\n public function render_block( $attributes, $block_content, $block ) {\n $this->block_attributes = $attributes;\n\n add_filter( 'pre_get_posts', [ $this, 'latest_posts_query_types' ] );\n\n $block_content = (string) call_user_func( $this->original_render_callback, $attributes, $block_content, $block );\n\n remove_filter( 'pre_get_posts', [ $this, 'latest_posts_query_types' ] );\n\n return $block_content;\n }\n}\n\nWPSE326869_LatestPostsPostTypes::get_instance();\n</code></pre>\n<hr />\n<h1>Summary & Point of Failure</h1>\n<h2>What Works</h2>\n<p>All of the above in place, we end up with a function "Post Types" control added to the Latest Post block's sidebar settings (with autocomplete suggestions, to boot!) which stores it's values in a new attribute added to the block, and uses that attribute to appropriately adjust the block's server-side query.</p>\n<p>At this point, the modified block will successfully display post-type filtered latest posts on the front-end!</p>\n<h2>What Doesn't</h2>\n<p>Back in the Block Editor, however, there's a little wonkiness afoot. It all boils down to <a href=\"https://github.com/WordPress/gutenberg/blob/b33794de5a71df92b42562f326ebdec2d10ff6d8/packages/block-library/src/latest-posts/edit.js#L103\" rel=\"nofollow noreferrer\">the <code>edit()</code> component using a REST API request hard-coded for the <code>post</code> post-type</a> in order to quickly deliver visual updates in the editor instead of the block's PHP render callback. The result is that the block does not display posts of the selected types within the editor.</p>\n<p>You might think to use more <code>pre_get_posts</code> hackery to modify the results of that query - but doing so could well lead to the Gutenberg data stores incorrectly classifying the results as <code>posts</code>, which could cause all sorts of other issues.</p>\n<p>The only functional approach I can see would be to totally abuse the <code>editor.BlockEdit</code> filter and completely replace the block's <code>edit()</code> component. While that should be possible on paper, I feel it would be such an egregious no-no that I will not explore or demonstrate the possibility. Silently swapping out the implementation of core functionality on-the-fly is a sure-fire way to create bugs, confusion, and chaos.</p>\n<h2>What Might, Someday</h2>\n<p>I haven't dug into it too far, but <a href=\"https://github.com/WordPress/gutenberg/pull/870\" rel=\"nofollow noreferrer\">the PRs which introduced the Latest Posts Block</a> and <a href=\"https://github.com/WordPress/gutenberg/pull/5602\" rel=\"nofollow noreferrer\">the Server Side Rendering solution</a> both heavily reference each other. I haven't researched why the Latest Posts block ultimately did not end up using the SSR component for rendering in the Block Editor. If it ever did however, I believe the solution implemented above would be fully functional.</p>\n<p>It's also possible that core will introduce more applicable block filters or even additional props to the Latest Posts block which would make this more plausible.</p>\n"
}
] | 2019/01/27 | [
"https://wordpress.stackexchange.com/questions/326869",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37548/"
] | When adding the "Latest Posts" block within Gutenberg, is it possible to filter by custom post type?
Here are the options I can see:
[](https://i.stack.imgur.com/B9GzP.png)
Would I need to create a custom block for this type of functionality?
I've found a good discussion [here](https://github.com/WordPress/gutenberg/issues/2685), but I've ended up down a bit of GitHub rabbit hole. | It's Not (Reasonably) Possible (Yet) :(
=======================================
This was such an interesting question to dig into. In short, we can get really, really close to accomplishing this using [Block Filters](https://developer.wordpress.org/block-editor/reference-guides/filters/block-filters/) and some hackish duct-tape on the PHP side. But it falls apart in the home stretch.
It's worth noting that the crux of the complication is specific to the Latest Posts block's implementation - doing something similar to other core blocks is totally possible, depending on the block and modification.
**To get this working properly in the editor without weird side-effects requires a degree of hackery that goes so far beyond an acceptable compromise - I strongly discourage doing so**. I've detailed the specific point of failure in the last section of this answer.
There's also a chance that a change in core might result in this solution automagically becoming fully-functional as-is at a later date, or adding the necessary extension points to complete the solution otherwise.
The best solution would be to deregister `core/latest-posts` in favor of a custom block, perhaps even using the Gutenberg repo as upstream in order to pull in new developments to the core block.
---
(But We Can Get Suuuuper Close)
===============================
[](https://i.stack.imgur.com/h3quY.png)
In short, it's possible to add post-type filtering to the latest posts block in a manner that's fully functional on the front-end and with working controls in the Block Editor. What we can't do is get the block in the editor to display posts of the appropriate type.
Despite falling short of a stable solution, much of what went into this attempt has a lot of merit for other customizations and modifications - particularly on the JS side. There's a lot that can be learned here to apply elsewhere, so I think it's still worth examining the attempt and where it breaks down.
Register Additional Block Attributes
------------------------------------
We can add a new `postTypes` array attribute to the Latest Posts block in order to store the selected post types using a [`blocks.registerBlockType` filter](https://developer.wordpress.org/block-editor/reference-guides/filters/block-filters/#blocks-registerblocktype):
```js
import { addFilter } from '@wordpress/hooks';
function addPostTypesAttribute( settings, name ) {
if( name !== 'core/latest-posts' )
return settings;
settings.attributes = {
...settings.attributes,
postTypes: {
type: 'array',
default: [ 'post' ]
}
};
return settings;
}
addFilter(
'blocks.registerBlockType',
'wpse326869/latest-posts-post-types/add-attribute',
addPostTypesAttribute
);
```
Add Controls to Interact with New Attributes
--------------------------------------------
### Filter the Edit Component
[The `editor.BlockEdit` filter](https://developer.wordpress.org/block-editor/reference-guides/filters/block-filters/#editor-blockedit) allows us to interact with/modify the component returned from the block's `edit()` function.
### Shim Components and Functionality with a HOC
[The `@wordpress/compose` package](https://www.npmjs.com/package/@wordpress/compose) provides a handy utility for "wrapping" a component in a [Higher-Order Component/"HOC"](https://reactjs.org/docs/higher-order-components.html) (a function which takes a component as an argument and returns an augmented or wrapped version of it), effectively allowing us to shim our own components and functionality into a pre-existing component.
### Place Sidebar Controls with the SlotFills System
To [add control components for a block to the sidebar](https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/block-controls-toolbar-and-sidebar/), we simply add them as children of an `<InspectorControls>` component, and [Gutenberg's nifty `SlotFills` system](https://developer.wordpress.org/block-editor/reference-guides/slotfills/) will render them outside of the block in the appropriate location.
### Select a Control
In my opinion, [`FormTokenField`](https://wordpress.github.io/gutenberg/?path=/story/components-formtokenfield--default) is the perfect component to allow the user to enter a number of different post types. But a [`SelectControl`](https://wordpress.github.io/gutenberg/?path=/story/components-selectcontrol--default) or [`ComboboxControl`](https://wordpress.github.io/gutenberg/?path=/story/components-comboboxcontrol--default) might be more appropriate for your use-case.
Some amount of documentation for most controls can be found in [The Block Editor Handboox](https://developer.wordpress.org/block-editor/reference-guides/components/form-token-field/), but often times you might find that you need to scour [the sources on GitHub](https://github.com/WordPress/gutenberg/tree/trunk/packages/components/src/form-token-field) to make sense of everything.
### Implementation
All the above in mind, we can add controls to interact with our new `postTypes` attribute as such:
```js
import { createHigherOrderComponent } from '@wordpress/compose';
import { Fragment } from '@wordpress/element';
import { InspectorControls } from '@wordpress/block-editor';
import { FormTokenField } from '@wordpress/components'
import { useSelect } from '@wordpress/data';
// A multiple Post-Type selection control implemented on top of FormTokenField.
const PostTypesControl = ( props ) => {
const { value = [], onChange } = props;
const types = useSelect(
( select ) => ( select( 'core' ).getPostTypes() ?? [] ).map( ( { slug, name } ) => ( { value: slug, title: name } ) ),
[]
);
const tokenIsValid = ( title ) => types.some( type => type.title === title );
const titleToValue = ( title ) => title ? types.find( type => type.title === title )?.value || '' : '';
return (
<FormTokenField
value={ value }
onChange={ onChange }
suggestions={ types.map( type => type.title ) }
saveTransform={ titleToValue }
__experimentalValidateInput={ tokenIsValid }
/>
);
};
// A HOC which adds a PostTypesControl to a block which has a `postTypes` attribute.
const withPostTypesControl = createHigherOrderComponent(
( BlockEdit ) => ( props ) => {
const {
name,
attributes: { postTypes = [ 'post' ] },
setAttributes,
} = props;
if( name !== 'core/latest-posts' )
return <BlockEdit {...props} />;
const setPostTypes = ( postTypes ) => setAttributes( { postTypes } );
return (
<Fragment>
<BlockEdit {...props} />
<InspectorControls>
<PanelBody title="Post Types" initialOpen={false}>
<PanelRow>
<PostTypesControl
value={ postTypes }
onChange={ setPostTypes }
/>
</PanelRow>
</PanelBody>
</InspectorControls>
</Fragment>
);
},
'wpse326869withPostTypesControl'
);
addFilter(
'editor.BlockEdit',
'wpse326869/latest-posts-post-types/add-controls',
withPostTypesControl
);
```
Use the Attribute to Filter Posts Query
---------------------------------------
Were Latest Posts a static block type which rendered it's content directly to HTML stored in the `post_content`, we'd probably use a `blocks.getSaveElement` filter here to use the attribute and modify the markup.
But Latest Posts is a dynamic block, meaning that when WordPress renders the block on the front-end it executes a PHP function in order to produce the content per page-load, just like a shortcode.
Unfortunately, looking at [the source for the PHP function responsible for rendering the block](https://github.com/WordPress/gutenberg/blob/dbba2600e2dbe0a118d492b6681d9f33d1abd30a/packages/block-library/src/latest-posts/index.php#L36), there's no useful filter to modify the arguments which are sent to `get_posts()`...
What we can do, however, is get a little hacky and use a [`block_type_metadata_settings` filter](https://developer.wordpress.org/reference/hooks/block_type_metadata_settings/) to hijack the Latest Post block's PHP render callback - **this generally seems inadvisable; I probably wouldn't distribute code leveraging such a hack.** In our custom render callback, we can add a `pre_get_posts` filter to add our `postTypes` attribute to the query, execute the original render callback, and then remove the filter once more.
For ease of state management between these functions, I've chosen to use a singleton class to implement the above.
```php
class WPSE326869_LatestPostsPostTypes {
protected static $instance = null;
protected $original_render_callback;
protected $block_attributes;
protected function __construct() {
add_filter( 'block_type_metadata_settings', [ $this, 'filter_block_settings' ], 10, 2 );
}
public static function get_instance() {
if( is_null( self::$instance ) )
self::$instance = new self();
return self::$instance;
}
public function filter_block_settings( $args, $data ) {
if( $data['name'] !== 'core/latest-posts' )
return $args;
$this->original_render_callback = $args['render_callback'];
$args['render_callback'] = [ $this, 'render_block' ];
return $args;
}
public function latest_posts_query_types( $query ) {
if( empty( $this->block_attributes['postTypes'] ) )
return;
$public_types = get_post_types(
[
'show_in_rest' => true,
]
);
$types = array_intersect( $public_types, $this->block_attributes['postTypes'] );
$query->set( 'post_type', $types );
}
public function render_block( $attributes, $block_content, $block ) {
$this->block_attributes = $attributes;
add_filter( 'pre_get_posts', [ $this, 'latest_posts_query_types' ] );
$block_content = (string) call_user_func( $this->original_render_callback, $attributes, $block_content, $block );
remove_filter( 'pre_get_posts', [ $this, 'latest_posts_query_types' ] );
return $block_content;
}
}
WPSE326869_LatestPostsPostTypes::get_instance();
```
---
Summary & Point of Failure
==========================
What Works
----------
All of the above in place, we end up with a function "Post Types" control added to the Latest Post block's sidebar settings (with autocomplete suggestions, to boot!) which stores it's values in a new attribute added to the block, and uses that attribute to appropriately adjust the block's server-side query.
At this point, the modified block will successfully display post-type filtered latest posts on the front-end!
What Doesn't
------------
Back in the Block Editor, however, there's a little wonkiness afoot. It all boils down to [the `edit()` component using a REST API request hard-coded for the `post` post-type](https://github.com/WordPress/gutenberg/blob/b33794de5a71df92b42562f326ebdec2d10ff6d8/packages/block-library/src/latest-posts/edit.js#L103) in order to quickly deliver visual updates in the editor instead of the block's PHP render callback. The result is that the block does not display posts of the selected types within the editor.
You might think to use more `pre_get_posts` hackery to modify the results of that query - but doing so could well lead to the Gutenberg data stores incorrectly classifying the results as `posts`, which could cause all sorts of other issues.
The only functional approach I can see would be to totally abuse the `editor.BlockEdit` filter and completely replace the block's `edit()` component. While that should be possible on paper, I feel it would be such an egregious no-no that I will not explore or demonstrate the possibility. Silently swapping out the implementation of core functionality on-the-fly is a sure-fire way to create bugs, confusion, and chaos.
What Might, Someday
-------------------
I haven't dug into it too far, but [the PRs which introduced the Latest Posts Block](https://github.com/WordPress/gutenberg/pull/870) and [the Server Side Rendering solution](https://github.com/WordPress/gutenberg/pull/5602) both heavily reference each other. I haven't researched why the Latest Posts block ultimately did not end up using the SSR component for rendering in the Block Editor. If it ever did however, I believe the solution implemented above would be fully functional.
It's also possible that core will introduce more applicable block filters or even additional props to the Latest Posts block which would make this more plausible. |
326,894 | <p>How can change the text for "Select a category" in the product category widget?</p>
<p><a href="https://i.stack.imgur.com/DeQTo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DeQTo.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 326898,
"author": "obiPlabon",
"author_id": 135737,
"author_profile": "https://wordpress.stackexchange.com/users/135737",
"pm_score": 1,
"selected": false,
"text": "<p>Use the following code snippet, hope it'll work for you. I've tested it on my dev machine and it works just fine.</p>\n\n<pre><code>/**\n * Change product category dropdown placeholder text.\n *\n * Product category dropdown uses selectWoo/select2\n * that's why it's not possible to change the placeholder text using\n * woocommerce_product_categories_widget_dropdown_args filter hook.\n *\n * data-placeholder=\"\" is select2 standard data api.\n *\n * @param string $html Dropdown html\n * @param array $args Dropdown setup arguments\n *\n * @return string Updated $html\n */\nadd_filter( 'wp_dropdown_cats', function( $html, $args ) {\n if ( $args['taxonomy'] === 'product_cat' ) {\n $html = str_replace( '<select', '<select data-placeholder=\"Custom placeholder\"', $html );\n }\n return $html;\n}, 10, 2);\n</code></pre>\n"
},
{
"answer_id": 356591,
"author": "Dharmishtha Patel",
"author_id": 135085,
"author_profile": "https://wordpress.stackexchange.com/users/135085",
"pm_score": 1,
"selected": true,
"text": "<pre><code>function _category_dropdown_filter( $cat_args ) {\n $cat_args['show_option_none'] = __('My Category');\n return $cat_args;\n}\nadd_filter( 'widget_categories_dropdown_args', '_category_dropdown_filter' );\n</code></pre>\n"
}
] | 2019/01/28 | [
"https://wordpress.stackexchange.com/questions/326894",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/135085/"
] | How can change the text for "Select a category" in the product category widget?
[](https://i.stack.imgur.com/DeQTo.png) | ```
function _category_dropdown_filter( $cat_args ) {
$cat_args['show_option_none'] = __('My Category');
return $cat_args;
}
add_filter( 'widget_categories_dropdown_args', '_category_dropdown_filter' );
``` |
326,900 | <p>My website is running on WordPress version <code>4.9.8</code>.</p>
<p>When I go to <code><mysite>/wp-admin/update-core.php</code>, it says,</p>
<blockquote>
<p>You have the latest version of WordPress. Future security updates will
be applied automatically.</p>
</blockquote>
<p><strong>I want to upgrade my site to version 5.0.x</strong></p>
<p>How can I do that?</p>
| [
{
"answer_id": 326898,
"author": "obiPlabon",
"author_id": 135737,
"author_profile": "https://wordpress.stackexchange.com/users/135737",
"pm_score": 1,
"selected": false,
"text": "<p>Use the following code snippet, hope it'll work for you. I've tested it on my dev machine and it works just fine.</p>\n\n<pre><code>/**\n * Change product category dropdown placeholder text.\n *\n * Product category dropdown uses selectWoo/select2\n * that's why it's not possible to change the placeholder text using\n * woocommerce_product_categories_widget_dropdown_args filter hook.\n *\n * data-placeholder=\"\" is select2 standard data api.\n *\n * @param string $html Dropdown html\n * @param array $args Dropdown setup arguments\n *\n * @return string Updated $html\n */\nadd_filter( 'wp_dropdown_cats', function( $html, $args ) {\n if ( $args['taxonomy'] === 'product_cat' ) {\n $html = str_replace( '<select', '<select data-placeholder=\"Custom placeholder\"', $html );\n }\n return $html;\n}, 10, 2);\n</code></pre>\n"
},
{
"answer_id": 356591,
"author": "Dharmishtha Patel",
"author_id": 135085,
"author_profile": "https://wordpress.stackexchange.com/users/135085",
"pm_score": 1,
"selected": true,
"text": "<pre><code>function _category_dropdown_filter( $cat_args ) {\n $cat_args['show_option_none'] = __('My Category');\n return $cat_args;\n}\nadd_filter( 'widget_categories_dropdown_args', '_category_dropdown_filter' );\n</code></pre>\n"
}
] | 2019/01/28 | [
"https://wordpress.stackexchange.com/questions/326900",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/160014/"
] | My website is running on WordPress version `4.9.8`.
When I go to `<mysite>/wp-admin/update-core.php`, it says,
>
> You have the latest version of WordPress. Future security updates will
> be applied automatically.
>
>
>
**I want to upgrade my site to version 5.0.x**
How can I do that? | ```
function _category_dropdown_filter( $cat_args ) {
$cat_args['show_option_none'] = __('My Category');
return $cat_args;
}
add_filter( 'widget_categories_dropdown_args', '_category_dropdown_filter' );
``` |
326,931 | <p>I have created a post type and a taxonomy for this post type .</p>
<p>After I create a page to display all taxonomies for the post type.</p>
<p>When i'm click on one of the taxonomy displayed I would like to show all post type linked to this taxonomy .</p>
<p>Actually my loop is:</p>
<pre><code>$last_post = new WP_Query( array(
'post_type' => 'conseil',
'post_status' => 'publish',
'posts_per_page' => -1
));
</code></pre>
<p>I know I must create an array with the taxonomy name but it's not working..</p>
| [
{
"answer_id": 326933,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p>You shouldn't need to use a custom query for this. Just link to the term's existing archive page which will automatically list all posts in that term. You can do this using <a href=\"https://developer.wordpress.org/reference/functions/get_term_link/\" rel=\"nofollow noreferrer\"><code>get_term_link()</code></a>. For example, this displays the URLs for each term in the taxonomy:</p>\n\n<pre><code>$terms = get_terms( [ 'taxonomy' => 'conseil' ] );\n\nforeach ( $terms as $term ) {\n echo esc_url( get_term_link( $term ) );\n}\n</code></pre>\n"
},
{
"answer_id": 326938,
"author": "Damien Denis",
"author_id": 160037,
"author_profile": "https://wordpress.stackexchange.com/users/160037",
"pm_score": 0,
"selected": false,
"text": "<p>Actually I use that code in a different way to get the current taxonomy name:</p>\n\n<pre><code><?php\n $tax = $wp_query->get_queried_object();\n\n $args = array(\n 'posts_per_page' => -1,\n 'post_type' => 'conseil', // Custom Post Type like Movies\n 'tax_query' => array(\n array(\n 'taxonomy' => 'type-conseils', //Custom Taxonomy Name \n 'field' => 'slug',\n 'terms' => array(\n $tax->name\n )\n )\n )\n );\n\n\n $new = new WP_Query($args);\n\n if (have_posts()):\n\n while ($new->have_posts()) : $new->the_post();\n // do things\n</code></pre>\n\n<p>?></p>\n"
}
] | 2019/01/28 | [
"https://wordpress.stackexchange.com/questions/326931",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/160037/"
] | I have created a post type and a taxonomy for this post type .
After I create a page to display all taxonomies for the post type.
When i'm click on one of the taxonomy displayed I would like to show all post type linked to this taxonomy .
Actually my loop is:
```
$last_post = new WP_Query( array(
'post_type' => 'conseil',
'post_status' => 'publish',
'posts_per_page' => -1
));
```
I know I must create an array with the taxonomy name but it's not working.. | You shouldn't need to use a custom query for this. Just link to the term's existing archive page which will automatically list all posts in that term. You can do this using [`get_term_link()`](https://developer.wordpress.org/reference/functions/get_term_link/). For example, this displays the URLs for each term in the taxonomy:
```
$terms = get_terms( [ 'taxonomy' => 'conseil' ] );
foreach ( $terms as $term ) {
echo esc_url( get_term_link( $term ) );
}
``` |
326,943 | <p>This is something I have never tried so far. On a webspace I want to have a subdirectory like this:</p>
<blockquote>
<p>blognetwork.example.com</p>
</blockquote>
<p>Then I want to run Multisite with subdirectories like this:</p>
<pre><code>blognetwork.example.com/blog/
blognetwork.example.com/site1/
blognetwork.example.com/site2/
</code></pre>
<p>Is this possible or will it lead to unpredictable issues? Someone ever tried this?</p>
| [
{
"answer_id": 326944,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>Yes, it is.</p>\n\n<p>All you need to do is to install your WordPress on the subdomain, turn the Multisite on and set it to use subdirectories for sites.</p>\n\n<p>Make sure the following is set in multisite constants:</p>\n\n<pre><code>define( 'SUBDOMAIN_INSTALL', false );\n</code></pre>\n"
},
{
"answer_id": 326946,
"author": "Gufran Hasan",
"author_id": 137328,
"author_profile": "https://wordpress.stackexchange.com/users/137328",
"pm_score": 1,
"selected": false,
"text": "<p>Yes, you can do it by putting this <code>define('WP_ALLOW_MULTISITE', true);</code> in <code>config.php</code> file.</p>\n\n<p><a href=\"https://www.wpbeginner.com/wp-tutorials/how-to-install-and-setup-wordpress-multisite-network/\" rel=\"nofollow noreferrer\">For mere please follow this link</a></p>\n"
}
] | 2019/01/28 | [
"https://wordpress.stackexchange.com/questions/326943",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/12035/"
] | This is something I have never tried so far. On a webspace I want to have a subdirectory like this:
>
> blognetwork.example.com
>
>
>
Then I want to run Multisite with subdirectories like this:
```
blognetwork.example.com/blog/
blognetwork.example.com/site1/
blognetwork.example.com/site2/
```
Is this possible or will it lead to unpredictable issues? Someone ever tried this? | Yes, it is.
All you need to do is to install your WordPress on the subdomain, turn the Multisite on and set it to use subdirectories for sites.
Make sure the following is set in multisite constants:
```
define( 'SUBDOMAIN_INSTALL', false );
``` |
326,959 | <p>I'm writing a function to allow only some custom blocks - essentially I want to register all the blocks, then based on a database table of 'selected' blocks disallow any other custom block. </p>
<p>I can use <code>allowed_block_types</code> to make an array of allowed blocks, but it wipes all the core ones, is there a way to either get a reliable list of core blocks, or only add a filter for plugin/theme registered blocks? Or possibly, allow all block
categories then my own block category is filtered?</p>
| [
{
"answer_id": 326963,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 4,
"selected": true,
"text": "<p>AFAIK there is only one way to remove blocks from Gutenberg - you have to use <code>allowed_block_types</code> filter.</p>\n\n<p>Unfortunately Gutenberg developers are not very familiar with WordPress hooks and filters, so they created a little monster with this one. So instead of passing a list of core blocks in there, they pass <code>true</code> to enable all blocks. That way you're unable to obtain the list of all blocks registered.</p>\n\n<p>So if you want to disable just one block, then you have to get all blocks bu yourself...</p>\n\n<p>Here's the list of core blocks:</p>\n\n<ul>\n<li>core/shortcode</li>\n<li>core/image</li>\n<li>core/gallery</li>\n<li>core/heading</li>\n<li>core/quote</li>\n<li>core/embed</li>\n<li>core/list</li>\n<li>core/separator</li>\n<li>core/more</li>\n<li>core/button</li>\n<li>core/pullquote</li>\n<li>core/table</li>\n<li>core/preformatted</li>\n<li>core/code</li>\n<li>core/html</li>\n<li>core/freeform</li>\n<li>core/latest-posts</li>\n<li>core/categories</li>\n<li>core/cover (previously <code>core/cover-image</code>)</li>\n<li>core/text-columns</li>\n<li>core/verse</li>\n<li>core/video</li>\n<li>core/audio</li>\n<li>core/block</li>\n<li><p>core/paragraph</p></li>\n<li><p>core-embed/twitter</p></li>\n<li>core-embed/youtube</li>\n<li>core-embed/facebook</li>\n<li>core-embed/instagram</li>\n<li>core-embed/wordpress</li>\n<li>core-embed/soundcloud</li>\n<li>core-embed/spotify</li>\n<li>core-embed/flickr</li>\n<li>core-embed/vimeo</li>\n<li>core-embed/animoto</li>\n<li>core-embed/cloudup</li>\n<li>core-embed/collegehumor</li>\n<li>core-embed/dailymotion</li>\n<li>core-embed/funnyordie</li>\n<li>core-embed/hulu</li>\n<li>core-embed/imgur</li>\n<li>core-embed/issuu</li>\n<li>core-embed/kickstarter</li>\n<li>core-embed/meetup-com</li>\n<li>core-embed/mixcloud</li>\n<li>core-embed/photobucket</li>\n<li>core-embed/polldaddy</li>\n<li>core-embed/reddit</li>\n<li>core-embed/reverbnation</li>\n<li>core-embed/screencast</li>\n<li>core-embed/scribd</li>\n<li>core-embed/slideshare</li>\n<li>core-embed/smugmug</li>\n<li>core-embed/speaker</li>\n<li>core-embed/ted</li>\n<li>core-embed/tumblr</li>\n<li>core-embed/videopress</li>\n<li>core-embed/wordpress-tv</li>\n</ul>\n\n<h2>On the other hand...</h2>\n\n<p>It's a lot easier to unregister given block in JS... In there you can use:</p>\n\n<pre><code>wp.blocks.unregisterBlockType( 'core/verse' );\n</code></pre>\n"
},
{
"answer_id": 326969,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 4,
"selected": false,
"text": "<p>There's a <strong>whitelist</strong> blocks removal example from the <a href=\"https://wordpress.org/gutenberg/handbook/designers-developers/developers/filters/block-filters/#using-a-whitelist\" rel=\"noreferrer\">Gutenberg Handbook</a>:</p>\n\n<pre><code>var allowedBlocks = [\n 'core/paragraph',\n 'core/image',\n 'core/html',\n 'core/freeform'\n];\n\nwp.blocks.getBlockTypes().forEach( function( blockType ) {\n if ( allowedBlocks.indexOf( blockType.name ) === -1 ) {\n wp.blocks.unregisterBlockType( blockType.name );\n }\n} );\n</code></pre>\n\n<p>One might try to modify it to remove blocks that do not start with <code>core</code> and are not part of <code>allowedExtraBlocks</code> (untested):</p>\n\n<pre><code>var allowedExtraBlocks = [\n 'my-plugin/block-example-1',\n 'my-plugin/block-example-2'\n];\n\nwp.blocks.getBlockTypes().forEach( function( blockType ) {\n if ( ! blockType.name.startsWith( 'core' )\n && allowedExtraBlocks.indexOf( blockType.name ) === -1\n ) {\n wp.blocks.unregisterBlockType( blockType.name );\n }\n} );\n</code></pre>\n\n<p>One could adjust this further to match block names that start with <code>core/</code> or <code>core-embed/</code> instead of <code>core</code> to be more precise.</p>\n\n<p>The <a href=\"https://wordpress.org/gutenberg/handbook/designers-developers/developers/filters/block-filters/#using-a-blacklist\" rel=\"noreferrer\">blacklist example</a> wraps it with: </p>\n\n<pre><code>wp.domReady( function() {\n // ...\n} );\n</code></pre>\n\n<p>so this might be needed for the whitelist example too.</p>\n\n<hr>\n\n<p>Here's a quick way to see available blocks on the editing page, in the browser's console:</p>\n\n<p>In the 5.1 version there are 70 core blocks available, according to </p>\n\n<pre><code>wp.blocks.getBlockTypes().length;\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/FI3LZ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/FI3LZ.png\" alt=\"number of core blocks\"></a></p>\n\n<p>The list of available block names:</p>\n\n<pre><code>wp.blocks.getBlockTypes().forEach( function( blockType ){ console.log( blockType.name ); }); \n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/e1LEe.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/e1LEe.png\" alt=\"block names\"></a></p>\n\n<p>Here's a table of available blocks:</p>\n\n<pre><code>console.table( wp.blocks.getBlockTypes() );\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/gzkDq.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/gzkDq.png\" alt=\"Table of available blocks\"></a></p>\n"
},
{
"answer_id": 379095,
"author": "sebix",
"author_id": 198298,
"author_profile": "https://wordpress.stackexchange.com/users/198298",
"pm_score": 2,
"selected": false,
"text": "<p>@birgire 's answer is very good.\n<a href=\"https://wordpress.stackexchange.com/a/326969/198298\">https://wordpress.stackexchange.com/a/326969/198298</a></p>\n<p>Some information might be missing though.</p>\n<p>As @birgire guesses, it really is necessary to wrap the code inside a</p>\n<pre class=\"lang-js prettyprint-override\"><code>wp.domReady( function() {\n // ...\n} );\n</code></pre>\n<p>even if the script is loaded with the dependencies <code>array( 'wp-blocks', 'wp-dom-ready', 'wp-edit-post' )</code> like it is recommended in the <a href=\"https://developer.wordpress.org/block-editor/developers/filters/block-filters/#using-a-deny-list\" rel=\"nofollow noreferrer\">block filters guide</a>.</p>\n<p>Speaking of loading: If you're no plugin developer (like me) but only want to remove some block types for the users of your (company's) blog, you should load\nthe js file for this in your child-theme's <code>functions.php</code> like that:</p>\n<pre class=\"lang-php prettyprint-override\"><code>/** Allow js-side adjustments to block editor (aka Gutenberg), i.e. remove certain block types. */\nfunction my_childtheme_enqueue_block_editor_adj() {\n wp_enqueue_script(\n 'block-editor-adjustments',\n get_stylesheet_directory_uri() . '/js/block-editor-adjustments.js',\n array( 'wp-blocks', 'wp-dom-ready', 'wp-edit-post' ),\n );\n}\nadd_action( 'enqueue_block_editor_assets', 'my_childtheme_enqueue_block_editor_adj' );\n</code></pre>\n<p>My js file looks like this:</p>\n<pre class=\"lang-js prettyprint-override\"><code>wp.domReady(function () {\n /**\n * Remove some blocks from the block editor.\n * This is not possible in php unfortunately.\n */\n wp.blocks.unregisterBlockType('core/embed');\n\n var allowedEmbedBlocks = [\n 'core-embed/twitter',\n 'core-embed/youtube',\n 'core-embed/facebook',\n 'core-embed/instagram',\n 'core-embed/wordpress',\n 'core-embed/flickr',\n 'core-embed/vimeo',\n ];\n\n wp.blocks.getBlockTypes().forEach(function (blockType) {\n if (blockType.name.startsWith('core-embed')\n && allowedEmbedBlocks.indexOf(blockType.name) === -1\n ) {\n wp.blocks.unregisterBlockType(blockType.name);\n }\n });\n});\n</code></pre>\n<p>This way I can now focus on the embed options in <code>allowedEmbedBlocks</code> regarding the Usercentrics data privacy settings.</p>\n"
},
{
"answer_id": 379624,
"author": "Jules",
"author_id": 5986,
"author_profile": "https://wordpress.stackexchange.com/users/5986",
"pm_score": 2,
"selected": false,
"text": "<p><code>core-embed</code> does no longer exist in the latest version of the Gutenberg editor. All embeds now seem to be block variations of <code>core/embed</code>. So you cannot unregister the default <code>core/embed</code> block, because if you do, you will automatically unregister all its variations. However, you can unregister any variations with <code>wp.blocks.unregisterBlockVariation(blockName, variationName)</code>.</p>\n<p><strong>Example</strong>: only allow the YouTube embed block:</p>\n<pre><code>wp.domReady( function() {\n const allowedEmbedBlocks = [\n 'youtube',\n ];\n\n wp.blocks.getBlockType( 'core/embed' ).variations.forEach( function( blockVariation ) {\n if (\n allowedEmbedBlocks.indexOf( blockVariation.name ) === -1\n ) {\n wp.blocks.unregisterBlockVariation( 'core/embed', blockVariation.name );\n }\n } );\n} );\n</code></pre>\n<p>(Sadly you will still be able to use the regular embed block as well. I'm not sure yet how this can be removed.)</p>\n"
},
{
"answer_id": 413407,
"author": "Erik",
"author_id": 127675,
"author_profile": "https://wordpress.stackexchange.com/users/127675",
"pm_score": 0,
"selected": false,
"text": "<p>This is a one liner solution to remove all blocks that aren't of the core group:</p>\n<pre><code>wp.blocks.getBlockTypes()\n.filter( b => ! b.name.startsWith('core') )\n.forEach( b => wp.blocks.unregisterBlockType(b.name) )\n</code></pre>\n<p>I hope it will be useful to someone in the future!</p>\n"
}
] | 2019/01/28 | [
"https://wordpress.stackexchange.com/questions/326959",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/49852/"
] | I'm writing a function to allow only some custom blocks - essentially I want to register all the blocks, then based on a database table of 'selected' blocks disallow any other custom block.
I can use `allowed_block_types` to make an array of allowed blocks, but it wipes all the core ones, is there a way to either get a reliable list of core blocks, or only add a filter for plugin/theme registered blocks? Or possibly, allow all block
categories then my own block category is filtered? | AFAIK there is only one way to remove blocks from Gutenberg - you have to use `allowed_block_types` filter.
Unfortunately Gutenberg developers are not very familiar with WordPress hooks and filters, so they created a little monster with this one. So instead of passing a list of core blocks in there, they pass `true` to enable all blocks. That way you're unable to obtain the list of all blocks registered.
So if you want to disable just one block, then you have to get all blocks bu yourself...
Here's the list of core blocks:
* core/shortcode
* core/image
* core/gallery
* core/heading
* core/quote
* core/embed
* core/list
* core/separator
* core/more
* core/button
* core/pullquote
* core/table
* core/preformatted
* core/code
* core/html
* core/freeform
* core/latest-posts
* core/categories
* core/cover (previously `core/cover-image`)
* core/text-columns
* core/verse
* core/video
* core/audio
* core/block
* core/paragraph
* core-embed/twitter
* core-embed/youtube
* core-embed/facebook
* core-embed/instagram
* core-embed/wordpress
* core-embed/soundcloud
* core-embed/spotify
* core-embed/flickr
* core-embed/vimeo
* core-embed/animoto
* core-embed/cloudup
* core-embed/collegehumor
* core-embed/dailymotion
* core-embed/funnyordie
* core-embed/hulu
* core-embed/imgur
* core-embed/issuu
* core-embed/kickstarter
* core-embed/meetup-com
* core-embed/mixcloud
* core-embed/photobucket
* core-embed/polldaddy
* core-embed/reddit
* core-embed/reverbnation
* core-embed/screencast
* core-embed/scribd
* core-embed/slideshare
* core-embed/smugmug
* core-embed/speaker
* core-embed/ted
* core-embed/tumblr
* core-embed/videopress
* core-embed/wordpress-tv
On the other hand...
--------------------
It's a lot easier to unregister given block in JS... In there you can use:
```
wp.blocks.unregisterBlockType( 'core/verse' );
``` |
326,974 | <p>I am using the following code for displaying a custom attribute on the Woocommerce shop page. But for some reason, the year is displayed above the product image instead of after the product title (In between the product title and the price). </p>
<pre><code>add_action('woocommerce_after_shop_loop_item_title', 'YearOfMake', 10);
function YearOfMake()
{
global $product;
$abv = $product->get_attribute('year-made');
if (empty($abv))
return;
echo __($abv, 'woocommerce');
}
</code></pre>
<p>Link: <a href="https://groovygarbs.com/cars/" rel="nofollow noreferrer">https://groovygarbs.com/cars/</a></p>
| [
{
"answer_id": 326989,
"author": "Zeshan",
"author_id": 50543,
"author_profile": "https://wordpress.stackexchange.com/users/50543",
"pm_score": 0,
"selected": false,
"text": "<pre><code>add_action('woocommerce_after_shop_loop_item_title', 'YearOfMake', 15);\nfunction YearOfMake()\n{\n global $product;\n $attribute = 'year-made';\n $abv = $product->get_attribute($attribute);\n if(!empty($abv))\n {\n echo '<p>' . $abv . '</p>';\n }\n}\n</code></pre>\n"
},
{
"answer_id": 327091,
"author": "Zeshan",
"author_id": 50543,
"author_profile": "https://wordpress.stackexchange.com/users/50543",
"pm_score": 1,
"selected": false,
"text": "<pre><code>add_filter( 'the_title', 'YearOfMake', 10, 2 );\nfunction YearOfMake( $title, $post_id ) \n{\n\n if ( get_post_type( $post_id ) != 'product' && ! is_archive() )\n return $title;\n\n if ( ! ( is_shop() || is_product_category() || is_product_tag() ) )\n return $title;\n /*\n global $product;\n $attribute = 'year-made';\n $abv = $product->get_attribute($attribute);\n if(!empty($abv))\n {\n $title .= '<br /><p>' . $abv . '</p>';\n }\n */\n $terms = wp_get_post_terms( $post_id, 'product_tag' );\n $term = reset( $terms );\n if ( !empty( $term->name ))\n {\n $title .= '<br /><p>' . strtoupper( $term->name ) . '</p>';\n }\n return $title;\n}\n</code></pre>\n"
}
] | 2019/01/28 | [
"https://wordpress.stackexchange.com/questions/326974",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145088/"
] | I am using the following code for displaying a custom attribute on the Woocommerce shop page. But for some reason, the year is displayed above the product image instead of after the product title (In between the product title and the price).
```
add_action('woocommerce_after_shop_loop_item_title', 'YearOfMake', 10);
function YearOfMake()
{
global $product;
$abv = $product->get_attribute('year-made');
if (empty($abv))
return;
echo __($abv, 'woocommerce');
}
```
Link: <https://groovygarbs.com/cars/> | ```
add_filter( 'the_title', 'YearOfMake', 10, 2 );
function YearOfMake( $title, $post_id )
{
if ( get_post_type( $post_id ) != 'product' && ! is_archive() )
return $title;
if ( ! ( is_shop() || is_product_category() || is_product_tag() ) )
return $title;
/*
global $product;
$attribute = 'year-made';
$abv = $product->get_attribute($attribute);
if(!empty($abv))
{
$title .= '<br /><p>' . $abv . '</p>';
}
*/
$terms = wp_get_post_terms( $post_id, 'product_tag' );
$term = reset( $terms );
if ( !empty( $term->name ))
{
$title .= '<br /><p>' . strtoupper( $term->name ) . '</p>';
}
return $title;
}
``` |
326,983 | <p>I'm trying to learn how to create blocks for the block editor. I can't seem to find a list of form elements to add. For example, I need a toggle switch, dropdown, etc.</p>
<p>I found <a href="https://github.com/WordPress/gutenberg/tree/master/packages/components/src/toggle-control" rel="nofollow noreferrer">THIS toggle</a>, but I'm not sure how to use it and can't find any examples.</p>
<p>Here is my code, so far I have been able to add PlainText, RichText and MediaUpload. Is there a list of these somewhere? More examples?</p>
<pre><code>const { RichText, MediaUpload, PlainText } = wp.editor;
const { registerBlockType } = wp.blocks;
const { Button } = wp.components;
import './style.scss';
import './editor.scss';
registerBlockType('card-block/main', {
title: 'Slider',
icon: 'images-alt2',
category: 'common',
attributes: {
title: {
source: 'text',
selector: '.slider__title'
},
body: {
type: 'array',
source: 'children',
selector: '.slider__body'
},
imageAlt: {
attribute: 'alt',
selector: '.slider__image'
},
imageUrl: {
attribute: 'src',
selector: '.slider__image'
}
},
edit({ attributes, className, setAttributes }) {
const getImageButton = (openEvent) => {
if (attributes.imageUrl) {
return (
<img
src={attributes.imageUrl}
onClick={openEvent}
className="image"
/>
);
}
else {
return (
<div className="button-container">
<Button
onClick={openEvent}
className="button button-large"
>
Pick an Image
</Button>
</div>
);
}
};
return(
<div className="container">
<MediaUpload
onSelect={media => { setAttributes({ imageAlt: media.alt, imageUrl: media.url }); }}
type="image"
value={attributes.imageID}
render={({ open }) => getImageButton(open)}
/>
<PlainText
onChange={content => setAttributes({ title: content })}
value={attributes.title}
placeholder="Your card title"
className="heading"
/>
<RichText
onChange={content => setAttributes({ body: content })}
value={attributes.body}
multiline="p"
placeholder="Your card text"
/>
</div>
);
},
save({ attributes }) {
const cardImage = (src, alt) => {
if (!src) return null;
if (alt) {
return (
<img
className="slider__image"
src={src}
alt={alt}
/>
);
}
return (
<img
className="slider__image"
src={src}
alt=""
aria-hidden="true"
/>
);
};
return (
<div className="card">
{cardImage(attributes.imageUrl, attributes.imageAlt)}
<div className="slider__content">
<h3 className="slider__title">{attributes.title}</h3>
<div className="slider__body">
{attributes.body}
</div>
</div>
</div>
);
}
});
</code></pre>
<p>Any help would be greatly appreciated! I am picking up ES6 & JSX as well so this has been a pain! </p>
| [
{
"answer_id": 326984,
"author": "Alvaro",
"author_id": 16533,
"author_profile": "https://wordpress.stackexchange.com/users/16533",
"pm_score": 2,
"selected": false,
"text": "<p>There are two main packages that provide components which can be used inside the <a href=\"https://github.com/WordPress/gutenberg/tree/master/packages/blocks\" rel=\"nofollow noreferrer\">blocks API</a> or the <a href=\"https://github.com/WordPress/gutenberg/tree/master/packages/blocks\" rel=\"nofollow noreferrer\">plugins API</a> (to create your own blocks or plugins).</p>\n\n<p>The components found in the <a href=\"https://github.com/WordPress/gutenberg/tree/master/packages/components/src\" rel=\"nofollow noreferrer\"><strong>wp.components</strong> package</a> can be used to manipulate data. This data could be the attributes from a block or the data from your custom store or one of the <a href=\"https://github.com/WordPress/gutenberg/tree/master/docs/designers-developers/developers/data\" rel=\"nofollow noreferrer\">default stores</a>. They can actually be used outside of the block editor.</p>\n\n<p>The components found in the <a href=\"https://github.com/WordPress/gutenberg/tree/master/packages/editor/src/components\" rel=\"nofollow noreferrer\"><strong>wp.editor</strong> package</a> are meant to be used inside the editor to manipulate it. They are used internally by the block editor itself or core blocks and can be used in your own blocks as well. These components make use of the block editor data stores so they have to be used inside it. Currently, the block editor can only be loaded inside the post editor but this is something that will probably <a href=\"https://github.com/WordPress/gutenberg/pull/13088\" rel=\"nofollow noreferrer\">change soon</a>.</p>\n"
},
{
"answer_id": 327018,
"author": "Ashiquzzaman Kiron",
"author_id": 78505,
"author_profile": "https://wordpress.stackexchange.com/users/78505",
"pm_score": 2,
"selected": false,
"text": "<p>You can use this Gutenberg handbook for component list - <a href=\"https://wordpress.org/gutenberg/handbook/designers-developers/developers/components/\" rel=\"nofollow noreferrer\">Component List</a> and if you don't want to keep track of what to import from where which component you can use this <a href=\"https://marketplace.visualstudio.com/items?itemName=ashiqkiron.gutensnip\" rel=\"nofollow noreferrer\">VSC Extension</a> (I build it) It will import all the component so that you don't have to waste time on importing.</p>\n\n<p><strong>Here's dropdown code -</strong> </p>\n\n<pre><code>import { Button, Dropdown } from '@wordpress/components';\n\nconst MyDropdown = () => (\n <Dropdown\n className=\"my-container-class-name\"\n contentClassName=\"my-popover-content-classname\"\n position=\"bottom right\"\n renderToggle={ ( { isOpen, onToggle } ) => (\n <Button isPrimary onClick={ onToggle } aria-expanded={ isOpen }>\n Toggle Popover!\n </Button>\n ) }\n renderContent={ () => (\n <div>\n This is the content of the popover.\n </div>\n ) }\n />\n);\n</code></pre>\n\n<p><strong>and ToggleControl code -</strong></p>\n\n<pre><code>import { ToggleControl } from '@wordpress/components';\nimport { withState } from '@wordpress/compose';\n\nconst MyToggleControl = withState( {\n hasFixedBackground: false,\n} )( ( { hasFixedBackground, setState } ) => ( \n <ToggleControl\n label=\"Fixed Background\"\n help={ hasFixedBackground ? 'Has fixed background.' : 'No fixed background.' } \n checked={ hasFixedBackground }\n onChange={ () => setState( ( state ) => ( { hasFixedBackground: ! state.hasFixedBackground } ) ) }\n />\n) );\n</code></pre>\n"
}
] | 2019/01/29 | [
"https://wordpress.stackexchange.com/questions/326983",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/157172/"
] | I'm trying to learn how to create blocks for the block editor. I can't seem to find a list of form elements to add. For example, I need a toggle switch, dropdown, etc.
I found [THIS toggle](https://github.com/WordPress/gutenberg/tree/master/packages/components/src/toggle-control), but I'm not sure how to use it and can't find any examples.
Here is my code, so far I have been able to add PlainText, RichText and MediaUpload. Is there a list of these somewhere? More examples?
```
const { RichText, MediaUpload, PlainText } = wp.editor;
const { registerBlockType } = wp.blocks;
const { Button } = wp.components;
import './style.scss';
import './editor.scss';
registerBlockType('card-block/main', {
title: 'Slider',
icon: 'images-alt2',
category: 'common',
attributes: {
title: {
source: 'text',
selector: '.slider__title'
},
body: {
type: 'array',
source: 'children',
selector: '.slider__body'
},
imageAlt: {
attribute: 'alt',
selector: '.slider__image'
},
imageUrl: {
attribute: 'src',
selector: '.slider__image'
}
},
edit({ attributes, className, setAttributes }) {
const getImageButton = (openEvent) => {
if (attributes.imageUrl) {
return (
<img
src={attributes.imageUrl}
onClick={openEvent}
className="image"
/>
);
}
else {
return (
<div className="button-container">
<Button
onClick={openEvent}
className="button button-large"
>
Pick an Image
</Button>
</div>
);
}
};
return(
<div className="container">
<MediaUpload
onSelect={media => { setAttributes({ imageAlt: media.alt, imageUrl: media.url }); }}
type="image"
value={attributes.imageID}
render={({ open }) => getImageButton(open)}
/>
<PlainText
onChange={content => setAttributes({ title: content })}
value={attributes.title}
placeholder="Your card title"
className="heading"
/>
<RichText
onChange={content => setAttributes({ body: content })}
value={attributes.body}
multiline="p"
placeholder="Your card text"
/>
</div>
);
},
save({ attributes }) {
const cardImage = (src, alt) => {
if (!src) return null;
if (alt) {
return (
<img
className="slider__image"
src={src}
alt={alt}
/>
);
}
return (
<img
className="slider__image"
src={src}
alt=""
aria-hidden="true"
/>
);
};
return (
<div className="card">
{cardImage(attributes.imageUrl, attributes.imageAlt)}
<div className="slider__content">
<h3 className="slider__title">{attributes.title}</h3>
<div className="slider__body">
{attributes.body}
</div>
</div>
</div>
);
}
});
```
Any help would be greatly appreciated! I am picking up ES6 & JSX as well so this has been a pain! | There are two main packages that provide components which can be used inside the [blocks API](https://github.com/WordPress/gutenberg/tree/master/packages/blocks) or the [plugins API](https://github.com/WordPress/gutenberg/tree/master/packages/blocks) (to create your own blocks or plugins).
The components found in the [**wp.components** package](https://github.com/WordPress/gutenberg/tree/master/packages/components/src) can be used to manipulate data. This data could be the attributes from a block or the data from your custom store or one of the [default stores](https://github.com/WordPress/gutenberg/tree/master/docs/designers-developers/developers/data). They can actually be used outside of the block editor.
The components found in the [**wp.editor** package](https://github.com/WordPress/gutenberg/tree/master/packages/editor/src/components) are meant to be used inside the editor to manipulate it. They are used internally by the block editor itself or core blocks and can be used in your own blocks as well. These components make use of the block editor data stores so they have to be used inside it. Currently, the block editor can only be loaded inside the post editor but this is something that will probably [change soon](https://github.com/WordPress/gutenberg/pull/13088). |
327,080 | <p>is it possible to alternate between two homepages in Wordpress without messing up SEO or anything unforeseen? We want to create Home-old and Home-new for A/B testing purposes. </p>
<p>Thank you!</p>
| [
{
"answer_id": 327083,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 0,
"selected": false,
"text": "<p>It depends on what and how you are making these changes. </p>\n\n<p>If you are changing the HTML, changing or moving elements around like headings, keys word, text, etc. than yes of course it can effect your SEO. Once Google re-indexing your site it could potentially effect SEO.</p>\n\n<p>If you are just changing the look of the page through styles (CSS) of the page than this shouldn't effect your SEO.</p>\n\n<p>It's a little unclear exactly what your doing, but in general that is what I would say.</p>\n"
},
{
"answer_id": 327118,
"author": "Alexander Holsgrove",
"author_id": 48962,
"author_profile": "https://wordpress.stackexchange.com/users/48962",
"pm_score": 1,
"selected": false,
"text": "<p>Your question seems to conflict itself - you want to run A/B testing, but don't want to mess up your SEO? The point of running A/B testing is to compare which page performs better, so naturally there will be a difference in how each page performs - hopefully your new page variation performs better (which is why you created a new page right?)</p>\n\n<p>To answer the question, you can either load different components onto your homepage using <a href=\"https://developer.wordpress.org/reference/functions/get_template_part/\" rel=\"nofollow noreferrer\">get_template_part</a>:</p>\n\n<pre><code>if($ab_test_version == 'a') {\n get_template_part('template-parts/old-homepage-content');\n} else {\n get_template_part('template-parts/new-homepage-content');\n}\n</code></pre>\n\n<p>Or you can change the entire template using the <a href=\"https://developer.wordpress.org/reference/hooks/template_include/\" rel=\"nofollow noreferrer\">template_include filter</a>:</p>\n\n<pre><code>function ab_test_homepage($template) {\n // Set some sort of variable to divide users between A and B variations\n $which_test = 'b';\n\n if (is_front_page() && $which_test == 'b') {\n $new_template = locate_template(array('new-homepage.php'));\n if(!empty($new_template)) {\n return $new_template;\n }\n }\n return $template;\n}\n\nadd_filter('template_include', 'ab_test_homepage', 99);\n</code></pre>\n\n<p>You of course want to add some sort of tracking and \"goal\" to measure the performance of both pages, but you can raise that in another question on the <a href=\"https://webmasters.stackexchange.com/\">appropriate site</a>.</p>\n"
}
] | 2019/01/30 | [
"https://wordpress.stackexchange.com/questions/327080",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/160138/"
] | is it possible to alternate between two homepages in Wordpress without messing up SEO or anything unforeseen? We want to create Home-old and Home-new for A/B testing purposes.
Thank you! | Your question seems to conflict itself - you want to run A/B testing, but don't want to mess up your SEO? The point of running A/B testing is to compare which page performs better, so naturally there will be a difference in how each page performs - hopefully your new page variation performs better (which is why you created a new page right?)
To answer the question, you can either load different components onto your homepage using [get\_template\_part](https://developer.wordpress.org/reference/functions/get_template_part/):
```
if($ab_test_version == 'a') {
get_template_part('template-parts/old-homepage-content');
} else {
get_template_part('template-parts/new-homepage-content');
}
```
Or you can change the entire template using the [template\_include filter](https://developer.wordpress.org/reference/hooks/template_include/):
```
function ab_test_homepage($template) {
// Set some sort of variable to divide users between A and B variations
$which_test = 'b';
if (is_front_page() && $which_test == 'b') {
$new_template = locate_template(array('new-homepage.php'));
if(!empty($new_template)) {
return $new_template;
}
}
return $template;
}
add_filter('template_include', 'ab_test_homepage', 99);
```
You of course want to add some sort of tracking and "goal" to measure the performance of both pages, but you can raise that in another question on the [appropriate site](https://webmasters.stackexchange.com/). |
327,090 | <p>Second level of my navigation menu (drop-down) doesn't seem to be working.</p>
<p>Things to note:</p>
<ul>
<li>It's not loading into the site (i.e. not showing in source code <em>image below</em>)</li>
<li>I'm using bootstrap 4 for the layout of my theme (the menu is not bootstrap however)</li>
<li>I'm trying to get prouct categories in dropdown, though other pages aren't showing either</li>
</ul>
<p>I have spent 3 hours looking for a solution. Any idea to what the issue is would be greatly appriciated!</p>
<p><img src="https://i.stack.imgur.com/XMXlO.png" alt="enter image description here">
<a href="https://i.stack.imgur.com/iNKSK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iNKSK.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 327083,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 0,
"selected": false,
"text": "<p>It depends on what and how you are making these changes. </p>\n\n<p>If you are changing the HTML, changing or moving elements around like headings, keys word, text, etc. than yes of course it can effect your SEO. Once Google re-indexing your site it could potentially effect SEO.</p>\n\n<p>If you are just changing the look of the page through styles (CSS) of the page than this shouldn't effect your SEO.</p>\n\n<p>It's a little unclear exactly what your doing, but in general that is what I would say.</p>\n"
},
{
"answer_id": 327118,
"author": "Alexander Holsgrove",
"author_id": 48962,
"author_profile": "https://wordpress.stackexchange.com/users/48962",
"pm_score": 1,
"selected": false,
"text": "<p>Your question seems to conflict itself - you want to run A/B testing, but don't want to mess up your SEO? The point of running A/B testing is to compare which page performs better, so naturally there will be a difference in how each page performs - hopefully your new page variation performs better (which is why you created a new page right?)</p>\n\n<p>To answer the question, you can either load different components onto your homepage using <a href=\"https://developer.wordpress.org/reference/functions/get_template_part/\" rel=\"nofollow noreferrer\">get_template_part</a>:</p>\n\n<pre><code>if($ab_test_version == 'a') {\n get_template_part('template-parts/old-homepage-content');\n} else {\n get_template_part('template-parts/new-homepage-content');\n}\n</code></pre>\n\n<p>Or you can change the entire template using the <a href=\"https://developer.wordpress.org/reference/hooks/template_include/\" rel=\"nofollow noreferrer\">template_include filter</a>:</p>\n\n<pre><code>function ab_test_homepage($template) {\n // Set some sort of variable to divide users between A and B variations\n $which_test = 'b';\n\n if (is_front_page() && $which_test == 'b') {\n $new_template = locate_template(array('new-homepage.php'));\n if(!empty($new_template)) {\n return $new_template;\n }\n }\n return $template;\n}\n\nadd_filter('template_include', 'ab_test_homepage', 99);\n</code></pre>\n\n<p>You of course want to add some sort of tracking and \"goal\" to measure the performance of both pages, but you can raise that in another question on the <a href=\"https://webmasters.stackexchange.com/\">appropriate site</a>.</p>\n"
}
] | 2019/01/30 | [
"https://wordpress.stackexchange.com/questions/327090",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159903/"
] | Second level of my navigation menu (drop-down) doesn't seem to be working.
Things to note:
* It's not loading into the site (i.e. not showing in source code *image below*)
* I'm using bootstrap 4 for the layout of my theme (the menu is not bootstrap however)
* I'm trying to get prouct categories in dropdown, though other pages aren't showing either
I have spent 3 hours looking for a solution. Any idea to what the issue is would be greatly appriciated!

[](https://i.stack.imgur.com/iNKSK.png) | Your question seems to conflict itself - you want to run A/B testing, but don't want to mess up your SEO? The point of running A/B testing is to compare which page performs better, so naturally there will be a difference in how each page performs - hopefully your new page variation performs better (which is why you created a new page right?)
To answer the question, you can either load different components onto your homepage using [get\_template\_part](https://developer.wordpress.org/reference/functions/get_template_part/):
```
if($ab_test_version == 'a') {
get_template_part('template-parts/old-homepage-content');
} else {
get_template_part('template-parts/new-homepage-content');
}
```
Or you can change the entire template using the [template\_include filter](https://developer.wordpress.org/reference/hooks/template_include/):
```
function ab_test_homepage($template) {
// Set some sort of variable to divide users between A and B variations
$which_test = 'b';
if (is_front_page() && $which_test == 'b') {
$new_template = locate_template(array('new-homepage.php'));
if(!empty($new_template)) {
return $new_template;
}
}
return $template;
}
add_filter('template_include', 'ab_test_homepage', 99);
```
You of course want to add some sort of tracking and "goal" to measure the performance of both pages, but you can raise that in another question on the [appropriate site](https://webmasters.stackexchange.com/). |
327,104 | <p>I created a custom shortcode from my child theme's functions.php, And I want that shortcode to display in Post Category Description. But it's not working. </p>
<p>Do you guys have an idea on how to enable display of shortcodes in post category description?</p>
<p><a href="https://i.stack.imgur.com/kNnTQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kNnTQ.png" alt="enter image description here"></a></p>
<p>Just correct me if I'm wrong.</p>
<p>Thanks!</p>
| [
{
"answer_id": 327106,
"author": "Chinmoy Kumar Paul",
"author_id": 57436,
"author_profile": "https://wordpress.stackexchange.com/users/57436",
"pm_score": 0,
"selected": false,
"text": "<p>I am not sure what kind of code is using in your theme. I am sharing the code for idea.</p>\n\n<pre><code>$cat_desc = category_description();\n\necho do_shortcode( $cat_desc );\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/category_description/\" rel=\"nofollow noreferrer\">category_description()</a> function is getting the a category description. do_shortcode() function is searching the content for shortcodes and filter shortcodes through their hooks.</p>\n"
},
{
"answer_id": 327110,
"author": "MazeStricks",
"author_id": 115131,
"author_profile": "https://wordpress.stackexchange.com/users/115131",
"pm_score": 1,
"selected": false,
"text": "<p>I found the answer to my own question.</p>\n\n<pre><code>add_filter( 'term_description', 'shortcode_unautop' );\nadd_filter( 'term_description', 'do_shortcode' );\nremove_filter( 'pre_term_description', 'wp_filter_kses' );\n</code></pre>\n\n<p>I just added those line of codes into the Child theme's function.php.</p>\n\n<p>Thanks to this post: <a href=\"https://wordpress.stackexchange.com/questions/232411/how-get-a-shortcode-working-in-category-description/232418#232418\">How to get a shortcode working in category description</a></p>\n"
},
{
"answer_id": 327111,
"author": "Chinmoy Kumar Paul",
"author_id": 57436,
"author_profile": "https://wordpress.stackexchange.com/users/57436",
"pm_score": 0,
"selected": false,
"text": "<p>I have no idea about Divi theme but I got a filter. You try this code</p>\n\n<pre><code>add_filter( \"category_description\", \"wse_parse_shortcode\" );\nfunction wse_parse_shortcode( $value ) {\n return do_shortcode( $value );\n}\n</code></pre>\n\n<p>category_description filter is defined in <a href=\"https://developer.wordpress.org/reference/functions/sanitize_term_field/\" rel=\"nofollow noreferrer\"><strong>sanitize_term_field</strong></a> function </p>\n"
}
] | 2019/01/30 | [
"https://wordpress.stackexchange.com/questions/327104",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115131/"
] | I created a custom shortcode from my child theme's functions.php, And I want that shortcode to display in Post Category Description. But it's not working.
Do you guys have an idea on how to enable display of shortcodes in post category description?
[](https://i.stack.imgur.com/kNnTQ.png)
Just correct me if I'm wrong.
Thanks! | I found the answer to my own question.
```
add_filter( 'term_description', 'shortcode_unautop' );
add_filter( 'term_description', 'do_shortcode' );
remove_filter( 'pre_term_description', 'wp_filter_kses' );
```
I just added those line of codes into the Child theme's function.php.
Thanks to this post: [How to get a shortcode working in category description](https://wordpress.stackexchange.com/questions/232411/how-get-a-shortcode-working-in-category-description/232418#232418) |
327,130 | <p>I'm trying to do a single WP_Query to get the posts that are in 2 different custom post types but the second post type has to be from a specific taxonomy.</p>
<p>This is what I'm currently doing:</p>
<pre><code> $query1 = new WP_Query(array(
'numberposts' => $postsnumber,
'posts_per_page' => $postsnumber,
'orderby' => 'publish_date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish',
'suppress_filters' => false
));
$query2 = new WP_Query(array(
'numberposts' => $postsnumber,
'posts_per_page' => $postsnumber,
'orderby' => 'publish_date',
'order' => 'DESC',
'post_type' => 'js_videos',
'tax_query' => array(
array (
'taxonomy' => 'video_category',
'field' => 'tag_ID',
'terms' => '41',
)
),
'post_status' => 'publish',
'suppress_filters' => false
));
$wp_query = null;
$wp_query = new WP_Query();
$wp_query->posts = array_merge( $query1->posts, $query2->posts );
</code></pre>
<p>However I need to still order by publish_date after mergining.</p>
| [
{
"answer_id": 327106,
"author": "Chinmoy Kumar Paul",
"author_id": 57436,
"author_profile": "https://wordpress.stackexchange.com/users/57436",
"pm_score": 0,
"selected": false,
"text": "<p>I am not sure what kind of code is using in your theme. I am sharing the code for idea.</p>\n\n<pre><code>$cat_desc = category_description();\n\necho do_shortcode( $cat_desc );\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/category_description/\" rel=\"nofollow noreferrer\">category_description()</a> function is getting the a category description. do_shortcode() function is searching the content for shortcodes and filter shortcodes through their hooks.</p>\n"
},
{
"answer_id": 327110,
"author": "MazeStricks",
"author_id": 115131,
"author_profile": "https://wordpress.stackexchange.com/users/115131",
"pm_score": 1,
"selected": false,
"text": "<p>I found the answer to my own question.</p>\n\n<pre><code>add_filter( 'term_description', 'shortcode_unautop' );\nadd_filter( 'term_description', 'do_shortcode' );\nremove_filter( 'pre_term_description', 'wp_filter_kses' );\n</code></pre>\n\n<p>I just added those line of codes into the Child theme's function.php.</p>\n\n<p>Thanks to this post: <a href=\"https://wordpress.stackexchange.com/questions/232411/how-get-a-shortcode-working-in-category-description/232418#232418\">How to get a shortcode working in category description</a></p>\n"
},
{
"answer_id": 327111,
"author": "Chinmoy Kumar Paul",
"author_id": 57436,
"author_profile": "https://wordpress.stackexchange.com/users/57436",
"pm_score": 0,
"selected": false,
"text": "<p>I have no idea about Divi theme but I got a filter. You try this code</p>\n\n<pre><code>add_filter( \"category_description\", \"wse_parse_shortcode\" );\nfunction wse_parse_shortcode( $value ) {\n return do_shortcode( $value );\n}\n</code></pre>\n\n<p>category_description filter is defined in <a href=\"https://developer.wordpress.org/reference/functions/sanitize_term_field/\" rel=\"nofollow noreferrer\"><strong>sanitize_term_field</strong></a> function </p>\n"
}
] | 2019/01/30 | [
"https://wordpress.stackexchange.com/questions/327130",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/8289/"
] | I'm trying to do a single WP\_Query to get the posts that are in 2 different custom post types but the second post type has to be from a specific taxonomy.
This is what I'm currently doing:
```
$query1 = new WP_Query(array(
'numberposts' => $postsnumber,
'posts_per_page' => $postsnumber,
'orderby' => 'publish_date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish',
'suppress_filters' => false
));
$query2 = new WP_Query(array(
'numberposts' => $postsnumber,
'posts_per_page' => $postsnumber,
'orderby' => 'publish_date',
'order' => 'DESC',
'post_type' => 'js_videos',
'tax_query' => array(
array (
'taxonomy' => 'video_category',
'field' => 'tag_ID',
'terms' => '41',
)
),
'post_status' => 'publish',
'suppress_filters' => false
));
$wp_query = null;
$wp_query = new WP_Query();
$wp_query->posts = array_merge( $query1->posts, $query2->posts );
```
However I need to still order by publish\_date after mergining. | I found the answer to my own question.
```
add_filter( 'term_description', 'shortcode_unautop' );
add_filter( 'term_description', 'do_shortcode' );
remove_filter( 'pre_term_description', 'wp_filter_kses' );
```
I just added those line of codes into the Child theme's function.php.
Thanks to this post: [How to get a shortcode working in category description](https://wordpress.stackexchange.com/questions/232411/how-get-a-shortcode-working-in-category-description/232418#232418) |
327,138 | <p>Complete Code.</p>
<p>
<pre><code>// Set UI labels for Custom Post Type
$labels = array(
'name' => _x( 'Events', 'evn_calendar'),
'singular_name' => _x( 'events', 'evn_calendar'),
'menu_name' => __( 'Events', 'evn_calendar' ),
'parent_item_colon' => __( 'Parent Event', 'evn_calendar' ),
'all_items' => __( 'All Events', 'evn_calendar' ),
'view_item' => __( 'View Event', 'evn_calendar' ),
'add_new_item' => __( 'Add New Event', 'evn_calendar' ),
'add_new' => __( 'Add New', 'evn_calendar' ),
'edit_item' => __( 'Edit Event', 'evn_calendar' ),
'update_item' => __( 'Update Event', 'evn_calendar' ),
'search_items' => __( 'Search Event', 'evn_calendar' ),
'not_found' => __( 'Not Found', 'evn_calendar' ),
'not_found_in_trash' => __( 'Not found in Trash', 'evn_calendar' ),
);
// Set other options for Custom Post Type
$args = array(
'label' => __( 'events', 'evn_calendar' ),
'description' => __( 'Event news and reviews', 'evn_calendar' ),
'labels' => $labels,
// Features this CPT supports in Post Editor
'supports' => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'revisions', ),
// You can associate this CPT with a taxonomy or custom taxonomy.
'taxonomies' => array( 'genres' ),
/* 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' => 20,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'post',
);
// Registering your Custom Post Type
register_post_type( 'events', $args );
function eventcalendar_add_meta_box() {
$screens = array( 'events' );
foreach ( $screens as $screen ) {
add_meta_box(
'Event Information',
'Event Information',
'eventcalendar_show_custom_meta_box',
$screen,
'normal',
'high'
);
}
}
add_action( 'add_meta_boxes', 'eventcalendar_add_meta_box' );
function eventcalendar_show_custom_meta_box( $post ) {
wp_nonce_field( 'evn_from_date', 'evn_from_date_nonce' );
$from_date = get_post_meta( $post->ID, '_evn_from_date', true );
echo '<label for="evn_from_date">'; _e( 'When', 'event-calendar-plugin' ); echo '</label> ';
echo '<input type="date" id="evn_from_date" name="evn_from_date" value="' . esc_attr( $from_date ) . '" size="25" />';
wp_nonce_field( 'evn_from_time', 'evn_from_time_nonce' );
$from_time = get_post_meta( $post->ID, '_evn_from_time', true );
echo '<input type="time" id="evn_from_time" name="evn_from_time" value="' . esc_attr( $from_time ) . '" size="25" />';
wp_nonce_field( 'evn_to_date', 'evn_to_date_nonce' );
$from_date = get_post_meta( $post->ID, '_evn_to_date', true );
echo '<label for="evn_to_date">'; _e( 'To', 'event-calendar-plugin' ); echo '</label> ';
echo '<input type="date" id="evn_to_date" name="evn_to_date" value="' . esc_attr( $from_date ) . '" size="25" />';
wp_nonce_field( 'evn_to_time', 'evn_to_time_nonce' );
$from_time = get_post_meta( $post->ID, '_evn_to_time', true );
echo '<input type="time" id="evn_to_time" name="evn_to_time" value="' . esc_attr( $from_time ) . '" size="25" />';
$request = wp_safe_remote_get(plugins_url('/js/latest.json', __FILE__));
$data = wp_remote_retrieve_body( $request );
$data = json_decode($data);
wp_nonce_field( 'evn_timezone', 'evn_timezone_nonce' );
$evn_timezone = get_post_meta( $post->ID, '_evn_timezone', true );
echo '<select id="evn_timezone" name="evn_timezone" >';
foreach ($data->countries as $country) {
$selected = ( $country[ $country->name ] == esc_attr( $country->name ) ) ? ' selected="selected"' : '';
printf( '<option value="%s(%s)"%s>%s</option>', $country->abbr, $country->name, $selected, $country->name );
}
echo '</select>';
wp_nonce_field( 'evn_all_day', 'evn_all_day_nonce' );
$evn_all_day = get_post_meta( $post->ID, 'evn_all_day', true );
echo '<input type="checkbox" id="evn_all_day" name="evn_all_day" value="' . esc_attr( $evn_all_day ) . '" />';
echo '<label for="evn_all_day">'; _e( 'All day?', 'event-calendar-plugin' ); echo '</label> ';
wp_nonce_field( 'evn_location', 'evn_location_nonce' );
$evn_location = get_post_meta( $post->ID, '_evn_location', true );
echo '<br><label for="evn_location">'; _e( 'Event Location', 'event-calendar-plugin' ); echo '</label> ';
echo '<input type="text" id="evn_location" name="evn_location" value="' . esc_attr( $evn_location ) . '" size="100" />';
wp_nonce_field( 'evn_link', 'evn_link_nonce' );
$evn_link = get_post_meta( $post->ID, '_evn_link', true );
echo '<br><label for="evn_link">'; _e( 'Link', 'event-calendar-plugin' ); echo '</label> ';
echo '<input type="text" id="evn_link" name="evn_link" value="' . esc_attr( $evn_link ) . '" size="100" placeholder=""/>';
}
function eventcalendar_save_meta_box_data( $post_id ) {
if ( ! isset( $_POST['evn_from_date_nonce'] ) &&
! isset( $_POST['evn_from_time_nonce'] ) &&
! isset( $_POST['evn_to_date_nonce'] ) &&
! isset( $_POST['evn_to_time_nonce'] ) &&
! isset( $_POST['evn_location_nonce'] ) &&
! isset( $_POST['evn_timezone'] ) &&
! isset( $_POST['evn_link'] ))
{
return;
}
if (! wp_verify_nonce( $_POST['evn_from_date_nonce'], 'evn_from_date' ) &&
! wp_verify_nonce( $_POST['evn_from_time_nonce'], 'evn_from_time' ) &&
! wp_verify_nonce( $_POST['evn_to_date_nonce'], 'evn_to_date' ) &&
! wp_verify_nonce( $_POST['evn_to_time_nonce'], 'evn_to_time' ) &&
! wp_verify_nonce( $_POST['evn_timezone_nonce'], 'evn_timezone' ) &&
! wp_verify_nonce( $_POST['evn_location_nonce'], 'evn_location' ) &&
! wp_verify_nonce( $_POST['evn_link_nonce'], 'evn_link' ) ) {
return;
}
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] ) {
if ( ! current_user_can( 'edit_page', $post_id ) ) {
return;
}
} else {
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
}
if ( ! isset( $_POST['evn_from_date'] ) &&
! isset( $_POST['evn_from_time'] ) &&
! isset( $_POST['evn_to_date'] ) &&
! isset( $_POST['evn_to_time'] ) &&
! isset( $_POST['evn_timezone'] ) &&
! isset( $_POST['evn_location'] )&&
! isset( $_POST['evn_link'] )
) {
return;
}
$evn_from_date = sanitize_text_field( $_POST['evn_from_date'] );
update_post_meta( $post_id, '_evn_from_date', $evn_from_date );
$evn_from_time = sanitize_text_field( $_POST['evn_from_time'] );
update_post_meta( $post_id, '_evn_from_time', $evn_from_time );
$evn_to_date = sanitize_text_field( $_POST['evn_to_date'] );
update_post_meta( $post_id, '_evn_to_date', $evn_to_date );
$evn_to_time = sanitize_text_field( $_POST['evn_to_time'] );
update_post_meta( $post_id, '_evn_to_time', $evn_to_time );
$evn_timezone = sanitize_text_field( $_POST['evn_timezone'] );
update_post_meta( $post_id, '_evn_timezone', $evn_timezone );
$evn_link = sanitize_text_field( $_POST['evn_link'] );
update_post_meta( $post_id, '_evn_link', $evn_link );
$evn_location = sanitize_text_field( $_POST['evn_location'] );
update_post_meta( $post_id, '_evn_location', $evn_location );
}
add_action( 'save_post', 'eventcalendar_save_meta_box_data' );
</code></pre>
| [
{
"answer_id": 327106,
"author": "Chinmoy Kumar Paul",
"author_id": 57436,
"author_profile": "https://wordpress.stackexchange.com/users/57436",
"pm_score": 0,
"selected": false,
"text": "<p>I am not sure what kind of code is using in your theme. I am sharing the code for idea.</p>\n\n<pre><code>$cat_desc = category_description();\n\necho do_shortcode( $cat_desc );\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/category_description/\" rel=\"nofollow noreferrer\">category_description()</a> function is getting the a category description. do_shortcode() function is searching the content for shortcodes and filter shortcodes through their hooks.</p>\n"
},
{
"answer_id": 327110,
"author": "MazeStricks",
"author_id": 115131,
"author_profile": "https://wordpress.stackexchange.com/users/115131",
"pm_score": 1,
"selected": false,
"text": "<p>I found the answer to my own question.</p>\n\n<pre><code>add_filter( 'term_description', 'shortcode_unautop' );\nadd_filter( 'term_description', 'do_shortcode' );\nremove_filter( 'pre_term_description', 'wp_filter_kses' );\n</code></pre>\n\n<p>I just added those line of codes into the Child theme's function.php.</p>\n\n<p>Thanks to this post: <a href=\"https://wordpress.stackexchange.com/questions/232411/how-get-a-shortcode-working-in-category-description/232418#232418\">How to get a shortcode working in category description</a></p>\n"
},
{
"answer_id": 327111,
"author": "Chinmoy Kumar Paul",
"author_id": 57436,
"author_profile": "https://wordpress.stackexchange.com/users/57436",
"pm_score": 0,
"selected": false,
"text": "<p>I have no idea about Divi theme but I got a filter. You try this code</p>\n\n<pre><code>add_filter( \"category_description\", \"wse_parse_shortcode\" );\nfunction wse_parse_shortcode( $value ) {\n return do_shortcode( $value );\n}\n</code></pre>\n\n<p>category_description filter is defined in <a href=\"https://developer.wordpress.org/reference/functions/sanitize_term_field/\" rel=\"nofollow noreferrer\"><strong>sanitize_term_field</strong></a> function </p>\n"
}
] | 2019/01/30 | [
"https://wordpress.stackexchange.com/questions/327138",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83079/"
] | Complete Code.
```
// Set UI labels for Custom Post Type
$labels = array(
'name' => _x( 'Events', 'evn_calendar'),
'singular_name' => _x( 'events', 'evn_calendar'),
'menu_name' => __( 'Events', 'evn_calendar' ),
'parent_item_colon' => __( 'Parent Event', 'evn_calendar' ),
'all_items' => __( 'All Events', 'evn_calendar' ),
'view_item' => __( 'View Event', 'evn_calendar' ),
'add_new_item' => __( 'Add New Event', 'evn_calendar' ),
'add_new' => __( 'Add New', 'evn_calendar' ),
'edit_item' => __( 'Edit Event', 'evn_calendar' ),
'update_item' => __( 'Update Event', 'evn_calendar' ),
'search_items' => __( 'Search Event', 'evn_calendar' ),
'not_found' => __( 'Not Found', 'evn_calendar' ),
'not_found_in_trash' => __( 'Not found in Trash', 'evn_calendar' ),
);
// Set other options for Custom Post Type
$args = array(
'label' => __( 'events', 'evn_calendar' ),
'description' => __( 'Event news and reviews', 'evn_calendar' ),
'labels' => $labels,
// Features this CPT supports in Post Editor
'supports' => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'revisions', ),
// You can associate this CPT with a taxonomy or custom taxonomy.
'taxonomies' => array( 'genres' ),
/* 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' => 20,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'post',
);
// Registering your Custom Post Type
register_post_type( 'events', $args );
function eventcalendar_add_meta_box() {
$screens = array( 'events' );
foreach ( $screens as $screen ) {
add_meta_box(
'Event Information',
'Event Information',
'eventcalendar_show_custom_meta_box',
$screen,
'normal',
'high'
);
}
}
add_action( 'add_meta_boxes', 'eventcalendar_add_meta_box' );
function eventcalendar_show_custom_meta_box( $post ) {
wp_nonce_field( 'evn_from_date', 'evn_from_date_nonce' );
$from_date = get_post_meta( $post->ID, '_evn_from_date', true );
echo '<label for="evn_from_date">'; _e( 'When', 'event-calendar-plugin' ); echo '</label> ';
echo '<input type="date" id="evn_from_date" name="evn_from_date" value="' . esc_attr( $from_date ) . '" size="25" />';
wp_nonce_field( 'evn_from_time', 'evn_from_time_nonce' );
$from_time = get_post_meta( $post->ID, '_evn_from_time', true );
echo '<input type="time" id="evn_from_time" name="evn_from_time" value="' . esc_attr( $from_time ) . '" size="25" />';
wp_nonce_field( 'evn_to_date', 'evn_to_date_nonce' );
$from_date = get_post_meta( $post->ID, '_evn_to_date', true );
echo '<label for="evn_to_date">'; _e( 'To', 'event-calendar-plugin' ); echo '</label> ';
echo '<input type="date" id="evn_to_date" name="evn_to_date" value="' . esc_attr( $from_date ) . '" size="25" />';
wp_nonce_field( 'evn_to_time', 'evn_to_time_nonce' );
$from_time = get_post_meta( $post->ID, '_evn_to_time', true );
echo '<input type="time" id="evn_to_time" name="evn_to_time" value="' . esc_attr( $from_time ) . '" size="25" />';
$request = wp_safe_remote_get(plugins_url('/js/latest.json', __FILE__));
$data = wp_remote_retrieve_body( $request );
$data = json_decode($data);
wp_nonce_field( 'evn_timezone', 'evn_timezone_nonce' );
$evn_timezone = get_post_meta( $post->ID, '_evn_timezone', true );
echo '<select id="evn_timezone" name="evn_timezone" >';
foreach ($data->countries as $country) {
$selected = ( $country[ $country->name ] == esc_attr( $country->name ) ) ? ' selected="selected"' : '';
printf( '<option value="%s(%s)"%s>%s</option>', $country->abbr, $country->name, $selected, $country->name );
}
echo '</select>';
wp_nonce_field( 'evn_all_day', 'evn_all_day_nonce' );
$evn_all_day = get_post_meta( $post->ID, 'evn_all_day', true );
echo '<input type="checkbox" id="evn_all_day" name="evn_all_day" value="' . esc_attr( $evn_all_day ) . '" />';
echo '<label for="evn_all_day">'; _e( 'All day?', 'event-calendar-plugin' ); echo '</label> ';
wp_nonce_field( 'evn_location', 'evn_location_nonce' );
$evn_location = get_post_meta( $post->ID, '_evn_location', true );
echo '<br><label for="evn_location">'; _e( 'Event Location', 'event-calendar-plugin' ); echo '</label> ';
echo '<input type="text" id="evn_location" name="evn_location" value="' . esc_attr( $evn_location ) . '" size="100" />';
wp_nonce_field( 'evn_link', 'evn_link_nonce' );
$evn_link = get_post_meta( $post->ID, '_evn_link', true );
echo '<br><label for="evn_link">'; _e( 'Link', 'event-calendar-plugin' ); echo '</label> ';
echo '<input type="text" id="evn_link" name="evn_link" value="' . esc_attr( $evn_link ) . '" size="100" placeholder=""/>';
}
function eventcalendar_save_meta_box_data( $post_id ) {
if ( ! isset( $_POST['evn_from_date_nonce'] ) &&
! isset( $_POST['evn_from_time_nonce'] ) &&
! isset( $_POST['evn_to_date_nonce'] ) &&
! isset( $_POST['evn_to_time_nonce'] ) &&
! isset( $_POST['evn_location_nonce'] ) &&
! isset( $_POST['evn_timezone'] ) &&
! isset( $_POST['evn_link'] ))
{
return;
}
if (! wp_verify_nonce( $_POST['evn_from_date_nonce'], 'evn_from_date' ) &&
! wp_verify_nonce( $_POST['evn_from_time_nonce'], 'evn_from_time' ) &&
! wp_verify_nonce( $_POST['evn_to_date_nonce'], 'evn_to_date' ) &&
! wp_verify_nonce( $_POST['evn_to_time_nonce'], 'evn_to_time' ) &&
! wp_verify_nonce( $_POST['evn_timezone_nonce'], 'evn_timezone' ) &&
! wp_verify_nonce( $_POST['evn_location_nonce'], 'evn_location' ) &&
! wp_verify_nonce( $_POST['evn_link_nonce'], 'evn_link' ) ) {
return;
}
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] ) {
if ( ! current_user_can( 'edit_page', $post_id ) ) {
return;
}
} else {
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
}
if ( ! isset( $_POST['evn_from_date'] ) &&
! isset( $_POST['evn_from_time'] ) &&
! isset( $_POST['evn_to_date'] ) &&
! isset( $_POST['evn_to_time'] ) &&
! isset( $_POST['evn_timezone'] ) &&
! isset( $_POST['evn_location'] )&&
! isset( $_POST['evn_link'] )
) {
return;
}
$evn_from_date = sanitize_text_field( $_POST['evn_from_date'] );
update_post_meta( $post_id, '_evn_from_date', $evn_from_date );
$evn_from_time = sanitize_text_field( $_POST['evn_from_time'] );
update_post_meta( $post_id, '_evn_from_time', $evn_from_time );
$evn_to_date = sanitize_text_field( $_POST['evn_to_date'] );
update_post_meta( $post_id, '_evn_to_date', $evn_to_date );
$evn_to_time = sanitize_text_field( $_POST['evn_to_time'] );
update_post_meta( $post_id, '_evn_to_time', $evn_to_time );
$evn_timezone = sanitize_text_field( $_POST['evn_timezone'] );
update_post_meta( $post_id, '_evn_timezone', $evn_timezone );
$evn_link = sanitize_text_field( $_POST['evn_link'] );
update_post_meta( $post_id, '_evn_link', $evn_link );
$evn_location = sanitize_text_field( $_POST['evn_location'] );
update_post_meta( $post_id, '_evn_location', $evn_location );
}
add_action( 'save_post', 'eventcalendar_save_meta_box_data' );
``` | I found the answer to my own question.
```
add_filter( 'term_description', 'shortcode_unautop' );
add_filter( 'term_description', 'do_shortcode' );
remove_filter( 'pre_term_description', 'wp_filter_kses' );
```
I just added those line of codes into the Child theme's function.php.
Thanks to this post: [How to get a shortcode working in category description](https://wordpress.stackexchange.com/questions/232411/how-get-a-shortcode-working-in-category-description/232418#232418) |
327,139 | <p>Here's the situation;</p>
<p>I am using get_terms to retrieve all terms from <strong>Tax 1</strong> with posts associated with it. Using the following </p>
<pre><code>$args = array(
'hide_empty' => 0,
'orderby' => 'name',
'taxonomy' => 'tax_1'
);
$terms = get_terms( $args );
</code></pre>
<p>Pretty simple. However that returns all terms, and does not consider the second taxonomy <strong>Tax 2</strong> which I want to compare against <strong>term x</strong></p>
<p>Ultimately I want to get all <strong>Tax 1 terms</strong> that have posts which also have <strong>Tax 2 term x</strong></p>
<p>I could most likely to a query directly on posts and create an array of terms where the post has both of the above but that seems a bit messy, I am hoping there is a way to query this directly.</p>
<p>Thanks</p>
| [
{
"answer_id": 327143,
"author": "Alexander Holsgrove",
"author_id": 48962,
"author_profile": "https://wordpress.stackexchange.com/users/48962",
"pm_score": 2,
"selected": false,
"text": "<p>You could use the tax_query argument, for example:</p>\n\n<pre><code>'tax_query' => array(\n 'relation' => 'AND',\n array(\n 'taxonomy' => 'tax1',\n 'field' => 'slug',\n 'terms' => $terms,\n ),\n array(\n 'taxonomy' => 'tax2',\n 'field' => 'slug',\n 'terms' => $terms,\n )\n)\n</code></pre>\n\n<p>To get all posts which have both terms. You can then use get_terms and pass the <code>object_ids</code> as a parameter. See the <a href=\"https://developer.wordpress.org/reference/classes/wp_term_query/__construct/\" rel=\"nofollow noreferrer\">WP_Term_Query documentation</a> for more details.</p>\n"
},
{
"answer_id": 327150,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": false,
"text": "<p>Just to start, you say <em>\"I am using get_terms to retrieve all terms from Tax 1 with posts associated with it\"</em>, however your actual code gets all terms in that taxonomy regardless of whether or not they have posts. You need to set <code>hide_empty</code> to <code>true</code>.</p>\n\n<p>So with that out of the way, the bad news: You won't be able to do this with <code>get_terms()</code>. That type of information doesn't exist without querying posts and comparing the terms. So the messy solution you wanted to avoid is unfortunately necessary.</p>\n\n<p>Ultimately I think this is a situation where you might be better off just using SQL. This code will use <code>$wpdb</code> to get terms from Taxonomy A that have any posts of a given post type that have a specific term in Taxonomy B:</p>\n\n<pre><code>$post_type = 'post';\n$taxonomy_a = 'post_tag';\n$taxonomy_b = 'category';\n$term_b_id = 12;\n\n$query = $wpdb->prepare(\n \"SELECT DISTINCT\n terms.*\n FROM\n `wp_terms` terms\n INNER JOIN\n `wp_term_taxonomy` tt1 ON\n tt1.term_id = terms.term_id\n INNER JOIN\n `wp_term_relationships` tr1 ON\n tr1.term_taxonomy_id = tt1.term_taxonomy_id\n INNER JOIN\n `wp_posts` p ON\n p.ID = tr1.object_id\n INNER JOIN \n `wp_term_relationships` tr2 ON\n tr2.object_ID = p.ID\n INNER JOIN \n `wp_term_taxonomy` tt2 ON\n tt2.term_taxonomy_id = tr2.term_taxonomy_id\n WHERE\n p.post_type = %s AND\n p.post_status = 'publish' AND\n tt1.taxonomy = %s AND\n tt2.taxonomy = %s AND\n tt2.term_id = %d\",\n [\n $post_type,\n $taxonomy_a,\n $taxonomy_b,\n $term_b_id,\n ]\n);\n\n$results = $wpdb->get_results( $query );\n\nif ( $results ) {\n $terms = array_map( 'get_term', $results );\n}\n</code></pre>\n\n<p>So that code gets all <em>Tags</em> that have <em>Posts</em> that are assigned to the <em>Category</em> with the ID <em>12</em>.</p>\n\n<p>The last little bit with <code>get_term()</code> ensures that the final array contains the same <code>WP_Term</code> objects that you would get by running <code>get_terms()</code>.</p>\n"
}
] | 2019/01/30 | [
"https://wordpress.stackexchange.com/questions/327139",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103782/"
] | Here's the situation;
I am using get\_terms to retrieve all terms from **Tax 1** with posts associated with it. Using the following
```
$args = array(
'hide_empty' => 0,
'orderby' => 'name',
'taxonomy' => 'tax_1'
);
$terms = get_terms( $args );
```
Pretty simple. However that returns all terms, and does not consider the second taxonomy **Tax 2** which I want to compare against **term x**
Ultimately I want to get all **Tax 1 terms** that have posts which also have **Tax 2 term x**
I could most likely to a query directly on posts and create an array of terms where the post has both of the above but that seems a bit messy, I am hoping there is a way to query this directly.
Thanks | Just to start, you say *"I am using get\_terms to retrieve all terms from Tax 1 with posts associated with it"*, however your actual code gets all terms in that taxonomy regardless of whether or not they have posts. You need to set `hide_empty` to `true`.
So with that out of the way, the bad news: You won't be able to do this with `get_terms()`. That type of information doesn't exist without querying posts and comparing the terms. So the messy solution you wanted to avoid is unfortunately necessary.
Ultimately I think this is a situation where you might be better off just using SQL. This code will use `$wpdb` to get terms from Taxonomy A that have any posts of a given post type that have a specific term in Taxonomy B:
```
$post_type = 'post';
$taxonomy_a = 'post_tag';
$taxonomy_b = 'category';
$term_b_id = 12;
$query = $wpdb->prepare(
"SELECT DISTINCT
terms.*
FROM
`wp_terms` terms
INNER JOIN
`wp_term_taxonomy` tt1 ON
tt1.term_id = terms.term_id
INNER JOIN
`wp_term_relationships` tr1 ON
tr1.term_taxonomy_id = tt1.term_taxonomy_id
INNER JOIN
`wp_posts` p ON
p.ID = tr1.object_id
INNER JOIN
`wp_term_relationships` tr2 ON
tr2.object_ID = p.ID
INNER JOIN
`wp_term_taxonomy` tt2 ON
tt2.term_taxonomy_id = tr2.term_taxonomy_id
WHERE
p.post_type = %s AND
p.post_status = 'publish' AND
tt1.taxonomy = %s AND
tt2.taxonomy = %s AND
tt2.term_id = %d",
[
$post_type,
$taxonomy_a,
$taxonomy_b,
$term_b_id,
]
);
$results = $wpdb->get_results( $query );
if ( $results ) {
$terms = array_map( 'get_term', $results );
}
```
So that code gets all *Tags* that have *Posts* that are assigned to the *Category* with the ID *12*.
The last little bit with `get_term()` ensures that the final array contains the same `WP_Term` objects that you would get by running `get_terms()`. |
327,167 | <p>I should first mention I am fairly new to wordpress and web development.</p>
<p>I was given the task to update an existing site which includes the navigation bar. I have been digging through code trying to figure out where the actual code has been stored for the nav. The site is a custom build theme which looks to be built using the "Bones" theme. I've tried using the customizer to alter nav but there are no options available for what is needed. I've accessed the hosting through ftp and reviewed the php files in httpdocs/wp-content/themes etc. The closest thing I've found was in the header.php in the themes>"custom theme">header.php, however, this does not contain the full menu it only references the logo and one outdated dropdown button. I am getting nowhere.</p>
<p>The nav bar should be altered from this:
<a href="https://i.stack.imgur.com/dlaJX.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dlaJX.jpg" alt="enter image description here"></a></p>
<p>to this:
<a href="https://i.stack.imgur.com/TlNMC.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TlNMC.jpg" alt="enter image description here"></a></p>
<p>I hope this makes more sense with a visual.</p>
<p>The site is cowboycauldron.com</p>
<p>I appreciate any help.</p>
<p>Thanks</p>
| [
{
"answer_id": 327176,
"author": "Karl Poppery",
"author_id": 160195,
"author_profile": "https://wordpress.stackexchange.com/users/160195",
"pm_score": -1,
"selected": false,
"text": "<p>On your Dashboard, go to appearance -> menus and add the pages you want to the menu</p>\n"
},
{
"answer_id": 327182,
"author": "amatusko",
"author_id": 11726,
"author_profile": "https://wordpress.stackexchange.com/users/11726",
"pm_score": 0,
"selected": false,
"text": "<p>The first step is to make the \"Shopping Nav\" Active. It's currently set to \"display:none\" in the css, probably because the menu isn't active. Once you change display:none on that menu, then you can start positioning it to be split from the other menu at the top of the screen. </p>\n\n<p>This is what needs to be changed in the CSS. Not directly, though. You need to change the menu to display in your settings. This is what I see when I look at the HTML of your site: </p>\n\n<pre><code>nav.shopping-nav {\n display: none;\n}\n</code></pre>\n"
}
] | 2019/01/30 | [
"https://wordpress.stackexchange.com/questions/327167",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/160189/"
] | I should first mention I am fairly new to wordpress and web development.
I was given the task to update an existing site which includes the navigation bar. I have been digging through code trying to figure out where the actual code has been stored for the nav. The site is a custom build theme which looks to be built using the "Bones" theme. I've tried using the customizer to alter nav but there are no options available for what is needed. I've accessed the hosting through ftp and reviewed the php files in httpdocs/wp-content/themes etc. The closest thing I've found was in the header.php in the themes>"custom theme">header.php, however, this does not contain the full menu it only references the logo and one outdated dropdown button. I am getting nowhere.
The nav bar should be altered from this:
[](https://i.stack.imgur.com/dlaJX.jpg)
to this:
[](https://i.stack.imgur.com/TlNMC.jpg)
I hope this makes more sense with a visual.
The site is cowboycauldron.com
I appreciate any help.
Thanks | The first step is to make the "Shopping Nav" Active. It's currently set to "display:none" in the css, probably because the menu isn't active. Once you change display:none on that menu, then you can start positioning it to be split from the other menu at the top of the screen.
This is what needs to be changed in the CSS. Not directly, though. You need to change the menu to display in your settings. This is what I see when I look at the HTML of your site:
```
nav.shopping-nav {
display: none;
}
``` |
327,197 | <p>I am trying to add a few meta boxes for a Custom Post Type through a Class. I am using the <code>"register_meta_box_cb"</code> parameter while registering the Custom Post Type to specify the callback function for adding meta boxes. </p>
<p>Sample code - (outline of my code) -</p>
<p>
<pre><code>class ABC
{
public static function add_customposttype()
{
$abc_o = new ABC();
$abc_o->reg();
}
public function reg()
{
$args = array(
"label" => "ABC",
"description" => "New CPT",
"public" => true,
"register_meta_box_cb" => array($this, "meta_box_callback")
);
register_post_type("abc", $args);
}
public function meta_box_callback()
{
$meta_fields = get_all_meta_fields(); // This gets me an array of objects of classes 'c_box, b_box and a_box'
foreach($meta_fields as $object)
{
add_meta_box($object->name, $object->label, array($object, 'render_meta_box'), 'abc', $object->context, $object->priority);
}
}
}
class c_box
{
public $name;
public $label;
public $context;
public $priority;
public function __construct()
{
$this->name = 'c_box';
$this->label = 'C Box';
$this->context = 'normal';
$this->priority = 'high';
}
public function render_meta_box($post)
{
echo "<p>This is a C Box</p>"; // Never executes
}
}
class b_box
{
public $name;
public $label;
public $context;
public $priority;
public function __construct()
{
$this->name = 'b_box';
$this->label = 'B Box';
$this->context = 'normal';
$this->priority = 'high';
}
public function render_meta_box($post)
{
echo "<p>This is a B Box</p>"; // Never executes
}
}
class a_box
{
public $name;
public $label;
public $context;
public $priority;
public function __construct()
{
$this->name = 'a_box';
$this->label = 'A Box';
$this->context = 'normal';
$this->priority = 'high';
}
public function render_meta_box($post)
{
echo "<p>This is a A Box</p>"; // Never executes
}
}
</code></pre>
<p>So I have different Classes defined for different meta boxes. I want all of them to have a common <code>render_meta_box</code> function so that I can create objects of all these Classes, put them in an array and traverse through it so that I can call the <code>render_meta_box</code> function for all of them one after the other.</p>
<p>Basically, a meta box will have its own class with a <code>render_meta_box</code> function and some other functions, and I can create an object of each of such classes and run their functions one after the other, thus making it easy to add new meta boxes in the future.</p>
<p>The problem I am facing is, when I define the <code>render_meta_box</code> method in separate classes with HTML code in it to be echoed, it looks like <code>add_meta_box</code> never executes that callback function. I tried to see if I could get it to print something in the <code>render_meta_box</code> method but it never reached that print statement.</p>
<p>Am I missing something here? I thought I could call the <code>render_meta_box</code> methods using different objects to have them all execute differently, is my approach incorrect?</p>
<p>Thanks in advance!</p>
| [
{
"answer_id": 327176,
"author": "Karl Poppery",
"author_id": 160195,
"author_profile": "https://wordpress.stackexchange.com/users/160195",
"pm_score": -1,
"selected": false,
"text": "<p>On your Dashboard, go to appearance -> menus and add the pages you want to the menu</p>\n"
},
{
"answer_id": 327182,
"author": "amatusko",
"author_id": 11726,
"author_profile": "https://wordpress.stackexchange.com/users/11726",
"pm_score": 0,
"selected": false,
"text": "<p>The first step is to make the \"Shopping Nav\" Active. It's currently set to \"display:none\" in the css, probably because the menu isn't active. Once you change display:none on that menu, then you can start positioning it to be split from the other menu at the top of the screen. </p>\n\n<p>This is what needs to be changed in the CSS. Not directly, though. You need to change the menu to display in your settings. This is what I see when I look at the HTML of your site: </p>\n\n<pre><code>nav.shopping-nav {\n display: none;\n}\n</code></pre>\n"
}
] | 2019/01/31 | [
"https://wordpress.stackexchange.com/questions/327197",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/128119/"
] | I am trying to add a few meta boxes for a Custom Post Type through a Class. I am using the `"register_meta_box_cb"` parameter while registering the Custom Post Type to specify the callback function for adding meta boxes.
Sample code - (outline of my code) -
```
class ABC
{
public static function add_customposttype()
{
$abc_o = new ABC();
$abc_o->reg();
}
public function reg()
{
$args = array(
"label" => "ABC",
"description" => "New CPT",
"public" => true,
"register_meta_box_cb" => array($this, "meta_box_callback")
);
register_post_type("abc", $args);
}
public function meta_box_callback()
{
$meta_fields = get_all_meta_fields(); // This gets me an array of objects of classes 'c_box, b_box and a_box'
foreach($meta_fields as $object)
{
add_meta_box($object->name, $object->label, array($object, 'render_meta_box'), 'abc', $object->context, $object->priority);
}
}
}
class c_box
{
public $name;
public $label;
public $context;
public $priority;
public function __construct()
{
$this->name = 'c_box';
$this->label = 'C Box';
$this->context = 'normal';
$this->priority = 'high';
}
public function render_meta_box($post)
{
echo "<p>This is a C Box</p>"; // Never executes
}
}
class b_box
{
public $name;
public $label;
public $context;
public $priority;
public function __construct()
{
$this->name = 'b_box';
$this->label = 'B Box';
$this->context = 'normal';
$this->priority = 'high';
}
public function render_meta_box($post)
{
echo "<p>This is a B Box</p>"; // Never executes
}
}
class a_box
{
public $name;
public $label;
public $context;
public $priority;
public function __construct()
{
$this->name = 'a_box';
$this->label = 'A Box';
$this->context = 'normal';
$this->priority = 'high';
}
public function render_meta_box($post)
{
echo "<p>This is a A Box</p>"; // Never executes
}
}
```
So I have different Classes defined for different meta boxes. I want all of them to have a common `render_meta_box` function so that I can create objects of all these Classes, put them in an array and traverse through it so that I can call the `render_meta_box` function for all of them one after the other.
Basically, a meta box will have its own class with a `render_meta_box` function and some other functions, and I can create an object of each of such classes and run their functions one after the other, thus making it easy to add new meta boxes in the future.
The problem I am facing is, when I define the `render_meta_box` method in separate classes with HTML code in it to be echoed, it looks like `add_meta_box` never executes that callback function. I tried to see if I could get it to print something in the `render_meta_box` method but it never reached that print statement.
Am I missing something here? I thought I could call the `render_meta_box` methods using different objects to have them all execute differently, is my approach incorrect?
Thanks in advance! | The first step is to make the "Shopping Nav" Active. It's currently set to "display:none" in the css, probably because the menu isn't active. Once you change display:none on that menu, then you can start positioning it to be split from the other menu at the top of the screen.
This is what needs to be changed in the CSS. Not directly, though. You need to change the menu to display in your settings. This is what I see when I look at the HTML of your site:
```
nav.shopping-nav {
display: none;
}
``` |
327,210 | <p>How to translate my website into another language like <strong><em>Malayalam</em></strong>. Can You suggest something. There is a problem when I used GTranslate plugin, that is it doesn't translate correctly. There is any chance of content editing/ changing the content when translating a page? </p>
| [
{
"answer_id": 327176,
"author": "Karl Poppery",
"author_id": 160195,
"author_profile": "https://wordpress.stackexchange.com/users/160195",
"pm_score": -1,
"selected": false,
"text": "<p>On your Dashboard, go to appearance -> menus and add the pages you want to the menu</p>\n"
},
{
"answer_id": 327182,
"author": "amatusko",
"author_id": 11726,
"author_profile": "https://wordpress.stackexchange.com/users/11726",
"pm_score": 0,
"selected": false,
"text": "<p>The first step is to make the \"Shopping Nav\" Active. It's currently set to \"display:none\" in the css, probably because the menu isn't active. Once you change display:none on that menu, then you can start positioning it to be split from the other menu at the top of the screen. </p>\n\n<p>This is what needs to be changed in the CSS. Not directly, though. You need to change the menu to display in your settings. This is what I see when I look at the HTML of your site: </p>\n\n<pre><code>nav.shopping-nav {\n display: none;\n}\n</code></pre>\n"
}
] | 2019/01/31 | [
"https://wordpress.stackexchange.com/questions/327210",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/154128/"
] | How to translate my website into another language like ***Malayalam***. Can You suggest something. There is a problem when I used GTranslate plugin, that is it doesn't translate correctly. There is any chance of content editing/ changing the content when translating a page? | The first step is to make the "Shopping Nav" Active. It's currently set to "display:none" in the css, probably because the menu isn't active. Once you change display:none on that menu, then you can start positioning it to be split from the other menu at the top of the screen.
This is what needs to be changed in the CSS. Not directly, though. You need to change the menu to display in your settings. This is what I see when I look at the HTML of your site:
```
nav.shopping-nav {
display: none;
}
``` |
327,221 | <p>I am updating one of my plugins for Gutenberg. I need to check for the presence of a custom post meta field when a post is updated or published, so I've hooked into <code>publish_post</code>:</p>
<pre><code>function process_meta( $ID, $post ) {
if (get_post_meta($ID, 'my_post_meta_field', true)) {
// do something
}
}
add_action('publish_post', 'process_meta', 10, 2);
</code></pre>
<p>The problem is that post meta fields have not yet been saved to the database when this hook (or any others that I'm aware of) fires, so unless a post draft has already been saved, <code>my_post_meta_field</code> always appears empty at this point in my code.</p>
<p>In the old version of my plugin, I would simply check the contents of the <code>$_POST[]</code> array. However, Gutenberg now saves content directly via the WordPress API, so there is no <code>POST</code> data to intercept.</p>
<p>How can I work around this problem?</p>
| [
{
"answer_id": 327222,
"author": "Chinmoy Kumar Paul",
"author_id": 57436,
"author_profile": "https://wordpress.stackexchange.com/users/57436",
"pm_score": -1,
"selected": false,
"text": "<p>Replace <code>add_action('publish_post', 'process_meta', 10, 2);</code> with <code>add_action('save_post', 'process_meta', 10, 2);</code></p>\n\n<p>My Code:</p>\n\n<pre><code>function process_meta( $ID, $post ) {\n // Saving the data for future use\n if ( isset( $_POST['YOUR CUSTOM FIELD NAME'] ) ) {\n update_post_meta( 'my_post_meta_field', $_POST['YOUR CUSTOM FIELD NAME']);\n }\n}\nadd_action('save_post', 'process_meta', 10, 2);\n</code></pre>\n\n<p>You will access the value in your other PHP or plugin's file like this way <code>get_post_meta( get_the_ID(), 'my_post_meta_field', true );</code> .</p>\n"
},
{
"answer_id": 327484,
"author": "0Seven",
"author_id": 160222,
"author_profile": "https://wordpress.stackexchange.com/users/160222",
"pm_score": 2,
"selected": true,
"text": "<p>The solution is to use a different hook which fires after post meta data has been saved by Gutenberg to the WP API. After reading <a href=\"https://github.com/WordPress/gutenberg/issues/12903\" rel=\"nofollow noreferrer\">this related discussion</a> on Github and inspecting <a href=\"https://gist.github.com/n7studios/56fd05f19f5da26f19f6da0ccb57b144\" rel=\"nofollow noreferrer\">this code by n7studios</a>, I discovered that <code>rest_after_insert_post</code> is a hook to use.</p>\n\n<p>So, the way to reliably check for the existence of a WordPress Post Meta field when using Gutenberg:</p>\n\n<pre><code>function read_my_meta_field( $post, $request ) {\n $my_meta_field = get_post_meta($post->ID, 'my_post_meta_field', true);\n\n // Process $my_meta_field as desired...\n}\nadd_action('rest_after_insert_post', 'read_my_meta_field', 10, 2);\n</code></pre>\n\n<p>Note that you can handle meta fields from other post types by simply changing <code>post</code> in the first parameter to the <code>add_action()</code> function, so instead of using <code>'rest_after_insert_post'</code> you would use <code>'rest_after_insert_whatever'</code>.</p>\n\n<p>Finally, here is a more complete answer to my own question, which checks the meta field only on post publication.</p>\n\n<pre><code>function run_on_post_publication( $ID, $post ) {\n // Only register this hook if we really are publishing a new post\n add_action('rest_after_insert_post', 'read_my_postmeta_field', 10, 2);\n}\nadd_action('publish_post', 'run_on_post_publication', 10, 2);\n\nfunction read_my_postmeta_field( $post, $request ) {\n $my_meta_field = get_post_meta( $post->ID, 'my_post_meta_field', true);\n\n // Process $my_meta_field as desired...\n}\n</code></pre>\n\n<p>For reference, if you want more control over when, exactly, your code runs, check out the <a href=\"https://developer.wordpress.org/reference/hooks/transition_post_status/\" rel=\"nofollow noreferrer\">'transition_post_status' hook</a>.</p>\n"
}
] | 2019/01/31 | [
"https://wordpress.stackexchange.com/questions/327221",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/160222/"
] | I am updating one of my plugins for Gutenberg. I need to check for the presence of a custom post meta field when a post is updated or published, so I've hooked into `publish_post`:
```
function process_meta( $ID, $post ) {
if (get_post_meta($ID, 'my_post_meta_field', true)) {
// do something
}
}
add_action('publish_post', 'process_meta', 10, 2);
```
The problem is that post meta fields have not yet been saved to the database when this hook (or any others that I'm aware of) fires, so unless a post draft has already been saved, `my_post_meta_field` always appears empty at this point in my code.
In the old version of my plugin, I would simply check the contents of the `$_POST[]` array. However, Gutenberg now saves content directly via the WordPress API, so there is no `POST` data to intercept.
How can I work around this problem? | The solution is to use a different hook which fires after post meta data has been saved by Gutenberg to the WP API. After reading [this related discussion](https://github.com/WordPress/gutenberg/issues/12903) on Github and inspecting [this code by n7studios](https://gist.github.com/n7studios/56fd05f19f5da26f19f6da0ccb57b144), I discovered that `rest_after_insert_post` is a hook to use.
So, the way to reliably check for the existence of a WordPress Post Meta field when using Gutenberg:
```
function read_my_meta_field( $post, $request ) {
$my_meta_field = get_post_meta($post->ID, 'my_post_meta_field', true);
// Process $my_meta_field as desired...
}
add_action('rest_after_insert_post', 'read_my_meta_field', 10, 2);
```
Note that you can handle meta fields from other post types by simply changing `post` in the first parameter to the `add_action()` function, so instead of using `'rest_after_insert_post'` you would use `'rest_after_insert_whatever'`.
Finally, here is a more complete answer to my own question, which checks the meta field only on post publication.
```
function run_on_post_publication( $ID, $post ) {
// Only register this hook if we really are publishing a new post
add_action('rest_after_insert_post', 'read_my_postmeta_field', 10, 2);
}
add_action('publish_post', 'run_on_post_publication', 10, 2);
function read_my_postmeta_field( $post, $request ) {
$my_meta_field = get_post_meta( $post->ID, 'my_post_meta_field', true);
// Process $my_meta_field as desired...
}
```
For reference, if you want more control over when, exactly, your code runs, check out the ['transition\_post\_status' hook](https://developer.wordpress.org/reference/hooks/transition_post_status/). |
327,233 | <p>I am going to find a way for logged in users to create pages from front page. For example there are three buttons so called button1,2,3. When logged in users clicks on button1, a page with title newyork1 is created and if user clicks on New York button for one more time, a new page newyork1-1 and newyork1-2 are created and the same logical with Tokyo and London. I have tried Wordpress Rest API then wp_insert_post() function but it not working as it cannot get the author and title as i aspected. If you guys have a better idea, please help. Thank you</p>
<pre><code><ul>
<li> <a href="" data-name="newyork"> New York</a></li>
<li> <a href="" data-name="tokyo"> Tokyo</a></li>
<li> <a href="" data-name="london"> London</a></li>
</ul>
</code></pre>
| [
{
"answer_id": 327222,
"author": "Chinmoy Kumar Paul",
"author_id": 57436,
"author_profile": "https://wordpress.stackexchange.com/users/57436",
"pm_score": -1,
"selected": false,
"text": "<p>Replace <code>add_action('publish_post', 'process_meta', 10, 2);</code> with <code>add_action('save_post', 'process_meta', 10, 2);</code></p>\n\n<p>My Code:</p>\n\n<pre><code>function process_meta( $ID, $post ) {\n // Saving the data for future use\n if ( isset( $_POST['YOUR CUSTOM FIELD NAME'] ) ) {\n update_post_meta( 'my_post_meta_field', $_POST['YOUR CUSTOM FIELD NAME']);\n }\n}\nadd_action('save_post', 'process_meta', 10, 2);\n</code></pre>\n\n<p>You will access the value in your other PHP or plugin's file like this way <code>get_post_meta( get_the_ID(), 'my_post_meta_field', true );</code> .</p>\n"
},
{
"answer_id": 327484,
"author": "0Seven",
"author_id": 160222,
"author_profile": "https://wordpress.stackexchange.com/users/160222",
"pm_score": 2,
"selected": true,
"text": "<p>The solution is to use a different hook which fires after post meta data has been saved by Gutenberg to the WP API. After reading <a href=\"https://github.com/WordPress/gutenberg/issues/12903\" rel=\"nofollow noreferrer\">this related discussion</a> on Github and inspecting <a href=\"https://gist.github.com/n7studios/56fd05f19f5da26f19f6da0ccb57b144\" rel=\"nofollow noreferrer\">this code by n7studios</a>, I discovered that <code>rest_after_insert_post</code> is a hook to use.</p>\n\n<p>So, the way to reliably check for the existence of a WordPress Post Meta field when using Gutenberg:</p>\n\n<pre><code>function read_my_meta_field( $post, $request ) {\n $my_meta_field = get_post_meta($post->ID, 'my_post_meta_field', true);\n\n // Process $my_meta_field as desired...\n}\nadd_action('rest_after_insert_post', 'read_my_meta_field', 10, 2);\n</code></pre>\n\n<p>Note that you can handle meta fields from other post types by simply changing <code>post</code> in the first parameter to the <code>add_action()</code> function, so instead of using <code>'rest_after_insert_post'</code> you would use <code>'rest_after_insert_whatever'</code>.</p>\n\n<p>Finally, here is a more complete answer to my own question, which checks the meta field only on post publication.</p>\n\n<pre><code>function run_on_post_publication( $ID, $post ) {\n // Only register this hook if we really are publishing a new post\n add_action('rest_after_insert_post', 'read_my_postmeta_field', 10, 2);\n}\nadd_action('publish_post', 'run_on_post_publication', 10, 2);\n\nfunction read_my_postmeta_field( $post, $request ) {\n $my_meta_field = get_post_meta( $post->ID, 'my_post_meta_field', true);\n\n // Process $my_meta_field as desired...\n}\n</code></pre>\n\n<p>For reference, if you want more control over when, exactly, your code runs, check out the <a href=\"https://developer.wordpress.org/reference/hooks/transition_post_status/\" rel=\"nofollow noreferrer\">'transition_post_status' hook</a>.</p>\n"
}
] | 2019/01/31 | [
"https://wordpress.stackexchange.com/questions/327233",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159012/"
] | I am going to find a way for logged in users to create pages from front page. For example there are three buttons so called button1,2,3. When logged in users clicks on button1, a page with title newyork1 is created and if user clicks on New York button for one more time, a new page newyork1-1 and newyork1-2 are created and the same logical with Tokyo and London. I have tried Wordpress Rest API then wp\_insert\_post() function but it not working as it cannot get the author and title as i aspected. If you guys have a better idea, please help. Thank you
```
<ul>
<li> <a href="" data-name="newyork"> New York</a></li>
<li> <a href="" data-name="tokyo"> Tokyo</a></li>
<li> <a href="" data-name="london"> London</a></li>
</ul>
``` | The solution is to use a different hook which fires after post meta data has been saved by Gutenberg to the WP API. After reading [this related discussion](https://github.com/WordPress/gutenberg/issues/12903) on Github and inspecting [this code by n7studios](https://gist.github.com/n7studios/56fd05f19f5da26f19f6da0ccb57b144), I discovered that `rest_after_insert_post` is a hook to use.
So, the way to reliably check for the existence of a WordPress Post Meta field when using Gutenberg:
```
function read_my_meta_field( $post, $request ) {
$my_meta_field = get_post_meta($post->ID, 'my_post_meta_field', true);
// Process $my_meta_field as desired...
}
add_action('rest_after_insert_post', 'read_my_meta_field', 10, 2);
```
Note that you can handle meta fields from other post types by simply changing `post` in the first parameter to the `add_action()` function, so instead of using `'rest_after_insert_post'` you would use `'rest_after_insert_whatever'`.
Finally, here is a more complete answer to my own question, which checks the meta field only on post publication.
```
function run_on_post_publication( $ID, $post ) {
// Only register this hook if we really are publishing a new post
add_action('rest_after_insert_post', 'read_my_postmeta_field', 10, 2);
}
add_action('publish_post', 'run_on_post_publication', 10, 2);
function read_my_postmeta_field( $post, $request ) {
$my_meta_field = get_post_meta( $post->ID, 'my_post_meta_field', true);
// Process $my_meta_field as desired...
}
```
For reference, if you want more control over when, exactly, your code runs, check out the ['transition\_post\_status' hook](https://developer.wordpress.org/reference/hooks/transition_post_status/). |
327,284 | <p>I have home page with a main slider and news section.</p>
<ul>
<li>Main slider</li>
<li>Sport section news</li>
<li>Economy section news</li>
<li>Politic section news </li>
<li>and others section </li>
</ul>
<p>The main slider get posts by tag ='slider', and display 10 posts limit.</p>
<p>The sections get posts by category (each section by specific category) </p>
<p>What i wold like is to : exclude the posts displaying in slider, from the sections until the posts is out the slider. </p>
<p>Here is the code of the slider and a sample of section: </p>
<p><strong>Slider Code :</strong></p>
<pre><code><?php
// Slider
$tag = ap_option('slider_tag');
$count = ap_option('slider_count');
$slid = new WP_Query(
array(
'tag' => $tag ,
'posts_per_page' => $count ,
'post__not_in' => get_option( 'sticky_posts' ),
)
);
?>
<div class="thumbslider">
<div class="postlist">
<?php while ( $slid->have_posts() ) : $slid->the_post(); ?>
<div class="item">
<div class="det">
<h2><a href="<?php the_permalink() ?>" title="<?php the_title();?>"><?php
the_title(); ?></a></h2>
</div>
<div class="thumbnail">
<a href="<?php the_permalink() ?>" title="<?php the_title();?>">
<?php
if ( has_post_thumbnail() ) {
the_post_thumbnail( 'slider' );
} else {
echo '<img alt="Assahifa.com" title="Assahifa.com" src="https://placeholdit.imgix.net/~text?txtsize=20&bg=eee&txtclr=8C8C8C%26text%3Dthree&txt=ap&w=650&h=420">';
}
?>
</a>
</div>
</div>
<?php endwhile;wp_reset_postdata(); ?>
</div>
</div>
</code></pre>
<p><strong>Section News Sample :</strong> </p>
<pre><code> <?php
// cat eco
$n=0;
$cat_eco = ap_option('sec_eco_cat');
$count_eco = ap_option('sec_eco_count');
$eco = new WP_Query(
array(
'cat' => $cat_eco ,
'posts_per_page' => $count_eco ,
'post__not_in' => get_option( 'sticky_posts' ),
'offset' => 0,
)
);
?>
<section class="main_eco clearfix">
<div class="box">
<div class="title" style="color: <?php echo ap_option('eco-color'); ?>;">
<h3 style="color: <?php echo ap_option('eco-color'); ?>;"><a href="<?php
echo get_category_link( $cat_eco ); ?>" title="<?php echo
ap_option('sec_eco_title'); ?>" style="color: <?php echo ap_option('eco-
color'); ?>;"><?php echo ap_option('sec_eco_title'); ?></a></h3></div>
<div class="postlist">
<?php while ( $eco->have_posts() ) : $eco->the_post();$n++; ?>
<div class="item clearfix">
<div class="thumbnail imgtrans">
<a href="<?php the_permalink() ?>" title="<?php the_title();?>">
<?php
if ( has_post_thumbnail() ) {
the_post_thumbnail( 'md' );
} else {
echo '<img alt="AisPanel" title="AisPanel"
src="https://placeholdit.imgix.net/~text?
txtsize=20&bg=eee&txtclr=8C8C8C%26text%3Dthree&txt=ap&w=650&h=420">';
}
?>
</a>
</div>
<div class="det">
<h2><a href="<?php the_permalink() ?>" title="<?php the_title();?
>"><?php the_title(); ?></a></h2>
<!--<?php if($n == 1) the_excerpt(); ?>-->
</div>
</div>
<?php endwhile;wp_reset_postdata(); ?>
</div>
</div>
</section>
</code></pre>
| [
{
"answer_id": 327270,
"author": "Sabbir Hasan",
"author_id": 76587,
"author_profile": "https://wordpress.stackexchange.com/users/76587",
"pm_score": 0,
"selected": false,
"text": "<p>You have to do two things</p>\n\n<ol>\n<li>Completely disable visual editor</li>\n<li>enable Markdown. </li>\n</ol>\n\n<p><strong>Disable Visual editor:</strong> Add this code in the themes function.php file or as a plugin.</p>\n\n<pre><code>add_filter( 'user_can_richedit' , '__return_false', 50 );\n</code></pre>\n\n<p><strong>Enable Markdown:</strong> Install this plugin <a href=\"https://wordpress.org/plugins/wp-markdown/\" rel=\"nofollow noreferrer\">Wp-Markdown</a></p>\n"
},
{
"answer_id": 327319,
"author": "mzykin",
"author_id": 160284,
"author_profile": "https://wordpress.stackexchange.com/users/160284",
"pm_score": 2,
"selected": true,
"text": "<p>You can try <code>remove_filter( 'the_content', 'wpautop' );</code> to remove the added HTML tags.</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wpautop\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wpautop</a></p>\n"
}
] | 2019/01/31 | [
"https://wordpress.stackexchange.com/questions/327284",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/158072/"
] | I have home page with a main slider and news section.
* Main slider
* Sport section news
* Economy section news
* Politic section news
* and others section
The main slider get posts by tag ='slider', and display 10 posts limit.
The sections get posts by category (each section by specific category)
What i wold like is to : exclude the posts displaying in slider, from the sections until the posts is out the slider.
Here is the code of the slider and a sample of section:
**Slider Code :**
```
<?php
// Slider
$tag = ap_option('slider_tag');
$count = ap_option('slider_count');
$slid = new WP_Query(
array(
'tag' => $tag ,
'posts_per_page' => $count ,
'post__not_in' => get_option( 'sticky_posts' ),
)
);
?>
<div class="thumbslider">
<div class="postlist">
<?php while ( $slid->have_posts() ) : $slid->the_post(); ?>
<div class="item">
<div class="det">
<h2><a href="<?php the_permalink() ?>" title="<?php the_title();?>"><?php
the_title(); ?></a></h2>
</div>
<div class="thumbnail">
<a href="<?php the_permalink() ?>" title="<?php the_title();?>">
<?php
if ( has_post_thumbnail() ) {
the_post_thumbnail( 'slider' );
} else {
echo '<img alt="Assahifa.com" title="Assahifa.com" src="https://placeholdit.imgix.net/~text?txtsize=20&bg=eee&txtclr=8C8C8C%26text%3Dthree&txt=ap&w=650&h=420">';
}
?>
</a>
</div>
</div>
<?php endwhile;wp_reset_postdata(); ?>
</div>
</div>
```
**Section News Sample :**
```
<?php
// cat eco
$n=0;
$cat_eco = ap_option('sec_eco_cat');
$count_eco = ap_option('sec_eco_count');
$eco = new WP_Query(
array(
'cat' => $cat_eco ,
'posts_per_page' => $count_eco ,
'post__not_in' => get_option( 'sticky_posts' ),
'offset' => 0,
)
);
?>
<section class="main_eco clearfix">
<div class="box">
<div class="title" style="color: <?php echo ap_option('eco-color'); ?>;">
<h3 style="color: <?php echo ap_option('eco-color'); ?>;"><a href="<?php
echo get_category_link( $cat_eco ); ?>" title="<?php echo
ap_option('sec_eco_title'); ?>" style="color: <?php echo ap_option('eco-
color'); ?>;"><?php echo ap_option('sec_eco_title'); ?></a></h3></div>
<div class="postlist">
<?php while ( $eco->have_posts() ) : $eco->the_post();$n++; ?>
<div class="item clearfix">
<div class="thumbnail imgtrans">
<a href="<?php the_permalink() ?>" title="<?php the_title();?>">
<?php
if ( has_post_thumbnail() ) {
the_post_thumbnail( 'md' );
} else {
echo '<img alt="AisPanel" title="AisPanel"
src="https://placeholdit.imgix.net/~text?
txtsize=20&bg=eee&txtclr=8C8C8C%26text%3Dthree&txt=ap&w=650&h=420">';
}
?>
</a>
</div>
<div class="det">
<h2><a href="<?php the_permalink() ?>" title="<?php the_title();?
>"><?php the_title(); ?></a></h2>
<!--<?php if($n == 1) the_excerpt(); ?>-->
</div>
</div>
<?php endwhile;wp_reset_postdata(); ?>
</div>
</div>
</section>
``` | You can try `remove_filter( 'the_content', 'wpautop' );` to remove the added HTML tags.
<https://codex.wordpress.org/Function_Reference/wpautop> |
327,296 | <p>I am trying to understand how to add a class to a set of images in WordPress. Specifically I am trying to add a class, for example, <code>.no-lazy-load</code>, to exclude those images from being lazy loaded via the <a href="https://wordpress.org/plugins/a3-lazy-load/" rel="nofollow noreferrer">a3 Lazy Load plugin</a>. The set is a series of 6 images within a Slick slideshow, and they have no other class or id (other than the <code>.lazy-loaded</code> class added by the plugin) when the html is rendered.</p>
<p>I'm using the Jevelin theme with the Classic Editor plugin and don't see an option to add a class to an image via Advanced Options. In fact I don't see the Advanced options for editing the image at all.</p>
<p>I was thinking about using <a href="https://stackoverflow.com/questions/20473004/how-to-add-automatic-class-in-image-for-wordpress-post">something like this</a> but don't know how to add this hook to that set of images instead of all images in the DOM. For example, can I create an array of attachment IDs using <code>wp_get_attachment_image</code> and apply the hook to only those?</p>
<p>I'm not very well-versed in WordPress and apologize if this is an overly broad question. Any help or getting pointed in the right direction would be very much appreciated!</p>
| [
{
"answer_id": 327525,
"author": "Sabbir Hasan",
"author_id": 76587,
"author_profile": "https://wordpress.stackexchange.com/users/76587",
"pm_score": 0,
"selected": false,
"text": "<p>You can use jQuery to add remove classes on user browser. Approach can be something like this:</p>\n\n<pre><code>jQuery.( document ).ready(function($){\n $( \".lazy-loaded\" ).each(function() {\n //You can simply add the class then remove existing one like this\n $( this ).addClass( \"no-lazy-loaded\" ).removeClass('lazy-loaded');\n\n //You can just add the class like this\n $( this ).addClass( \"no-lazy-loaded\" );\n\n\n //Only use one of above methods\n });\n});\n</code></pre>\n\n<p>This will allow you to manipulate the output. You can add this in your footer.php file.</p>\n\n<p>****Again I'm just suggesting an approach.</p>\n"
},
{
"answer_id": 327651,
"author": "Alexander Holsgrove",
"author_id": 48962,
"author_profile": "https://wordpress.stackexchange.com/users/48962",
"pm_score": 3,
"selected": true,
"text": "<p>You can use the <a href=\"https://developer.wordpress.org/reference/hooks/get_image_tag_class/\" rel=\"nofollow noreferrer\">get_image_tag_class</a> filter which passes the attachment ID as an argument:</p>\n\n<pre><code>apply_filters('get_image_tag_class', string $class, int $id, string $align, string|array $size)\n</code></pre>\n\n<p>So you can use:</p>\n\n<pre><code>function my_image_tag_class($class, $id, $align, $size) {\n // Logic to check your attachment IDs\n if($some_logic) {\n $class .= ' no-lazy-loaded';\n }\n return $class;\n}\nadd_filter('get_image_tag_class','my_image_tag_class');\n</code></pre>\n\n<p>If you have an array of attachment IDs you want to filter, your logic would be:</p>\n\n<pre><code>if(in_array($id, $your_array_of_attachments)) { ...\n</code></pre>\n"
},
{
"answer_id": 327673,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 0,
"selected": false,
"text": "<p>It depends on through which hooks and functions does the mentioned plugin outputs the HTML. As you haven't posted the exact function (code) which generates the output.</p>\n\n<p>1) As we don't have enough time to dig into the plugin, I might suggest in unknown scenarios, a simple hook:</p>\n\n<pre><code>add_filter('a3_lazy_load_images_after','output_change');\n</code></pre>\n\n<p>// or even: add_filter('the_content','output_change');</p>\n\n<pre><code>function output_change($html_output) { \n return str_replace('.lazy-loaded', '.no-lazy-loaded', $html_output);\n}\n</code></pre>\n\n<p>2) This approach be used too:</p>\n\n<pre><code>add_filters( 'a3_lazy_load_run_filter', '__return_false');\n</code></pre>\n\n<p>before your chosen post is output. after that, restore the behavior:</p>\n\n<pre><code>add_filters( 'a3_lazy_load_run_filter', '__return_true');\n</code></pre>\n"
},
{
"answer_id": 328202,
"author": "tmdesigned",
"author_id": 28273,
"author_profile": "https://wordpress.stackexchange.com/users/28273",
"pm_score": 0,
"selected": false,
"text": "<p>It sounds like the easiest option is to add the class you want to the images yourself. You were looking for this option but said you could not find it. However if you are using the Classic Editor as you said, it is in fact possible.</p>\n\n<p>To add a class to an image using the classic editor:</p>\n\n<ol>\n<li>Add the image to the page using the Add Media button</li>\n<li>Once the image is in the editor, click it once to bring up the menu buttons</li>\n<li>Select the edit (pencil) button</li>\n<li>On the Image Details popup, click the words \"Advanced Options\" on the left</li>\n<li>Enter the class name you want (i.e. no-lazy-loaded) into the field, \"Image CSS\nClass\"</li>\n</ol>\n"
}
] | 2019/01/31 | [
"https://wordpress.stackexchange.com/questions/327296",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/152391/"
] | I am trying to understand how to add a class to a set of images in WordPress. Specifically I am trying to add a class, for example, `.no-lazy-load`, to exclude those images from being lazy loaded via the [a3 Lazy Load plugin](https://wordpress.org/plugins/a3-lazy-load/). The set is a series of 6 images within a Slick slideshow, and they have no other class or id (other than the `.lazy-loaded` class added by the plugin) when the html is rendered.
I'm using the Jevelin theme with the Classic Editor plugin and don't see an option to add a class to an image via Advanced Options. In fact I don't see the Advanced options for editing the image at all.
I was thinking about using [something like this](https://stackoverflow.com/questions/20473004/how-to-add-automatic-class-in-image-for-wordpress-post) but don't know how to add this hook to that set of images instead of all images in the DOM. For example, can I create an array of attachment IDs using `wp_get_attachment_image` and apply the hook to only those?
I'm not very well-versed in WordPress and apologize if this is an overly broad question. Any help or getting pointed in the right direction would be very much appreciated! | You can use the [get\_image\_tag\_class](https://developer.wordpress.org/reference/hooks/get_image_tag_class/) filter which passes the attachment ID as an argument:
```
apply_filters('get_image_tag_class', string $class, int $id, string $align, string|array $size)
```
So you can use:
```
function my_image_tag_class($class, $id, $align, $size) {
// Logic to check your attachment IDs
if($some_logic) {
$class .= ' no-lazy-loaded';
}
return $class;
}
add_filter('get_image_tag_class','my_image_tag_class');
```
If you have an array of attachment IDs you want to filter, your logic would be:
```
if(in_array($id, $your_array_of_attachments)) { ...
``` |
327,334 | <p>I have a (weird) issue - can't get the ACF field to work on my page. I have a simple <code>text_field</code> and it shows on the <code>Homepage</code> page section:</p>
<p>ACF settings:
<a href="https://i.stack.imgur.com/4pRMz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4pRMz.png" alt="enter image description here"></a>
<hr>
Homepage settings (when I refresh the panel it shows <code>Lorem ipsum</code> so it's saved in the databse):
<a href="https://i.stack.imgur.com/0rGHY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0rGHY.png" alt="enter image description here"></a></p>
<p>And in my <code>index.php</code> page I have:</p>
<pre><code><?php
$hero = the_field('hero_title');
/* tried also */
/* $hero = get_field('text_field'); */
echo '<h1>'.$hero.'</h1>';
?>
</code></pre>
<p>Where it shows the blank <code><h1></h1></code> on my page:<br>
<a href="https://i.stack.imgur.com/dvEz9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dvEz9.png" alt="enter image description here"></a></p>
<p>What am I doing wrong? I also tried with <code>group</code> type and I have the same issue.</p>
| [
{
"answer_id": 327336,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p><code>the_field()</code> function shows the value and it doesn't get/return anything. Like <code>the_title()</code> and other template tags starting with <code>the_</code>.</p>\n\n<p>It means that:</p>\n\n<p>This line prints the value and <code>$hero</code> variable is empty.</p>\n\n<pre><code>$hero = the_field('hero_title');\n</code></pre>\n\n<p>This line prints only <code><h1></code> tags.</p>\n\n<pre><code>echo '<h1>'.$hero.'</h1>';\n</code></pre>\n\n<p>What you want is:</p>\n\n<pre><code>echo '<h1>' . get_field('hero_title') . '</h1>';\n</code></pre>\n"
},
{
"answer_id": 327337,
"author": "Pratik Patel",
"author_id": 143123,
"author_profile": "https://wordpress.stackexchange.com/users/143123",
"pm_score": 1,
"selected": false,
"text": "<p>Try </p>\n\n<pre><code>$hero = get_field('hero_title');\n</code></pre>\n\n<p>Instead of</p>\n\n<pre><code>$hero = the_field('hero_title');\n</code></pre>\n"
}
] | 2019/02/01 | [
"https://wordpress.stackexchange.com/questions/327334",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/59688/"
] | I have a (weird) issue - can't get the ACF field to work on my page. I have a simple `text_field` and it shows on the `Homepage` page section:
ACF settings:
[](https://i.stack.imgur.com/4pRMz.png)
---
Homepage settings (when I refresh the panel it shows `Lorem ipsum` so it's saved in the databse):
[](https://i.stack.imgur.com/0rGHY.png)
And in my `index.php` page I have:
```
<?php
$hero = the_field('hero_title');
/* tried also */
/* $hero = get_field('text_field'); */
echo '<h1>'.$hero.'</h1>';
?>
```
Where it shows the blank `<h1></h1>` on my page:
[](https://i.stack.imgur.com/dvEz9.png)
What am I doing wrong? I also tried with `group` type and I have the same issue. | `the_field()` function shows the value and it doesn't get/return anything. Like `the_title()` and other template tags starting with `the_`.
It means that:
This line prints the value and `$hero` variable is empty.
```
$hero = the_field('hero_title');
```
This line prints only `<h1>` tags.
```
echo '<h1>'.$hero.'</h1>';
```
What you want is:
```
echo '<h1>' . get_field('hero_title') . '</h1>';
``` |
327,361 | <p>i have a problem with my woocommerce, I cant remove the page title in the product on desktop view. Anyone know what can i do ? thank you very much</p>
<p>store <a href="https://kingsport.ro" rel="nofollow noreferrer">https://kingsport.ro</a></p>
<p><a href="https://i.stack.imgur.com/KQNy6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KQNy6.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 327363,
"author": "Manoj Patel",
"author_id": 158186,
"author_profile": "https://wordpress.stackexchange.com/users/158186",
"pm_score": 0,
"selected": false,
"text": "<p>You can use below css to remove the title on desktop view through the media query</p>\n\n<pre><code>.post-type-archive-product .page-title {\n display: none;\n}\n</code></pre>\n"
},
{
"answer_id": 327364,
"author": "Chinmoy Kumar Paul",
"author_id": 57436,
"author_profile": "https://wordpress.stackexchange.com/users/57436",
"pm_score": 1,
"selected": false,
"text": "<p>Write the CSS into style.css file</p>\n\n<pre><code>@media only screen and (min-width: 768px) {\n .single-product .title-desc {\n display: none;\n }\n}\n</code></pre>\n\n<p><code>.single-product</code> CSS will only work on single product details. It will not create any issue on other pages.</p>\n"
}
] | 2019/02/01 | [
"https://wordpress.stackexchange.com/questions/327361",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/160326/"
] | i have a problem with my woocommerce, I cant remove the page title in the product on desktop view. Anyone know what can i do ? thank you very much
store <https://kingsport.ro>
[](https://i.stack.imgur.com/KQNy6.png) | Write the CSS into style.css file
```
@media only screen and (min-width: 768px) {
.single-product .title-desc {
display: none;
}
}
```
`.single-product` CSS will only work on single product details. It will not create any issue on other pages. |
327,365 | <p>Hey guys so I'm trying to enqueue a javascript with filemtime but every time I do it the custom js script I wrote doesn't seem to enqueue.</p>
<pre><code>function add_js_scripts(){
wp_register_script('lib',
get_template_directory_uri().'/js/lib.js',
array(),
filemtime(get_template_directory() . '/js/lib.js'),
null,
'all'
);
wp_enqueue_script('lib');
}
add_action('wp_enqueue_scripts','add_js_scripts');
</code></pre>
<p>The problem is now the lib.js file isnt showing up at all on the website. There are no php errors and if i remove the <code>filemtime</code> argument it shows up. Ive been version controlling it for development purposes.</p>
<p>Can someone tell me firstly if there is a better way to enqueue the script and if there is a way to enqueue it correctly with filemtime.</p>
<p>Also note i enqueued a style sheet successfully this way:</p>
<pre><code>function add_css_scripts() {
wp_register_style( 'style',
get_template_directory_uri() . '/style/style.css',
array(),
filemtime(get_template_directory() . '/style/style.css'),
null,
'all'
);
wp_enqueue_style('style');
}
add_action( 'wp_enqueue_scripts', 'add_css_scripts' );
</code></pre>
| [
{
"answer_id": 327366,
"author": "Chinmoy Kumar Paul",
"author_id": 57436,
"author_profile": "https://wordpress.stackexchange.com/users/57436",
"pm_score": 2,
"selected": false,
"text": "<p><strong>wp_register_script()</strong> function is accepting the 5 parameters. You are passing the 6 parameter. So replace the</p>\n\n<pre><code>wp_register_script(\n 'lib',\n get_template_directory_uri().'/js/lib.js', \n array(), \n filemtime(get_template_directory() . '/js/lib.js'), \n null, \n 'all'\n);\n</code></pre>\n\n<p>WITH</p>\n\n<pre><code>wp_register_script(\n 'lib',\n get_template_directory_uri().'/js/lib.js', \n array(), \n filemtime(get_template_directory() . '/js/lib.js'), \n true\n); \n</code></pre>\n"
},
{
"answer_id": 327371,
"author": "Zayd Bhyat",
"author_id": 93537,
"author_profile": "https://wordpress.stackexchange.com/users/93537",
"pm_score": 2,
"selected": true,
"text": "<p>So it seems that sometimes for some reason certain scripts dont seem to enqueue when you register the script then enqueue it when using filemtime in the parameter:</p>\n\n<pre><code>function add_js_scripts(){\nwp_register_script('lib',\nget_template_directory_uri().'/js/lib.js', \narray(),\nfilemtime(get_template_directory() . '/js/lib.js'), \ntrue); \nwp_enqueue_script('lib');\n}\nadd_action('wp_enqueue_scripts','add_js_scripts');\n</code></pre>\n\n<p>To solve this you can try and enqueue the script in one sub function like this:</p>\n\n<pre><code>wp_enqueue_script('lib',\nget_template_directory_uri().'/js/lib.js', array(),\nfilemtime(get_template_directory() . '/js/lib.js'), \ntrue); \n</code></pre>\n\n<p>This seemed to solve the problem of the script not enqueueing for me. I jsut wanna thank\nChinmoy Kumar Paul for guiding me in the right direction.</p>\n"
}
] | 2019/02/01 | [
"https://wordpress.stackexchange.com/questions/327365",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93537/"
] | Hey guys so I'm trying to enqueue a javascript with filemtime but every time I do it the custom js script I wrote doesn't seem to enqueue.
```
function add_js_scripts(){
wp_register_script('lib',
get_template_directory_uri().'/js/lib.js',
array(),
filemtime(get_template_directory() . '/js/lib.js'),
null,
'all'
);
wp_enqueue_script('lib');
}
add_action('wp_enqueue_scripts','add_js_scripts');
```
The problem is now the lib.js file isnt showing up at all on the website. There are no php errors and if i remove the `filemtime` argument it shows up. Ive been version controlling it for development purposes.
Can someone tell me firstly if there is a better way to enqueue the script and if there is a way to enqueue it correctly with filemtime.
Also note i enqueued a style sheet successfully this way:
```
function add_css_scripts() {
wp_register_style( 'style',
get_template_directory_uri() . '/style/style.css',
array(),
filemtime(get_template_directory() . '/style/style.css'),
null,
'all'
);
wp_enqueue_style('style');
}
add_action( 'wp_enqueue_scripts', 'add_css_scripts' );
``` | So it seems that sometimes for some reason certain scripts dont seem to enqueue when you register the script then enqueue it when using filemtime in the parameter:
```
function add_js_scripts(){
wp_register_script('lib',
get_template_directory_uri().'/js/lib.js',
array(),
filemtime(get_template_directory() . '/js/lib.js'),
true);
wp_enqueue_script('lib');
}
add_action('wp_enqueue_scripts','add_js_scripts');
```
To solve this you can try and enqueue the script in one sub function like this:
```
wp_enqueue_script('lib',
get_template_directory_uri().'/js/lib.js', array(),
filemtime(get_template_directory() . '/js/lib.js'),
true);
```
This seemed to solve the problem of the script not enqueueing for me. I jsut wanna thank
Chinmoy Kumar Paul for guiding me in the right direction. |
327,384 | <p>I've created a theme that includes a custom dashboard outside of wp-admin. </p>
<p>I would like a user who doesn't have access to the wp-admin (but does have access to my custom dashboard) to be able to receive an update notification for their theme.</p>
<p>If that's impossible, I could also work with the user just receiving the update notification, and sending them to wp-admin/themes.php, but that wouldn't be ideal.</p>
<p>Any ideas on how to push that notification to the front-end?</p>
<p>Edit -- This theme is hosted on a private GitHub repo, and updates are sent with <a href="https://github.com/afragen/github-updater" rel="nofollow noreferrer">this plugin.</a></p>
| [
{
"answer_id": 327366,
"author": "Chinmoy Kumar Paul",
"author_id": 57436,
"author_profile": "https://wordpress.stackexchange.com/users/57436",
"pm_score": 2,
"selected": false,
"text": "<p><strong>wp_register_script()</strong> function is accepting the 5 parameters. You are passing the 6 parameter. So replace the</p>\n\n<pre><code>wp_register_script(\n 'lib',\n get_template_directory_uri().'/js/lib.js', \n array(), \n filemtime(get_template_directory() . '/js/lib.js'), \n null, \n 'all'\n);\n</code></pre>\n\n<p>WITH</p>\n\n<pre><code>wp_register_script(\n 'lib',\n get_template_directory_uri().'/js/lib.js', \n array(), \n filemtime(get_template_directory() . '/js/lib.js'), \n true\n); \n</code></pre>\n"
},
{
"answer_id": 327371,
"author": "Zayd Bhyat",
"author_id": 93537,
"author_profile": "https://wordpress.stackexchange.com/users/93537",
"pm_score": 2,
"selected": true,
"text": "<p>So it seems that sometimes for some reason certain scripts dont seem to enqueue when you register the script then enqueue it when using filemtime in the parameter:</p>\n\n<pre><code>function add_js_scripts(){\nwp_register_script('lib',\nget_template_directory_uri().'/js/lib.js', \narray(),\nfilemtime(get_template_directory() . '/js/lib.js'), \ntrue); \nwp_enqueue_script('lib');\n}\nadd_action('wp_enqueue_scripts','add_js_scripts');\n</code></pre>\n\n<p>To solve this you can try and enqueue the script in one sub function like this:</p>\n\n<pre><code>wp_enqueue_script('lib',\nget_template_directory_uri().'/js/lib.js', array(),\nfilemtime(get_template_directory() . '/js/lib.js'), \ntrue); \n</code></pre>\n\n<p>This seemed to solve the problem of the script not enqueueing for me. I jsut wanna thank\nChinmoy Kumar Paul for guiding me in the right direction.</p>\n"
}
] | 2019/02/01 | [
"https://wordpress.stackexchange.com/questions/327384",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/160341/"
] | I've created a theme that includes a custom dashboard outside of wp-admin.
I would like a user who doesn't have access to the wp-admin (but does have access to my custom dashboard) to be able to receive an update notification for their theme.
If that's impossible, I could also work with the user just receiving the update notification, and sending them to wp-admin/themes.php, but that wouldn't be ideal.
Any ideas on how to push that notification to the front-end?
Edit -- This theme is hosted on a private GitHub repo, and updates are sent with [this plugin.](https://github.com/afragen/github-updater) | So it seems that sometimes for some reason certain scripts dont seem to enqueue when you register the script then enqueue it when using filemtime in the parameter:
```
function add_js_scripts(){
wp_register_script('lib',
get_template_directory_uri().'/js/lib.js',
array(),
filemtime(get_template_directory() . '/js/lib.js'),
true);
wp_enqueue_script('lib');
}
add_action('wp_enqueue_scripts','add_js_scripts');
```
To solve this you can try and enqueue the script in one sub function like this:
```
wp_enqueue_script('lib',
get_template_directory_uri().'/js/lib.js', array(),
filemtime(get_template_directory() . '/js/lib.js'),
true);
```
This seemed to solve the problem of the script not enqueueing for me. I jsut wanna thank
Chinmoy Kumar Paul for guiding me in the right direction. |
327,395 | <p>I've seen this solution for querying pages based off of template type: <a href="https://wordpress.stackexchange.com/questions/29918/page-template-query-with-wp-query">Page template query with WP_Query</a></p>
<p>I'm having trouble getting it to work with posts, that are using a "Single Post Template:" rather than a "Template Name:" definition.</p>
<p>Here is my code:</p>
<pre><code> // query
$the_query = new WP_Query( array(
'post_type' => 'post',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => '_wp_page_template',
'value' => 'single-current.php'
)
)
));
</code></pre>
<p>Is there a different 'key' I should be using? </p>
<p>Something like '_wp_post_template'</p>
<p>Thanks.</p>
| [
{
"answer_id": 327366,
"author": "Chinmoy Kumar Paul",
"author_id": 57436,
"author_profile": "https://wordpress.stackexchange.com/users/57436",
"pm_score": 2,
"selected": false,
"text": "<p><strong>wp_register_script()</strong> function is accepting the 5 parameters. You are passing the 6 parameter. So replace the</p>\n\n<pre><code>wp_register_script(\n 'lib',\n get_template_directory_uri().'/js/lib.js', \n array(), \n filemtime(get_template_directory() . '/js/lib.js'), \n null, \n 'all'\n);\n</code></pre>\n\n<p>WITH</p>\n\n<pre><code>wp_register_script(\n 'lib',\n get_template_directory_uri().'/js/lib.js', \n array(), \n filemtime(get_template_directory() . '/js/lib.js'), \n true\n); \n</code></pre>\n"
},
{
"answer_id": 327371,
"author": "Zayd Bhyat",
"author_id": 93537,
"author_profile": "https://wordpress.stackexchange.com/users/93537",
"pm_score": 2,
"selected": true,
"text": "<p>So it seems that sometimes for some reason certain scripts dont seem to enqueue when you register the script then enqueue it when using filemtime in the parameter:</p>\n\n<pre><code>function add_js_scripts(){\nwp_register_script('lib',\nget_template_directory_uri().'/js/lib.js', \narray(),\nfilemtime(get_template_directory() . '/js/lib.js'), \ntrue); \nwp_enqueue_script('lib');\n}\nadd_action('wp_enqueue_scripts','add_js_scripts');\n</code></pre>\n\n<p>To solve this you can try and enqueue the script in one sub function like this:</p>\n\n<pre><code>wp_enqueue_script('lib',\nget_template_directory_uri().'/js/lib.js', array(),\nfilemtime(get_template_directory() . '/js/lib.js'), \ntrue); \n</code></pre>\n\n<p>This seemed to solve the problem of the script not enqueueing for me. I jsut wanna thank\nChinmoy Kumar Paul for guiding me in the right direction.</p>\n"
}
] | 2019/02/01 | [
"https://wordpress.stackexchange.com/questions/327395",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/160347/"
] | I've seen this solution for querying pages based off of template type: [Page template query with WP\_Query](https://wordpress.stackexchange.com/questions/29918/page-template-query-with-wp-query)
I'm having trouble getting it to work with posts, that are using a "Single Post Template:" rather than a "Template Name:" definition.
Here is my code:
```
// query
$the_query = new WP_Query( array(
'post_type' => 'post',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => '_wp_page_template',
'value' => 'single-current.php'
)
)
));
```
Is there a different 'key' I should be using?
Something like '\_wp\_post\_template'
Thanks. | So it seems that sometimes for some reason certain scripts dont seem to enqueue when you register the script then enqueue it when using filemtime in the parameter:
```
function add_js_scripts(){
wp_register_script('lib',
get_template_directory_uri().'/js/lib.js',
array(),
filemtime(get_template_directory() . '/js/lib.js'),
true);
wp_enqueue_script('lib');
}
add_action('wp_enqueue_scripts','add_js_scripts');
```
To solve this you can try and enqueue the script in one sub function like this:
```
wp_enqueue_script('lib',
get_template_directory_uri().'/js/lib.js', array(),
filemtime(get_template_directory() . '/js/lib.js'),
true);
```
This seemed to solve the problem of the script not enqueueing for me. I jsut wanna thank
Chinmoy Kumar Paul for guiding me in the right direction. |
327,396 | <p>I want to set the <em>default</em> target of the image block in Gutenberg to "Media File":</p>
<p><a href="https://i.stack.imgur.com/thhKx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/thhKx.png" alt="Link target"></a></p>
<p>I've found solutions for the <a href="https://wordpress.stackexchange.com/questions/251429/set-default-options-for-inserting-media">classic editor</a>, and one that appears to work for <a href="https://wordpress.stackexchange.com/a/323224/138112">Gutenberg galleries</a> by editing the block's template, but I was under the impression that the intended way to modify the editor's behaviour is via JavaScript hooks in the block editor.</p>
<p>Is there a way to set the default target using a JavaScript hook in the block editor?</p>
<p>UPDATE: I made a pull request on the Gutenberg GitHub repository to try to implement the ability to override the default link target with a plugin. The latest version is <a href="https://github.com/WordPress/gutenberg/pull/17401" rel="nofollow noreferrer">here</a>. As of writing, this has not yet been merged.</p>
| [
{
"answer_id": 327400,
"author": "Alvaro",
"author_id": 16533,
"author_profile": "https://wordpress.stackexchange.com/users/16533",
"pm_score": 2,
"selected": false,
"text": "<p>Using the filter <code>blocks.registerBlockType</code> we can alter block registration settings. We simply need to target the <code>core/image</code> block and modify the default value for the attribute <code>linkDestination</code> which is <em>none</em> by default.</p>\n\n<pre><code>function modifyLinkDestinationDefault(settings, name) {\n if (name !== \"core/image\") {\n return settings;\n }\n\n settings.attributes.linkDestination.default = \"media\";\n\n return settings;\n}\n\nwp.hooks.addFilter(\n \"blocks.registerBlockType\",\n \"my-plugin/modify-linkDestination-default\",\n modifyLinkDestinationDefault\n);\n</code></pre>\n"
},
{
"answer_id": 379463,
"author": "Will",
"author_id": 48698,
"author_profile": "https://wordpress.stackexchange.com/users/48698",
"pm_score": 3,
"selected": true,
"text": "<p>This was (finally) fixed to Gutenberg (and will be applicable for both the image and the gallery blocks); and will add an option to WordPress options' database table.\nthis was done in\n<a href=\"https://github.com/WordPress/gutenberg/pull/25578\" rel=\"nofollow noreferrer\">https://github.com/WordPress/gutenberg/pull/25578</a> and <a href=\"https://github.com/WordPress/gutenberg/pull/25582\" rel=\"nofollow noreferrer\">https://github.com/WordPress/gutenberg/pull/25582</a></p>\n<p>It'll be added to WordPress 5.6 but it's already available in the Gutenberg plugin.</p>\n<p>To link the image to the file by default, issue the following in your theme or plugin:</p>\n<pre><code>add_action( 'after_setup_theme', function() {\n update_option( 'image_default_link_type', 'file' );\n});\n</code></pre>\n<p>Replace <code>file</code> with <code>attachment</code> if you want to link to the attachment page for some reason, or <code>none</code> if you don't want to the image to have a link.</p>\n<p>As for javascript: modifying blocks so that they alter the site's options is possible in Gutenberg although I haven't gotten it to work yet, check out:\n<a href=\"https://github.com/WordPress/gutenberg/issues/20731\" rel=\"nofollow noreferrer\">https://github.com/WordPress/gutenberg/issues/20731</a></p>\n<p>Note that if you try do the image_default_link_type equivalent in javascript, don't use "file" and "post" as the options (as long as this ticket is open) - see <a href=\"https://github.com/WordPress/gutenberg/issues/25587\" rel=\"nofollow noreferrer\">https://github.com/WordPress/gutenberg/issues/25587</a></p>\n"
},
{
"answer_id": 397086,
"author": "Fabien",
"author_id": 213805,
"author_profile": "https://wordpress.stackexchange.com/users/213805",
"pm_score": 0,
"selected": false,
"text": "<p>The correct default attributes for linkTo in core/gallery it's that :</p>\n<pre><code>settings.attributes.linkTo.default = 'file';\n</code></pre>\n"
}
] | 2019/02/01 | [
"https://wordpress.stackexchange.com/questions/327396",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/138112/"
] | I want to set the *default* target of the image block in Gutenberg to "Media File":
[](https://i.stack.imgur.com/thhKx.png)
I've found solutions for the [classic editor](https://wordpress.stackexchange.com/questions/251429/set-default-options-for-inserting-media), and one that appears to work for [Gutenberg galleries](https://wordpress.stackexchange.com/a/323224/138112) by editing the block's template, but I was under the impression that the intended way to modify the editor's behaviour is via JavaScript hooks in the block editor.
Is there a way to set the default target using a JavaScript hook in the block editor?
UPDATE: I made a pull request on the Gutenberg GitHub repository to try to implement the ability to override the default link target with a plugin. The latest version is [here](https://github.com/WordPress/gutenberg/pull/17401). As of writing, this has not yet been merged. | This was (finally) fixed to Gutenberg (and will be applicable for both the image and the gallery blocks); and will add an option to WordPress options' database table.
this was done in
<https://github.com/WordPress/gutenberg/pull/25578> and <https://github.com/WordPress/gutenberg/pull/25582>
It'll be added to WordPress 5.6 but it's already available in the Gutenberg plugin.
To link the image to the file by default, issue the following in your theme or plugin:
```
add_action( 'after_setup_theme', function() {
update_option( 'image_default_link_type', 'file' );
});
```
Replace `file` with `attachment` if you want to link to the attachment page for some reason, or `none` if you don't want to the image to have a link.
As for javascript: modifying blocks so that they alter the site's options is possible in Gutenberg although I haven't gotten it to work yet, check out:
<https://github.com/WordPress/gutenberg/issues/20731>
Note that if you try do the image\_default\_link\_type equivalent in javascript, don't use "file" and "post" as the options (as long as this ticket is open) - see <https://github.com/WordPress/gutenberg/issues/25587> |
327,403 | <p>I'm using my featured image as a background image on a div and I would like to add a second background-image to that same div on hover (I need them both because I want to blend them). Any suggestions?</p>
<p>I was able to achieve that using regular html and css, but now that I'm using the featured image as the background, I can't figure it out. Any suggestions?</p>
| [
{
"answer_id": 327405,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>If you want something to happen when you 'hover', you can do that with some CSS. Assign a id (since they need to be unique, so your CSS will only affect the div with that id) of some name to the image tag, then use this as a starting point: <a href=\"https://www.w3schools.com/howto/howto_css_image_overlay.asp\" rel=\"nofollow noreferrer\">https://www.w3schools.com/howto/howto_css_image_overlay.asp</a> </p>\n\n<p>You could also use some JS to change things. But CSS will work. The above link will give you some ideas.</p>\n\n<p>You might also be interested in this question <a href=\"https://stackoverflow.com/questions/18813299/changing-image-on-hover-with-css-html\">https://stackoverflow.com/questions/18813299/changing-image-on-hover-with-css-html</a> , which does something similar to what you want with this code:</p>\n\n<pre><code><div id=\"Library\"></div>\n\n#Library {\n background-image: url('LibraryTransparent.png');\n height: 70px;\n width: 120px;\n}\n\n#Library:hover {\n background-image: url('LibraryHoverTrans.png');\n}\n</code></pre>\n\n<p>The first CSS will set a background image for that div, and the second will change the background image on a hover. The first link also has references to some transition stuff, so you can fade-in/fade-out.</p>\n"
},
{
"answer_id": 327409,
"author": "C C",
"author_id": 83299,
"author_profile": "https://wordpress.stackexchange.com/users/83299",
"pm_score": 1,
"selected": false,
"text": "<p>Use a single element, with a pseudo element (:before) for the featured image, and appropriate hover styling to set its opacity and reveal a blend with the underlying second image. I threw in a gradual image transition just to make it look a little nicer.</p>\n\n<p><strong>html:</strong></p>\n\n<pre><code><div class=\"my-image-holder\">\n text and other contents we don't want affected by opacity\n</div>\n</code></pre>\n\n<p><strong>css:</strong></p>\n\n<pre><code>.my-image-holder {\n position: relative;\n z-index:1;\n width:200px;\n height:200px;\n margin:30px;\n background-image: url('//some-url-to-second-image');\n background-size: contain;\n font-size: 1.2em;\n color: white;\n}\n\n.my-image-holder:before {\n z-index:-1;\n position:absolute;\n width:200px;\n height:200px;\n left:0;\n top:0;\n content: url('//some-url-to-featured-image');\n opacity:1.0;\n -webkit-transition: opacity 1s linear;\n -o-transition: opacity 1s linear;\n -moz-transition: opacity 1s linear;\n transition: opacity 1s linear;\n}\n\n.my-image-holder:hover:before {\n opacity:0.5;\n}\n</code></pre>\n\n<p><strong><a href=\"https://jsfiddle.net/L59ydhmx/\" rel=\"nofollow noreferrer\">Example JSFiddle</a></strong></p>\n"
},
{
"answer_id": 327417,
"author": "CK MacLeod",
"author_id": 35923,
"author_profile": "https://wordpress.stackexchange.com/users/35923",
"pm_score": 0,
"selected": false,
"text": "<p>You can assign multiple background images to the same div.</p>\n\n<pre><code>#sample-div {\n background-image: url(/folder/image.jpg);\n}\n#sample-div:hover {\n background-image: url(/folder/image.jpg), url(/folder/image2.jpg);\n}\n</code></pre>\n\n<p>Each image can be separately assigned size, position, and other properties. See basics here: <a href=\"https://www.w3schools.com/css/css3_backgrounds.asp\" rel=\"nofollow noreferrer\">https://www.w3schools.com/css/css3_backgrounds.asp</a>. However, you may need pseudo-elements or absolute positioning of \"regular\" images, and so on, if you want to achieve smooth transitions, as mentioned in the other answers. </p>\n"
},
{
"answer_id": 327529,
"author": "lulufv",
"author_id": 160353,
"author_profile": "https://wordpress.stackexchange.com/users/160353",
"pm_score": 0,
"selected": false,
"text": "<p>Thank you guys! I actually figured it out and it was pretty easy. I just added both background images and changed the background-blend-mode from normal to multiply on hover.</p>\n"
}
] | 2019/02/02 | [
"https://wordpress.stackexchange.com/questions/327403",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/160353/"
] | I'm using my featured image as a background image on a div and I would like to add a second background-image to that same div on hover (I need them both because I want to blend them). Any suggestions?
I was able to achieve that using regular html and css, but now that I'm using the featured image as the background, I can't figure it out. Any suggestions? | Use a single element, with a pseudo element (:before) for the featured image, and appropriate hover styling to set its opacity and reveal a blend with the underlying second image. I threw in a gradual image transition just to make it look a little nicer.
**html:**
```
<div class="my-image-holder">
text and other contents we don't want affected by opacity
</div>
```
**css:**
```
.my-image-holder {
position: relative;
z-index:1;
width:200px;
height:200px;
margin:30px;
background-image: url('//some-url-to-second-image');
background-size: contain;
font-size: 1.2em;
color: white;
}
.my-image-holder:before {
z-index:-1;
position:absolute;
width:200px;
height:200px;
left:0;
top:0;
content: url('//some-url-to-featured-image');
opacity:1.0;
-webkit-transition: opacity 1s linear;
-o-transition: opacity 1s linear;
-moz-transition: opacity 1s linear;
transition: opacity 1s linear;
}
.my-image-holder:hover:before {
opacity:0.5;
}
```
**[Example JSFiddle](https://jsfiddle.net/L59ydhmx/)** |
327,416 | <p>I'm working on a site for a school and the teachers all want to post the homework for their students online, but only so each student can see his or her own class's homework posted by their teacher.</p>
<p>What i want to do is basically this: </p>
<ul>
<li>get user role</li>
<li>if user role = rolename1, display posts by category 1, hide all other posts</li>
<li>if user role = rolename2, display posts by category 2, hide all other posts</li>
<li>and so on for the 22 different user roles </li>
</ul>
<p>All of these user roles are subscriber levels, I just have them broken down this way as it was the easiest way to separate them into categories.</p>
<p>Ideally I want to have one blog page where the feed for all the posts for the site are displayed and you only see the ones that are appropriate for you within this feed. Everything else is hidden.</p>
<p>I also want to restrict each author to using only the categories I assign them rather than choosing from all the categories available.</p>
<p>Any ideas? Snippets or plugin recommendations would be highly appreciated.</p>
| [
{
"answer_id": 327428,
"author": "Md. Ehsanul Haque Kanan",
"author_id": 75705,
"author_profile": "https://wordpress.stackexchange.com/users/75705",
"pm_score": 0,
"selected": false,
"text": "<p>You can try using <a href=\"https://wordpress.org/plugins/wp-private-content-plus/\" rel=\"nofollow noreferrer\">WP Private Content Plus</a> plugin. It allows you to restrict your content to specific user roles or or group of selected users. You just need to use the shortcode. </p>\n\n<p>For multiple user roles, you have to use this shortcode:</p>\n\n<pre><code>[wppcp_private_content allowed_roles=\"subscriber,editor\" ]\nPrivate Content for Users with\nSubscriber or Editor User Role\n[/wppcp_private_content]\n</code></pre>\n"
},
{
"answer_id": 327737,
"author": "Bram",
"author_id": 60517,
"author_profile": "https://wordpress.stackexchange.com/users/60517",
"pm_score": 1,
"selected": false,
"text": "<p>The problem consists of three parts: getting the current user data, linking that to a category and retrieving and displaying the posts. You can include these snippets on a custom page template, which you assign to the 'My homework'-page. </p>\n\n<p>Below these three sub-answers, I share some additional suggestions on ways of making this more user-friendly / user-manageable. </p>\n\n<h1>Getting the user data</h1>\n\n<p>This is done very easily using <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_current_user\" rel=\"nofollow noreferrer\"><code>wp_get_current_user</code></a>. This yields a <a href=\"https://codex.wordpress.org/Class_Reference/WP_User\" rel=\"nofollow noreferrer\">WordPress User object</a>, from which you can retrieve the roles using <code>$current_user->roles</code> (assuming you have set <code>$current_user = wp_get_current_user();</code>). This yields an array. I'm assuming the users only have one role, so that the first element in that array is the element we're checking against.</p>\n\n<h1>Linking users to categories</h1>\n\n<p>You can do this using an <code>if-elseif</code>-statement, as follows.</p>\n\n<pre><code>$roles = $current_user->roles;\n\nif ($roles[0] == 'role'){\n $category_name = 'category-name';\n}elseif ($roles[0] == 'other-role'){\n $category_name = 'other-category-name';\n}\n</code></pre>\n\n<p>You can extend this as you like, by adding additional <code>elseif</code>-clauses. Replace <code>role</code> (and <code>other-role</code>) by the slugs of the roles, and <code>category-name</code> and <code>other-category-name</code> by the slugs of the categories.</p>\n\n<h1>Retrieving and displaying the posts</h1>\n\n<p>Using <code>$category_name</code> in the arguments of a <code>WP_Query</code> limits the result that query retrieves to the categories.</p>\n\n<pre><code>$qrt_args = array(\n 'category_name' => $category_name\n);\n\n$posts = new WP_Query( $qry_args ); \n</code></pre>\n\n<p>You can now use <code>$posts</code> in a regular <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Multiple_Loops\" rel=\"nofollow noreferrer\">loop</a> and display the results.</p>\n\n<h1>Other ideas</h1>\n\n<p>Although the code above should work (haven't tested it), it requires you to edit code in order to make adjustments. That might be less convenient, for example if you at some point in time, are unavailable to make these changes.</p>\n\n<p>Another option is to create a post for each student, subsequently assign the relevant category (or categories) to that post and set the author as the student. This way, you can match students and categories in the Wordpress Dashboard. Also, this provides a little more flexibility and robustness, for example to assign multiple categories to the same student. (The code posted above assumes only one category.) Of course, this will also display the post you've used to set up the match on the page with homework problems, but you can use that to your benefit (\"Hey John, please find your homework problems below\"). It is, however, also possible to prevent that from happening using an additional category or tag.</p>\n\n<p>Another option, which is even nicer but also a bit more difficult to implement, is to create a new usermeta-field in which you save which categories of posts that user should be able to see. </p>\n\n<p>Please note this does not (yet) provide a solution to this part of your problem:</p>\n\n<blockquote>\n <p>I also want to restrict each author to using only the categories I assign them rather than choosing from all the categories available.</p>\n</blockquote>\n"
}
] | 2019/02/02 | [
"https://wordpress.stackexchange.com/questions/327416",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37676/"
] | I'm working on a site for a school and the teachers all want to post the homework for their students online, but only so each student can see his or her own class's homework posted by their teacher.
What i want to do is basically this:
* get user role
* if user role = rolename1, display posts by category 1, hide all other posts
* if user role = rolename2, display posts by category 2, hide all other posts
* and so on for the 22 different user roles
All of these user roles are subscriber levels, I just have them broken down this way as it was the easiest way to separate them into categories.
Ideally I want to have one blog page where the feed for all the posts for the site are displayed and you only see the ones that are appropriate for you within this feed. Everything else is hidden.
I also want to restrict each author to using only the categories I assign them rather than choosing from all the categories available.
Any ideas? Snippets or plugin recommendations would be highly appreciated. | The problem consists of three parts: getting the current user data, linking that to a category and retrieving and displaying the posts. You can include these snippets on a custom page template, which you assign to the 'My homework'-page.
Below these three sub-answers, I share some additional suggestions on ways of making this more user-friendly / user-manageable.
Getting the user data
=====================
This is done very easily using [`wp_get_current_user`](https://codex.wordpress.org/Function_Reference/wp_get_current_user). This yields a [WordPress User object](https://codex.wordpress.org/Class_Reference/WP_User), from which you can retrieve the roles using `$current_user->roles` (assuming you have set `$current_user = wp_get_current_user();`). This yields an array. I'm assuming the users only have one role, so that the first element in that array is the element we're checking against.
Linking users to categories
===========================
You can do this using an `if-elseif`-statement, as follows.
```
$roles = $current_user->roles;
if ($roles[0] == 'role'){
$category_name = 'category-name';
}elseif ($roles[0] == 'other-role'){
$category_name = 'other-category-name';
}
```
You can extend this as you like, by adding additional `elseif`-clauses. Replace `role` (and `other-role`) by the slugs of the roles, and `category-name` and `other-category-name` by the slugs of the categories.
Retrieving and displaying the posts
===================================
Using `$category_name` in the arguments of a `WP_Query` limits the result that query retrieves to the categories.
```
$qrt_args = array(
'category_name' => $category_name
);
$posts = new WP_Query( $qry_args );
```
You can now use `$posts` in a regular [loop](https://codex.wordpress.org/Class_Reference/WP_Query#Multiple_Loops) and display the results.
Other ideas
===========
Although the code above should work (haven't tested it), it requires you to edit code in order to make adjustments. That might be less convenient, for example if you at some point in time, are unavailable to make these changes.
Another option is to create a post for each student, subsequently assign the relevant category (or categories) to that post and set the author as the student. This way, you can match students and categories in the Wordpress Dashboard. Also, this provides a little more flexibility and robustness, for example to assign multiple categories to the same student. (The code posted above assumes only one category.) Of course, this will also display the post you've used to set up the match on the page with homework problems, but you can use that to your benefit ("Hey John, please find your homework problems below"). It is, however, also possible to prevent that from happening using an additional category or tag.
Another option, which is even nicer but also a bit more difficult to implement, is to create a new usermeta-field in which you save which categories of posts that user should be able to see.
Please note this does not (yet) provide a solution to this part of your problem:
>
> I also want to restrict each author to using only the categories I assign them rather than choosing from all the categories available.
>
>
> |
327,424 | <p>The links in the navbar menu, in (My sites > Manage the network) are pointing (and keep redirecting) to incorrect URLs.</p>
<p>The incorrect URLs are in this pattern:</p>
<pre><code>https://https//www.domain.com/wp-admin/network/
https://https//www.domain.com/wp-admin/network/sites.php
https://https//www.domain.com/wp-admin/network/settings.php
</code></pre>
<p>Even if I manually entered the correct URL without the repeated https, I am redirected to the wrong URL again.</p>
<p>It seems that <code>https//www</code> is set somewhere instead of <code>https://www</code>, I can't find where.</p>
<p>Places that I have looked and they were OK:</p>
<ul>
<li>wp-config.php (DOMAIN_CURRENT_SITE)</li>
<li>.htaccess</li>
<li>site table (domain only, with www but not https or /)</li>
<li>options table (situeurl and home)</li>
<li>sitemeta table</li>
</ul>
<p>I haven't updated any of the above-mentioned. They were OK. (So not cache issue)</p>
<p>I tried the Search option of my phpMyAdmin using <code>https//www</code> but didn't return any match.</p>
<p>Where else should I look?</p>
| [
{
"answer_id": 327425,
"author": "Md. Ehsanul Haque Kanan",
"author_id": 75705,
"author_profile": "https://wordpress.stackexchange.com/users/75705",
"pm_score": 0,
"selected": false,
"text": "<p>Have you checked <strong>wp_blogs</strong>? Is it OK?</p>\n\n<p>Also, make sure that all the pre-defined constants in your <strong>wp-config.php</strong> file are commented out. Otherwise, they will override the database settings.</p>\n"
},
{
"answer_id": 327426,
"author": "Arvind Singh",
"author_id": 113501,
"author_profile": "https://wordpress.stackexchange.com/users/113501",
"pm_score": 0,
"selected": false,
"text": "<p>Add this code to your <strong>wp-config.php</strong> file,</p>\n\n<pre><code>define('WP_HOME','https://yoursite.com');\ndefine('WP_SITEURL','https://yoursite.com');\n</code></pre>\n\n<p>If still, you face the issue then login to your <strong>phpMyAdmin</strong> and then,</p>\n\n<ul>\n<li>Choose the name of the database from the left-hand sidebar and open the <strong>wp_options</strong> database table.</li>\n<li>Search for the site URL and home rows, click edit to modify the URLs. You can see a box in front of <strong>option_value</strong> to fill in the URL.</li>\n<li>Click on the <strong>Go</strong> button to save settings.</li>\n</ul>\n\n<p>Also, make your URL start with https:// not http// (you mentioned above) </p>\n"
},
{
"answer_id": 327451,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 2,
"selected": false,
"text": "<p>The multisite URLs are available for editing on the Network Admin, Sites page, then edit the subsites (click on a subsite's edit link, then the Settings tab). You can only do this for subsites. </p>\n\n<p>The 'siteurl' and 'home' values should be the full URL of the site, including the protocol, as in <a href=\"https://www.example.com/site1\" rel=\"nofollow noreferrer\">https://www.example.com/site1</a> . If those values do not include the protocol (the 'https://' part), then any links of the site will include the 'double protocol' value that you are experiencing.</p>\n\n<p>The main site URL cannot be edited on this screen; go into the wp-options table to fix that (in two places).</p>\n\n<p>I never change the site URLs in the wp-config.php file, as suggested by other answers and comments. The proper place (IMHO) to make the site URL setting is the wp-options table (for the main site), and the procedure above for the sub-sites.</p>\n\n<p>Note that the above procedure will also let you change any incorrect URLs saved by any plugins that write to the options table. I've had to change that a couple of times when I moved a site to a new domain.</p>\n"
},
{
"answer_id": 334109,
"author": "Дтдця",
"author_id": 127652,
"author_profile": "https://wordpress.stackexchange.com/users/127652",
"pm_score": 3,
"selected": false,
"text": "<p>There are 5 values need to change. \nFrom database.</p>\n\n<pre><code>wp_options: options named “siteurl” and “home”\n\nwp_site\n\nwp_sitemeta: the option named “siteurl”\n\nwp_blogs: any entries in the “domains” column that have the old domain name\n\nwp_#_options: Each sub-site will have sets of tables that correspond to the blog_id in the wp_blogs table. You need to go to the wp_#_options table, where # corresponds to the blog_id, and update the “siteurl” and “home” settings in that table.\n</code></pre>\n\n<p>Note: In most cases, you may/will need to update an entry in your WP-Config.php file. The code I would recommend taking a look at is the code snippet here:</p>\n\n<pre><code>define('WP_ALLOW_MULTISITE', true);\ndefine( 'MULTISITE', true );\ndefine( 'SUBDOMAIN_INSTALL', true );\n$base = '/';\ndefine( 'DOMAIN_CURRENT_SITE', 'mysite.com' );\ndefine( 'PATH_CURRENT_SITE', '/' );\ndefine( 'SITE_ID_CURRENT_SITE', 1 );\ndefine( 'BLOG_ID_CURRENT_SITE', 1 );\n</code></pre>\n"
},
{
"answer_id": 359557,
"author": "Shahzaib Chadhar",
"author_id": 183408,
"author_profile": "https://wordpress.stackexchange.com/users/183408",
"pm_score": 0,
"selected": false,
"text": "<p>You have to change at two places:</p>\n\n<p>1- in Database wp_blogs table change <code>example.com to www.example.com</code></p>\n\n<p>2- in wp-config.php change <code>define('DOMAIN_CURRENT_SITE', 'example.com'); to define('DOMAIN_CURRENT_SITE', 'www.example.com');</code></p>\n\n<p>It will work automatically.</p>\n"
},
{
"answer_id": 377166,
"author": "Albert S.",
"author_id": 142181,
"author_profile": "https://wordpress.stackexchange.com/users/142181",
"pm_score": 0,
"selected": false,
"text": "<p>Simply change this in phpmyadmin in "prefix"_options table siteurl & homeurl in column option_name</p>\n"
}
] | 2019/02/02 | [
"https://wordpress.stackexchange.com/questions/327424",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101507/"
] | The links in the navbar menu, in (My sites > Manage the network) are pointing (and keep redirecting) to incorrect URLs.
The incorrect URLs are in this pattern:
```
https://https//www.domain.com/wp-admin/network/
https://https//www.domain.com/wp-admin/network/sites.php
https://https//www.domain.com/wp-admin/network/settings.php
```
Even if I manually entered the correct URL without the repeated https, I am redirected to the wrong URL again.
It seems that `https//www` is set somewhere instead of `https://www`, I can't find where.
Places that I have looked and they were OK:
* wp-config.php (DOMAIN\_CURRENT\_SITE)
* .htaccess
* site table (domain only, with www but not https or /)
* options table (situeurl and home)
* sitemeta table
I haven't updated any of the above-mentioned. They were OK. (So not cache issue)
I tried the Search option of my phpMyAdmin using `https//www` but didn't return any match.
Where else should I look? | There are 5 values need to change.
From database.
```
wp_options: options named “siteurl” and “home”
wp_site
wp_sitemeta: the option named “siteurl”
wp_blogs: any entries in the “domains” column that have the old domain name
wp_#_options: Each sub-site will have sets of tables that correspond to the blog_id in the wp_blogs table. You need to go to the wp_#_options table, where # corresponds to the blog_id, and update the “siteurl” and “home” settings in that table.
```
Note: In most cases, you may/will need to update an entry in your WP-Config.php file. The code I would recommend taking a look at is the code snippet here:
```
define('WP_ALLOW_MULTISITE', true);
define( 'MULTISITE', true );
define( 'SUBDOMAIN_INSTALL', true );
$base = '/';
define( 'DOMAIN_CURRENT_SITE', 'mysite.com' );
define( 'PATH_CURRENT_SITE', '/' );
define( 'SITE_ID_CURRENT_SITE', 1 );
define( 'BLOG_ID_CURRENT_SITE', 1 );
``` |
327,447 | <p>I have a taxonomy called <code>coupon_category</code>. In a <code>query_post</code> I am trying to call all posts from related custom taxonomy with the same <code>coupon_category</code>.</p>
<p>If I use:</p>
<pre><code><?php
// show all active coupons for this category from related store and setup pagination
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts( array(
'post_type' => APP_POST_TYPE,
'post_status' => 'publish',
'posts_per_page' => 4,
'tax_query' => array(
array(
'taxonomy' => 'coupon_category',
'field' => 'slug',
'terms' => 'mode',
),
)
) );
?>
</code></pre>
<p>I can show all related posts with the term "mode" however I would like to automate it, so that always the terms (<code>coupon_category</code>) that are already in use on the page are shown.</p>
| [
{
"answer_id": 327455,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 0,
"selected": false,
"text": "<p>You'll have to get the terms of current post with <code>get_the_terms</code> function and then use them in your query.</p>\n\n<pre><code>// this will get terms and then get only term_ids from them\n$term_ids = wp_list_pluck( get_the_terms( get_the_ID(), 'coupon_category' ), 'term_id' );\n\n$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;\n$related = new WP_Query( array(\n 'post_type' => APP_POST_TYPE,\n 'post_status' => 'publish',\n 'posts_per_page' => 4,\n 'tax_query' => array( \n array(\n 'taxonomy' => 'coupon_category', \n 'field' => 'term_id',\n 'terms' => $term_ids, \n ),\n )\n) ); \n</code></pre>\n\n<p>So we use <a href=\"https://developer.wordpress.org/reference/functions/get_the_terms/\" rel=\"nofollow noreferrer\"><code>get_the_terms</code></a> to get list of terms for current post and then we call <a href=\"https://codex.wordpress.org/Function_Reference/wp_list_pluck\" rel=\"nofollow noreferrer\"><code>wp_list_pluck</code></a>, which is a very handy function, that will get array containing only one field from all of given objects.</p>\n\n<p>PS. I've also changed your <code>query_posts</code> to <code>WP_Query</code> - it's better for your efficiency.</p>\n"
},
{
"answer_id": 327457,
"author": "joloshop",
"author_id": 153850,
"author_profile": "https://wordpress.stackexchange.com/users/153850",
"pm_score": -1,
"selected": false,
"text": "<p>Found a solution, quite similar to yours:</p>\n\n<pre><code>$tax = get_the_terms($id, 'coupon_category');\n $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;\n query_posts( array(\n 'post_type' => APP_POST_TYPE,\n 'post_status' => 'publish',\n 'posts_per_page' => 4,\n 'tax_query' => array( \n array(\n 'taxonomy' => 'coupon_category', // Taxonomy\n 'field' => 'slug',\n 'terms' => $tax[0]->slug, // Your category slug\n ),\n )\n\n ) );\n</code></pre>\n\n<p>Now I only need to exclude post from <code>APP_TAX_STORE</code> with current slug or from taxonomy <code>stores</code>.</p>\n"
},
{
"answer_id": 330775,
"author": "joloshop",
"author_id": 153850,
"author_profile": "https://wordpress.stackexchange.com/users/153850",
"pm_score": 1,
"selected": true,
"text": "<p>Okay after a lot of reading I finally changed to 'wp_query' and this is the perfect solution:</p>\n\n<pre><code>$tax = get_the_terms($id, 'coupon_category');\n $args = array(\n 'post_type' => APP_POST_TYPE,\n 'post_status' => 'publish',\n 'posts_per_page' => 5,\n 'meta_key' => 'clpr_topcoupon',\n APP_TAX_TAG => 'gutschein',\n 'orderby' => array(\n 'meta_value_num' => 'DESC',\n 'post_date' => 'DESC',\n ), \n 'tax_query' => array( \n 'relation' => 'AND',\n array(\n 'taxonomy' => 'coupon_category',\n 'field' => 'slug',\n 'terms' => $tax[0]->slug, \n ),\n array(\n 'taxonomy' => APP_TAX_STORE,\n 'field' => 'slug',\n 'terms' => $term->slug,\n 'operator' => 'NOT IN',\n ),\n ), \n );\n $query = new WP_Query( $args );\n while ( $query->have_posts() ) :\n $query->the_post();\n get_template_part( 'loop', 'coupon' ); \n endwhile;\n wp_reset_postdata();\n</code></pre>\n"
}
] | 2019/02/02 | [
"https://wordpress.stackexchange.com/questions/327447",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/153850/"
] | I have a taxonomy called `coupon_category`. In a `query_post` I am trying to call all posts from related custom taxonomy with the same `coupon_category`.
If I use:
```
<?php
// show all active coupons for this category from related store and setup pagination
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts( array(
'post_type' => APP_POST_TYPE,
'post_status' => 'publish',
'posts_per_page' => 4,
'tax_query' => array(
array(
'taxonomy' => 'coupon_category',
'field' => 'slug',
'terms' => 'mode',
),
)
) );
?>
```
I can show all related posts with the term "mode" however I would like to automate it, so that always the terms (`coupon_category`) that are already in use on the page are shown. | Okay after a lot of reading I finally changed to 'wp\_query' and this is the perfect solution:
```
$tax = get_the_terms($id, 'coupon_category');
$args = array(
'post_type' => APP_POST_TYPE,
'post_status' => 'publish',
'posts_per_page' => 5,
'meta_key' => 'clpr_topcoupon',
APP_TAX_TAG => 'gutschein',
'orderby' => array(
'meta_value_num' => 'DESC',
'post_date' => 'DESC',
),
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'coupon_category',
'field' => 'slug',
'terms' => $tax[0]->slug,
),
array(
'taxonomy' => APP_TAX_STORE,
'field' => 'slug',
'terms' => $term->slug,
'operator' => 'NOT IN',
),
),
);
$query = new WP_Query( $args );
while ( $query->have_posts() ) :
$query->the_post();
get_template_part( 'loop', 'coupon' );
endwhile;
wp_reset_postdata();
``` |
327,465 | <p>I have this code:</p>
<pre><code>query_posts( array(
'post_type' => APP_POST_TYPE,
'post_status' => 'publish',
'posts_per_page' => 4,
),
) );
</code></pre>
<p>now I need to remove all post from this Query <code>APP_TAX_STORE => $term->slug</code></p>
<p>Meaning I need to show all posts except the one from this one taxonomy.</p>
| [
{
"answer_id": 327495,
"author": "phatskat",
"author_id": 20143,
"author_profile": "https://wordpress.stackexchange.com/users/20143",
"pm_score": 1,
"selected": false,
"text": "<p>The easiest way I can see is to gather a list of the terms in that taxonomy, and use them with a <code>NOT IN</code> operator in your query's <code>tax_query</code>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>// Get all the terms in your custom taxonomy.\n$slugs = get_terms( [\n 'taxonomy' => 'industry',\n 'fields' => 'slugs',\n] );\n\n$posts = query_posts( [\n 'post_type' => 'post',\n 'posts_per_page' => 4,\n 'post_status' => 'publish',\n 'tax_query' => [\n [\n 'taxonomy' => APP_TAX_STORE,\n 'operator' => 'NOT IN',\n 'field' => 'slug',\n 'terms' => $slugs, \n ]\n ]\n] );\n</code></pre>\n\n<p>I would suggest reading up on <a href=\"https://developer.wordpress.org/reference/functions/query_posts/\" rel=\"nofollow noreferrer\">query_posts</a> if you haven't already - heed the warning that it could cause confusion and trouble down the road. <code>get_posts</code> should get you the same results without the burden of overwriting the main query.</p>\n"
},
{
"answer_id": 327527,
"author": "joloshop",
"author_id": 153850,
"author_profile": "https://wordpress.stackexchange.com/users/153850",
"pm_score": 1,
"selected": true,
"text": "<p>Okay found a solution that's working as well:</p>\n\n<pre><code>query_posts( array(\n 'post_type' => APP_POST_TYPE,\n 'post_status' => 'publish',\n 'posts_per_page' => 4,\n 'tax_query' => array(\n array(\n 'taxonomy' => APP_TAX_STORE,\n 'field' => 'slug',\n 'terms' => $term->slug,\n 'operator' => 'NOT IN',\n ),\n ),\n) );\n</code></pre>\n"
}
] | 2019/02/02 | [
"https://wordpress.stackexchange.com/questions/327465",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/153850/"
] | I have this code:
```
query_posts( array(
'post_type' => APP_POST_TYPE,
'post_status' => 'publish',
'posts_per_page' => 4,
),
) );
```
now I need to remove all post from this Query `APP_TAX_STORE => $term->slug`
Meaning I need to show all posts except the one from this one taxonomy. | Okay found a solution that's working as well:
```
query_posts( array(
'post_type' => APP_POST_TYPE,
'post_status' => 'publish',
'posts_per_page' => 4,
'tax_query' => array(
array(
'taxonomy' => APP_TAX_STORE,
'field' => 'slug',
'terms' => $term->slug,
'operator' => 'NOT IN',
),
),
) );
``` |
327,469 | <p>I'm building a custom child theme using the <a href="https://wordpress.org/themes/twentynineteen/" rel="nofollow noreferrer">Twenty Nineteen</a> default WordPress theme as the parent.</p>
<p>I added some text in the excerpt section available in the Editor as follows:</p>
<p><a href="https://i.stack.imgur.com/pB1ao.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pB1ao.png" alt="enter image description here"></a></p>
<p>But the full content of each post is displayed on the blog/posts page instead of just the excerpt.</p>
<hr>
<p>What is the proper way of adding/using excerpts in the new Gutenberg editor?</p>
| [
{
"answer_id": 327475,
"author": "Arturo Gallegos",
"author_id": 130585,
"author_profile": "https://wordpress.stackexchange.com/users/130585",
"pm_score": 0,
"selected": false,
"text": "<p>you need modify your template, in your PHP change <code>the_content()</code> to <code>the_excerpt()</code></p>\n\n<p>This php functions print the content and the excerpt respectively</p>\n"
},
{
"answer_id": 327492,
"author": "phatskat",
"author_id": 20143,
"author_profile": "https://wordpress.stackexchange.com/users/20143",
"pm_score": 1,
"selected": false,
"text": "<p>You should use a custom page for this. For reference, we can modify the default (twentynineteen) post content block. Depending on your theme, you may need to modify <code>single.php</code>, or a content block included from there. In the <code>twentynineteen</code> theme, we can see this on line <code>24</code>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>get_template_part( 'template-parts/content/content', 'single' );\n</code></pre>\n\n<p>Following that, we can look into <code>template-parts/content/content-single.php</code> at line <code>23</code>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code> 23 the_content(\n 24 sprintf(\n 25 wp_kses(\n 26 /* translators: %s: Name of current post. Only visible to screen readers */\n 27 __( 'Continue reading<span class=\"screen-reader-text\"> \"%s\"</span>', 'twentynineteen' ),\n 28 array(\n 29 'span' => array(\n 30 'class' => array(),\n 31 ),\n 32 )\n 33 ),\n 34 get_the_title()\n 35 )\n 36 );\n 37 \n</code></pre>\n\n<p>So, you could replace this call to <code>the_content</code> with something like this:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>the_excerpt(); // Echo the excerpt directly.\n$excerpt = get_the_excerpt(); // Store the excerpt in $excerpt.\n\n// Retrieve the \"raw\" exceprt - this has not passed any filters etc,\n// and instead comes directly from the database.\n$post = get_post();\necho $post->post_excerpt;\n</code></pre>\n"
},
{
"answer_id": 330079,
"author": "Rob Hoff",
"author_id": 162126,
"author_profile": "https://wordpress.stackexchange.com/users/162126",
"pm_score": 1,
"selected": false,
"text": "<p>The <code>twentynineteen</code> front page is controlled by the file <code>/wp-content/themes/twentynineteen/index.php</code>. It contains the code</p>\n\n<pre><code>while (have_posts()) {\n the_post();\n get_template_part('template-parts/content/content');\n}\n</code></pre>\n\n<p>This code applies the template from the <strong>.php</strong> file in <code>template-parts/content/content.php</code>. (Note <code>template-parts/content</code> is a sub-directory of the theme directory) Change <code>content</code> to <code>content-excerpt</code> as follows</p>\n\n<pre><code>while (have_posts()) {\n the_post();\n get_template_part('template-parts/content/content-excerpt');\n}\n</code></pre>\n\n<p>Now the <strong>.php</strong> file <code>template-parts/content/content-excerpt.php</code> is loaded instead, which is what you want</p>\n"
}
] | 2019/02/02 | [
"https://wordpress.stackexchange.com/questions/327469",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74607/"
] | I'm building a custom child theme using the [Twenty Nineteen](https://wordpress.org/themes/twentynineteen/) default WordPress theme as the parent.
I added some text in the excerpt section available in the Editor as follows:
[](https://i.stack.imgur.com/pB1ao.png)
But the full content of each post is displayed on the blog/posts page instead of just the excerpt.
---
What is the proper way of adding/using excerpts in the new Gutenberg editor? | You should use a custom page for this. For reference, we can modify the default (twentynineteen) post content block. Depending on your theme, you may need to modify `single.php`, or a content block included from there. In the `twentynineteen` theme, we can see this on line `24`:
```php
get_template_part( 'template-parts/content/content', 'single' );
```
Following that, we can look into `template-parts/content/content-single.php` at line `23`:
```php
23 the_content(
24 sprintf(
25 wp_kses(
26 /* translators: %s: Name of current post. Only visible to screen readers */
27 __( 'Continue reading<span class="screen-reader-text"> "%s"</span>', 'twentynineteen' ),
28 array(
29 'span' => array(
30 'class' => array(),
31 ),
32 )
33 ),
34 get_the_title()
35 )
36 );
37
```
So, you could replace this call to `the_content` with something like this:
```php
the_excerpt(); // Echo the excerpt directly.
$excerpt = get_the_excerpt(); // Store the excerpt in $excerpt.
// Retrieve the "raw" exceprt - this has not passed any filters etc,
// and instead comes directly from the database.
$post = get_post();
echo $post->post_excerpt;
``` |
327,491 | <p>We are looking for a way to add Advanced Custom Fields data to a user / subscriber after they have purchased a product (Woocommerce). The subscriber should be able to edit these fields on the frontend and save to their own account. We have been using Buddypress's XProfile fields to handle this but isn't ideal for what we need to do. </p>
<p>We know you can use ACF to add user fields but how to then bring those fields to the frontend?</p>
| [
{
"answer_id": 327879,
"author": "Anton Shinkarenko",
"author_id": 160690,
"author_profile": "https://wordpress.stackexchange.com/users/160690",
"pm_score": 0,
"selected": false,
"text": "<p>You can use ACF on the frontend in similar way</p>\n\n<pre><code>$user_id = 'user_' . $user->ID . '';\n$field = get_field( 'some_field', $user_id );\n</code></pre>\n\n<p>Please note that some settings must be set</p>\n\n<p><a href=\"https://i.stack.imgur.com/SfFnK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/SfFnK.png\" alt=\"enter image description here\"></a></p>\n\n<p>Than you can use AJAX to update necessary fields from the frontend</p>\n\n<pre><code>$post_id = $_POST['post_id'];\n$some_post_data = $_POST['some_post_data'];\n$field_ref = get_field_reference('some_field', $post_id);\n$field = get_field('some_field', $post_id);\n\n$value = $field;\nvar_dump($value);\n//$value modification\nupdate_field($field_ref, $value, $post_id);\n</code></pre>\n"
},
{
"answer_id": 327989,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 2,
"selected": false,
"text": "<p>ACF has a built in way to do this. Its <a href=\"https://www.advancedcustomfields.com/resources/acf_form/\" rel=\"nofollow noreferrer\">acf_form()</a>. Essentially it lets you build a form on the frontend that will update your custom fields.</p>\n\n<p>Here is a basic example from their site. Note the use of <a href=\"https://www.advancedcustomfields.com/resources/acf_form_head/\" rel=\"nofollow noreferrer\">acf_form_head()</a>, which is needed to actually save the data.</p>\n\n<pre><code><?php acf_form_head(); ?>\n<?php get_header(); ?>\n\n <div id=\"primary\" class=\"content-area\">\n <div id=\"content\" class=\"site-content\" role=\"main\">\n\n <?php /* The loop */ ?>\n <?php while ( have_posts() ) : the_post(); ?>\n\n <?php acf_form(array(\n 'post_id' => 123,\n 'post_title' => false,\n 'submit_value' => 'Update the post!'\n )); ?>\n\n <?php endwhile; ?>\n\n </div><!-- #content -->\n </div><!-- #primary -->\n\n<?php get_sidebar(); ?>\n<?php get_footer(); ?>\n</code></pre>\n\n<p>As stated in one of the comments, <a href=\"https://usersinsights.com/acf-user-profile/\" rel=\"nofollow noreferrer\">this tutorial</a> walks you through basically what you are trying to do.</p>\n"
}
] | 2019/02/03 | [
"https://wordpress.stackexchange.com/questions/327491",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58254/"
] | We are looking for a way to add Advanced Custom Fields data to a user / subscriber after they have purchased a product (Woocommerce). The subscriber should be able to edit these fields on the frontend and save to their own account. We have been using Buddypress's XProfile fields to handle this but isn't ideal for what we need to do.
We know you can use ACF to add user fields but how to then bring those fields to the frontend? | ACF has a built in way to do this. Its [acf\_form()](https://www.advancedcustomfields.com/resources/acf_form/). Essentially it lets you build a form on the frontend that will update your custom fields.
Here is a basic example from their site. Note the use of [acf\_form\_head()](https://www.advancedcustomfields.com/resources/acf_form_head/), which is needed to actually save the data.
```
<?php acf_form_head(); ?>
<?php get_header(); ?>
<div id="primary" class="content-area">
<div id="content" class="site-content" role="main">
<?php /* The loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php acf_form(array(
'post_id' => 123,
'post_title' => false,
'submit_value' => 'Update the post!'
)); ?>
<?php endwhile; ?>
</div><!-- #content -->
</div><!-- #primary -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
```
As stated in one of the comments, [this tutorial](https://usersinsights.com/acf-user-profile/) walks you through basically what you are trying to do. |
327,515 | <p>I have been searching at this site posts about blogs being hacker, but I haven't find something like this.</p>
<p>One of our Editor's account has started to publish random posts. Our first thought was his password being stolen, so we changed it and we told him not to log in for a certain time. Random posts appeared again at the next day.</p>
<p>We tried yesterday to change his role to Subscriber, so he doesn't have permission to post. Random posts have appeared again this morning.</p>
<p>Have any of you been in a similar situation? Any solution to this?
Thanks.</p>
| [
{
"answer_id": 327879,
"author": "Anton Shinkarenko",
"author_id": 160690,
"author_profile": "https://wordpress.stackexchange.com/users/160690",
"pm_score": 0,
"selected": false,
"text": "<p>You can use ACF on the frontend in similar way</p>\n\n<pre><code>$user_id = 'user_' . $user->ID . '';\n$field = get_field( 'some_field', $user_id );\n</code></pre>\n\n<p>Please note that some settings must be set</p>\n\n<p><a href=\"https://i.stack.imgur.com/SfFnK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/SfFnK.png\" alt=\"enter image description here\"></a></p>\n\n<p>Than you can use AJAX to update necessary fields from the frontend</p>\n\n<pre><code>$post_id = $_POST['post_id'];\n$some_post_data = $_POST['some_post_data'];\n$field_ref = get_field_reference('some_field', $post_id);\n$field = get_field('some_field', $post_id);\n\n$value = $field;\nvar_dump($value);\n//$value modification\nupdate_field($field_ref, $value, $post_id);\n</code></pre>\n"
},
{
"answer_id": 327989,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 2,
"selected": false,
"text": "<p>ACF has a built in way to do this. Its <a href=\"https://www.advancedcustomfields.com/resources/acf_form/\" rel=\"nofollow noreferrer\">acf_form()</a>. Essentially it lets you build a form on the frontend that will update your custom fields.</p>\n\n<p>Here is a basic example from their site. Note the use of <a href=\"https://www.advancedcustomfields.com/resources/acf_form_head/\" rel=\"nofollow noreferrer\">acf_form_head()</a>, which is needed to actually save the data.</p>\n\n<pre><code><?php acf_form_head(); ?>\n<?php get_header(); ?>\n\n <div id=\"primary\" class=\"content-area\">\n <div id=\"content\" class=\"site-content\" role=\"main\">\n\n <?php /* The loop */ ?>\n <?php while ( have_posts() ) : the_post(); ?>\n\n <?php acf_form(array(\n 'post_id' => 123,\n 'post_title' => false,\n 'submit_value' => 'Update the post!'\n )); ?>\n\n <?php endwhile; ?>\n\n </div><!-- #content -->\n </div><!-- #primary -->\n\n<?php get_sidebar(); ?>\n<?php get_footer(); ?>\n</code></pre>\n\n<p>As stated in one of the comments, <a href=\"https://usersinsights.com/acf-user-profile/\" rel=\"nofollow noreferrer\">this tutorial</a> walks you through basically what you are trying to do.</p>\n"
}
] | 2019/02/03 | [
"https://wordpress.stackexchange.com/questions/327515",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/160396/"
] | I have been searching at this site posts about blogs being hacker, but I haven't find something like this.
One of our Editor's account has started to publish random posts. Our first thought was his password being stolen, so we changed it and we told him not to log in for a certain time. Random posts appeared again at the next day.
We tried yesterday to change his role to Subscriber, so he doesn't have permission to post. Random posts have appeared again this morning.
Have any of you been in a similar situation? Any solution to this?
Thanks. | ACF has a built in way to do this. Its [acf\_form()](https://www.advancedcustomfields.com/resources/acf_form/). Essentially it lets you build a form on the frontend that will update your custom fields.
Here is a basic example from their site. Note the use of [acf\_form\_head()](https://www.advancedcustomfields.com/resources/acf_form_head/), which is needed to actually save the data.
```
<?php acf_form_head(); ?>
<?php get_header(); ?>
<div id="primary" class="content-area">
<div id="content" class="site-content" role="main">
<?php /* The loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php acf_form(array(
'post_id' => 123,
'post_title' => false,
'submit_value' => 'Update the post!'
)); ?>
<?php endwhile; ?>
</div><!-- #content -->
</div><!-- #primary -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
```
As stated in one of the comments, [this tutorial](https://usersinsights.com/acf-user-profile/) walks you through basically what you are trying to do. |
327,520 | <p>I created a custom post type and I am trying to get the posts from it using WP-API, however, when I try to access the API I get the error rest_no_route message.
The set up for my custom post type is below:</p>
<pre><code>function cw_post_type_pil() {
$supports = array('title', //
post title'editor', // post content
'author', // post author
'thumbnail', // featured images
'excerpt', // post excerpt
'custom-fields', // custom fields
'comments', // post comments
'revisions', // post revisions
'post-formats', // post formats
);
$labels = array(
'name' => _x('Profiles', 'plural'),
'singular_name' => _x('Profile', 'singular'),
'menu_name' => _x('Profile In Law', 'admin menu'),
'name_admin_bar' => _x('Profiles In Law', 'admin bar'),
'add_new' => _x('Add New Profile', 'add new'),
'add_new_item' => __('Add New profile'),
'new_item' => __('New Profile'),
'edit_item' => __('Edit Profile'),
'view_item' => __('View Profile'),
'all_items' => __('All Profiles'),
'search_items' => __('Search Profiles'),
'not_found' => __('No results found.'),
);
$args = array(
'supports' => $supports,
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'capability_type' => 'post',
'query_var' => true,
'rewrite' => array('slug' => 'pil'),
'has_archive' => true,
'hierarchical' => false,
'show_in_rest' => true,
'rest_controller_class' => 'WP_REST_Terms_Controller',
'rest_base' => 'profiles-api',
);
register_post_type('profiles_in_law', $args);
}
add_action('init', 'cw_post_type_pil');
</code></pre>
<p>This is stored in my functions.php file. </p>
<p>Currently, I am accessing the API using the address: <a href="https://newtontest.staging.wpengine.com/wp-json/wp/v2/profiles-api" rel="nofollow noreferrer">https://newtontest.staging.wpengine.com/wp-json/wp/v2/profiles-api</a></p>
<p>While I get the following error:</p>
<pre><code>{"code":"rest_no_route","message":"No route was found matching the URL and request method","data":{"status":404}}
</code></pre>
<p>This post type has 38 posts in them, but no data is returned as well.</p>
<p>I have gone through most of the articles and questions on allowing the use of the WP API on custom post types and have been making changes to the post type definition as well, but to no avail.</p>
<p>I am currently running Wordpress 4.7</p>
<p>Any help regarding this, is much appreciated.</p>
| [
{
"answer_id": 327879,
"author": "Anton Shinkarenko",
"author_id": 160690,
"author_profile": "https://wordpress.stackexchange.com/users/160690",
"pm_score": 0,
"selected": false,
"text": "<p>You can use ACF on the frontend in similar way</p>\n\n<pre><code>$user_id = 'user_' . $user->ID . '';\n$field = get_field( 'some_field', $user_id );\n</code></pre>\n\n<p>Please note that some settings must be set</p>\n\n<p><a href=\"https://i.stack.imgur.com/SfFnK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/SfFnK.png\" alt=\"enter image description here\"></a></p>\n\n<p>Than you can use AJAX to update necessary fields from the frontend</p>\n\n<pre><code>$post_id = $_POST['post_id'];\n$some_post_data = $_POST['some_post_data'];\n$field_ref = get_field_reference('some_field', $post_id);\n$field = get_field('some_field', $post_id);\n\n$value = $field;\nvar_dump($value);\n//$value modification\nupdate_field($field_ref, $value, $post_id);\n</code></pre>\n"
},
{
"answer_id": 327989,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 2,
"selected": false,
"text": "<p>ACF has a built in way to do this. Its <a href=\"https://www.advancedcustomfields.com/resources/acf_form/\" rel=\"nofollow noreferrer\">acf_form()</a>. Essentially it lets you build a form on the frontend that will update your custom fields.</p>\n\n<p>Here is a basic example from their site. Note the use of <a href=\"https://www.advancedcustomfields.com/resources/acf_form_head/\" rel=\"nofollow noreferrer\">acf_form_head()</a>, which is needed to actually save the data.</p>\n\n<pre><code><?php acf_form_head(); ?>\n<?php get_header(); ?>\n\n <div id=\"primary\" class=\"content-area\">\n <div id=\"content\" class=\"site-content\" role=\"main\">\n\n <?php /* The loop */ ?>\n <?php while ( have_posts() ) : the_post(); ?>\n\n <?php acf_form(array(\n 'post_id' => 123,\n 'post_title' => false,\n 'submit_value' => 'Update the post!'\n )); ?>\n\n <?php endwhile; ?>\n\n </div><!-- #content -->\n </div><!-- #primary -->\n\n<?php get_sidebar(); ?>\n<?php get_footer(); ?>\n</code></pre>\n\n<p>As stated in one of the comments, <a href=\"https://usersinsights.com/acf-user-profile/\" rel=\"nofollow noreferrer\">this tutorial</a> walks you through basically what you are trying to do.</p>\n"
}
] | 2019/02/03 | [
"https://wordpress.stackexchange.com/questions/327520",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/160421/"
] | I created a custom post type and I am trying to get the posts from it using WP-API, however, when I try to access the API I get the error rest\_no\_route message.
The set up for my custom post type is below:
```
function cw_post_type_pil() {
$supports = array('title', //
post title'editor', // post content
'author', // post author
'thumbnail', // featured images
'excerpt', // post excerpt
'custom-fields', // custom fields
'comments', // post comments
'revisions', // post revisions
'post-formats', // post formats
);
$labels = array(
'name' => _x('Profiles', 'plural'),
'singular_name' => _x('Profile', 'singular'),
'menu_name' => _x('Profile In Law', 'admin menu'),
'name_admin_bar' => _x('Profiles In Law', 'admin bar'),
'add_new' => _x('Add New Profile', 'add new'),
'add_new_item' => __('Add New profile'),
'new_item' => __('New Profile'),
'edit_item' => __('Edit Profile'),
'view_item' => __('View Profile'),
'all_items' => __('All Profiles'),
'search_items' => __('Search Profiles'),
'not_found' => __('No results found.'),
);
$args = array(
'supports' => $supports,
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'capability_type' => 'post',
'query_var' => true,
'rewrite' => array('slug' => 'pil'),
'has_archive' => true,
'hierarchical' => false,
'show_in_rest' => true,
'rest_controller_class' => 'WP_REST_Terms_Controller',
'rest_base' => 'profiles-api',
);
register_post_type('profiles_in_law', $args);
}
add_action('init', 'cw_post_type_pil');
```
This is stored in my functions.php file.
Currently, I am accessing the API using the address: <https://newtontest.staging.wpengine.com/wp-json/wp/v2/profiles-api>
While I get the following error:
```
{"code":"rest_no_route","message":"No route was found matching the URL and request method","data":{"status":404}}
```
This post type has 38 posts in them, but no data is returned as well.
I have gone through most of the articles and questions on allowing the use of the WP API on custom post types and have been making changes to the post type definition as well, but to no avail.
I am currently running Wordpress 4.7
Any help regarding this, is much appreciated. | ACF has a built in way to do this. Its [acf\_form()](https://www.advancedcustomfields.com/resources/acf_form/). Essentially it lets you build a form on the frontend that will update your custom fields.
Here is a basic example from their site. Note the use of [acf\_form\_head()](https://www.advancedcustomfields.com/resources/acf_form_head/), which is needed to actually save the data.
```
<?php acf_form_head(); ?>
<?php get_header(); ?>
<div id="primary" class="content-area">
<div id="content" class="site-content" role="main">
<?php /* The loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php acf_form(array(
'post_id' => 123,
'post_title' => false,
'submit_value' => 'Update the post!'
)); ?>
<?php endwhile; ?>
</div><!-- #content -->
</div><!-- #primary -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
```
As stated in one of the comments, [this tutorial](https://usersinsights.com/acf-user-profile/) walks you through basically what you are trying to do. |
327,534 | <p>I need some help, again.</p>
<p>I use this query:</p>
<pre><code>$tax = get_the_terms($id, 'coupon_category');
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts( array(
'post_type' => APP_POST_TYPE,
'post_status' => 'publish',
'posts_per_page' => 4,
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'coupon_category', // Taxonomy
'field' => 'slug',
'terms' => $tax[0]->slug, // Your category slug
),
array(
'taxonomy' => APP_TAX_STORE,
'field' => 'slug',
'terms' => $term->slug,
'operator' => 'NOT IN',
),
),
) );
</code></pre>
<p>I know need a solution to only show one post from each Taxonomy term <code>APP_TAX_STORE</code>. Tried some solutions from this userfull forum but non worked for me.</p>
| [
{
"answer_id": 327543,
"author": "Mohsin Ghouri",
"author_id": 159253,
"author_profile": "https://wordpress.stackexchange.com/users/159253",
"pm_score": 0,
"selected": false,
"text": "<p>You can't get the only one post of each taxonomy in a single query. You have to get the single post by using <code>posts_per_page=> 1</code> for each term and then use the <code>post__in</code> to get the one post of each taxonomy.</p>\n"
},
{
"answer_id": 327548,
"author": "Mohsin Ghouri",
"author_id": 159253,
"author_profile": "https://wordpress.stackexchange.com/users/159253",
"pm_score": 1,
"selected": false,
"text": "<p>Yeah sure. </p>\n\n<pre><code><?php \n $included_post_ids =array();\n $args = array(\n 'post_type' => 'APP_POST_TYPE',\n 'post_status' => 'publish',\n 'posts_per_page' => 1,\n 'tax_query' => array( \n\n array(\n 'taxonomy' => 'coupon_category', // Taxonomy\n 'field' => 'slug',\n 'terms' => $tax[0]->slug, // Your category slug\n ),\n ),\n );\n $custom_posts = get_posts( $args );\n if( !empty( $custom_posts ) ){\n foreach ($custom_posts as $key => $postObj) {\n $included_post_ids[] = $postObj->ID;\n }\n }\n //Similar proceduce for other taxonomies \n $args = array(\n 'post__in' => $included_post_ids,\n 'post_type' => 'APP_POST_TYPE',\n )\n $final_posts = new WP_Query( $args );\n if ( $final_posts->have_posts() ) {\n }\n</code></pre>\n\n<p>?></p>\n"
}
] | 2019/02/03 | [
"https://wordpress.stackexchange.com/questions/327534",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/153850/"
] | I need some help, again.
I use this query:
```
$tax = get_the_terms($id, 'coupon_category');
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts( array(
'post_type' => APP_POST_TYPE,
'post_status' => 'publish',
'posts_per_page' => 4,
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'coupon_category', // Taxonomy
'field' => 'slug',
'terms' => $tax[0]->slug, // Your category slug
),
array(
'taxonomy' => APP_TAX_STORE,
'field' => 'slug',
'terms' => $term->slug,
'operator' => 'NOT IN',
),
),
) );
```
I know need a solution to only show one post from each Taxonomy term `APP_TAX_STORE`. Tried some solutions from this userfull forum but non worked for me. | Yeah sure.
```
<?php
$included_post_ids =array();
$args = array(
'post_type' => 'APP_POST_TYPE',
'post_status' => 'publish',
'posts_per_page' => 1,
'tax_query' => array(
array(
'taxonomy' => 'coupon_category', // Taxonomy
'field' => 'slug',
'terms' => $tax[0]->slug, // Your category slug
),
),
);
$custom_posts = get_posts( $args );
if( !empty( $custom_posts ) ){
foreach ($custom_posts as $key => $postObj) {
$included_post_ids[] = $postObj->ID;
}
}
//Similar proceduce for other taxonomies
$args = array(
'post__in' => $included_post_ids,
'post_type' => 'APP_POST_TYPE',
)
$final_posts = new WP_Query( $args );
if ( $final_posts->have_posts() ) {
}
```
?> |
327,535 | <p>I want to give the user the ability to order posts by post date/alphabetically either on ASC or DESC order through a <code>select</code> input on an archive page.</p>
<p>The easy way would be to show two inputs on the front end: one controlling the <code>order_by</code> parameter, and other controlling the <code>order</code> parameter.</p>
<p>But it would be a lot better if it were just one select input field with four options:</p>
<ul>
<li>Latest</li>
<li>Oldest</li>
<li>Alphabetical A-Z</li>
<li>Alphabetical Z-A</li>
</ul>
<p>I tried cheating, using <code>&</code> inside each option's value, but it gets automatically escaped on the URL.</p>
<pre><code><form action="">
<select name="orderby" id="">
<option value="post_date&order=DESC">Latest</option>
<option value="post_date&order=ASC">Oldest</option>
<option value="post_title&order=ASC">Alphabetical A-Z</option>
<option value="post_title&order=DESC">Alphabetical A-Z</option>
</select>
<button>Filter</button>
</form>
</code></pre>
<p>This code gives me a URL like this: <code>http://example.com/?orderby=post_date%26order%3DASC</code></p>
<p>I could do it easily with javascript, or with PHP, but I wanted to know if there was a better solution. </p>
| [
{
"answer_id": 327543,
"author": "Mohsin Ghouri",
"author_id": 159253,
"author_profile": "https://wordpress.stackexchange.com/users/159253",
"pm_score": 0,
"selected": false,
"text": "<p>You can't get the only one post of each taxonomy in a single query. You have to get the single post by using <code>posts_per_page=> 1</code> for each term and then use the <code>post__in</code> to get the one post of each taxonomy.</p>\n"
},
{
"answer_id": 327548,
"author": "Mohsin Ghouri",
"author_id": 159253,
"author_profile": "https://wordpress.stackexchange.com/users/159253",
"pm_score": 1,
"selected": false,
"text": "<p>Yeah sure. </p>\n\n<pre><code><?php \n $included_post_ids =array();\n $args = array(\n 'post_type' => 'APP_POST_TYPE',\n 'post_status' => 'publish',\n 'posts_per_page' => 1,\n 'tax_query' => array( \n\n array(\n 'taxonomy' => 'coupon_category', // Taxonomy\n 'field' => 'slug',\n 'terms' => $tax[0]->slug, // Your category slug\n ),\n ),\n );\n $custom_posts = get_posts( $args );\n if( !empty( $custom_posts ) ){\n foreach ($custom_posts as $key => $postObj) {\n $included_post_ids[] = $postObj->ID;\n }\n }\n //Similar proceduce for other taxonomies \n $args = array(\n 'post__in' => $included_post_ids,\n 'post_type' => 'APP_POST_TYPE',\n )\n $final_posts = new WP_Query( $args );\n if ( $final_posts->have_posts() ) {\n }\n</code></pre>\n\n<p>?></p>\n"
}
] | 2019/02/03 | [
"https://wordpress.stackexchange.com/questions/327535",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/136994/"
] | I want to give the user the ability to order posts by post date/alphabetically either on ASC or DESC order through a `select` input on an archive page.
The easy way would be to show two inputs on the front end: one controlling the `order_by` parameter, and other controlling the `order` parameter.
But it would be a lot better if it were just one select input field with four options:
* Latest
* Oldest
* Alphabetical A-Z
* Alphabetical Z-A
I tried cheating, using `&` inside each option's value, but it gets automatically escaped on the URL.
```
<form action="">
<select name="orderby" id="">
<option value="post_date&order=DESC">Latest</option>
<option value="post_date&order=ASC">Oldest</option>
<option value="post_title&order=ASC">Alphabetical A-Z</option>
<option value="post_title&order=DESC">Alphabetical A-Z</option>
</select>
<button>Filter</button>
</form>
```
This code gives me a URL like this: `http://example.com/?orderby=post_date%26order%3DASC`
I could do it easily with javascript, or with PHP, but I wanted to know if there was a better solution. | Yeah sure.
```
<?php
$included_post_ids =array();
$args = array(
'post_type' => 'APP_POST_TYPE',
'post_status' => 'publish',
'posts_per_page' => 1,
'tax_query' => array(
array(
'taxonomy' => 'coupon_category', // Taxonomy
'field' => 'slug',
'terms' => $tax[0]->slug, // Your category slug
),
),
);
$custom_posts = get_posts( $args );
if( !empty( $custom_posts ) ){
foreach ($custom_posts as $key => $postObj) {
$included_post_ids[] = $postObj->ID;
}
}
//Similar proceduce for other taxonomies
$args = array(
'post__in' => $included_post_ids,
'post_type' => 'APP_POST_TYPE',
)
$final_posts = new WP_Query( $args );
if ( $final_posts->have_posts() ) {
}
```
?> |
327,538 | <p><a href="https://i.stack.imgur.com/yN5Q4.png" rel="noreferrer"><img src="https://i.stack.imgur.com/yN5Q4.png" alt="enter image description here"></a></p>
<p>How can I add custom metabox in document tab in gutenberg?</p>
<p>There is documentation about adding plugin sidebar <a href="https://wordpress.org/gutenberg/handbook/designers-developers/developers/tutorials/plugin-sidebar-0/" rel="noreferrer">here</a>, but I'm looking for adding custom metabox in existing document tab.</p>
| [
{
"answer_id": 330417,
"author": "Spanners",
"author_id": 162325,
"author_profile": "https://wordpress.stackexchange.com/users/162325",
"pm_score": 3,
"selected": false,
"text": "<p>I took a look at <a href=\"https://richardtape.com/2018/10/05/add-a-custom-sidebar-panel-to-gutenberg/\" rel=\"noreferrer\">Richard Tape's article</a> which required you create your own Gutenberg React component (which is likely the best, most customisable way to do it). But I also have <strong>Advanced Custom Fields Pro</strong> installed (it has to be <a href=\"https://cornerstone.lndo.site/wp-admin/edit.php?post_type=acf-field-group&page=acf-settings-info&tab=changelog\" rel=\"noreferrer\">version 5.8.0-beta3</a>). That provides a much easier method to add a custom meta field to the Gutenberg sidebar.</p>\n\n<p><strong>Create a new field in ACF Pro</strong> and in the <em>Field group settings</em>, ensure you have the following settings configured:</p>\n\n<ol>\n<li>Style: Standard (WP Metabox)</li>\n<li>Position: Side</li>\n</ol>\n\n<p>This has worked for me ( added a <em>Reading time</em> field). Hope this helps.</p>\n"
},
{
"answer_id": 330844,
"author": "X-NicON",
"author_id": 87447,
"author_profile": "https://wordpress.stackexchange.com/users/87447",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://wordpress.org/gutenberg/handbook/designers-developers/developers/backward-compatibility/meta-box/\" rel=\"nofollow noreferrer\">https://wordpress.org/gutenberg/handbook/designers-developers/developers/backward-compatibility/meta-box/</a>\nand\n<a href=\"https://developer.wordpress.org/reference/functions/add_meta_box/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/add_meta_box/</a></p>\n\n<p>use $context = 'side'</p>\n\n<p>Example:</p>\n\n<pre><code>add_meta_box( 'my-meta-box', 'My Meta Box', 'my_meta_box_callback',\n null, 'side', 'high',\n array(\n '__back_compat_meta_box' => true,\n )\n);\n</code></pre>\n"
},
{
"answer_id": 361493,
"author": "Asaquzzaman Mishu",
"author_id": 178213,
"author_profile": "https://wordpress.stackexchange.com/users/178213",
"pm_score": 4,
"selected": true,
"text": "<p>Here is the solution. Hope it will help you</p>\n\n<pre>\nconst { registerPlugin } = wp.plugins;\nconst { PluginDocumentSettingPanel } = wp.editPost;\n\nconst MyDocumentSettingTest = () => (\n <PluginDocumentSettingPanel className=\"my-document-setting-plugin\" title=\"My Panel\">\n <p>My Document Setting Panel</p>\n </PluginDocumentSettingPanel>\n );\n\nregisterPlugin( 'document-setting-test', { render: MyDocumentSettingTest } );\n</pre>\n\n<p><a href=\"https://github.com/WordPress/gutenberg/blob/master/packages/edit-post/src/components/sidebar/plugin-document-setting-panel/index.js#L86\" rel=\"noreferrer\">https://github.com/WordPress/gutenberg/blob/master/packages/edit-post/src/components/sidebar/plugin-document-setting-panel/index.js#L86</a></p>\n"
}
] | 2019/02/03 | [
"https://wordpress.stackexchange.com/questions/327538",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/51280/"
] | [](https://i.stack.imgur.com/yN5Q4.png)
How can I add custom metabox in document tab in gutenberg?
There is documentation about adding plugin sidebar [here](https://wordpress.org/gutenberg/handbook/designers-developers/developers/tutorials/plugin-sidebar-0/), but I'm looking for adding custom metabox in existing document tab. | Here is the solution. Hope it will help you
```
const { registerPlugin } = wp.plugins;
const { PluginDocumentSettingPanel } = wp.editPost;
const MyDocumentSettingTest = () => (
<PluginDocumentSettingPanel className="my-document-setting-plugin" title="My Panel">
<p>My Document Setting Panel</p>
</PluginDocumentSettingPanel>
);
registerPlugin( 'document-setting-test', { render: MyDocumentSettingTest } );
```
<https://github.com/WordPress/gutenberg/blob/master/packages/edit-post/src/components/sidebar/plugin-document-setting-panel/index.js#L86> |
327,550 | <p>I added a taxonomy and custom post type, but for some reason, my taxonomy isn't showing up when I add a new marker. I half expected it to be there like when selecting a category for a post, but it isn't. Any ideas what the issue might be? </p>
<pre><code>function register_mm_post_types()
{
register_taxonomy('marker_types',
array('markers'),
array(
'labels' => array(
'name' => __('Marker type', 'moxxie'),
'singular_name' => __('Marker type', 'moxxie'),
'search_items' => __('Search marker types', 'moxxie'),
'all_items' => __('All marker types', 'moxxie'),
'parent_item' => __('Parent marker type', 'moxxie'),
'parent_item_colon' => __('Parent marker type:', 'moxxie'),
'edit_item' => __('Edit marker type', 'moxxie'),
'update_item' => __('Update marker type', 'moxxie'),
'add_new_item' => __('Add new marker type', 'moxxie'),
'new_item_name' => __('New marker type name', 'moxxie'),
'menu_name' => __('Marker types', 'moxxie')
),
'show_ui' => true,
'query_var' => true,
'hierarchical' => true,
'show_admin_column' => true,
'rewrite' => array('slug' => 'marker_types')
));
register_post_type('markers',
array( 'taxonomies' => array('marker_types'),
'labels' => array(
'name' => __('Map markers', 'moxxie'),
'singular_name' => __('Marker', 'moxxie'),
'add_new' => __('Add a new marker', 'moxxie'),
'edit_item' => __('Edit marker', 'moxxie'),
'new_item' => __('New marker', 'moxxie'),
'view_item' => __('View marker', 'moxxie'),
'search_items' => __('Search in maps', 'moxxie'),
'not_found' => __('No markers found', 'moxxie'),
'not_found_in_trash' => __('No markers found in trash', 'moxxie')
),
'has_archive' => true,
'show_in_rest' => true,
'hierarchical' => true,
'public' => true,
'menu_icon' => 'dashicons-location',
'capability_type' => 'post'
));
}
add_action('init', 'register_mm_post_types', 1);
</code></pre>
<p>As you can see, no taxonomy is shown. It would have to appear in the right-hand column, just like categories do in posts.</p>
<p><a href="https://i.stack.imgur.com/MNFx3.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/MNFx3.jpg" alt="As you can see, no taxonomy"></a></p>
| [
{
"answer_id": 327556,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 6,
"selected": true,
"text": "<p>The Gutenberg editor relies on the REST API, so both post types and taxonomies require the <code>show_in_rest</code> parameter be set to <code>true</code> when registering them. Your post type has this, but it's missing from your taxonomy.</p>\n"
},
{
"answer_id": 404021,
"author": "Niharika Kejriwal",
"author_id": 220572,
"author_profile": "https://wordpress.stackexchange.com/users/220572",
"pm_score": 1,
"selected": false,
"text": "<p>Need to add in register_post_type</p>\n<pre><code>'has_archive' => true,\n'show_in_rest' => true,\n'taxonomies'=>array('marker_types'),\n</code></pre>\n<p>Like this. This work for me.</p>\n"
}
] | 2019/02/03 | [
"https://wordpress.stackexchange.com/questions/327550",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/9243/"
] | I added a taxonomy and custom post type, but for some reason, my taxonomy isn't showing up when I add a new marker. I half expected it to be there like when selecting a category for a post, but it isn't. Any ideas what the issue might be?
```
function register_mm_post_types()
{
register_taxonomy('marker_types',
array('markers'),
array(
'labels' => array(
'name' => __('Marker type', 'moxxie'),
'singular_name' => __('Marker type', 'moxxie'),
'search_items' => __('Search marker types', 'moxxie'),
'all_items' => __('All marker types', 'moxxie'),
'parent_item' => __('Parent marker type', 'moxxie'),
'parent_item_colon' => __('Parent marker type:', 'moxxie'),
'edit_item' => __('Edit marker type', 'moxxie'),
'update_item' => __('Update marker type', 'moxxie'),
'add_new_item' => __('Add new marker type', 'moxxie'),
'new_item_name' => __('New marker type name', 'moxxie'),
'menu_name' => __('Marker types', 'moxxie')
),
'show_ui' => true,
'query_var' => true,
'hierarchical' => true,
'show_admin_column' => true,
'rewrite' => array('slug' => 'marker_types')
));
register_post_type('markers',
array( 'taxonomies' => array('marker_types'),
'labels' => array(
'name' => __('Map markers', 'moxxie'),
'singular_name' => __('Marker', 'moxxie'),
'add_new' => __('Add a new marker', 'moxxie'),
'edit_item' => __('Edit marker', 'moxxie'),
'new_item' => __('New marker', 'moxxie'),
'view_item' => __('View marker', 'moxxie'),
'search_items' => __('Search in maps', 'moxxie'),
'not_found' => __('No markers found', 'moxxie'),
'not_found_in_trash' => __('No markers found in trash', 'moxxie')
),
'has_archive' => true,
'show_in_rest' => true,
'hierarchical' => true,
'public' => true,
'menu_icon' => 'dashicons-location',
'capability_type' => 'post'
));
}
add_action('init', 'register_mm_post_types', 1);
```
As you can see, no taxonomy is shown. It would have to appear in the right-hand column, just like categories do in posts.
[](https://i.stack.imgur.com/MNFx3.jpg) | The Gutenberg editor relies on the REST API, so both post types and taxonomies require the `show_in_rest` parameter be set to `true` when registering them. Your post type has this, but it's missing from your taxonomy. |
327,554 | <p>So I recently, built and LAMP server and installed wordpress on it. I connected it to the web via a reverse ssh tunnel using serveo.net. I decided to add ssl and the rest of the website seem to work fine, but wordpress keeps breaking when I try to use ssl. I went to the general settings and changed the urls to http instead of https, but when I load the pages, in the source code the css and js urls are using http instead of https, so they won't load. Then wp-admin part won't even load. How do I fix this? I've looked at quite a few posts about people having similar problems, but none of them helped.</p>
| [
{
"answer_id": 327562,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 1,
"selected": false,
"text": "<p>Check two things: </p>\n\n<ul>\n<li>in the wp-options table, the site URLs (in two places) should be the full URL, as in <a href=\"https://www.example.com\" rel=\"nofollow noreferrer\">https://www.example.com</a> .</li>\n<li>check the site's htaccess file for proper rewrite of http to https. </li>\n</ul>\n\n<p>For a htaccess rule, this one works in most case: </p>\n\n<pre><code>RewriteEngine On\n RewriteCond %{HTTPS} !=on\n RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n</code></pre>\n\n<p>Then look at your theme files to ensure that any references to CSS/JS include the https protocol, not http. Most well-written themes will use relative rather than absolute references to files to include. </p>\n\n<p>It's also possible a plugin might be specifying http rather than https.</p>\n\n<p>Use the Network tab in Developer Tools (usually F12 in your browser) to look at each request to see where it is coming from. If the request is to a plugin folder, then check the code in there.</p>\n"
},
{
"answer_id": 345548,
"author": "Vincere Sempre",
"author_id": 173852,
"author_profile": "https://wordpress.stackexchange.com/users/173852",
"pm_score": 1,
"selected": false,
"text": "<p>Had the similar issue.</p>\n\n<p>This <a href=\"https://wordpress.stackexchange.com/q/75921/173852\">answer</a> solves most of the issues and I'm hoping you've gone through it.</p>\n\n<p>The reason, I found, for HTTPS (SSL) not working on my Wordpress even after changing<br>\n1. Virtual Host File aka <code><web_directory>.conf</code> file inside <code>/ect/apache2/sites-available</code><br>\n2. <code>wp-config</code> file inside <code>/var/www/<web_directory>/</code><br>\n3. [For AWS EC2 Users] Adding a load balancer with a SSL certificate for HTTPS connections</p>\n\n<p>If after doing all this, you can view your website w/o CSS and JS working, then,</p>\n\n<p>Last step </p>\n\n<ol>\n<li><p>Inside your Wordpress Dashboard, go to <code>Settings>General</code> </p>\n\n<p>Under, <code>Wordpress Address (URL)</code> add, <code>https://<yourdomain>.com</code><br>\nUnder, <code>Site Address (URL)</code> add, <code>https://<yourdomain>.com</code> </p></li>\n</ol>\n\n<p>I found that, when only <code>Site Address (URL)</code> has been activated with the website URL, Wordpress Themes automatically direct towards, the css files with HTTPS aka, <code>https://<WordPressAddress>/css/index.css</code>. </p>\n\n<p>Only your domain has SSL access hence, adding your domain name at <code>Wordpress Address (URL)</code> solved the problems for me. </p>\n"
},
{
"answer_id": 345551,
"author": "F.A",
"author_id": 139889,
"author_profile": "https://wordpress.stackexchange.com/users/139889",
"pm_score": 0,
"selected": false,
"text": "<p>Add this code to <code>wp-config.php</code> in your <code>wordpress</code> root folder.<br>\nAlso, in <code>General Settings</code> on the Admin Panel, change <code>http</code> to <code>https</code> for your siteurl an home.</p>\n\n<pre><code>define('FORCE_SSL_ADMIN', true);\nif (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false)\n $_SERVER['HTTPS']='on';\n</code></pre>\n"
},
{
"answer_id": 366077,
"author": "Shady Mohamed Sherif",
"author_id": 98924,
"author_profile": "https://wordpress.stackexchange.com/users/98924",
"pm_score": 0,
"selected": false,
"text": "<p>I had the same issue when I hosted my site on Azure webapp service Linux.</p>\n\n<p>Try this plugin. take care when it active it works.\n<a href=\"https://wordpress.org/plugins/jsm-force-ssl/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/jsm-force-ssl/</a></p>\n\n<blockquote>\n <p>This plugin uses native WordPress filters, instead of PHP’s output\n buffer, for maximum reliability, performance and caching compatibility\n (this plugin does not affect caching performance), along with 301\n permanent redirects for best SEO (301 redirects are considered best\n for SEO when moving from HTTP to HTTPS).</p>\n \n <p>Honors proxy / load-balancing variables for large hosting\n environments:</p>\n \n <p>HTTP_X_FORWARDED_PROTO HTTP_X_FORWARDED_SSL Requirements:</p>\n \n <p>Your web server must be configured with an SSL certificate and able to\n handle HTTPS request. </p>\n \n <p>Simply activate the plugin and you’re done:</p>\n \n <p>There are no plugin settings to adjust, and no changes are made to\n your WordPress configuration — simply activate or deactivate the\n plugin to enable / disable the filters and dynamic redirects.</p>\n</blockquote>\n"
}
] | 2019/02/03 | [
"https://wordpress.stackexchange.com/questions/327554",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/160439/"
] | So I recently, built and LAMP server and installed wordpress on it. I connected it to the web via a reverse ssh tunnel using serveo.net. I decided to add ssl and the rest of the website seem to work fine, but wordpress keeps breaking when I try to use ssl. I went to the general settings and changed the urls to http instead of https, but when I load the pages, in the source code the css and js urls are using http instead of https, so they won't load. Then wp-admin part won't even load. How do I fix this? I've looked at quite a few posts about people having similar problems, but none of them helped. | Check two things:
* in the wp-options table, the site URLs (in two places) should be the full URL, as in <https://www.example.com> .
* check the site's htaccess file for proper rewrite of http to https.
For a htaccess rule, this one works in most case:
```
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
```
Then look at your theme files to ensure that any references to CSS/JS include the https protocol, not http. Most well-written themes will use relative rather than absolute references to files to include.
It's also possible a plugin might be specifying http rather than https.
Use the Network tab in Developer Tools (usually F12 in your browser) to look at each request to see where it is coming from. If the request is to a plugin folder, then check the code in there. |
327,560 | <p>I am currently setting up a WordPress website and everything is going fine except for one issue I simply can't figure out.</p>
<p>So basically I have a booking form on my website that allows people to select a couple values (number of bedrooms and bathrooms) and then when they click the button those values are amended to the booking-page URL and loaded.</p>
<p>The problem I'm running into is that the code is being amended to the end of my current (home) page and thus not having any effect/ just reloading the page.</p>
<p>After hours of looking around/ troubleshooting, and guessing I believe the code of interest is as follows from the theme I have installed. Would it be an issue of permalink (20) not existing and thus just returning the current page? If so that's odd since this theme is supposed to be ready to go right from install.</p>
<p>That same button further down my page directs to myhomepage.com/ ?post_type=acf-field&p=20 instead of the booking page.</p>
<p>Literally any help whatsoever with this would be greatly appreciated. It's fun looking around and learning a lot, but I really need my website to work as soon as possible. Thank you again.</p>
<p>The code I THINK might be part of the problem:</p>
<pre><code> <form action="<?php echo get_permalink( 20 ); ?>" method="get">
<select name="service_id" data-custom-class="select-bedrooms">
<option value="" disabled selected><?php _e( 'Bedrooms', 'themestreet' ); ?></option>
<?php if ( have_rows( 'bedroom_list','option' ) ) : $i = 1; ?>
<?php while ( have_rows( 'bedroom_list','option' ) ) : the_row();
// vars
$value = get_sub_field( 'value' );
$title = get_sub_field( 'title' );
?><option value="<?php echo $value; ?>"><?php echo $title; ?></option>
<?php $i++; ?>
<?php endwhile; ?>
<?php else: ?>
<option value="" disabled selected><?php _e( 'Bedrooms', 'themestreet' ); ?></option>
<option value="1"><?php _e('One Bedroom','themestreet'); ?></option>
<option value="2"><?php _e('Two Bedrooms','themestreet'); ?></option>
<option value="3"><?php _e('Three Bedrooms','themestreet'); ?></option>
<option value="4"><?php _e('Four Bedrooms','themestreet'); ?></option>
<option value="5"><?php _e('Five Bedrooms','themestreet'); ?></option>
<option value="6"><?php _e('Six Bedrooms','themestreet'); ?></option>
<?php endif; ?>
</select>
<select name="pricing_param_quantity" data-custom-class="select-bathrooms">
<option value="" disabled selected><?php _e( 'Bathrooms', 'themestreet' ); ?></option>
<?php if ( have_rows( 'bathroom_list','option' ) ) : $i = 1; ?>
<?php while ( have_rows( 'bathroom_list','option' ) ) : the_row();
// vars
$value = get_sub_field( 'value' );
$title = get_sub_field( 'title' );
?><option value="<?php echo $value; ?>"><?php echo $title; ?></option>
<?php $i++; ?>
<?php endwhile; ?>
<?php else: ?>
<option value="" disabled selected><?php _e( 'Bathrooms', 'themestreet' ); ?></option>
<option value="1"><?php _e('1 Bathroom','themestreet'); ?></option>
<option value="2"><?php _e('2 Bathrooms','themestreet'); ?></option>
<option value="3"><?php _e('3 Bathrooms','themestreet'); ?></option>
<option value="4"><?php _e('4 Bathrooms','themestreet'); ?></option>
<option value="5"><?php _e('5 Bathrooms','themestreet'); ?></option>
<option value="6"><?php _e('6 Bathrooms','themestreet'); ?></option>
<?php endif; ?>
</select>
<button class="btn btn--primary"><?php _e( 'BOOK A CLEANING NOW', 'themestreet' ); ?></button>
</form>
</code></pre>
| [
{
"answer_id": 327562,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 1,
"selected": false,
"text": "<p>Check two things: </p>\n\n<ul>\n<li>in the wp-options table, the site URLs (in two places) should be the full URL, as in <a href=\"https://www.example.com\" rel=\"nofollow noreferrer\">https://www.example.com</a> .</li>\n<li>check the site's htaccess file for proper rewrite of http to https. </li>\n</ul>\n\n<p>For a htaccess rule, this one works in most case: </p>\n\n<pre><code>RewriteEngine On\n RewriteCond %{HTTPS} !=on\n RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n</code></pre>\n\n<p>Then look at your theme files to ensure that any references to CSS/JS include the https protocol, not http. Most well-written themes will use relative rather than absolute references to files to include. </p>\n\n<p>It's also possible a plugin might be specifying http rather than https.</p>\n\n<p>Use the Network tab in Developer Tools (usually F12 in your browser) to look at each request to see where it is coming from. If the request is to a plugin folder, then check the code in there.</p>\n"
},
{
"answer_id": 345548,
"author": "Vincere Sempre",
"author_id": 173852,
"author_profile": "https://wordpress.stackexchange.com/users/173852",
"pm_score": 1,
"selected": false,
"text": "<p>Had the similar issue.</p>\n\n<p>This <a href=\"https://wordpress.stackexchange.com/q/75921/173852\">answer</a> solves most of the issues and I'm hoping you've gone through it.</p>\n\n<p>The reason, I found, for HTTPS (SSL) not working on my Wordpress even after changing<br>\n1. Virtual Host File aka <code><web_directory>.conf</code> file inside <code>/ect/apache2/sites-available</code><br>\n2. <code>wp-config</code> file inside <code>/var/www/<web_directory>/</code><br>\n3. [For AWS EC2 Users] Adding a load balancer with a SSL certificate for HTTPS connections</p>\n\n<p>If after doing all this, you can view your website w/o CSS and JS working, then,</p>\n\n<p>Last step </p>\n\n<ol>\n<li><p>Inside your Wordpress Dashboard, go to <code>Settings>General</code> </p>\n\n<p>Under, <code>Wordpress Address (URL)</code> add, <code>https://<yourdomain>.com</code><br>\nUnder, <code>Site Address (URL)</code> add, <code>https://<yourdomain>.com</code> </p></li>\n</ol>\n\n<p>I found that, when only <code>Site Address (URL)</code> has been activated with the website URL, Wordpress Themes automatically direct towards, the css files with HTTPS aka, <code>https://<WordPressAddress>/css/index.css</code>. </p>\n\n<p>Only your domain has SSL access hence, adding your domain name at <code>Wordpress Address (URL)</code> solved the problems for me. </p>\n"
},
{
"answer_id": 345551,
"author": "F.A",
"author_id": 139889,
"author_profile": "https://wordpress.stackexchange.com/users/139889",
"pm_score": 0,
"selected": false,
"text": "<p>Add this code to <code>wp-config.php</code> in your <code>wordpress</code> root folder.<br>\nAlso, in <code>General Settings</code> on the Admin Panel, change <code>http</code> to <code>https</code> for your siteurl an home.</p>\n\n<pre><code>define('FORCE_SSL_ADMIN', true);\nif (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false)\n $_SERVER['HTTPS']='on';\n</code></pre>\n"
},
{
"answer_id": 366077,
"author": "Shady Mohamed Sherif",
"author_id": 98924,
"author_profile": "https://wordpress.stackexchange.com/users/98924",
"pm_score": 0,
"selected": false,
"text": "<p>I had the same issue when I hosted my site on Azure webapp service Linux.</p>\n\n<p>Try this plugin. take care when it active it works.\n<a href=\"https://wordpress.org/plugins/jsm-force-ssl/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/jsm-force-ssl/</a></p>\n\n<blockquote>\n <p>This plugin uses native WordPress filters, instead of PHP’s output\n buffer, for maximum reliability, performance and caching compatibility\n (this plugin does not affect caching performance), along with 301\n permanent redirects for best SEO (301 redirects are considered best\n for SEO when moving from HTTP to HTTPS).</p>\n \n <p>Honors proxy / load-balancing variables for large hosting\n environments:</p>\n \n <p>HTTP_X_FORWARDED_PROTO HTTP_X_FORWARDED_SSL Requirements:</p>\n \n <p>Your web server must be configured with an SSL certificate and able to\n handle HTTPS request. </p>\n \n <p>Simply activate the plugin and you’re done:</p>\n \n <p>There are no plugin settings to adjust, and no changes are made to\n your WordPress configuration — simply activate or deactivate the\n plugin to enable / disable the filters and dynamic redirects.</p>\n</blockquote>\n"
}
] | 2019/02/03 | [
"https://wordpress.stackexchange.com/questions/327560",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/160445/"
] | I am currently setting up a WordPress website and everything is going fine except for one issue I simply can't figure out.
So basically I have a booking form on my website that allows people to select a couple values (number of bedrooms and bathrooms) and then when they click the button those values are amended to the booking-page URL and loaded.
The problem I'm running into is that the code is being amended to the end of my current (home) page and thus not having any effect/ just reloading the page.
After hours of looking around/ troubleshooting, and guessing I believe the code of interest is as follows from the theme I have installed. Would it be an issue of permalink (20) not existing and thus just returning the current page? If so that's odd since this theme is supposed to be ready to go right from install.
That same button further down my page directs to myhomepage.com/ ?post\_type=acf-field&p=20 instead of the booking page.
Literally any help whatsoever with this would be greatly appreciated. It's fun looking around and learning a lot, but I really need my website to work as soon as possible. Thank you again.
The code I THINK might be part of the problem:
```
<form action="<?php echo get_permalink( 20 ); ?>" method="get">
<select name="service_id" data-custom-class="select-bedrooms">
<option value="" disabled selected><?php _e( 'Bedrooms', 'themestreet' ); ?></option>
<?php if ( have_rows( 'bedroom_list','option' ) ) : $i = 1; ?>
<?php while ( have_rows( 'bedroom_list','option' ) ) : the_row();
// vars
$value = get_sub_field( 'value' );
$title = get_sub_field( 'title' );
?><option value="<?php echo $value; ?>"><?php echo $title; ?></option>
<?php $i++; ?>
<?php endwhile; ?>
<?php else: ?>
<option value="" disabled selected><?php _e( 'Bedrooms', 'themestreet' ); ?></option>
<option value="1"><?php _e('One Bedroom','themestreet'); ?></option>
<option value="2"><?php _e('Two Bedrooms','themestreet'); ?></option>
<option value="3"><?php _e('Three Bedrooms','themestreet'); ?></option>
<option value="4"><?php _e('Four Bedrooms','themestreet'); ?></option>
<option value="5"><?php _e('Five Bedrooms','themestreet'); ?></option>
<option value="6"><?php _e('Six Bedrooms','themestreet'); ?></option>
<?php endif; ?>
</select>
<select name="pricing_param_quantity" data-custom-class="select-bathrooms">
<option value="" disabled selected><?php _e( 'Bathrooms', 'themestreet' ); ?></option>
<?php if ( have_rows( 'bathroom_list','option' ) ) : $i = 1; ?>
<?php while ( have_rows( 'bathroom_list','option' ) ) : the_row();
// vars
$value = get_sub_field( 'value' );
$title = get_sub_field( 'title' );
?><option value="<?php echo $value; ?>"><?php echo $title; ?></option>
<?php $i++; ?>
<?php endwhile; ?>
<?php else: ?>
<option value="" disabled selected><?php _e( 'Bathrooms', 'themestreet' ); ?></option>
<option value="1"><?php _e('1 Bathroom','themestreet'); ?></option>
<option value="2"><?php _e('2 Bathrooms','themestreet'); ?></option>
<option value="3"><?php _e('3 Bathrooms','themestreet'); ?></option>
<option value="4"><?php _e('4 Bathrooms','themestreet'); ?></option>
<option value="5"><?php _e('5 Bathrooms','themestreet'); ?></option>
<option value="6"><?php _e('6 Bathrooms','themestreet'); ?></option>
<?php endif; ?>
</select>
<button class="btn btn--primary"><?php _e( 'BOOK A CLEANING NOW', 'themestreet' ); ?></button>
</form>
``` | Check two things:
* in the wp-options table, the site URLs (in two places) should be the full URL, as in <https://www.example.com> .
* check the site's htaccess file for proper rewrite of http to https.
For a htaccess rule, this one works in most case:
```
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
```
Then look at your theme files to ensure that any references to CSS/JS include the https protocol, not http. Most well-written themes will use relative rather than absolute references to files to include.
It's also possible a plugin might be specifying http rather than https.
Use the Network tab in Developer Tools (usually F12 in your browser) to look at each request to see where it is coming from. If the request is to a plugin folder, then check the code in there. |
327,577 | <p>I have a native app project that gets all data from <code>/wp-json/wp/v2</code>.</p>
<p>I've registered phone using this</p>
<pre><code>register_meta('user', 'phone', array(
"type" => "string",
"show_in_rest" => true
));
</code></pre>
<p>to the functions.php and I can see the user metadata using this</p>
<pre><code>http://example.com/wp-json/wp/v2/users/1
</code></pre>
<p>How can I create/update the usermeta using WP REST API outside WordPress?</p>
<p>any help will be great.</p>
<p>Thanks</p>
| [
{
"answer_id": 327602,
"author": "adeguk Loggcity",
"author_id": 160489,
"author_profile": "https://wordpress.stackexchange.com/users/160489",
"pm_score": 0,
"selected": false,
"text": "<p>I found these 2 post helpful</p>\n\n<ul>\n<li><a href=\"https://www.wpsuperstars.net/wordpress-rest-api/\" rel=\"nofollow noreferrer\">https://www.wpsuperstars.net/wordpress-rest-api/</a></li>\n<li><a href=\"https://kinsta.com/blog/wordpress-rest-api/\" rel=\"nofollow noreferrer\">https://kinsta.com/blog/wordpress-rest-api/</a></li>\n</ul>\n"
},
{
"answer_id": 338628,
"author": "ngearing",
"author_id": 50184,
"author_profile": "https://wordpress.stackexchange.com/users/50184",
"pm_score": 2,
"selected": false,
"text": "<p>I had to do this yesterday, here's how I did it.</p>\n\n<p>Like you have already done <code>register_meta</code> to appear in the api.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>register_meta('user', 'meta_key', array(\n \"type\" => \"string\",\n \"show_in_rest\" => true,\n \"single\" => true,\n));\n</code></pre>\n\n<p>Then you will need to make a POST or PUT request to the users endpoint with the meta values in the body of the request.</p>\n\n<p>I accomplished this using javascript's <code>fetch</code> api but you could also do it with <code>ajax</code> or using WordPress's <code>wp_remote_request()</code> function.</p>\n\n<p>First I enqueued my javascript.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>wp_register_script( 'theme-js', get_theme_file_uri( './dist/scripts/main.js' ), [ 'jquery' ], '', true );\nwp_localize_script(\n 'theme-js',\n 'wpApiSettings',\n array(\n 'root' => esc_url_raw( rest_url() ), // Rest api root\n 'nonce' => wp_create_nonce( 'wp_rest' ), // For auth\n 'currentUser' => get_current_user_id() ?: false,\n )\n);\nwp_enqueue_script( 'theme-js' );\n</code></pre>\n\n<p>Then I setup my fetch function.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>const fetchApi = function(route, data, method) {\n if (!route) route = 'posts'\n if (!method) method = 'GET'\n\n return fetch(wpApiSettings.root + 'wp/v2/' + route, {\n method,\n credentials: 'same-origin',\n body: JSON.stringify(data),\n headers: {\n 'X-WP-Nonce': wpApiSettings.nonce,\n 'Content-Type': 'application/json'\n }\n })\n}\n</code></pre>\n\n<p>Then call the function when you need.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>fetchApi(\n `users/${wpApiSettings.currentUser}`,\n {\n meta: {\n meta_key: value\n }\n },\n 'POST'\n)\n .then(resp => {\n console.log(resp)\n if (resp.ok) {\n return resp.json()\n }\n return false\n })\n .then(json => console.log(json))\n</code></pre>\n"
}
] | 2019/02/04 | [
"https://wordpress.stackexchange.com/questions/327577",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/160468/"
] | I have a native app project that gets all data from `/wp-json/wp/v2`.
I've registered phone using this
```
register_meta('user', 'phone', array(
"type" => "string",
"show_in_rest" => true
));
```
to the functions.php and I can see the user metadata using this
```
http://example.com/wp-json/wp/v2/users/1
```
How can I create/update the usermeta using WP REST API outside WordPress?
any help will be great.
Thanks | I had to do this yesterday, here's how I did it.
Like you have already done `register_meta` to appear in the api.
```php
register_meta('user', 'meta_key', array(
"type" => "string",
"show_in_rest" => true,
"single" => true,
));
```
Then you will need to make a POST or PUT request to the users endpoint with the meta values in the body of the request.
I accomplished this using javascript's `fetch` api but you could also do it with `ajax` or using WordPress's `wp_remote_request()` function.
First I enqueued my javascript.
```php
wp_register_script( 'theme-js', get_theme_file_uri( './dist/scripts/main.js' ), [ 'jquery' ], '', true );
wp_localize_script(
'theme-js',
'wpApiSettings',
array(
'root' => esc_url_raw( rest_url() ), // Rest api root
'nonce' => wp_create_nonce( 'wp_rest' ), // For auth
'currentUser' => get_current_user_id() ?: false,
)
);
wp_enqueue_script( 'theme-js' );
```
Then I setup my fetch function.
```js
const fetchApi = function(route, data, method) {
if (!route) route = 'posts'
if (!method) method = 'GET'
return fetch(wpApiSettings.root + 'wp/v2/' + route, {
method,
credentials: 'same-origin',
body: JSON.stringify(data),
headers: {
'X-WP-Nonce': wpApiSettings.nonce,
'Content-Type': 'application/json'
}
})
}
```
Then call the function when you need.
```js
fetchApi(
`users/${wpApiSettings.currentUser}`,
{
meta: {
meta_key: value
}
},
'POST'
)
.then(resp => {
console.log(resp)
if (resp.ok) {
return resp.json()
}
return false
})
.then(json => console.log(json))
``` |
327,597 | <p>I want users to change their avatar on a general site, because some plugins only work with that.
for example </p>
<blockquote>
<p>www.example.com/members/user1/profile/change-avatar/</p>
</blockquote>
<p>And </p>
<blockquote>
<p>www.example.com/members/user2/profile/change-avatar/</p>
</blockquote>
<p>Should both redirect to </p>
<blockquote>
<p>www.example.com/change-avatar/</p>
</blockquote>
| [
{
"answer_id": 327615,
"author": "0Mr_X0",
"author_id": 160485,
"author_profile": "https://wordpress.stackexchange.com/users/160485",
"pm_score": 2,
"selected": true,
"text": "<p>Solved it.</p>\n\n<pre><code>add_action('init','redirect_to_change_avatar');\n\nfunction redirect_to_change_avatar() {\n if ( strpos($_SERVER['REQUEST_URI'], '/profile/change-avatar/') !== false ) {\n wp_redirect('/change-avatar/');\n exit;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 327688,
"author": "phatskat",
"author_id": 20143,
"author_profile": "https://wordpress.stackexchange.com/users/20143",
"pm_score": 0,
"selected": false,
"text": "<p>I would recommend something a little more robust for your logic, that way if the URL changes you aren't still using the same position arguments:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function redirect_to_change_avatar() {\n $request_uri = filter_input( INPUT_SERVER, 'REQUEST_URI', FILTER_SANITIZE_STRING );\n\n // Strpos will return boolean FALSE if the string does not match at all.\n // N.B the strict === comparison:\n if ( false === strpos( $request_uri, '/profile/change-avatar/' )) {\n return;\n }\n\n wp_redirect( '/change-avatar/' );\n exit;\n}\n</code></pre>\n"
}
] | 2019/02/04 | [
"https://wordpress.stackexchange.com/questions/327597",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/160485/"
] | I want users to change their avatar on a general site, because some plugins only work with that.
for example
>
> www.example.com/members/user1/profile/change-avatar/
>
>
>
And
>
> www.example.com/members/user2/profile/change-avatar/
>
>
>
Should both redirect to
>
> www.example.com/change-avatar/
>
>
> | Solved it.
```
add_action('init','redirect_to_change_avatar');
function redirect_to_change_avatar() {
if ( strpos($_SERVER['REQUEST_URI'], '/profile/change-avatar/') !== false ) {
wp_redirect('/change-avatar/');
exit;
}
}
``` |
327,628 | <p>What is the easiest approach to iterate through the sub-sites (in Multi-Site network) and let's say <code>add_option("xyz", 123)</code> for each of site.</p>
| [
{
"answer_id": 327629,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 2,
"selected": false,
"text": "<p>Well, you can get sites with <a href=\"https://developer.wordpress.org/reference/functions/get_sites/\" rel=\"nofollow noreferrer\"><code>get_sites</code></a> and loop through them:</p>\n\n<pre><code>if ( function_exists( 'get_sites' ) && class_exists( 'WP_Site_Query' ) ) {\n $sites = get_sites();\n foreach ( $sites as $site ) {\n // do something\n }\n return;\n}\n</code></pre>\n"
},
{
"answer_id": 327633,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 2,
"selected": false,
"text": "<p>I've found this so far to work for me:</p>\n\n<pre><code>foreach (get_sites() as $blog){\n switch_to_blog($blog->blog_id);\n // get_option (...) \n restore_current_blog();\n}\n</code></pre>\n"
}
] | 2019/02/04 | [
"https://wordpress.stackexchange.com/questions/327628",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/33667/"
] | What is the easiest approach to iterate through the sub-sites (in Multi-Site network) and let's say `add_option("xyz", 123)` for each of site. | Well, you can get sites with [`get_sites`](https://developer.wordpress.org/reference/functions/get_sites/) and loop through them:
```
if ( function_exists( 'get_sites' ) && class_exists( 'WP_Site_Query' ) ) {
$sites = get_sites();
foreach ( $sites as $site ) {
// do something
}
return;
}
``` |
327,634 | <p>I have this hook. How i can add this hook with get_template_part()? I created a file "myfile.php" where I store the HTML code of my search bar, but a can't manage to connect my template</p>
<pre><code>add_filter('wp_nav_menu_items', 'add_search_form', 10, 2);
function add_search_form($items, $args) {
if( $args->theme_location == 'MENU-NAME' )
$items .= '<li class="search"><form role="search" method="get" id="searchform" action="'.home_url( '/' ).'"><input type="text" value="search" name="s" id="s" /><input type="submit" id="searchsubmit" value="'. esc_attr__('Search') .'" /></form></li>';
return $items;
}
</code></pre>
| [
{
"answer_id": 327637,
"author": "Alexander Holsgrove",
"author_id": 48962,
"author_profile": "https://wordpress.stackexchange.com/users/48962",
"pm_score": 1,
"selected": false,
"text": "<p>OK, so one simple way would be to edit your template, I assume <code>header.php</code> for where you want the menu to appear. Use the template include to load <code>myfile.php</code></p>\n\n<pre><code>get_template_part('template-parts/myfile');\n</code></pre>\n\n<p>Then inside <code>myfile.php</code>:</p>\n\n<pre><code><?php\n\n$search .= '<li class=\"search\"><form role=\"search\" method=\"get\" id=\"searchform\" action=\"'.home_url( '/' ).'\"><input type=\"text\" value=\"search\" name=\"s\" id=\"s\" /><input type=\"submit\" id=\"searchsubmit\" value=\"'. esc_attr__('Search') .'\" /></form></li>';\n\nwp_nav_menu(array(\n 'menu' => 'Menu Name',\n 'theme_location' => 'menu-name',\n 'container' => 'nav',\n 'container_class' => 'main-menu-class',\n 'container_id' => '',\n 'items_wrap' => '<ul class=\"navbar-nav\">%3$s'. $search .'</ul>'\n));\n</code></pre>\n\n<p>So your myfile contains the menu as well as the search form. This isn't tested, but you get the idea - change out the menu name and HTML elements & classes.</p>\n"
},
{
"answer_id": 327658,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to include an external PHP file inside your template (or code), then put that code inside another template (called, say, mycode.php). Put that mycode.php file in your theme folder.</p>\n\n<p>Then you can <code>get_template_part('mycode')</code>. Note that you do not include the '.php' part as the parameter of get_template_part.</p>\n\n<p>Your code in mycode.php will be executed at the point of the get_template_part call. Note that this is a good way to include an external functions call that is only needed by a template.</p>\n\n<p><strong>Added</strong></p>\n\n<p>More experimentation on how to 'include' a file that has functions inside your template. I learned that the <code>locate_template</code> command is better in all cases. <code>get_template_part</code> may not happen 'soon' enough for your page.</p>\n\n<p>So I now use </p>\n\n<pre><code>locate_template(\"myfunctions.php\",true,true);\n</code></pre>\n\n<p>where the <code>myfunctions.php</code> is located in the active theme folder. The two 'true' parameters ensure that the file is loaded at the proper time. The first 'true' will load the file if found. The second 'true' will use <code>require_once</code> instead of a <code>require</code>.</p>\n\n<p>My use of this was in a template. I needed some functions that would add things to the head (with an <code>apply_filter('wp_head')</code>). The functions are in the <code>my_functions.php</code> file. So the template contains the <code>locate_template</code> first, then the filters for the <code>wp_head</code> after. </p>\n\n<p>This is a clever and useful way to get a file of your functions to load with a template, while not requiring the functions to be available globally - just in your template.</p>\n"
}
] | 2019/02/04 | [
"https://wordpress.stackexchange.com/questions/327634",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159993/"
] | I have this hook. How i can add this hook with get\_template\_part()? I created a file "myfile.php" where I store the HTML code of my search bar, but a can't manage to connect my template
```
add_filter('wp_nav_menu_items', 'add_search_form', 10, 2);
function add_search_form($items, $args) {
if( $args->theme_location == 'MENU-NAME' )
$items .= '<li class="search"><form role="search" method="get" id="searchform" action="'.home_url( '/' ).'"><input type="text" value="search" name="s" id="s" /><input type="submit" id="searchsubmit" value="'. esc_attr__('Search') .'" /></form></li>';
return $items;
}
``` | OK, so one simple way would be to edit your template, I assume `header.php` for where you want the menu to appear. Use the template include to load `myfile.php`
```
get_template_part('template-parts/myfile');
```
Then inside `myfile.php`:
```
<?php
$search .= '<li class="search"><form role="search" method="get" id="searchform" action="'.home_url( '/' ).'"><input type="text" value="search" name="s" id="s" /><input type="submit" id="searchsubmit" value="'. esc_attr__('Search') .'" /></form></li>';
wp_nav_menu(array(
'menu' => 'Menu Name',
'theme_location' => 'menu-name',
'container' => 'nav',
'container_class' => 'main-menu-class',
'container_id' => '',
'items_wrap' => '<ul class="navbar-nav">%3$s'. $search .'</ul>'
));
```
So your myfile contains the menu as well as the search form. This isn't tested, but you get the idea - change out the menu name and HTML elements & classes. |
327,665 | <p>I spent some time in my DB trying to figure out how I can clean out some completed order data. Below is the query that I am confident will help remove the data from completed woocommerce orders. </p>
<p>My question is more of a DB Query one:</p>
<pre><code>DELETE * FROM wp_post
JOIN wp_postmeta ON wp_post.ID = wp_postmeta.post_id
JOIN wp_woocommerce_order_items ON wp_postmeta.post_id = wp_woocommerce_order_items.order_item_id
JOIN wp_woocommerce_order_itemmeta ON wp_postmeta.post_id = wp_woocommerce_order_itemmeta.order_item_id
WHERE wp_post.post_type = "shop_order"
AND wp_post.post_status = "wc-completed"
</code></pre>
<p>When I run the above query I get the following MySQL error:</p>
<pre><code>#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '* FROM wp_post
JOIN wp_postmeta ON wp_post.ID = wp_postmeta.post_id
JOIN wp_wo' at line 1
</code></pre>
<p>Am I not <code>JOIN</code> my WordPress Tables correctly?</p>
<p>This question may be more appropriate for stackoverflow but figured I would try here first. </p>
<p>Below is the correct query string:</p>
<pre><code>DELETE wp_posts, wp_postmeta, wp_woocommerce_order_items, wp_woocommerce_order_itemmeta FROM
JOIN wp_posts.ID = wp_postmeta.post_id,
wp_postmeta.post_id = wp_woocommerce_order_itemmeta.order_item_id,
wp_posts.ID = wp_woocommerce_order_items.order_item_id
WHERE wp_posts.post_type = "shop_order"
AND wp_posts.post_status = "wc-completed"
</code></pre>
<p>Which fixed the wp_posts not wp_post and included all of the tables in-between the DELETE and FROM.</p>
| [
{
"answer_id": 327670,
"author": "mzykin",
"author_id": 160284,
"author_profile": "https://wordpress.stackexchange.com/users/160284",
"pm_score": 2,
"selected": false,
"text": "<p>Try <code>wp_posts</code> instead of <code>wp_post</code>.</p>\n"
},
{
"answer_id": 404818,
"author": "Harkály Gergő",
"author_id": 71655,
"author_profile": "https://wordpress.stackexchange.com/users/71655",
"pm_score": 1,
"selected": false,
"text": "<p>Here is my solution for delete WordPress WooCommerce orders with SQL:</p>\n<pre><code>DELETE wp_posts, wp_postmeta, wp_woocommerce_order_items, wp_woocommerce_order_itemmeta\nFROM wp_posts\nLEFT JOIN wp_postmeta ON wp_posts.ID = wp_postmeta.post_id\nLEFT JOIN wp_woocommerce_order_itemmeta ON wp_postmeta.post_id = wp_woocommerce_order_itemmeta.order_item_id\nLEFT JOIN wp_woocommerce_order_items ON wp_posts.ID = wp_woocommerce_order_items.order_item_id\nWHERE wp_posts.post_type = "shop_order" \nAND wp_posts.post_date < '2019-03-01';\n</code></pre>\n"
}
] | 2019/02/04 | [
"https://wordpress.stackexchange.com/questions/327665",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/6296/"
] | I spent some time in my DB trying to figure out how I can clean out some completed order data. Below is the query that I am confident will help remove the data from completed woocommerce orders.
My question is more of a DB Query one:
```
DELETE * FROM wp_post
JOIN wp_postmeta ON wp_post.ID = wp_postmeta.post_id
JOIN wp_woocommerce_order_items ON wp_postmeta.post_id = wp_woocommerce_order_items.order_item_id
JOIN wp_woocommerce_order_itemmeta ON wp_postmeta.post_id = wp_woocommerce_order_itemmeta.order_item_id
WHERE wp_post.post_type = "shop_order"
AND wp_post.post_status = "wc-completed"
```
When I run the above query I get the following MySQL error:
```
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '* FROM wp_post
JOIN wp_postmeta ON wp_post.ID = wp_postmeta.post_id
JOIN wp_wo' at line 1
```
Am I not `JOIN` my WordPress Tables correctly?
This question may be more appropriate for stackoverflow but figured I would try here first.
Below is the correct query string:
```
DELETE wp_posts, wp_postmeta, wp_woocommerce_order_items, wp_woocommerce_order_itemmeta FROM
JOIN wp_posts.ID = wp_postmeta.post_id,
wp_postmeta.post_id = wp_woocommerce_order_itemmeta.order_item_id,
wp_posts.ID = wp_woocommerce_order_items.order_item_id
WHERE wp_posts.post_type = "shop_order"
AND wp_posts.post_status = "wc-completed"
```
Which fixed the wp\_posts not wp\_post and included all of the tables in-between the DELETE and FROM. | Try `wp_posts` instead of `wp_post`. |
327,698 | <p>I want to modify the output of <code>wp_link_pages</code>.</p>
<p>Basically what I need is to show Previous and Next buttons and current page/total number of pages.
I created the Previous and Next button. Now in between them I want to add a current page and the total pages number.</p>
<p>Here is my code</p>
<pre><code>wp_link_pages( array(
'before' => '<div class="page-links">' . __(''),
'after' => '</div>',
'next_or_number' => 'next',
'nextpagelink' => __('Next'),
'previouspagelink' => __('Previous'),
'pagelink' => '%',
'echo' => 1,
) );
</code></pre>
<p>I am not sure what to do.
The effect I want to get is just like below image.<a href="https://i.stack.imgur.com/moQTN.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/moQTN.jpg" alt="enter image description here"></a></p>
| [
{
"answer_id": 327670,
"author": "mzykin",
"author_id": 160284,
"author_profile": "https://wordpress.stackexchange.com/users/160284",
"pm_score": 2,
"selected": false,
"text": "<p>Try <code>wp_posts</code> instead of <code>wp_post</code>.</p>\n"
},
{
"answer_id": 404818,
"author": "Harkály Gergő",
"author_id": 71655,
"author_profile": "https://wordpress.stackexchange.com/users/71655",
"pm_score": 1,
"selected": false,
"text": "<p>Here is my solution for delete WordPress WooCommerce orders with SQL:</p>\n<pre><code>DELETE wp_posts, wp_postmeta, wp_woocommerce_order_items, wp_woocommerce_order_itemmeta\nFROM wp_posts\nLEFT JOIN wp_postmeta ON wp_posts.ID = wp_postmeta.post_id\nLEFT JOIN wp_woocommerce_order_itemmeta ON wp_postmeta.post_id = wp_woocommerce_order_itemmeta.order_item_id\nLEFT JOIN wp_woocommerce_order_items ON wp_posts.ID = wp_woocommerce_order_items.order_item_id\nWHERE wp_posts.post_type = "shop_order" \nAND wp_posts.post_date < '2019-03-01';\n</code></pre>\n"
}
] | 2019/02/05 | [
"https://wordpress.stackexchange.com/questions/327698",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/160548/"
] | I want to modify the output of `wp_link_pages`.
Basically what I need is to show Previous and Next buttons and current page/total number of pages.
I created the Previous and Next button. Now in between them I want to add a current page and the total pages number.
Here is my code
```
wp_link_pages( array(
'before' => '<div class="page-links">' . __(''),
'after' => '</div>',
'next_or_number' => 'next',
'nextpagelink' => __('Next'),
'previouspagelink' => __('Previous'),
'pagelink' => '%',
'echo' => 1,
) );
```
I am not sure what to do.
The effect I want to get is just like below image.[](https://i.stack.imgur.com/moQTN.jpg) | Try `wp_posts` instead of `wp_post`. |
327,755 | <p>I'm going through some training on internationalization and escaping data. But I feel stuck with escaping the title attribute. I have the following code in a helper function...</p>
<pre><code> echo '<h2 class="m-title">';
printf(
esc_html__('%s','tn'),
'<a href="'.esc_url(get_permalink()).'" title="'.the_title_attribute().'">
'. esc_html(get_the_title()).'
</a>
'
);
echo '</h2>';
</code></pre>
<p>Everything appears to be working fine with it, except the title attribute. The output looks like this....</p>
<pre><code>Hello world! Hello world!
</code></pre>
<p>Because the DOM is loading the following:</p>
<pre><code><h2 class="m-title">
Hello world!
<a href="http://local.dev.site/mysite/?p=26" title="">
Hello world!
</a>
</h2>
</code></pre>
<p>What I am doing wrong with calling <code>the_title_attribute()</code>? <a href="https://developer.wordpress.org/reference/functions/the_title_attribute/" rel="nofollow noreferrer">According to the docs</a>, its already escaped.</p>
<p>Thanks for any tips!</p>
| [
{
"answer_id": 327758,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 2,
"selected": true,
"text": "<p>Some screen readers read the title attribute plus the link text - so those visitors would hear \"Hello world! Hello world!\" - so unless your real title attribute is different than the link text and provides additional context to users of screen readers, you may wish to just not use the title attribute.</p>\n\n<p>Or, you should be able to rewrite everything so that instead of echoing you have something like</p>\n\n<pre><code><?php // your other code here ?>\n<h2 class=\"m-title\">\n <a href=\"<?php echo esc_url(get_permalink()); ?>\" title=\"<?php the_title_attribute(); ?>\">\n <?php the_title(); ?>\n </a>\n</h2>\n</code></pre>\n\n<p>This way you're mixing HTML and PHP but it allows you to immediately output both, so that <code>the_title_attribute()</code> is outputting in the right spot and not before everything else is parsed. You can add the additional <code>esc_html__()</code> call wrapped within each set of PHP tags but it's not clear why those would be needed for fields like <code>the_permalink()</code>.</p>\n"
},
{
"answer_id": 327765,
"author": "klewis",
"author_id": 98671,
"author_profile": "https://wordpress.stackexchange.com/users/98671",
"pm_score": 2,
"selected": false,
"text": "<p>I just wanted to also add something I overlooked on the use of <code>the_title_attribute</code>. There are <a href=\"https://developer.wordpress.org/reference/functions/the_title_attribute/\" rel=\"nofollow noreferrer\">$args</a> that can be applied. So in the event of returning the title one could simply set echo to false like so...</p>\n\n<pre><code> echo '<h2 class=\"m-title\">';\n printf(\n esc_html__('%s','tn'),\n '<a href=\"'.esc_url(get_permalink()).'\" title=\"'.the_title_attribute(['echo' => false]).'\">\n '. esc_html(get_the_title()).'\n </a> \n '\n );\n echo '</h2>';\n</code></pre>\n\n<p>This is what I was originally looking for, but sense I am not doing a good job in providing a translatable string through <a href=\"https://developer.wordpress.org/reference/functions/esc_html__/\" rel=\"nofollow noreferrer\">esc_html__()</a>, it would make more sense to simply echo the title, as shown in the selected answer.</p>\n"
}
] | 2019/02/05 | [
"https://wordpress.stackexchange.com/questions/327755",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98671/"
] | I'm going through some training on internationalization and escaping data. But I feel stuck with escaping the title attribute. I have the following code in a helper function...
```
echo '<h2 class="m-title">';
printf(
esc_html__('%s','tn'),
'<a href="'.esc_url(get_permalink()).'" title="'.the_title_attribute().'">
'. esc_html(get_the_title()).'
</a>
'
);
echo '</h2>';
```
Everything appears to be working fine with it, except the title attribute. The output looks like this....
```
Hello world! Hello world!
```
Because the DOM is loading the following:
```
<h2 class="m-title">
Hello world!
<a href="http://local.dev.site/mysite/?p=26" title="">
Hello world!
</a>
</h2>
```
What I am doing wrong with calling `the_title_attribute()`? [According to the docs](https://developer.wordpress.org/reference/functions/the_title_attribute/), its already escaped.
Thanks for any tips! | Some screen readers read the title attribute plus the link text - so those visitors would hear "Hello world! Hello world!" - so unless your real title attribute is different than the link text and provides additional context to users of screen readers, you may wish to just not use the title attribute.
Or, you should be able to rewrite everything so that instead of echoing you have something like
```
<?php // your other code here ?>
<h2 class="m-title">
<a href="<?php echo esc_url(get_permalink()); ?>" title="<?php the_title_attribute(); ?>">
<?php the_title(); ?>
</a>
</h2>
```
This way you're mixing HTML and PHP but it allows you to immediately output both, so that `the_title_attribute()` is outputting in the right spot and not before everything else is parsed. You can add the additional `esc_html__()` call wrapped within each set of PHP tags but it's not clear why those would be needed for fields like `the_permalink()`. |
327,799 | <p>I want to disable the default email that is send when user is registered.
I am using this plugin for email verification <code>User Verification
By PickPlugins</code>, which sends an email with confirmation link, but the problem is that by default and WordPress send an email via <code>pluggable.php</code>:</p>
<pre><code>function wp_new_user_notification( $user_id, $deprecated = null, $notify = '' ){...}
</code></pre>
<p>I am using a theme (which I am extending with a child theme), which calls <code>wp_create_user</code>. I have replaced that parent theme function and in my <code>functions.php</code> I have added:</p>
<pre><code>add_action( 'init', function(){
remove_action( 'register_new_user', 'wp_send_new_user_notifications'
);
add_action( 'register_new_user', 'wpse236122_send_new_user_notifications' );
});
function wpse236122_send_new_user_notifications( $user_id, $notify = 'user' ){
wp_send_new_user_notifications( $user_id, $notify );
}
</code></pre>
<p>The problem is, it still send both emails, from the plugin and default WordPress email for new user registration. I don't know how to disable this email.</p>
| [
{
"answer_id": 327758,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 2,
"selected": true,
"text": "<p>Some screen readers read the title attribute plus the link text - so those visitors would hear \"Hello world! Hello world!\" - so unless your real title attribute is different than the link text and provides additional context to users of screen readers, you may wish to just not use the title attribute.</p>\n\n<p>Or, you should be able to rewrite everything so that instead of echoing you have something like</p>\n\n<pre><code><?php // your other code here ?>\n<h2 class=\"m-title\">\n <a href=\"<?php echo esc_url(get_permalink()); ?>\" title=\"<?php the_title_attribute(); ?>\">\n <?php the_title(); ?>\n </a>\n</h2>\n</code></pre>\n\n<p>This way you're mixing HTML and PHP but it allows you to immediately output both, so that <code>the_title_attribute()</code> is outputting in the right spot and not before everything else is parsed. You can add the additional <code>esc_html__()</code> call wrapped within each set of PHP tags but it's not clear why those would be needed for fields like <code>the_permalink()</code>.</p>\n"
},
{
"answer_id": 327765,
"author": "klewis",
"author_id": 98671,
"author_profile": "https://wordpress.stackexchange.com/users/98671",
"pm_score": 2,
"selected": false,
"text": "<p>I just wanted to also add something I overlooked on the use of <code>the_title_attribute</code>. There are <a href=\"https://developer.wordpress.org/reference/functions/the_title_attribute/\" rel=\"nofollow noreferrer\">$args</a> that can be applied. So in the event of returning the title one could simply set echo to false like so...</p>\n\n<pre><code> echo '<h2 class=\"m-title\">';\n printf(\n esc_html__('%s','tn'),\n '<a href=\"'.esc_url(get_permalink()).'\" title=\"'.the_title_attribute(['echo' => false]).'\">\n '. esc_html(get_the_title()).'\n </a> \n '\n );\n echo '</h2>';\n</code></pre>\n\n<p>This is what I was originally looking for, but sense I am not doing a good job in providing a translatable string through <a href=\"https://developer.wordpress.org/reference/functions/esc_html__/\" rel=\"nofollow noreferrer\">esc_html__()</a>, it would make more sense to simply echo the title, as shown in the selected answer.</p>\n"
}
] | 2019/02/05 | [
"https://wordpress.stackexchange.com/questions/327799",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/152132/"
] | I want to disable the default email that is send when user is registered.
I am using this plugin for email verification `User Verification
By PickPlugins`, which sends an email with confirmation link, but the problem is that by default and WordPress send an email via `pluggable.php`:
```
function wp_new_user_notification( $user_id, $deprecated = null, $notify = '' ){...}
```
I am using a theme (which I am extending with a child theme), which calls `wp_create_user`. I have replaced that parent theme function and in my `functions.php` I have added:
```
add_action( 'init', function(){
remove_action( 'register_new_user', 'wp_send_new_user_notifications'
);
add_action( 'register_new_user', 'wpse236122_send_new_user_notifications' );
});
function wpse236122_send_new_user_notifications( $user_id, $notify = 'user' ){
wp_send_new_user_notifications( $user_id, $notify );
}
```
The problem is, it still send both emails, from the plugin and default WordPress email for new user registration. I don't know how to disable this email. | Some screen readers read the title attribute plus the link text - so those visitors would hear "Hello world! Hello world!" - so unless your real title attribute is different than the link text and provides additional context to users of screen readers, you may wish to just not use the title attribute.
Or, you should be able to rewrite everything so that instead of echoing you have something like
```
<?php // your other code here ?>
<h2 class="m-title">
<a href="<?php echo esc_url(get_permalink()); ?>" title="<?php the_title_attribute(); ?>">
<?php the_title(); ?>
</a>
</h2>
```
This way you're mixing HTML and PHP but it allows you to immediately output both, so that `the_title_attribute()` is outputting in the right spot and not before everything else is parsed. You can add the additional `esc_html__()` call wrapped within each set of PHP tags but it's not clear why those would be needed for fields like `the_permalink()`. |
327,817 | <p>I am trying to change the text of the publish button to save</p>
<pre class="lang-php prettyprint-override"><code>function change_publish_button( $translation, $text ) {
if ( $text == 'Publish' )
return 'Save';
return $translation;
}
add_filter( 'gettext', 'change_publish_button', 10, 2 );
</code></pre>
<p>I am trying to run the above code but it doesn't change the text of the publish button, can anyone please tell what is wrong with this code or suggest any new method. Thanks in advance</p>
<p>Update
I want to change the publish button shown in the figure below.
<a href="https://i.stack.imgur.com/Y1A5N.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Y1A5N.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 327818,
"author": "Lucien Dubois",
"author_id": 51306,
"author_profile": "https://wordpress.stackexchange.com/users/51306",
"pm_score": -1,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>function translate_publish( $translated_text, $untranslated_text, $domain ) {\n if( stripos( $untranslated_text, 'Publish' ) !== FALSE ) {\n $translated_text = str_ireplace( 'Publish', 'Save', $untranslated_text ) ;\n }\n return $translated_text;\n}\nif(is_admin()){\n add_filter( 'gettext', 'translate_publish', 99, 3 );\n}\n</code></pre>\n"
},
{
"answer_id": 327821,
"author": "Pratik Patel",
"author_id": 143123,
"author_profile": "https://wordpress.stackexchange.com/users/143123",
"pm_score": 0,
"selected": false,
"text": "<p>Put below code into your theme <strong>functions.php</strong> and try</p>\n\n<pre><code>function change_publish_button( $translation, $text ) {\n\n if ( $text == 'Publish...' ) // Your button text\n $text = 'Save';\n\n return $text;\n}\n\nadd_filter( 'gettext', 'change_publish_button', 10, 2 );\n</code></pre>\n\n<p>This one is worked for me</p>\n\n<p><a href=\"https://i.stack.imgur.com/aRdy2.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/aRdy2.png\" alt=\"enter image description here\"></a></p>\n\n<p>Hope it will help you!</p>\n"
}
] | 2019/02/06 | [
"https://wordpress.stackexchange.com/questions/327817",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/160561/"
] | I am trying to change the text of the publish button to save
```php
function change_publish_button( $translation, $text ) {
if ( $text == 'Publish' )
return 'Save';
return $translation;
}
add_filter( 'gettext', 'change_publish_button', 10, 2 );
```
I am trying to run the above code but it doesn't change the text of the publish button, can anyone please tell what is wrong with this code or suggest any new method. Thanks in advance
Update
I want to change the publish button shown in the figure below.
[](https://i.stack.imgur.com/Y1A5N.png) | Put below code into your theme **functions.php** and try
```
function change_publish_button( $translation, $text ) {
if ( $text == 'Publish...' ) // Your button text
$text = 'Save';
return $text;
}
add_filter( 'gettext', 'change_publish_button', 10, 2 );
```
This one is worked for me
[](https://i.stack.imgur.com/aRdy2.png)
Hope it will help you! |
327,839 | <p>I've almost finished my first custom theme for a website. I've created some custom post type to manage a portfolio and a staff member section. No problem with the code, but the client asked if is it possible to change the staff images when an user hover on it. Is there any way to achieve this in wordpress? </p>
<p>Here is a sample of my code</p>
<pre><code><div class="team-boxed">
<?php
$args = array(
'post_type' => 'team'
);
$team = new WP_Query($args);
?>
<div class="intro">
<h2 class="text-center text-uppercase" id="">Team</h2>
</div>
<div class="row people">
<?php if( $team->have_posts() ): while( $team->have_posts() ): $team->the_post(); ?>
<div class="col-md-6 col-lg-4 item">
<div class="box">
<div class="rounded-circle" style="background-image:url('<?php the_post_thumbnail_url('full'); ?>')" id="staff-pic"></div>
<h3 class="team-name"><?php the_title(); ?></h3>
<p class="description text-center"><?php echo get_the_content(); ?></p>
<div class="social"><a href="#"><i class="fab fa-facebook"></i></a><a href="#"><i class="fab fa-twitter"></i></a><a href="#"><i class="fab fa-instagram"></i></a></div>
</div>
</div>
<?php endwhile; ?>
<?php endif; wp_reset_postdata(); ?>
</div>
</div>
</code></pre>
| [
{
"answer_id": 327865,
"author": "mrben522",
"author_id": 84703,
"author_profile": "https://wordpress.stackexchange.com/users/84703",
"pm_score": 1,
"selected": false,
"text": "<p>This seems like a CSS problem and not a Wordpress problem. you just need hover styles that replace the background image. something like this:</p>\n\n<pre><code>.team-boxed .people .rounded-circle::hover {\n background-image:url(\"whatever\");\n}\n</code></pre>\n\n<p>If you need to get the new image URL from Wordpress then you could either inline that CSS and just dump in a PHP variable (<code>background-image:url(\"' . $newImageUrl . '\");</code>), or use javascript and pass it in as a variable via <a href=\"https://developer.wordpress.org/reference/functions/wp_localize_script/\" rel=\"nofollow noreferrer\">wp_localize_script</a></p>\n"
},
{
"answer_id": 327866,
"author": "Paul Elrich",
"author_id": 160341,
"author_profile": "https://wordpress.stackexchange.com/users/160341",
"pm_score": 2,
"selected": false,
"text": "<p>You can add a custom field to you team page, call it \"second_picture\", or whatever you want, and add the code</p>\n\n<pre><code> <div class=\"box\">\n <div class=\"rounded-circle\" style=\"background-image:url('<?php the_post_thumbnail_url('full'); ?>')\" id=\"staff-pic\">\n <div class=\"second-picture\" style=\"background-image:url(<?php the_field('second_picture'); ?>)\"></div>\n </div>\n <h3 class=\"team-name\"><?php the_title(); ?></h3>\n <p class=\"description text-center\"><?php echo get_the_content(); ?></p>\n <div class=\"social\"><a href=\"#\"><i class=\"fab fa-facebook\"></i></a><a href=\"#\"><i class=\"fab fa-twitter\"></i></a><a href=\"#\"><i class=\"fab fa-instagram\"></i></a></div>\n </div>\n</code></pre>\n\n<p>Then set the hover state</p>\n\n<pre><code>.second-picture{\n width:100%;\n height:100%;\n background-size:cover;\n background-position:center;\n opacity:0;\n transition:.2s;\n}\n.second-picture:hover{\n opacity:1;\n}\n</code></pre>\n"
}
] | 2019/02/06 | [
"https://wordpress.stackexchange.com/questions/327839",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159508/"
] | I've almost finished my first custom theme for a website. I've created some custom post type to manage a portfolio and a staff member section. No problem with the code, but the client asked if is it possible to change the staff images when an user hover on it. Is there any way to achieve this in wordpress?
Here is a sample of my code
```
<div class="team-boxed">
<?php
$args = array(
'post_type' => 'team'
);
$team = new WP_Query($args);
?>
<div class="intro">
<h2 class="text-center text-uppercase" id="">Team</h2>
</div>
<div class="row people">
<?php if( $team->have_posts() ): while( $team->have_posts() ): $team->the_post(); ?>
<div class="col-md-6 col-lg-4 item">
<div class="box">
<div class="rounded-circle" style="background-image:url('<?php the_post_thumbnail_url('full'); ?>')" id="staff-pic"></div>
<h3 class="team-name"><?php the_title(); ?></h3>
<p class="description text-center"><?php echo get_the_content(); ?></p>
<div class="social"><a href="#"><i class="fab fa-facebook"></i></a><a href="#"><i class="fab fa-twitter"></i></a><a href="#"><i class="fab fa-instagram"></i></a></div>
</div>
</div>
<?php endwhile; ?>
<?php endif; wp_reset_postdata(); ?>
</div>
</div>
``` | You can add a custom field to you team page, call it "second\_picture", or whatever you want, and add the code
```
<div class="box">
<div class="rounded-circle" style="background-image:url('<?php the_post_thumbnail_url('full'); ?>')" id="staff-pic">
<div class="second-picture" style="background-image:url(<?php the_field('second_picture'); ?>)"></div>
</div>
<h3 class="team-name"><?php the_title(); ?></h3>
<p class="description text-center"><?php echo get_the_content(); ?></p>
<div class="social"><a href="#"><i class="fab fa-facebook"></i></a><a href="#"><i class="fab fa-twitter"></i></a><a href="#"><i class="fab fa-instagram"></i></a></div>
</div>
```
Then set the hover state
```
.second-picture{
width:100%;
height:100%;
background-size:cover;
background-position:center;
opacity:0;
transition:.2s;
}
.second-picture:hover{
opacity:1;
}
``` |
327,851 | <p>Could someone tell me where I could find detailed information about what has beend changed/improved in a new WordPress major/minor version? Maybe some kind of changelog or something?</p>
| [
{
"answer_id": 327865,
"author": "mrben522",
"author_id": 84703,
"author_profile": "https://wordpress.stackexchange.com/users/84703",
"pm_score": 1,
"selected": false,
"text": "<p>This seems like a CSS problem and not a Wordpress problem. you just need hover styles that replace the background image. something like this:</p>\n\n<pre><code>.team-boxed .people .rounded-circle::hover {\n background-image:url(\"whatever\");\n}\n</code></pre>\n\n<p>If you need to get the new image URL from Wordpress then you could either inline that CSS and just dump in a PHP variable (<code>background-image:url(\"' . $newImageUrl . '\");</code>), or use javascript and pass it in as a variable via <a href=\"https://developer.wordpress.org/reference/functions/wp_localize_script/\" rel=\"nofollow noreferrer\">wp_localize_script</a></p>\n"
},
{
"answer_id": 327866,
"author": "Paul Elrich",
"author_id": 160341,
"author_profile": "https://wordpress.stackexchange.com/users/160341",
"pm_score": 2,
"selected": false,
"text": "<p>You can add a custom field to you team page, call it \"second_picture\", or whatever you want, and add the code</p>\n\n<pre><code> <div class=\"box\">\n <div class=\"rounded-circle\" style=\"background-image:url('<?php the_post_thumbnail_url('full'); ?>')\" id=\"staff-pic\">\n <div class=\"second-picture\" style=\"background-image:url(<?php the_field('second_picture'); ?>)\"></div>\n </div>\n <h3 class=\"team-name\"><?php the_title(); ?></h3>\n <p class=\"description text-center\"><?php echo get_the_content(); ?></p>\n <div class=\"social\"><a href=\"#\"><i class=\"fab fa-facebook\"></i></a><a href=\"#\"><i class=\"fab fa-twitter\"></i></a><a href=\"#\"><i class=\"fab fa-instagram\"></i></a></div>\n </div>\n</code></pre>\n\n<p>Then set the hover state</p>\n\n<pre><code>.second-picture{\n width:100%;\n height:100%;\n background-size:cover;\n background-position:center;\n opacity:0;\n transition:.2s;\n}\n.second-picture:hover{\n opacity:1;\n}\n</code></pre>\n"
}
] | 2019/02/06 | [
"https://wordpress.stackexchange.com/questions/327851",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/149002/"
] | Could someone tell me where I could find detailed information about what has beend changed/improved in a new WordPress major/minor version? Maybe some kind of changelog or something? | You can add a custom field to you team page, call it "second\_picture", or whatever you want, and add the code
```
<div class="box">
<div class="rounded-circle" style="background-image:url('<?php the_post_thumbnail_url('full'); ?>')" id="staff-pic">
<div class="second-picture" style="background-image:url(<?php the_field('second_picture'); ?>)"></div>
</div>
<h3 class="team-name"><?php the_title(); ?></h3>
<p class="description text-center"><?php echo get_the_content(); ?></p>
<div class="social"><a href="#"><i class="fab fa-facebook"></i></a><a href="#"><i class="fab fa-twitter"></i></a><a href="#"><i class="fab fa-instagram"></i></a></div>
</div>
```
Then set the hover state
```
.second-picture{
width:100%;
height:100%;
background-size:cover;
background-position:center;
opacity:0;
transition:.2s;
}
.second-picture:hover{
opacity:1;
}
``` |
327,870 | <p>I'm attempting to create a single WP loop, using a custom query, to display a custom-post-type - using Bootstrap 4 markup.
The complicating part for me is, I'd like the number of posts for each row to alternate in the following way:</p>
<ul>
<li>Row 1 - One Post - Full Screen width</li>
<li>Row 2 - Four Posts - col-md-6</li>
<li>Row 3 - Six Posts - col-md-4</li>
</ul>
<p>At the moment I'm running three individual loops which is messing-up the pagination. i.e. When pagination is clicked the page content remains the same - however the url indicates that the user is on the second page.
Grateful for any help.</p>
<pre><code> <!-- Loop 1 -->
<?php
$paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1;
$args=array(
'post_type' => 'workshop',
'post_status' => 'publish',
'posts_per_page' => 1,
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
$i = 0;
while ($my_query->have_posts()) : $my_query->the_post();
// modified to work with 3 columns
// output an open <div>
if($i % 1 == 0) { ?>
<div class="row">
<?php
}
?>
<!-- ROW 1 - FULL SCREEN WIDTH MARKUP -->
</div><!--/.row-->
<?php $i++;
if($i != 0 && $i % 1 == 0) { ?>
</div> <!-- End Container -->
<div class="clearfix"></div>
<?php
} ?>
<?php
endwhile;
}
wp_reset_postdata();
?>
</code></pre>
<pre><code> <!-- Loop Two -->
<?php
$paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1;
$args=array(
'post_type' => 'workshop',
'post_status' => 'publish',
'posts_per_page' => 4,
'offset' => 1,
'paged' => $paged
);
$my_query = null;
$do_not_duplicate[] = $post->ID;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
$i = 0;
while ($my_query->have_posts()) : $my_query->the_post();
// modified to work with 3 columns
// output an open <div>
if($i % 2 == 0) { ?>
<div class="row no-gutters">
<?php
}
?>
<!-- ROW 2 - [FOUR POSTS] MARKUP HERE -->
<?php $i++;
if($i != 0 && $i % 2 == 0) { ?>
</div><!--/.row-->
<?php
} ?>
<?php
endwhile;
}
wp_reset_query();
?>
</code></pre>
<p>
<pre><code> $args=array(
'post_type' => 'workshop',
'post_status' => 'publish',
'posts_per_page' => 6,
'offset' => 5,
'paged' => $paged
);
$my_query = null;
$do_not_duplicate[] = $post->ID;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
$i = 0;
while ($my_query->have_posts()) : $my_query->the_post();
// modified to work with 3 columns
// output an open <div>
if($i % 3 == 0) { ?>
<div class="row no-gutters">
<?php
}
?>
<!-- ROW 3 - [Six Posts] Markup -->
<?php $i++;
if($i != 0 && $i % 3 == 0) { ?>
</div><!--/.row-->
<?php
} ?>
<?php
endwhile;
}
wp_reset_query();
?>
</code></pre>
<p>
</p>
| [
{
"answer_id": 327875,
"author": "mrben522",
"author_id": 84703,
"author_profile": "https://wordpress.stackexchange.com/users/84703",
"pm_score": 2,
"selected": true,
"text": "<p>The easy-but-a-bit-hacky way to get there would be to initialize a counter variable before your loop and then use that to tell what post you're on. something like so:</p>\n\n<pre><code> $paged = (get_query_var('paged')) ? absint(get_query_var('paged')) : 1;\n$args = array(\n 'post_type' => 'workshop',\n 'post_status' => 'publish',\n 'posts_per_page' => 11,\n 'paged' => $paged,\n);\n$customQuery = new WP_Query($args);\n$counter = 1;\nif ($customQuery->have_posts()) :\n while ($customQuery->have_posts()) : $customQuery->the_post();\n if ($counter === 1) { ?>\n <div class=\"row\">\n <!-- ROW 1 - FULL SCREEN WIDTH MARKUP -->\n\n </div><!--/.row-->\n <?php\n } elseif ($counter <= 5) {\n if ($counter === 2) { ?>\n <div class=\"row no-gutters\">\n <?php }\n ?>\n <!-- ROW 2 - [FOUR POSTS] MARKUP HERE -->\n <?php if ($counter === 5) { ?>\n </div><!--/.row-->\n <?php }\n } else {\n if ($counter === 6) { ?>\n <div class=\"row no-gutters\">\n <?php } ?>\n <!-- ROW 3 - [Six Posts] Markup -->\n <?php if ($counter === 11) { ?>\n </div><!--/.row-->\n <?php } \n };\n $counter++;\n endwhile;\nendif;\n</code></pre>\n"
},
{
"answer_id": 329274,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 0,
"selected": false,
"text": "<p>There is no need to introduce a counter, you can use <code>$wp_query->current_post</code>.</p>\n\n<pre><code><?php\n\n$paged = (get_query_var('paged')) ? absint(get_query_var('paged')) : 1;\n\n$args = array(\n 'post_type' => 'workshop',\n 'post_status' => 'publish',\n 'posts_per_page' => 11,\n 'paged' => $paged,\n);\n\n$customQuery = new WP_Query($args);\n\n// Row 1 - One Post - Full Screen width\nwhile ($customQuery->have_posts() && $customQuery->current_post < 1 ) : $customQuery->the_post(); ?>\n\n <div class=\"row\"> \n <!-- ROW 1 - FULL SCREEN WIDTH MARKUP -->\n </div><!--/.row-->\n\n<?php endwhile;\n\n//Row 2 - Four Posts - col-md-6\nwhile ($customQuery->have_posts() && $customQuery->current_post < 5) : $customQuery->the_post(); ?>\n\n <div class=\"row no-gutters\">\n <!-- ROW 2 - [FOUR POSTS] MARKUP HERE -->\n </div><!--/.row-->\n\n<?php endwhile;\n\n//Row 3 - Six Posts - col-md-4\nwhile ($customQuery->have_posts()) : $customQuery->the_post(); ?>\n\n <div class=\"row no-gutters\">\n <!-- ROW 3 - [Six Posts] Markup -->\n </div><!--/.row-->\n\n<?php endwhile; ?>\n</code></pre>\n"
}
] | 2019/02/06 | [
"https://wordpress.stackexchange.com/questions/327870",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/135424/"
] | I'm attempting to create a single WP loop, using a custom query, to display a custom-post-type - using Bootstrap 4 markup.
The complicating part for me is, I'd like the number of posts for each row to alternate in the following way:
* Row 1 - One Post - Full Screen width
* Row 2 - Four Posts - col-md-6
* Row 3 - Six Posts - col-md-4
At the moment I'm running three individual loops which is messing-up the pagination. i.e. When pagination is clicked the page content remains the same - however the url indicates that the user is on the second page.
Grateful for any help.
```
<!-- Loop 1 -->
<?php
$paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1;
$args=array(
'post_type' => 'workshop',
'post_status' => 'publish',
'posts_per_page' => 1,
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
$i = 0;
while ($my_query->have_posts()) : $my_query->the_post();
// modified to work with 3 columns
// output an open <div>
if($i % 1 == 0) { ?>
<div class="row">
<?php
}
?>
<!-- ROW 1 - FULL SCREEN WIDTH MARKUP -->
</div><!--/.row-->
<?php $i++;
if($i != 0 && $i % 1 == 0) { ?>
</div> <!-- End Container -->
<div class="clearfix"></div>
<?php
} ?>
<?php
endwhile;
}
wp_reset_postdata();
?>
```
```
<!-- Loop Two -->
<?php
$paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1;
$args=array(
'post_type' => 'workshop',
'post_status' => 'publish',
'posts_per_page' => 4,
'offset' => 1,
'paged' => $paged
);
$my_query = null;
$do_not_duplicate[] = $post->ID;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
$i = 0;
while ($my_query->have_posts()) : $my_query->the_post();
// modified to work with 3 columns
// output an open <div>
if($i % 2 == 0) { ?>
<div class="row no-gutters">
<?php
}
?>
<!-- ROW 2 - [FOUR POSTS] MARKUP HERE -->
<?php $i++;
if($i != 0 && $i % 2 == 0) { ?>
</div><!--/.row-->
<?php
} ?>
<?php
endwhile;
}
wp_reset_query();
?>
```
```
$args=array(
'post_type' => 'workshop',
'post_status' => 'publish',
'posts_per_page' => 6,
'offset' => 5,
'paged' => $paged
);
$my_query = null;
$do_not_duplicate[] = $post->ID;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
$i = 0;
while ($my_query->have_posts()) : $my_query->the_post();
// modified to work with 3 columns
// output an open <div>
if($i % 3 == 0) { ?>
<div class="row no-gutters">
<?php
}
?>
<!-- ROW 3 - [Six Posts] Markup -->
<?php $i++;
if($i != 0 && $i % 3 == 0) { ?>
</div><!--/.row-->
<?php
} ?>
<?php
endwhile;
}
wp_reset_query();
?>
``` | The easy-but-a-bit-hacky way to get there would be to initialize a counter variable before your loop and then use that to tell what post you're on. something like so:
```
$paged = (get_query_var('paged')) ? absint(get_query_var('paged')) : 1;
$args = array(
'post_type' => 'workshop',
'post_status' => 'publish',
'posts_per_page' => 11,
'paged' => $paged,
);
$customQuery = new WP_Query($args);
$counter = 1;
if ($customQuery->have_posts()) :
while ($customQuery->have_posts()) : $customQuery->the_post();
if ($counter === 1) { ?>
<div class="row">
<!-- ROW 1 - FULL SCREEN WIDTH MARKUP -->
</div><!--/.row-->
<?php
} elseif ($counter <= 5) {
if ($counter === 2) { ?>
<div class="row no-gutters">
<?php }
?>
<!-- ROW 2 - [FOUR POSTS] MARKUP HERE -->
<?php if ($counter === 5) { ?>
</div><!--/.row-->
<?php }
} else {
if ($counter === 6) { ?>
<div class="row no-gutters">
<?php } ?>
<!-- ROW 3 - [Six Posts] Markup -->
<?php if ($counter === 11) { ?>
</div><!--/.row-->
<?php }
};
$counter++;
endwhile;
endif;
``` |
327,911 | <p>Can anyone provide a sample MySQL or WP_Query code snippet that returns the most recent post for each author on a single WordPress site? For example, if the site has 10 authors but 500 posts, then the query would return 10 records where each record is the most recent post by each author. Thanks!</p>
| [
{
"answer_id": 327912,
"author": "Lucien Dubois",
"author_id": 51306,
"author_profile": "https://wordpress.stackexchange.com/users/51306",
"pm_score": -1,
"selected": false,
"text": "<p>You could first get the users and then run a WP_Query for each:.\n(That would be the fast, easy, but non-optimized way to do it)</p>\n\n<pre><code>$users = get_users( );\nforeach ( $users as $user ) {\n\n $args = array(\n 'post_type' => array( 'post' ),\n 'author' => $user->ID\n 'posts_per_page' => '1',\n 'order' => 'DESC',\n 'orderby' => 'date',\n );\n $query = new WP_Query( $args );\n if ( $query->have_posts() ) {\n while ( $query->have_posts() ) {\n $query->the_post();\n // do something\n }\n }\n wp_reset_postdata();\n\n}\n</code></pre>\n"
},
{
"answer_id": 327917,
"author": "phatskat",
"author_id": 20143,
"author_profile": "https://wordpress.stackexchange.com/users/20143",
"pm_score": 1,
"selected": false,
"text": "<p>You can write a SQL query to achieve this:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code><?php\n\n$sql = <<<SQL\nSELECT\n p.ID,\n p.post_title,\n p.post_author\nFROM {$GLOBALS['wpdb']->posts} p INNER JOIN (\n SELECT ID, post_title\n FROM {$GLOBALS['wpdb']->posts} ORDER BY post_date DESC\n ) s ON p.ID=s.ID\nWHERE\n p.post_type = 'post'\nAND\n p.post_status = 'publish'\nGROUP BY\n p.post_author\nSQL;\n\n$rows = $GLOBALS['wpdb']->get_results( $sql );\n</code></pre>\n"
}
] | 2019/02/07 | [
"https://wordpress.stackexchange.com/questions/327911",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/149633/"
] | Can anyone provide a sample MySQL or WP\_Query code snippet that returns the most recent post for each author on a single WordPress site? For example, if the site has 10 authors but 500 posts, then the query would return 10 records where each record is the most recent post by each author. Thanks! | You can write a SQL query to achieve this:
```php
<?php
$sql = <<<SQL
SELECT
p.ID,
p.post_title,
p.post_author
FROM {$GLOBALS['wpdb']->posts} p INNER JOIN (
SELECT ID, post_title
FROM {$GLOBALS['wpdb']->posts} ORDER BY post_date DESC
) s ON p.ID=s.ID
WHERE
p.post_type = 'post'
AND
p.post_status = 'publish'
GROUP BY
p.post_author
SQL;
$rows = $GLOBALS['wpdb']->get_results( $sql );
``` |
327,945 | <p>I'd like to keep the pagination links for /page/2/, /page/373/, etc but instead of changing the URL on the browser i want everything to load on the archive main page.</p>
<p>Ideally all those paginated URLs should redirect to the first page of the archive.</p>
<p>I don't want a "load more" button i want to keep the logic of pages but load them via ajax keeping url unchanged.</p>
<p>How can i do this? Any help is appreciated.</p>
| [
{
"answer_id": 328271,
"author": "mtthias",
"author_id": 160740,
"author_profile": "https://wordpress.stackexchange.com/users/160740",
"pm_score": 2,
"selected": false,
"text": "<p>Very high Level:</p>\n\n<ul>\n<li>Via Javascript register an eventhandler for clicking on pagination links</li>\n<li>Utilize <a href=\"https://www.w3schools.com/jsref/event_preventdefault.asp\" rel=\"nofollow noreferrer\">preventDefault</a> so users with Javascript disabled still get the old behavoiur</li>\n<li>In the eventhandler make an ajax request that sends the kind of archive(ie.: for author xy) and the number of the page that should be shown (You can get both values from the link url) to your Wordpress ajax url</li>\n<li>In the PHP function triggerd by your request, make a new <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\">query</a> for posts of this archives(ie.: post from author xy)</li>\n<li>Additionally use <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Pagination_Parameters\" rel=\"nofollow noreferrer\">Pagination Parameters</a> to select the right page</li>\n<li>Once you have your query data, render your archives page just like in your archive.php, you can use template parts and theme functions</li>\n<li><p>Kill your backend process with die()</p></li>\n<li><p>Back on the frontend, take the markup the ajax request returned and replace your old markup</p></li>\n</ul>\n\n<p>This approach has the advantage, that your markup gets rendered the same way as your normal archive page.</p>\n\n<p>You could also try to accomplish this by making a call to the Wordpress <a href=\"https://developer.wordpress.org/rest-api/\" rel=\"nofollow noreferrer\">REST API</a>, but you would have to take care of templating in Javascript.</p>\n\n<p>If you need more details on a certain step, just ask.</p>\n"
},
{
"answer_id": 328491,
"author": "M Haseeb",
"author_id": 46058,
"author_profile": "https://wordpress.stackexchange.com/users/46058",
"pm_score": 3,
"selected": true,
"text": "<p>you might use the <a href=\"http://api.jquery.com/load/\" rel=\"nofollow noreferrer\"><code>$.load</code></a> and <a href=\"https://api.jquery.com/event.preventdefault/\" rel=\"nofollow noreferrer\"><code>preventDefault()</code></a> from jQuery. </p>\n\n<p>Assugming that you have <code>.page-link</code> link class on each url in pagination and you have all the posts in the <code>#content</code> div following code can help you to load the posts in that div on that particular page. </p>\n\n<pre><code>$(\"body\").on(\"click\", \"a.page-link\", function(e) {\n e.preventDefault();\n $(\"#content\").load($(this).attr(\"href\") + \" #content\");\n});\n</code></pre>\n\n<p>This will replace the current posts in that page with the new posts from that particular page. A look on your div structure might help me to write the complete code for you which can work on your site.</p>\n"
}
] | 2019/02/07 | [
"https://wordpress.stackexchange.com/questions/327945",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77283/"
] | I'd like to keep the pagination links for /page/2/, /page/373/, etc but instead of changing the URL on the browser i want everything to load on the archive main page.
Ideally all those paginated URLs should redirect to the first page of the archive.
I don't want a "load more" button i want to keep the logic of pages but load them via ajax keeping url unchanged.
How can i do this? Any help is appreciated. | you might use the [`$.load`](http://api.jquery.com/load/) and [`preventDefault()`](https://api.jquery.com/event.preventdefault/) from jQuery.
Assugming that you have `.page-link` link class on each url in pagination and you have all the posts in the `#content` div following code can help you to load the posts in that div on that particular page.
```
$("body").on("click", "a.page-link", function(e) {
e.preventDefault();
$("#content").load($(this).attr("href") + " #content");
});
```
This will replace the current posts in that page with the new posts from that particular page. A look on your div structure might help me to write the complete code for you which can work on your site. |
327,966 | <p>What I am trying to do is to use specific Reusable Blocks, that are editable by certain admins in the back end, within block templates for custom post types. So if you register a CTP or edit the capabilities of standard post types, you can use them like:</p>
<pre><code> function create_add_post_types() {
register_post_type( 'product',
array(
'public' => true,
'capability_type' => 'page',
'show_in_rest' => true,
'template' => array(
array( 'core/heading', array(
'placeholder' => 'Füge eine Überschrift hinzu',
'content' => 'Projektname - Stadt, Land',
'level' => 1,
) ),
)
);
}
add_action( 'init', 'create_add_post_types' );
</code></pre>
<p>..except that insteadt of a core block like the heading here a reusable block is called.</p>
| [
{
"answer_id": 327967,
"author": "Playnary",
"author_id": 148976,
"author_profile": "https://wordpress.stackexchange.com/users/148976",
"pm_score": 3,
"selected": true,
"text": "<p>I actually found a solution myself by following the way a reusable block is registered in <a href=\"https://wordpress.stackexchange.com/questions/324908/removing-default-gutenberg-blocks-but-keeping-reusable-block-functionality\">this stackexchange thread</a>:</p>\n\n<p>Reusable blocks are all stored in/as <strong>core/block</strong> and this block has the attribute <strong>ref</strong> which carries the post id of that block.</p>\n\n<p>So, you can use</p>\n\n<pre><code>array( 'core/block', array(\n 'ref' => [your block ID],\n) ),\n</code></pre>\n\n<p>and the ID of every registered block is visible via the URL of that block at <strong>[your-wordpress]/wp-admin/edit.php?post_type=wp_block</strong> </p>\n"
},
{
"answer_id": 376385,
"author": "gtamborero",
"author_id": 52236,
"author_profile": "https://wordpress.stackexchange.com/users/52236",
"pm_score": 0,
"selected": false,
"text": "<p>You can call a reusable block as you call to any post type:</p>\n<pre><code>$args = array(\n 'post_type' => 'wp_block',\n...\n</code></pre>\n<p>OR</p>\n<pre><code>get_page_by_title( 'Your Title', OBJECT, 'wp_block' );\n</code></pre>\n"
}
] | 2019/02/07 | [
"https://wordpress.stackexchange.com/questions/327966",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/148976/"
] | What I am trying to do is to use specific Reusable Blocks, that are editable by certain admins in the back end, within block templates for custom post types. So if you register a CTP or edit the capabilities of standard post types, you can use them like:
```
function create_add_post_types() {
register_post_type( 'product',
array(
'public' => true,
'capability_type' => 'page',
'show_in_rest' => true,
'template' => array(
array( 'core/heading', array(
'placeholder' => 'Füge eine Überschrift hinzu',
'content' => 'Projektname - Stadt, Land',
'level' => 1,
) ),
)
);
}
add_action( 'init', 'create_add_post_types' );
```
..except that insteadt of a core block like the heading here a reusable block is called. | I actually found a solution myself by following the way a reusable block is registered in [this stackexchange thread](https://wordpress.stackexchange.com/questions/324908/removing-default-gutenberg-blocks-but-keeping-reusable-block-functionality):
Reusable blocks are all stored in/as **core/block** and this block has the attribute **ref** which carries the post id of that block.
So, you can use
```
array( 'core/block', array(
'ref' => [your block ID],
) ),
```
and the ID of every registered block is visible via the URL of that block at **[your-wordpress]/wp-admin/edit.php?post\_type=wp\_block** |
328,005 | <p>/wp-json/wc/v3/products/categories</p>
<p>My site has 10 main categories. But when I run the query, only 3 main categories and their subcategories are listed. Other categories don’t come up with what could be the problem?</p>
| [
{
"answer_id": 327967,
"author": "Playnary",
"author_id": 148976,
"author_profile": "https://wordpress.stackexchange.com/users/148976",
"pm_score": 3,
"selected": true,
"text": "<p>I actually found a solution myself by following the way a reusable block is registered in <a href=\"https://wordpress.stackexchange.com/questions/324908/removing-default-gutenberg-blocks-but-keeping-reusable-block-functionality\">this stackexchange thread</a>:</p>\n\n<p>Reusable blocks are all stored in/as <strong>core/block</strong> and this block has the attribute <strong>ref</strong> which carries the post id of that block.</p>\n\n<p>So, you can use</p>\n\n<pre><code>array( 'core/block', array(\n 'ref' => [your block ID],\n) ),\n</code></pre>\n\n<p>and the ID of every registered block is visible via the URL of that block at <strong>[your-wordpress]/wp-admin/edit.php?post_type=wp_block</strong> </p>\n"
},
{
"answer_id": 376385,
"author": "gtamborero",
"author_id": 52236,
"author_profile": "https://wordpress.stackexchange.com/users/52236",
"pm_score": 0,
"selected": false,
"text": "<p>You can call a reusable block as you call to any post type:</p>\n<pre><code>$args = array(\n 'post_type' => 'wp_block',\n...\n</code></pre>\n<p>OR</p>\n<pre><code>get_page_by_title( 'Your Title', OBJECT, 'wp_block' );\n</code></pre>\n"
}
] | 2019/02/07 | [
"https://wordpress.stackexchange.com/questions/328005",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/160786/"
] | /wp-json/wc/v3/products/categories
My site has 10 main categories. But when I run the query, only 3 main categories and their subcategories are listed. Other categories don’t come up with what could be the problem? | I actually found a solution myself by following the way a reusable block is registered in [this stackexchange thread](https://wordpress.stackexchange.com/questions/324908/removing-default-gutenberg-blocks-but-keeping-reusable-block-functionality):
Reusable blocks are all stored in/as **core/block** and this block has the attribute **ref** which carries the post id of that block.
So, you can use
```
array( 'core/block', array(
'ref' => [your block ID],
) ),
```
and the ID of every registered block is visible via the URL of that block at **[your-wordpress]/wp-admin/edit.php?post\_type=wp\_block** |
328,006 | <p>I have created a WordPress multisite on the primary domain alaksns.com which is secure with ssl certificate. Then I added a new site as blog.alaksns.com which only works when accessed with http whenver I try to access it with https it gives a blankpage. I also tried by changing the url of the site from the network settings by adding https but it gives 404 error</p>
| [
{
"answer_id": 327967,
"author": "Playnary",
"author_id": 148976,
"author_profile": "https://wordpress.stackexchange.com/users/148976",
"pm_score": 3,
"selected": true,
"text": "<p>I actually found a solution myself by following the way a reusable block is registered in <a href=\"https://wordpress.stackexchange.com/questions/324908/removing-default-gutenberg-blocks-but-keeping-reusable-block-functionality\">this stackexchange thread</a>:</p>\n\n<p>Reusable blocks are all stored in/as <strong>core/block</strong> and this block has the attribute <strong>ref</strong> which carries the post id of that block.</p>\n\n<p>So, you can use</p>\n\n<pre><code>array( 'core/block', array(\n 'ref' => [your block ID],\n) ),\n</code></pre>\n\n<p>and the ID of every registered block is visible via the URL of that block at <strong>[your-wordpress]/wp-admin/edit.php?post_type=wp_block</strong> </p>\n"
},
{
"answer_id": 376385,
"author": "gtamborero",
"author_id": 52236,
"author_profile": "https://wordpress.stackexchange.com/users/52236",
"pm_score": 0,
"selected": false,
"text": "<p>You can call a reusable block as you call to any post type:</p>\n<pre><code>$args = array(\n 'post_type' => 'wp_block',\n...\n</code></pre>\n<p>OR</p>\n<pre><code>get_page_by_title( 'Your Title', OBJECT, 'wp_block' );\n</code></pre>\n"
}
] | 2019/02/07 | [
"https://wordpress.stackexchange.com/questions/328006",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/160787/"
] | I have created a WordPress multisite on the primary domain alaksns.com which is secure with ssl certificate. Then I added a new site as blog.alaksns.com which only works when accessed with http whenver I try to access it with https it gives a blankpage. I also tried by changing the url of the site from the network settings by adding https but it gives 404 error | I actually found a solution myself by following the way a reusable block is registered in [this stackexchange thread](https://wordpress.stackexchange.com/questions/324908/removing-default-gutenberg-blocks-but-keeping-reusable-block-functionality):
Reusable blocks are all stored in/as **core/block** and this block has the attribute **ref** which carries the post id of that block.
So, you can use
```
array( 'core/block', array(
'ref' => [your block ID],
) ),
```
and the ID of every registered block is visible via the URL of that block at **[your-wordpress]/wp-admin/edit.php?post\_type=wp\_block** |
328,018 | <p>I'm converting my posts over to use the new Block Editor. In the past I added an icon to the end of every post to act as a signature and marker saying the article is over (like print magazines do).</p>
<p>I did it like this:</p>
<pre><code>// Add Signature Image at End of Posts
add_filter('the_content','td_add_signature', 1);
function td_add_signature($text) {
global $post;
if(($post->post_type == 'post'))
$text .= '<span class="icon"></span>';
return $text;
}
</code></pre>
<p>That would insert the 'span class=icon' right after the final period, <strong>before</strong> the closing paragraph tag.</p>
<p>Now, with the new Block Editor, it adds it <strong>after</strong> the final closing paragraph tag. </p>
<p>So my question is, does anyone know a way to locate the final paragraph of the_content and then inject this HTML inside the 'block?' I'm assuming I might have to locate the last paragraph somehow, explode it or just string_replace the last closing p tag with the "HTML + p tag." </p>
<p>I'm simply not that good at PHP and am not sure how to "locate" the last paragraph in the_content. </p>
<p>I realize this can be done with jQuery easily but I'd much rather do it with a functions.php function and have it correct in the markup server-side. I could also create a custom "Last Paragraph" block that adds it for me, which is kind of goofy.</p>
<p>Thanks for any help or insight. It's my first question and post!</p>
| [
{
"answer_id": 328027,
"author": "tmdesigned",
"author_id": 28273,
"author_profile": "https://wordpress.stackexchange.com/users/28273",
"pm_score": 1,
"selected": true,
"text": "<p>So from a WordPress conceptual point of view, I like the idea of it being a block better. Without it being a block you have some of a post's content in the database, and some being injected here. It sounds fine for this case but would be prone to cause you headaches later down if some of your requirements changed.</p>\n\n<p>That being said, I think you could do this just by looking for the last html tag in the_content and injecting your icon's HTML in front of it. So it's a little more complicated than just appending it like you were.</p>\n\n<p>To show the concept:</p>\n\n<pre><code>$text = \"<div><p><div>text</div></p><p>text 2</p></div>\";\n\n//Find the position in the string of the last closing HTML tag, i.e. </ \n$last_tag = strrpos( $text, \"</\" );\n\n//Insert your HTML at that position, with an extra argument of 0 indicating you don't want to replace any of the original, just insert\necho substr_replace( $text, '<span class=\"icon\"></span>', $last_tag, 0 );\n\n//Results in <div><p><div>text</div></p><p>text 2</p><span class=\"icon\"></span></div>\n</code></pre>\n\n<p>In your case the $text variable would instead be passed into the function:</p>\n\n<pre><code>// Add Signature Image at End of Posts\nadd_filter('the_content','td_add_signature', 1);\nfunction td_add_signature($text) {\n global $post;\n if(($post->post_type == 'post')) {\n $last_tag = strrpos( $text, \"</\" );\n $text = substr_replace( $text, '<span class=\"icon\"></span>', $last_tag, 0 );\n }\n return $text;\n}\n</code></pre>\n"
},
{
"answer_id": 328170,
"author": "Loren Rosen",
"author_id": 158993,
"author_profile": "https://wordpress.stackexchange.com/users/158993",
"pm_score": 1,
"selected": false,
"text": "<p>Use a little CSS trickery to workaround the image location naturally coming after the last paragraph, instead of before its close. Make the last paragraph inline, and insert the image after it. Something like (in <code>style.css</code>)</p>\n\n<pre><code>.content p:last-of-type {\n display: inline;\n }\n\n.content p:last-of-type:after {\n content: url(site/path/to/image);\n }\n</code></pre>\n"
}
] | 2019/02/07 | [
"https://wordpress.stackexchange.com/questions/328018",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/160792/"
] | I'm converting my posts over to use the new Block Editor. In the past I added an icon to the end of every post to act as a signature and marker saying the article is over (like print magazines do).
I did it like this:
```
// Add Signature Image at End of Posts
add_filter('the_content','td_add_signature', 1);
function td_add_signature($text) {
global $post;
if(($post->post_type == 'post'))
$text .= '<span class="icon"></span>';
return $text;
}
```
That would insert the 'span class=icon' right after the final period, **before** the closing paragraph tag.
Now, with the new Block Editor, it adds it **after** the final closing paragraph tag.
So my question is, does anyone know a way to locate the final paragraph of the\_content and then inject this HTML inside the 'block?' I'm assuming I might have to locate the last paragraph somehow, explode it or just string\_replace the last closing p tag with the "HTML + p tag."
I'm simply not that good at PHP and am not sure how to "locate" the last paragraph in the\_content.
I realize this can be done with jQuery easily but I'd much rather do it with a functions.php function and have it correct in the markup server-side. I could also create a custom "Last Paragraph" block that adds it for me, which is kind of goofy.
Thanks for any help or insight. It's my first question and post! | So from a WordPress conceptual point of view, I like the idea of it being a block better. Without it being a block you have some of a post's content in the database, and some being injected here. It sounds fine for this case but would be prone to cause you headaches later down if some of your requirements changed.
That being said, I think you could do this just by looking for the last html tag in the\_content and injecting your icon's HTML in front of it. So it's a little more complicated than just appending it like you were.
To show the concept:
```
$text = "<div><p><div>text</div></p><p>text 2</p></div>";
//Find the position in the string of the last closing HTML tag, i.e. </
$last_tag = strrpos( $text, "</" );
//Insert your HTML at that position, with an extra argument of 0 indicating you don't want to replace any of the original, just insert
echo substr_replace( $text, '<span class="icon"></span>', $last_tag, 0 );
//Results in <div><p><div>text</div></p><p>text 2</p><span class="icon"></span></div>
```
In your case the $text variable would instead be passed into the function:
```
// Add Signature Image at End of Posts
add_filter('the_content','td_add_signature', 1);
function td_add_signature($text) {
global $post;
if(($post->post_type == 'post')) {
$last_tag = strrpos( $text, "</" );
$text = substr_replace( $text, '<span class="icon"></span>', $last_tag, 0 );
}
return $text;
}
``` |
328,028 | <p>I would like to show my most viewed categories (kind like the "<a href="https://wordpress.org/plugins/wp-postviews/" rel="nofollow noreferrer">WP-PostViews</a>" plugin).</p>
<p>I already did some research but I didn't find nothing about that. This made me think that it can't be done by some reason and I would like to know more about it...</p>
| [
{
"answer_id": 328027,
"author": "tmdesigned",
"author_id": 28273,
"author_profile": "https://wordpress.stackexchange.com/users/28273",
"pm_score": 1,
"selected": true,
"text": "<p>So from a WordPress conceptual point of view, I like the idea of it being a block better. Without it being a block you have some of a post's content in the database, and some being injected here. It sounds fine for this case but would be prone to cause you headaches later down if some of your requirements changed.</p>\n\n<p>That being said, I think you could do this just by looking for the last html tag in the_content and injecting your icon's HTML in front of it. So it's a little more complicated than just appending it like you were.</p>\n\n<p>To show the concept:</p>\n\n<pre><code>$text = \"<div><p><div>text</div></p><p>text 2</p></div>\";\n\n//Find the position in the string of the last closing HTML tag, i.e. </ \n$last_tag = strrpos( $text, \"</\" );\n\n//Insert your HTML at that position, with an extra argument of 0 indicating you don't want to replace any of the original, just insert\necho substr_replace( $text, '<span class=\"icon\"></span>', $last_tag, 0 );\n\n//Results in <div><p><div>text</div></p><p>text 2</p><span class=\"icon\"></span></div>\n</code></pre>\n\n<p>In your case the $text variable would instead be passed into the function:</p>\n\n<pre><code>// Add Signature Image at End of Posts\nadd_filter('the_content','td_add_signature', 1);\nfunction td_add_signature($text) {\n global $post;\n if(($post->post_type == 'post')) {\n $last_tag = strrpos( $text, \"</\" );\n $text = substr_replace( $text, '<span class=\"icon\"></span>', $last_tag, 0 );\n }\n return $text;\n}\n</code></pre>\n"
},
{
"answer_id": 328170,
"author": "Loren Rosen",
"author_id": 158993,
"author_profile": "https://wordpress.stackexchange.com/users/158993",
"pm_score": 1,
"selected": false,
"text": "<p>Use a little CSS trickery to workaround the image location naturally coming after the last paragraph, instead of before its close. Make the last paragraph inline, and insert the image after it. Something like (in <code>style.css</code>)</p>\n\n<pre><code>.content p:last-of-type {\n display: inline;\n }\n\n.content p:last-of-type:after {\n content: url(site/path/to/image);\n }\n</code></pre>\n"
}
] | 2019/02/07 | [
"https://wordpress.stackexchange.com/questions/328028",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/18693/"
] | I would like to show my most viewed categories (kind like the "[WP-PostViews](https://wordpress.org/plugins/wp-postviews/)" plugin).
I already did some research but I didn't find nothing about that. This made me think that it can't be done by some reason and I would like to know more about it... | So from a WordPress conceptual point of view, I like the idea of it being a block better. Without it being a block you have some of a post's content in the database, and some being injected here. It sounds fine for this case but would be prone to cause you headaches later down if some of your requirements changed.
That being said, I think you could do this just by looking for the last html tag in the\_content and injecting your icon's HTML in front of it. So it's a little more complicated than just appending it like you were.
To show the concept:
```
$text = "<div><p><div>text</div></p><p>text 2</p></div>";
//Find the position in the string of the last closing HTML tag, i.e. </
$last_tag = strrpos( $text, "</" );
//Insert your HTML at that position, with an extra argument of 0 indicating you don't want to replace any of the original, just insert
echo substr_replace( $text, '<span class="icon"></span>', $last_tag, 0 );
//Results in <div><p><div>text</div></p><p>text 2</p><span class="icon"></span></div>
```
In your case the $text variable would instead be passed into the function:
```
// Add Signature Image at End of Posts
add_filter('the_content','td_add_signature', 1);
function td_add_signature($text) {
global $post;
if(($post->post_type == 'post')) {
$last_tag = strrpos( $text, "</" );
$text = substr_replace( $text, '<span class="icon"></span>', $last_tag, 0 );
}
return $text;
}
``` |
328,030 | <p>I have several 404 errors with a URL such as: myWebsite/tag/foo/page/4/. Page no longer exists because a few posts were deleted tagged as "foo." Which is better: 301 redirect that to myWebsite/tag/foo/page/1/? Or just 410 delete them? </p>
<p>I'm thinking if I do a 301 redirect -- then add more posts tagged as "foo," a 4th page will exist but those will be redirected back to page 1. Or if I 410 delete page 4 and it later exists in the future, it won't be found. I'm confused. </p>
| [
{
"answer_id": 328027,
"author": "tmdesigned",
"author_id": 28273,
"author_profile": "https://wordpress.stackexchange.com/users/28273",
"pm_score": 1,
"selected": true,
"text": "<p>So from a WordPress conceptual point of view, I like the idea of it being a block better. Without it being a block you have some of a post's content in the database, and some being injected here. It sounds fine for this case but would be prone to cause you headaches later down if some of your requirements changed.</p>\n\n<p>That being said, I think you could do this just by looking for the last html tag in the_content and injecting your icon's HTML in front of it. So it's a little more complicated than just appending it like you were.</p>\n\n<p>To show the concept:</p>\n\n<pre><code>$text = \"<div><p><div>text</div></p><p>text 2</p></div>\";\n\n//Find the position in the string of the last closing HTML tag, i.e. </ \n$last_tag = strrpos( $text, \"</\" );\n\n//Insert your HTML at that position, with an extra argument of 0 indicating you don't want to replace any of the original, just insert\necho substr_replace( $text, '<span class=\"icon\"></span>', $last_tag, 0 );\n\n//Results in <div><p><div>text</div></p><p>text 2</p><span class=\"icon\"></span></div>\n</code></pre>\n\n<p>In your case the $text variable would instead be passed into the function:</p>\n\n<pre><code>// Add Signature Image at End of Posts\nadd_filter('the_content','td_add_signature', 1);\nfunction td_add_signature($text) {\n global $post;\n if(($post->post_type == 'post')) {\n $last_tag = strrpos( $text, \"</\" );\n $text = substr_replace( $text, '<span class=\"icon\"></span>', $last_tag, 0 );\n }\n return $text;\n}\n</code></pre>\n"
},
{
"answer_id": 328170,
"author": "Loren Rosen",
"author_id": 158993,
"author_profile": "https://wordpress.stackexchange.com/users/158993",
"pm_score": 1,
"selected": false,
"text": "<p>Use a little CSS trickery to workaround the image location naturally coming after the last paragraph, instead of before its close. Make the last paragraph inline, and insert the image after it. Something like (in <code>style.css</code>)</p>\n\n<pre><code>.content p:last-of-type {\n display: inline;\n }\n\n.content p:last-of-type:after {\n content: url(site/path/to/image);\n }\n</code></pre>\n"
}
] | 2019/02/08 | [
"https://wordpress.stackexchange.com/questions/328030",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105596/"
] | I have several 404 errors with a URL such as: myWebsite/tag/foo/page/4/. Page no longer exists because a few posts were deleted tagged as "foo." Which is better: 301 redirect that to myWebsite/tag/foo/page/1/? Or just 410 delete them?
I'm thinking if I do a 301 redirect -- then add more posts tagged as "foo," a 4th page will exist but those will be redirected back to page 1. Or if I 410 delete page 4 and it later exists in the future, it won't be found. I'm confused. | So from a WordPress conceptual point of view, I like the idea of it being a block better. Without it being a block you have some of a post's content in the database, and some being injected here. It sounds fine for this case but would be prone to cause you headaches later down if some of your requirements changed.
That being said, I think you could do this just by looking for the last html tag in the\_content and injecting your icon's HTML in front of it. So it's a little more complicated than just appending it like you were.
To show the concept:
```
$text = "<div><p><div>text</div></p><p>text 2</p></div>";
//Find the position in the string of the last closing HTML tag, i.e. </
$last_tag = strrpos( $text, "</" );
//Insert your HTML at that position, with an extra argument of 0 indicating you don't want to replace any of the original, just insert
echo substr_replace( $text, '<span class="icon"></span>', $last_tag, 0 );
//Results in <div><p><div>text</div></p><p>text 2</p><span class="icon"></span></div>
```
In your case the $text variable would instead be passed into the function:
```
// Add Signature Image at End of Posts
add_filter('the_content','td_add_signature', 1);
function td_add_signature($text) {
global $post;
if(($post->post_type == 'post')) {
$last_tag = strrpos( $text, "</" );
$text = substr_replace( $text, '<span class="icon"></span>', $last_tag, 0 );
}
return $text;
}
``` |
328,034 | <p>i have two websites i use Wordpress comments on one website and jetpack comments on another. Both websites shows website column, how do i remove it to save my site from giving unwanted backlinks ?</p>
| [
{
"answer_id": 328035,
"author": "Lucien Dubois",
"author_id": 51306,
"author_profile": "https://wordpress.stackexchange.com/users/51306",
"pm_score": 2,
"selected": false,
"text": "<p>I guess you are talking about the website \"field\". If it is so, add this code in the functions.php file to remove the field:</p>\n\n<pre><code>add_filter('comment_form_default_fields', 'remove_website_field');\nfunction remove_website_field($fields){\n if(isset($fields['url']))\n unset($fields['url']);\n return $fields;\n}\n</code></pre>\n"
},
{
"answer_id": 328052,
"author": "Vasim Shaikh",
"author_id": 87704,
"author_profile": "https://wordpress.stackexchange.com/users/87704",
"pm_score": 3,
"selected": true,
"text": "<p><strong>1. Using Plugins to disable Website field from comments</strong></p>\n\n<p>There are many plugins available in the WordPress repository that remove the Website field from the blog comments.</p>\n\n<p>The most easy way is to install Remove Fields or Remove Comment Website/URL Box.</p>\n\n<p><a href=\"https://wordpress.org/plugins/remove-fields/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/remove-fields/</a></p>\n\n<p><strong>2. Editing the WordPress Files to remove the Website field from comments</strong></p>\n\n<ul>\n<li>open functions.php file and add code.</li>\n</ul>\n\n<p><code>add_filter('comment_form_default_fields', 'website_remove');</code></p>\n\n<pre><code>function website_remove($fields)\n{\nif(isset($fields['url']))\nunset($fields['url']);\nreturn $fields;\n}\n</code></pre>\n"
},
{
"answer_id": 388877,
"author": "Vinu",
"author_id": 207054,
"author_profile": "https://wordpress.stackexchange.com/users/207054",
"pm_score": -1,
"selected": false,
"text": "<p>There are 3 easy ways to do it :</p>\n<p><strong>SIMPLE AND SHORT: EDITING CSS</strong>\nGo to customize and then custom css/js and add the following code</p>\n<pre><code>.comment-form-url{\n display:none;\n}\n</code></pre>\n<p><strong>ADD CODE SNIPPET TO FUNCTIONS.PHP</strong></p>\n<p>Go to Appearance > Theme editor and click on functions.php</p>\n<pre><code>// url field disabler\nfunction remove_url_comments($fields) {\n unset($fields['url']);\n return $fields;\n}\nadd_filter('comment_form_default_fields','remove_url_comments');\n</code></pre>\n<p><strong>USING PLUGINS</strong></p>\n<p>Go to Plugins > Add New and search for any one of the following plugin.\nRemove Fields or Remove Comment Website/URL box or disable-hide-comment-URL.</p>\n<p>For a full explanation, you can read my blog <a href=\"https://bloglikho.ml/how-to-remove-website-url-field-from-wordpress-comment-form/\" rel=\"nofollow noreferrer\">here</a></p>\n"
},
{
"answer_id": 405971,
"author": "brandonjp",
"author_id": 5380,
"author_profile": "https://wordpress.stackexchange.com/users/5380",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, as <a href=\"https://wordpress.stackexchange.com/a/328052/5380\">every</a> <a href=\"https://wordpress.stackexchange.com/a/328035/5380\">other</a> <a href=\"https://wordpress.stackexchange.com/a/388877/5380\">answer</a> has mentioned... definitely the preferred WordPress way would be using the <a href=\"https://developer.wordpress.org/reference/hooks/comment_form_default_fields/#comment-2565\" rel=\"nofollow noreferrer\"><code>comment_form_default_fields</code> filter</a>.</p>\n<p>However, it's very conceivable you might have a situation where you need other solutions. For example, if you're using a default theme and don't want to modify it (because you wouldn't want to lose the changes if the theme gets an update). I've got a site with very few plugins/customizations, but it does have an option for custom CSS/JS. I've used both Javascript and CSS solutions.</p>\n<p>This CSS hides it from the page (same as mentioned in <a href=\"https://wordpress.stackexchange.com/a/388877/5380\">Vinu's answer</a> )</p>\n<pre><code>form.comment-form .comment-form-url {\n display: none;\n}\n</code></pre>\n<p>Even better... this JS removes the url field from the page (actually in the weird event there is more than one on a page, this would remove them all):</p>\n<pre><code>document.querySelectorAll('.comment-form-url').forEach(child => child.parentNode.removeChild(child));\n</code></pre>\n"
}
] | 2019/02/08 | [
"https://wordpress.stackexchange.com/questions/328034",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] | i have two websites i use Wordpress comments on one website and jetpack comments on another. Both websites shows website column, how do i remove it to save my site from giving unwanted backlinks ? | **1. Using Plugins to disable Website field from comments**
There are many plugins available in the WordPress repository that remove the Website field from the blog comments.
The most easy way is to install Remove Fields or Remove Comment Website/URL Box.
<https://wordpress.org/plugins/remove-fields/>
**2. Editing the WordPress Files to remove the Website field from comments**
* open functions.php file and add code.
`add_filter('comment_form_default_fields', 'website_remove');`
```
function website_remove($fields)
{
if(isset($fields['url']))
unset($fields['url']);
return $fields;
}
``` |
328,036 | <p>I have an ACF field of <code>paid_attendance</code> - I only want it to display the field if the value is greater than 0. The below code only works if I swap <code>>0</code> out for an actual number (and that number matches the number set on the backend for a particular post(s). </p>
<p>Also, if I were to wrap the below in a div with an <code><h4></code> of "Paid Attendance" - how can I also make sure that the <code><h4></code> only shows up if the value is greater than 0 as well? In other words, if I get this working so it only displays <code>paid_attendance</code> if value is greater than 0, I dont want to have "Paid Attendance" still showing up for certain posts with nothing next to it (the posts where <code>paid_attendance</code> = 0). Thanks in advance.</p>
<pre><code><?php
// Different versions of a number
$unformatted = get_field('paid_attendance');
{
$integerValue = str_replace(",", "", $unformatted); // Remove commas from string
$integerValue = intval($integerValue); // Convert from string to integer
$integerValue = number_format($integerValue); // Apply number format
$floatValue = str_replace(",", "", $unformatted); // Remove commas from string
$floatValue = floatval($floatValue); // Convert from string to float
$floatValue = number_format($floatValue, 2); // Apply number format
if ( '0' == $unformatted ){
//do nothing
} elseif ( '>0' == $unformatted ) {
echo $integerValue;
}}
?>
</code></pre>
<p><strong>Update:</strong></p>
<p>Changed <code>( '>0' == $unformatted )</code> to <code>( $unformatted >0 )</code> and now its working. However, would appreciate if anyone has insight on my note above regarding only displaying the <code>h4</code> text if the value is >0 as well. thanks </p>
<p><strong>Update:</strong>
This does the trick:</p>
<pre><code>elseif ( $unformatted >0 ) {
echo '<h4 class="paid_tix">Paid Tickets: '; echo '</h4>';echo ' '; echo '<h4 class="integer">'; echo $integerValue; echo '</h4>';
</code></pre>
| [
{
"answer_id": 328035,
"author": "Lucien Dubois",
"author_id": 51306,
"author_profile": "https://wordpress.stackexchange.com/users/51306",
"pm_score": 2,
"selected": false,
"text": "<p>I guess you are talking about the website \"field\". If it is so, add this code in the functions.php file to remove the field:</p>\n\n<pre><code>add_filter('comment_form_default_fields', 'remove_website_field');\nfunction remove_website_field($fields){\n if(isset($fields['url']))\n unset($fields['url']);\n return $fields;\n}\n</code></pre>\n"
},
{
"answer_id": 328052,
"author": "Vasim Shaikh",
"author_id": 87704,
"author_profile": "https://wordpress.stackexchange.com/users/87704",
"pm_score": 3,
"selected": true,
"text": "<p><strong>1. Using Plugins to disable Website field from comments</strong></p>\n\n<p>There are many plugins available in the WordPress repository that remove the Website field from the blog comments.</p>\n\n<p>The most easy way is to install Remove Fields or Remove Comment Website/URL Box.</p>\n\n<p><a href=\"https://wordpress.org/plugins/remove-fields/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/remove-fields/</a></p>\n\n<p><strong>2. Editing the WordPress Files to remove the Website field from comments</strong></p>\n\n<ul>\n<li>open functions.php file and add code.</li>\n</ul>\n\n<p><code>add_filter('comment_form_default_fields', 'website_remove');</code></p>\n\n<pre><code>function website_remove($fields)\n{\nif(isset($fields['url']))\nunset($fields['url']);\nreturn $fields;\n}\n</code></pre>\n"
},
{
"answer_id": 388877,
"author": "Vinu",
"author_id": 207054,
"author_profile": "https://wordpress.stackexchange.com/users/207054",
"pm_score": -1,
"selected": false,
"text": "<p>There are 3 easy ways to do it :</p>\n<p><strong>SIMPLE AND SHORT: EDITING CSS</strong>\nGo to customize and then custom css/js and add the following code</p>\n<pre><code>.comment-form-url{\n display:none;\n}\n</code></pre>\n<p><strong>ADD CODE SNIPPET TO FUNCTIONS.PHP</strong></p>\n<p>Go to Appearance > Theme editor and click on functions.php</p>\n<pre><code>// url field disabler\nfunction remove_url_comments($fields) {\n unset($fields['url']);\n return $fields;\n}\nadd_filter('comment_form_default_fields','remove_url_comments');\n</code></pre>\n<p><strong>USING PLUGINS</strong></p>\n<p>Go to Plugins > Add New and search for any one of the following plugin.\nRemove Fields or Remove Comment Website/URL box or disable-hide-comment-URL.</p>\n<p>For a full explanation, you can read my blog <a href=\"https://bloglikho.ml/how-to-remove-website-url-field-from-wordpress-comment-form/\" rel=\"nofollow noreferrer\">here</a></p>\n"
},
{
"answer_id": 405971,
"author": "brandonjp",
"author_id": 5380,
"author_profile": "https://wordpress.stackexchange.com/users/5380",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, as <a href=\"https://wordpress.stackexchange.com/a/328052/5380\">every</a> <a href=\"https://wordpress.stackexchange.com/a/328035/5380\">other</a> <a href=\"https://wordpress.stackexchange.com/a/388877/5380\">answer</a> has mentioned... definitely the preferred WordPress way would be using the <a href=\"https://developer.wordpress.org/reference/hooks/comment_form_default_fields/#comment-2565\" rel=\"nofollow noreferrer\"><code>comment_form_default_fields</code> filter</a>.</p>\n<p>However, it's very conceivable you might have a situation where you need other solutions. For example, if you're using a default theme and don't want to modify it (because you wouldn't want to lose the changes if the theme gets an update). I've got a site with very few plugins/customizations, but it does have an option for custom CSS/JS. I've used both Javascript and CSS solutions.</p>\n<p>This CSS hides it from the page (same as mentioned in <a href=\"https://wordpress.stackexchange.com/a/388877/5380\">Vinu's answer</a> )</p>\n<pre><code>form.comment-form .comment-form-url {\n display: none;\n}\n</code></pre>\n<p>Even better... this JS removes the url field from the page (actually in the weird event there is more than one on a page, this would remove them all):</p>\n<pre><code>document.querySelectorAll('.comment-form-url').forEach(child => child.parentNode.removeChild(child));\n</code></pre>\n"
}
] | 2019/02/08 | [
"https://wordpress.stackexchange.com/questions/328036",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159682/"
] | I have an ACF field of `paid_attendance` - I only want it to display the field if the value is greater than 0. The below code only works if I swap `>0` out for an actual number (and that number matches the number set on the backend for a particular post(s).
Also, if I were to wrap the below in a div with an `<h4>` of "Paid Attendance" - how can I also make sure that the `<h4>` only shows up if the value is greater than 0 as well? In other words, if I get this working so it only displays `paid_attendance` if value is greater than 0, I dont want to have "Paid Attendance" still showing up for certain posts with nothing next to it (the posts where `paid_attendance` = 0). Thanks in advance.
```
<?php
// Different versions of a number
$unformatted = get_field('paid_attendance');
{
$integerValue = str_replace(",", "", $unformatted); // Remove commas from string
$integerValue = intval($integerValue); // Convert from string to integer
$integerValue = number_format($integerValue); // Apply number format
$floatValue = str_replace(",", "", $unformatted); // Remove commas from string
$floatValue = floatval($floatValue); // Convert from string to float
$floatValue = number_format($floatValue, 2); // Apply number format
if ( '0' == $unformatted ){
//do nothing
} elseif ( '>0' == $unformatted ) {
echo $integerValue;
}}
?>
```
**Update:**
Changed `( '>0' == $unformatted )` to `( $unformatted >0 )` and now its working. However, would appreciate if anyone has insight on my note above regarding only displaying the `h4` text if the value is >0 as well. thanks
**Update:**
This does the trick:
```
elseif ( $unformatted >0 ) {
echo '<h4 class="paid_tix">Paid Tickets: '; echo '</h4>';echo ' '; echo '<h4 class="integer">'; echo $integerValue; echo '</h4>';
``` | **1. Using Plugins to disable Website field from comments**
There are many plugins available in the WordPress repository that remove the Website field from the blog comments.
The most easy way is to install Remove Fields or Remove Comment Website/URL Box.
<https://wordpress.org/plugins/remove-fields/>
**2. Editing the WordPress Files to remove the Website field from comments**
* open functions.php file and add code.
`add_filter('comment_form_default_fields', 'website_remove');`
```
function website_remove($fields)
{
if(isset($fields['url']))
unset($fields['url']);
return $fields;
}
``` |
328,068 | <p>I use the following ACF query to generate a list, works perfectly.</p>
<p>Now, however, I want to order my list by standard WP “post title” instead of ACF custom field “datum”</p>
<p>How can I do that ?</p>
<pre><code>// args
$args = array(
'posts_per_page' => 999,
'post_type' => 'lezing',
'orderby' => 'meta_value',
'order' => 'ASC',
'meta_key' => 'datum',
'meta_query' => array(
array(
'key' => 'jaar',
'value' => '2019',
),
)
);
// query
$the_query = new WP_Query( $args );
</code></pre>
| [
{
"answer_id": 328070,
"author": "Alexander Holsgrove",
"author_id": 48962,
"author_profile": "https://wordpress.stackexchange.com/users/48962",
"pm_score": 0,
"selected": false,
"text": "<p>Your query will order using the meta term. To order by the post title, you just need to change the <code>orderby</code> to <code>title</code>.</p>\n\n<p>Take a look at the documentation for what the parameters mean:\n<a href=\"https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters</a></p>\n"
},
{
"answer_id": 328072,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>That query has nothing to do with ACF. It's a regular post query using WordPress' standard query class. As such you can refer to <a href=\"https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters\" rel=\"nofollow noreferrer\">the documentation</a> for the options for ordering your query. </p>\n\n<p>To sort by post title you just need to set <code>orderby</code> to <code>title</code>:</p>\n\n<pre><code><?php\n$args = array(\n 'posts_per_page' => 999,\n 'post_type' => 'lezing',\n 'orderby' => 'title',\n 'order' => 'ASC',\n 'meta_query' => array(\n array(\n 'key' => 'jaar',\n 'value' => '2019',\n ),\n ),\n);\n\n$the_query = new WP_Query( $args );\n</code></pre>\n\n<p>Also note that the quote marks in your original question are incorrect. You need to use non-fancy quotes like <code>'</code>. This can be an issue if you're copying code from incorrectly formatted blog/forum posts.</p>\n"
}
] | 2019/02/08 | [
"https://wordpress.stackexchange.com/questions/328068",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/160822/"
] | I use the following ACF query to generate a list, works perfectly.
Now, however, I want to order my list by standard WP “post title” instead of ACF custom field “datum”
How can I do that ?
```
// args
$args = array(
'posts_per_page' => 999,
'post_type' => 'lezing',
'orderby' => 'meta_value',
'order' => 'ASC',
'meta_key' => 'datum',
'meta_query' => array(
array(
'key' => 'jaar',
'value' => '2019',
),
)
);
// query
$the_query = new WP_Query( $args );
``` | That query has nothing to do with ACF. It's a regular post query using WordPress' standard query class. As such you can refer to [the documentation](https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters) for the options for ordering your query.
To sort by post title you just need to set `orderby` to `title`:
```
<?php
$args = array(
'posts_per_page' => 999,
'post_type' => 'lezing',
'orderby' => 'title',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'jaar',
'value' => '2019',
),
),
);
$the_query = new WP_Query( $args );
```
Also note that the quote marks in your original question are incorrect. You need to use non-fancy quotes like `'`. This can be an issue if you're copying code from incorrectly formatted blog/forum posts. |
328,082 | <p>I'm trying to remove trailing slash from a link which I get from <code>previous_posts_link()</code> function. Here is my code:</p>
<pre><code><?php rtrim(previous_posts_link( __( 'text', 'name' ) ), '/'); ?>
</code></pre>
<p>Unfortunetly it doesn't work and I still get the slash at the end of url.</p>
| [
{
"answer_id": 328085,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>There's two problems here:</p>\n\n<ol>\n<li><code>previous_posts_link()</code> <em>echoes</em> the link, rather than returning it.</li>\n<li><code>previous_posts_link()</code> returns the full HTML of the link, including <code><a href=\"\"></code> etc.</li>\n</ol>\n\n<p>The problem with #1 is that for you to be able pass the result of a function to another function (such as <code>rtrim()</code>) as an argument, that function needs to <code>return</code> a value, not print it to the screen using <code>echo</code> or similar. The function that <em>returns</em> the value of <code>previous_posts_link()</code> is <a href=\"https://developer.wordpress.org/reference/functions/get_previous_posts_link/\" rel=\"nofollow noreferrer\"><code>get_previous_posts_link()</code></a>.</p>\n\n<p>However, this still won't solve your problem, because of #2. <code>get_previous_posts_link()</code> will return a value like this:</p>\n\n<pre><code>'<a href=\"https://example.com/2019/02/08/previous-post/\">« Previous Post</a>'\n</code></pre>\n\n<p>As you can see, this does not end with a slash. The slash is in the middle of the string as part of the URL.</p>\n\n<p>If you only want the URL, you need to use <a href=\"https://developer.wordpress.org/reference/functions/get_previous_posts_page_link/\" rel=\"nofollow noreferrer\"><code>get_previous_posts_page_link()</code></a>. <em>Then</em> you can remove the trailing slash:</p>\n\n<pre><code><?php echo rtrim( get_previous_posts_page_link(), '/' ); ?>\n</code></pre>\n\n<p>Now, just to cover all my bases; if you want to get the full HTML link and remove the trailing slash from inside it, then you're going to need a couple more steps. </p>\n\n<p>Firstly, you're going to need to use <code>get_previous_posts_link()</code>, which is the function that returns the full HTML, rather than echoing it. Then you're going to need to extract the URL from the HTML, remove the trailing slash, then put it back. That will look something like this:</p>\n\n<pre><code>// Get the HTML for the link.\n$previous_posts_link = get_previous_posts_link( __( 'text', 'name' ) );\n\n// Find the URL.\npreg_match( '/href=\"([^\"]*)\"/', $previous_posts_link, $matches );\n\n// Remove the trailing slash from the original URL.\n$original_url = $matches[1];\n$trimmed_url = untrailingslashit( $original_url );\n\n// Replace the original URL with the version without a slash.\n$previous_posts_link = str_replace( $original_url, $trimmed_url, $previous_posts_link );\n\n// Output it\necho $previous_posts_link;\n</code></pre>\n\n<p>I have no idea why you'd want or need to do that though.</p>\n\n<p>PS: <code>untrailingslashit()</code> is a WordPress helper function that removes trailing forward and back slashes.</p>\n"
},
{
"answer_id": 357422,
"author": "moisty70",
"author_id": 181792,
"author_profile": "https://wordpress.stackexchange.com/users/181792",
"pm_score": 1,
"selected": false,
"text": "<p>You can add this line to your functions.php</p>\n\n<pre><code>add_filter('get_pagenum_link','untrailingslashit');\n</code></pre>\n"
},
{
"answer_id": 369505,
"author": "Serge Andreev",
"author_id": 116650,
"author_profile": "https://wordpress.stackexchange.com/users/116650",
"pm_score": 1,
"selected": false,
"text": "<p>try to add line to your functions.php</p>\n<pre><code>add_filter('paginate_links','untrailingslashit');\n</code></pre>\n"
}
] | 2019/02/08 | [
"https://wordpress.stackexchange.com/questions/328082",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145150/"
] | I'm trying to remove trailing slash from a link which I get from `previous_posts_link()` function. Here is my code:
```
<?php rtrim(previous_posts_link( __( 'text', 'name' ) ), '/'); ?>
```
Unfortunetly it doesn't work and I still get the slash at the end of url. | There's two problems here:
1. `previous_posts_link()` *echoes* the link, rather than returning it.
2. `previous_posts_link()` returns the full HTML of the link, including `<a href="">` etc.
The problem with #1 is that for you to be able pass the result of a function to another function (such as `rtrim()`) as an argument, that function needs to `return` a value, not print it to the screen using `echo` or similar. The function that *returns* the value of `previous_posts_link()` is [`get_previous_posts_link()`](https://developer.wordpress.org/reference/functions/get_previous_posts_link/).
However, this still won't solve your problem, because of #2. `get_previous_posts_link()` will return a value like this:
```
'<a href="https://example.com/2019/02/08/previous-post/">« Previous Post</a>'
```
As you can see, this does not end with a slash. The slash is in the middle of the string as part of the URL.
If you only want the URL, you need to use [`get_previous_posts_page_link()`](https://developer.wordpress.org/reference/functions/get_previous_posts_page_link/). *Then* you can remove the trailing slash:
```
<?php echo rtrim( get_previous_posts_page_link(), '/' ); ?>
```
Now, just to cover all my bases; if you want to get the full HTML link and remove the trailing slash from inside it, then you're going to need a couple more steps.
Firstly, you're going to need to use `get_previous_posts_link()`, which is the function that returns the full HTML, rather than echoing it. Then you're going to need to extract the URL from the HTML, remove the trailing slash, then put it back. That will look something like this:
```
// Get the HTML for the link.
$previous_posts_link = get_previous_posts_link( __( 'text', 'name' ) );
// Find the URL.
preg_match( '/href="([^"]*)"/', $previous_posts_link, $matches );
// Remove the trailing slash from the original URL.
$original_url = $matches[1];
$trimmed_url = untrailingslashit( $original_url );
// Replace the original URL with the version without a slash.
$previous_posts_link = str_replace( $original_url, $trimmed_url, $previous_posts_link );
// Output it
echo $previous_posts_link;
```
I have no idea why you'd want or need to do that though.
PS: `untrailingslashit()` is a WordPress helper function that removes trailing forward and back slashes. |
328,121 | <p>Question: how can I change text within the Block Editor itself?</p>
<ul>
<li><p>When a user with edit but not publish permissions makes changes to a published post and clicks "submit for review," the Block Editor presents a "post reverted to draft" success message. I would like to change this to my own text.</p></li>
<li><p>Also, in the Block Editor's Publish panel, there's text specific to WP Core roles - when a user with edit but not publish permissions hits Publish the first time and the pre-publish checks show up, a Core message says "When you're ready, submit your work for review, and an Editor will be able to approve it for you." (I use custom roles, so it's not an Editor who can help them.)</p></li>
</ul>
<p>I would like to either change that text (replace it with my own static text) or, ideally, find a way to pull a list of all users who have publishing permissions for this post type and output a list, saying something like, "One of these users will be able to approve it for you: (list of users' display names)."</p>
<p>I can't seem to find any documentation on filtering these messages, but surely I'm overlooking something since at the very least I'm sure they are translatable.</p>
| [
{
"answer_id": 328423,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not able to test it right now, so I won't guarantee that it will work, but...</p>\n\n<h2>1. post reverted to draft</h2>\n\n<p>When you grep through WP code searching for that string, only one occurrence appears. It's inside <code>wp-includes/post.php</code> file (<a href=\"https://core.trac.wordpress.org/browser/tags/5.0.3/src/wp-includes/post.php#L1538\" rel=\"nofollow noreferrer\">see on trac</a>) in <a href=\"https://developer.wordpress.org/reference/functions/get_post_type_labels/\" rel=\"nofollow noreferrer\"><code>get_post_type_labels</code></a> function. And there is a filter used inside that function: <a href=\"https://developer.wordpress.org/reference/hooks/post_type_labels_post_type/\" rel=\"nofollow noreferrer\"><code>post_type_labels_{$post_type}</code></a>.</p>\n\n<p>So something like this should do the trick:</p>\n\n<pre><code>function my_custom_post_labels( $labels ) {\n $labels->item_reverted_to_draft = 'MY OWN TEXT';\n}\nadd_filter( 'post_type_labels_post', 'my_custom_labels' );\n</code></pre>\n\n<h2>2. When you're ready, submit your work for review, and an Editor will be able to approve it for you.</h2>\n\n<p>This is a little bit harder. This string is placed directly in <code>wp-includes/js/dist/editor.js</code> (line 26896) in this context:</p>\n\n<pre><code>prePublishBodyText = Object(external_this_wp_i18n_[\"__\"])('When you’re ready, submit your work for review, and an Editor will be able to approve it for you.');\n</code></pre>\n\n<p>And <code>external_this_wp_i18n_</code> is the <a href=\"https://make.wordpress.org/core/2018/11/09/new-javascript-i18n-support-in-wordpress/\" rel=\"nofollow noreferrer\">new JS object introduced in 5.0</a>.</p>\n\n<p>I'm not very familiar with this mechanism, but... As long as I understand this article correctly, there is currently no way of running PHP filters for these strings, so we won't be able to make these strings dynamic... And that's the moment I'm really starting to hate this Gutenberg JS mess...</p>\n\n<p>On the other hand, if it doesn't have to be dynamic, you can use the method described in the article I've linked to \"translate\" that string.</p>\n"
},
{
"answer_id": 328440,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 4,
"selected": true,
"text": "<h2>Changing the \"<em>Post reverted to draft.</em>\" text</h2>\n\n<p>In WordPress version 5.0, WordPress introduced a new post type label which has the key <code>item_reverted_to_draft</code> and it's <a href=\"https://developer.wordpress.org/reference/functions/get_post_type_labels/#description\" rel=\"noreferrer\">defined</a> as:</p>\n\n<blockquote>\n <p><code>item_reverted_to_draft</code> – Label used when an item is switched to a\n draft. Default is ‘Post reverted to draft.’ / ‘Page reverted to\n draft.’</p>\n</blockquote>\n\n<p>Hence, as with any other post type labels — and as suggested in the previous answer, you can use the <a href=\"https://developer.wordpress.org/reference/hooks/post_type_labels_post_type/\" rel=\"noreferrer\"><code>post_type_labels_{$post_type}</code></a> filter to change the label (text):</p>\n\n<pre><code>function my_post_type_labels( $labels ) {\n $labels->item_reverted_to_draft = 'Your custom text.';\n\n return $labels;\n}\n\nadd_filter( 'post_type_labels_post', 'my_post_type_labels' ); // post\nadd_filter( 'post_type_labels_my_cpt', 'my_post_type_labels' ); // CPT\n</code></pre>\n\n<p>Or you can also use the <a href=\"https://developer.wordpress.org/reference/hooks/register_post_type_args/\" rel=\"noreferrer\"><code>register_post_type_args</code></a> filter or the <a href=\"https://developer.wordpress.org/reference/hooks/registered_post_type/\" rel=\"noreferrer\"><code>registered_post_type</code></a> action:</p>\n\n<pre><code>add_filter( 'register_post_type_args', function( $args, $post_type ){\n $labels = isset( $args['labels'] ) ? (array) $args['labels'] : [];\n if ( in_array( $post_type, ['post', 'my_cpt'] ) ) {\n $labels['item_reverted_to_draft'] = 'Your custom text.';\n }\n $args['labels'] = $labels;\n\n return $args;\n}, 10, 2 );\n</code></pre>\n\n<h2>Changing the \"<em>When you’re ready, submit your work for review, and an Editor will be able to approve it for you.</em>\" text</h2>\n\n<p>In WordPress version 5.0, WordPress <a href=\"https://make.wordpress.org/core/2018/11/09/new-javascript-i18n-support-in-wordpress/\" rel=\"noreferrer\">introduced</a> the JavaScript i18n support, which basically means you can use <code>__()</code>, <code>_n()</code>, etc. in JavaScript to retrieve the translation of a specific string/text like so:</p>\n\n<pre><code>// Equivalent example in PHP: <?php var_dump( __( 'My string', 'text-domain' ) ); ?>\nconsole.log( wp.i18n.__( 'My string', 'text-domain' ) );\n\n// Equivalent example in PHP: <?php var_dump( sprintf( _n( '%s Comment', '%s Comments', 9, 'text-domain' ), 9 ) ); ?>\nconsole.log( wp.i18n.sprintf( wp.i18n._n( '%s Comment', '%s Comments', 9, 'text-domain' ), 9 ) );\n</code></pre>\n\n<p>So as you can see, unlike in PHP, in JavaScript, we access the functions via <code>wp.i18n</code> which is the translation library. However, not all functions are available; for example, the <code>_e()</code> function as in <code><?php _e( 'Text' ); ?></code> — there's no <code>wp.i18n._e()</code> and <code>wp.i18n._e( 'Text' )</code> will result in an error.</p>\n\n<p>Now, for that text — <code>When you’re ready, submit your work for review, and an Editor will be able to approve it for you.</code> — which you're trying to customize, you can find it in the Block Editor script in <code>wp-includes/js/dist/editor.js</code> under a local function named <code>PostPublishPanelPrepublish</code>:</p>\n\n<pre><code>prePublishBodyText = Object(external_this_wp_i18n_[\"__\"])('When you’re ready, submit...');\n</code></pre>\n\n<p>And that <code>external_this_wp_i18n_</code> points to <code>wp.i18n</code>; hence the <code>external_this_wp_i18n_[\"__\"])</code> is equivalent to <code>wp.i18n.__</code>.</p>\n\n<p><strong>Now here's how you can change the text via JavaScript...</strong></p>\n\n<p>Use <a href=\"https://github.com/WordPress/gutenberg/blob/master/packages/i18n/src/index.js#L36\" rel=\"noreferrer\">wp.i18n.setLocaleData()</a>:</p>\n\n<pre><code>wp.i18n.setLocaleData({\n 'String to translate #1': [\n 'Translated string - singular',\n 'Translated string - plural'\n ],\n 'String to translate #2': [\n 'Translated string'\n // No plural.\n ]\n// Omit the text domain (or set it to '') if overriding the default WordPress translations.\n}, 'text-domain');\n</code></pre>\n\n<p>So for example, in your case:</p>\n\n<pre><code>wp.i18n.setLocaleData({\n 'When you’re ready, submit your work for review, and an Editor will be able to approve it for you.': [\n 'Publish when you are ready..'\n ]\n});\n</code></pre>\n\n<p><strong>And here's how you could add the script to the post/page edit screen...</strong></p>\n\n<p>Or any admin pages/screens where the <code>wp-i18n</code> script is being enqueued.</p>\n\n<pre><code>add_action( 'admin_print_footer_scripts', function(){\n // Make sure the `wp-i18n` has been \"done\".\n if ( wp_script_is( 'wp-i18n' ) ) :\n ?>\n <script>\n // Note: Make sure that `wp.i18n` has already been defined by the time you call `wp.i18n.setLocaleData()`.\n wp.i18n.setLocaleData({\n 'When you’re ready, submit your work for review, and an Editor will be able to approve it for you.': [\n 'Publish when you are ready..'\n ]\n });\n </script>\n <?php\n endif;\n}, 11 );\n</code></pre>\n\n<p>But of course, you could use other similar WordPress hook, or place the JavaScript code in a <code>.js</code> (external JavaScript) file and enqueue it by specifying the <code>wp-i18n</code> (remember, it's a <em>dash</em> and not a dot) as a dependency.</p>\n\n<h2>Displaying the \"<em>One of these users will be able to approve it for you: (list of users' display names).</em>\" text</h2>\n\n<pre><code>add_action( 'admin_print_footer_scripts', function(){\n // Make sure the `wp-i18n` has been \"done\".\n if ( wp_script_is( 'wp-i18n' ) ) :\n $wp_roles = wp_roles();\n $role_names = [];\n\n // Get the roles which have the publish_posts capability.\n foreach ( $wp_roles->role_objects as $name => $role ) {\n if ( $role && $role->has_cap( 'publish_posts' ) ) {\n $role_names[] = $name;\n }\n }\n\n // Get the users which have the role(s) in the `$role_names`.\n $users = get_users([\n 'role__in' => $role_names,\n ]);\n $user_names = [];\n\n foreach ( $users as $user ) {\n $user_names[] = $user->display_name;\n }\n\n $data = [\n 'When you’re ready, submit your work for review, and an Editor will be able to approve it for you.' => [\n 'One of these users will be able to approve it for you: ' . implode( ', ', $user_names )\n ],\n ];\n ?>\n <script>\n // Note: Make sure that `wp.i18n` has already been defined by the time you call `wp.i18n.setLocaleData()`.\n wp.i18n.setLocaleData(<?php echo json_encode( $data ); ?>);\n </script>\n <?php\n endif;\n}, 11 );\n</code></pre>\n\n<p>How to test the above snippet:</p>\n\n<ul>\n<li><p>Add the snippet to the theme's <code>functions.php</code> file.</p></li>\n<li><p>Login to the WordPress back-end as any user with a \"Contributor\" role.</p></li>\n<li><p>Create a new Post and click the \"Publish\" button.</p></li>\n<li><p>You should see something like <a href=\"https://i.ibb.co/SxDxFbF/image.png\" rel=\"noreferrer\">this</a>.</p></li>\n</ul>\n"
}
] | 2019/02/08 | [
"https://wordpress.stackexchange.com/questions/328121",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102815/"
] | Question: how can I change text within the Block Editor itself?
* When a user with edit but not publish permissions makes changes to a published post and clicks "submit for review," the Block Editor presents a "post reverted to draft" success message. I would like to change this to my own text.
* Also, in the Block Editor's Publish panel, there's text specific to WP Core roles - when a user with edit but not publish permissions hits Publish the first time and the pre-publish checks show up, a Core message says "When you're ready, submit your work for review, and an Editor will be able to approve it for you." (I use custom roles, so it's not an Editor who can help them.)
I would like to either change that text (replace it with my own static text) or, ideally, find a way to pull a list of all users who have publishing permissions for this post type and output a list, saying something like, "One of these users will be able to approve it for you: (list of users' display names)."
I can't seem to find any documentation on filtering these messages, but surely I'm overlooking something since at the very least I'm sure they are translatable. | Changing the "*Post reverted to draft.*" text
---------------------------------------------
In WordPress version 5.0, WordPress introduced a new post type label which has the key `item_reverted_to_draft` and it's [defined](https://developer.wordpress.org/reference/functions/get_post_type_labels/#description) as:
>
> `item_reverted_to_draft` – Label used when an item is switched to a
> draft. Default is ‘Post reverted to draft.’ / ‘Page reverted to
> draft.’
>
>
>
Hence, as with any other post type labels — and as suggested in the previous answer, you can use the [`post_type_labels_{$post_type}`](https://developer.wordpress.org/reference/hooks/post_type_labels_post_type/) filter to change the label (text):
```
function my_post_type_labels( $labels ) {
$labels->item_reverted_to_draft = 'Your custom text.';
return $labels;
}
add_filter( 'post_type_labels_post', 'my_post_type_labels' ); // post
add_filter( 'post_type_labels_my_cpt', 'my_post_type_labels' ); // CPT
```
Or you can also use the [`register_post_type_args`](https://developer.wordpress.org/reference/hooks/register_post_type_args/) filter or the [`registered_post_type`](https://developer.wordpress.org/reference/hooks/registered_post_type/) action:
```
add_filter( 'register_post_type_args', function( $args, $post_type ){
$labels = isset( $args['labels'] ) ? (array) $args['labels'] : [];
if ( in_array( $post_type, ['post', 'my_cpt'] ) ) {
$labels['item_reverted_to_draft'] = 'Your custom text.';
}
$args['labels'] = $labels;
return $args;
}, 10, 2 );
```
Changing the "*When you’re ready, submit your work for review, and an Editor will be able to approve it for you.*" text
-----------------------------------------------------------------------------------------------------------------------
In WordPress version 5.0, WordPress [introduced](https://make.wordpress.org/core/2018/11/09/new-javascript-i18n-support-in-wordpress/) the JavaScript i18n support, which basically means you can use `__()`, `_n()`, etc. in JavaScript to retrieve the translation of a specific string/text like so:
```
// Equivalent example in PHP: <?php var_dump( __( 'My string', 'text-domain' ) ); ?>
console.log( wp.i18n.__( 'My string', 'text-domain' ) );
// Equivalent example in PHP: <?php var_dump( sprintf( _n( '%s Comment', '%s Comments', 9, 'text-domain' ), 9 ) ); ?>
console.log( wp.i18n.sprintf( wp.i18n._n( '%s Comment', '%s Comments', 9, 'text-domain' ), 9 ) );
```
So as you can see, unlike in PHP, in JavaScript, we access the functions via `wp.i18n` which is the translation library. However, not all functions are available; for example, the `_e()` function as in `<?php _e( 'Text' ); ?>` — there's no `wp.i18n._e()` and `wp.i18n._e( 'Text' )` will result in an error.
Now, for that text — `When you’re ready, submit your work for review, and an Editor will be able to approve it for you.` — which you're trying to customize, you can find it in the Block Editor script in `wp-includes/js/dist/editor.js` under a local function named `PostPublishPanelPrepublish`:
```
prePublishBodyText = Object(external_this_wp_i18n_["__"])('When you’re ready, submit...');
```
And that `external_this_wp_i18n_` points to `wp.i18n`; hence the `external_this_wp_i18n_["__"])` is equivalent to `wp.i18n.__`.
**Now here's how you can change the text via JavaScript...**
Use [wp.i18n.setLocaleData()](https://github.com/WordPress/gutenberg/blob/master/packages/i18n/src/index.js#L36):
```
wp.i18n.setLocaleData({
'String to translate #1': [
'Translated string - singular',
'Translated string - plural'
],
'String to translate #2': [
'Translated string'
// No plural.
]
// Omit the text domain (or set it to '') if overriding the default WordPress translations.
}, 'text-domain');
```
So for example, in your case:
```
wp.i18n.setLocaleData({
'When you’re ready, submit your work for review, and an Editor will be able to approve it for you.': [
'Publish when you are ready..'
]
});
```
**And here's how you could add the script to the post/page edit screen...**
Or any admin pages/screens where the `wp-i18n` script is being enqueued.
```
add_action( 'admin_print_footer_scripts', function(){
// Make sure the `wp-i18n` has been "done".
if ( wp_script_is( 'wp-i18n' ) ) :
?>
<script>
// Note: Make sure that `wp.i18n` has already been defined by the time you call `wp.i18n.setLocaleData()`.
wp.i18n.setLocaleData({
'When you’re ready, submit your work for review, and an Editor will be able to approve it for you.': [
'Publish when you are ready..'
]
});
</script>
<?php
endif;
}, 11 );
```
But of course, you could use other similar WordPress hook, or place the JavaScript code in a `.js` (external JavaScript) file and enqueue it by specifying the `wp-i18n` (remember, it's a *dash* and not a dot) as a dependency.
Displaying the "*One of these users will be able to approve it for you: (list of users' display names).*" text
--------------------------------------------------------------------------------------------------------------
```
add_action( 'admin_print_footer_scripts', function(){
// Make sure the `wp-i18n` has been "done".
if ( wp_script_is( 'wp-i18n' ) ) :
$wp_roles = wp_roles();
$role_names = [];
// Get the roles which have the publish_posts capability.
foreach ( $wp_roles->role_objects as $name => $role ) {
if ( $role && $role->has_cap( 'publish_posts' ) ) {
$role_names[] = $name;
}
}
// Get the users which have the role(s) in the `$role_names`.
$users = get_users([
'role__in' => $role_names,
]);
$user_names = [];
foreach ( $users as $user ) {
$user_names[] = $user->display_name;
}
$data = [
'When you’re ready, submit your work for review, and an Editor will be able to approve it for you.' => [
'One of these users will be able to approve it for you: ' . implode( ', ', $user_names )
],
];
?>
<script>
// Note: Make sure that `wp.i18n` has already been defined by the time you call `wp.i18n.setLocaleData()`.
wp.i18n.setLocaleData(<?php echo json_encode( $data ); ?>);
</script>
<?php
endif;
}, 11 );
```
How to test the above snippet:
* Add the snippet to the theme's `functions.php` file.
* Login to the WordPress back-end as any user with a "Contributor" role.
* Create a new Post and click the "Publish" button.
* You should see something like [this](https://i.ibb.co/SxDxFbF/image.png). |
328,125 | <p>I just deployed a new Wordpress site. Everything looks good, now I'm setting up jQuery:</p>
<p><em>Child theme</em> <strong>functions.php:</strong></p>
<pre><code>//enqueue scripts
function my_theme_enqueue_scripts() {
wp_register_script( 'myjs', get_stylesheet_directory_uri() . '/my.js', array('jquery'),'1.0.0');
wp_enqueue_script('myjs');
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_scripts' );
</code></pre>
<p>Page template <strong>tpl-mypage.php</strong>:</p>
<pre><code><html>
<head>
<?php wp_head(); ?>
</head>
<body>
<div id=”test-script”></div>
</body>
</html>
</code></pre>
<p>The js file <strong>my.js</strong>:</p>
<pre><code>jQuery(document).ready(function( $ ){
$("#test-script").html("Hello World");
})
</code></pre>
<p>This is NOT working. I can see my.js being loaded on Chrome>Inspect>Network.</p>
<p>What could be the problem here?</p>
| [
{
"answer_id": 328127,
"author": "Mohsin Ghouri",
"author_id": 159253,
"author_profile": "https://wordpress.stackexchange.com/users/159253",
"pm_score": 2,
"selected": false,
"text": "<p>The code seems fine. Please check by loading the script in the footer and also use the wp_footer in your .php file.</p>\n"
},
{
"answer_id": 328130,
"author": "makkabi",
"author_id": 159243,
"author_profile": "https://wordpress.stackexchange.com/users/159243",
"pm_score": 1,
"selected": false,
"text": "<p>Set the $in_footer argument to true when registering the script:</p>\n\n<pre>\n wp_register_script( 'myjs', get_stylesheet_directory_uri() . '/my.js', array('jquery'),'1.0.0', true);\n</pre>\n\n<p>And also call wp_footer(), as Mohsin mentioned:</p>\n\n<pre><code> <html>\n <head>\n <?php wp_head(); ?> \n </head>\n <body>\n <div id=”test-script”></div>\n <?php wp_footer(); ?>\n </body>\n </html>\n</code></pre>\n"
},
{
"answer_id": 329232,
"author": "Deepal Samaraweera",
"author_id": 161583,
"author_profile": "https://wordpress.stackexchange.com/users/161583",
"pm_score": 0,
"selected": false,
"text": "<p>tried this way. No luck. need more help please. It works in locally but not inside wordpress.</p>\n\n<p>My code : <strong>myjquery.js</strong></p>\n\n<pre><code> $(document).ready(function($) {\n</code></pre>\n\n<p>$('.item-type').click(function() {\n $('.item-type').removeClass('item-type-active');\n $(this).addClass('item-type-active');\n });</p>\n\n<p>function rangeCalc(i) {\nvar totalPrice = 0;\nvar tariff = [{begin:1, price:1000}, ];\nvar tariffItem2 = [{begin:1, price:85}, {begin:3, price:80}, {begin:6, price:75}, {begin:11, price:70}, {begin:21, price:65}, {begin:61, price:60}];</p>\n\n<p>tariff.forEach(function(num, item) {\n if (tariff[item].begin <= i) {\n totalPrice = tariff[item].price;\n $('.calc-total-price').text(i*totalPrice);\n $('.calc-price').text(totalPrice);\n };</p>\n\n<p>});\n};</p>\n\n<p>$('.calc-range').on('input', function() {\n $('.calc-count').text(this.value);\n rangeCalc(this.value);\n});</p>\n\n<p>});</p>\n\n<p><strong>loaded like this way. and shows it in page source.</strong> </p>\n\n<p>function load_js_assets() {\n if( is_page( 292 ) ) {\n wp_enqueue_script('myjquery', '/js/myjquery.js', array('jquery'), '', true);</p>\n\n<pre><code>} \n</code></pre>\n\n<p>}</p>\n\n<p>add_action('wp_enqueue_scripts', 'load_js_assets'); </p>\n"
}
] | 2019/02/08 | [
"https://wordpress.stackexchange.com/questions/328125",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/64243/"
] | I just deployed a new Wordpress site. Everything looks good, now I'm setting up jQuery:
*Child theme* **functions.php:**
```
//enqueue scripts
function my_theme_enqueue_scripts() {
wp_register_script( 'myjs', get_stylesheet_directory_uri() . '/my.js', array('jquery'),'1.0.0');
wp_enqueue_script('myjs');
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_scripts' );
```
Page template **tpl-mypage.php**:
```
<html>
<head>
<?php wp_head(); ?>
</head>
<body>
<div id=”test-script”></div>
</body>
</html>
```
The js file **my.js**:
```
jQuery(document).ready(function( $ ){
$("#test-script").html("Hello World");
})
```
This is NOT working. I can see my.js being loaded on Chrome>Inspect>Network.
What could be the problem here? | The code seems fine. Please check by loading the script in the footer and also use the wp\_footer in your .php file. |
328,142 | <p>I am showing comments on my page. I want to show 1 ad after every 2 comments.</p>
<p><code><div class="panel-ads clearfix"></div></code> it's repeating the number of comments. </p>
<p>I would like to add the ad code after every 2 comments. </p>
<p>For example:</p>
<pre><code><div class="panel-ads clearfix"></div>
<div class="panel-ads clearfix"></div>
/*
* My ads code
*/
<div class="panel-ads clearfix"></div>
<div class="panel-ads clearfix"></div>
/*
* My ads code
*/
</code></pre>
<p><strong>My wp_list_comment() function: (<em>function.php</em>)</strong></p>
<pre><code><?php
function new_comment($comment, $args, $depth,$i=0) {
$GLOBALS['comment'] = $comment;
$PostAuthor = false;
if($comment->comment_author_email == get_the_author_email()){
$PostAuthor = true;
}elseif($comment->comment_author_email == '[email protected]'){
$PostAuthor = true;
}
?>
<div class="panel panel-default entry" id="comment-<?php echo $comment->comment_ID; ?>">
<div class="panel-body">
<div itemprop="text"> </div>
</div>
<div class="panel-footer clearfix">
<?php comment_text(); ?>
</div>
</div>
<?php
}
</code></pre>
| [
{
"answer_id": 328155,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<h2>The <code>end-callback</code> of <code>wp_list_comments()</code></h2>\n\n<p>One way is to use the <code>end-callback</code> argument in:</p>\n\n<pre><code>wp_list_comments( [ \n 'end-callback' => 'wpse_comments_ads_injection',\n ... other arguments ...\n], $comments );\n</code></pre>\n\n<p>in addtion to your other <code>wp_list_comments</code> arguments, by defining:</p>\n\n<pre><code>function wpse_comments_ads_injection( $comment, $args, $depth ) {\n static $instance = 0;\n $tag = ( 'div' == $args['style'] ) ? 'div' : 'li';\n\n echo \"</{$tag}><!-- #comment-## -->\\n\";\n\n if ( 0 === $instance % 2 ) {\n echo \"<{$tag} class=\\\"comment__ad\\\">YOUR AD HERE!</{$tag}>\";\n }\n\n $instance++;\n}\n</code></pre>\n\n<p>where we do the counting with the static variable <code>$instance</code> that's incremented for each call.</p>\n\n<p>This should inject the defined comment ads, using either <code>div</code> or <code>li</code> tags, depending on the styling.</p>\n\n<p>By using the end-callback, we don't need to modify the comment callback, if we don't need to, just to inject the ads. So if we need the default comment layout, we can also inject the ads this way.</p>\n\n<p>One could additionally use the comment <code>depth</code> to control the ads display.</p>\n\n<p>Note that the callback for both the <code>callback</code> and <code>end-callback</code> of <code>wp_list_comments()</code>, has three input arguments, not four.</p>\n\n<h2>The <code>wp_list_comments_args</code> filter</h2>\n\n<p>We can then adjust it further and use the <code>wp_list_comments_args</code> filter:</p>\n\n<pre><code>add_filter( 'wp_list_comments_args', function( $args ) {\n if ( ! isset( $args['end-callback'] ) ) {\n $args['end-callback'] = 'wpse_comments_ads_injection';\n }\n return $args;\n} );\n</code></pre>\n\n<p>instead of modifying the the <code>wp_list_comments()</code> directly.</p>\n\n<p>We can create a plugin for this or add this into the <code>functions.php</code> file in the current theme's directory.</p>\n\n<h2>Introducing injection's offset, rate and html</h2>\n\n<p>Then we can add a support for the injection's <em>rate</em>, <em>offset</em> and <em>html</em>:</p>\n\n<pre><code>add_filter( 'wp_list_comments_args', function( $args ) {\n if ( ! isset( $args['end-callback'] ) ) {\n // Modify this to your needs!\n $args['end-callback'] = 'wpse_comments_ads_injection';\n $args['_ads_offset'] = 0; // Start injecting after the 1st comment.\n $args['_ads_rate'] = 2; // Inject after every second comment.\n $args['_ads_html'] = '<img src=\"http://placekitten.com/g/500/100\" />';\n }\n return $args;\n} );\n</code></pre>\n\n<p>where we adjust the end-callback with:</p>\n\n<pre><code>/**\n * Inject Ads To WordPress Comments - end-callback for wp_list_comments().\n *\n * The Ads HTML is sanitized through wp_kses_post().\n *\n * @version 1.0.11\n * @see https://wordpress.stackexchange.com/a/328155/26350\n */\nfunction wpse_comments_ads_injection( $comment, $args, $depth ) {\n static $instance = 0;\n $tag = ( 'div' == $args['style'] ) ? 'div' : 'li';\n $ads_rate = isset( $args['_ads_rate' ] ) && $args['_ads_rate' ] > 0 \n ? (int) $args['_ads_rate' ] \n : 2;\n $ads_offset = isset( $args['_ads_offset' ] ) && $args['_ads_offset' ] > 0\n ? (int) $args['_ads_offset' ]\n : 0;\n $ads_html = isset( $args['_ads_html' ] ) \n ? wp_kses_post( $args['_ads_html' ] )\n : '';\n\n echo \"</{$tag}><!-- #comment-## -->\\n\";\n\n if ( $ads_offset <= $instance && 0 === ( $instance - $ads_offset ) % $ads_rate && ! empty( $ads_html ) ) {\n echo \"<{$tag} class=\\\"comment__ad\\\">{$ads_html}</{$tag}>\";\n }\n\n $instance++;\n}\n</code></pre>\n\n<p>Here's a <a href=\"https://gist.github.com/birgire/493f0d646491532e0ed5b0c5549f1a12\" rel=\"nofollow noreferrer\">gist</a> for the code to add into the <code>functions.php</code> file in the current themes directory.</p>\n\n<p><strike>This is untested</strike>, but I hope you can adjust this to your needs!</p>\n"
},
{
"answer_id": 328175,
"author": "phatskat",
"author_id": 20143,
"author_profile": "https://wordpress.stackexchange.com/users/20143",
"pm_score": 1,
"selected": false,
"text": "<p>Give this a shot, let me know if you have any questions.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code><?php\nfunction sinyor_comment($comment, $args, $depth,$i=0) { \n /**\n * This follows @birgire's answer, hat-tip for use of `static`.\n *\n * The `static` keyword declares `$count` as static to the\n * `sinyor_comment` method. That means that it will persist\n * within the function's scope on each run of `sinyor_comment`.\n *\n * Essentially: $count will always be what you set it to the\n * last time you called `sinyor_comment`, which you can use\n * to tell which comment you're on.\n */\n static $count = 0; // This assignment only happens the first time.\n\n // Not sure what you're using this for, but I would recommend\n // finding a better way to pass this around if you need\n // it elsewhere.\n $GLOBALS['comment'] = $comment;\n\n $PostAuthor = false; \n\n if($comment->comment_author_email == get_the_author_email()){\n $PostAuthor = true;\n }elseif($comment->comment_author_email == '[email protected]'){\n $PostAuthor = true;\n }\n?>\n\n<div class=\"panel panel-default entry\" id=\"comment-<?php echo $comment->comment_ID; ?>\" itemprop=\"suggestedAnswer\" itemscope itemtype=\"http://schema.org/Answer\">\n <div class=\"panel-body\">\n <div itemprop=\"text\"> </div>\n </div>\n <div class=\"panel-footer clearfix\">\n <?php comment_text(); ?>\n </div>\n</div>\n<?php\n\n // If we haven't had two comments, don't show the ad.\n if ( 2 > $count ) {\n // Increment $count by 1.\n $count++;\n return;\n }\n\n /**\n * Your Ad Code\n */\n\n // Reset count to zero.\n $count = 0;\n}\n</code></pre>\n"
}
] | 2019/02/08 | [
"https://wordpress.stackexchange.com/questions/328142",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/160866/"
] | I am showing comments on my page. I want to show 1 ad after every 2 comments.
`<div class="panel-ads clearfix"></div>` it's repeating the number of comments.
I would like to add the ad code after every 2 comments.
For example:
```
<div class="panel-ads clearfix"></div>
<div class="panel-ads clearfix"></div>
/*
* My ads code
*/
<div class="panel-ads clearfix"></div>
<div class="panel-ads clearfix"></div>
/*
* My ads code
*/
```
**My wp\_list\_comment() function: (*function.php*)**
```
<?php
function new_comment($comment, $args, $depth,$i=0) {
$GLOBALS['comment'] = $comment;
$PostAuthor = false;
if($comment->comment_author_email == get_the_author_email()){
$PostAuthor = true;
}elseif($comment->comment_author_email == '[email protected]'){
$PostAuthor = true;
}
?>
<div class="panel panel-default entry" id="comment-<?php echo $comment->comment_ID; ?>">
<div class="panel-body">
<div itemprop="text"> </div>
</div>
<div class="panel-footer clearfix">
<?php comment_text(); ?>
</div>
</div>
<?php
}
``` | The `end-callback` of `wp_list_comments()`
------------------------------------------
One way is to use the `end-callback` argument in:
```
wp_list_comments( [
'end-callback' => 'wpse_comments_ads_injection',
... other arguments ...
], $comments );
```
in addtion to your other `wp_list_comments` arguments, by defining:
```
function wpse_comments_ads_injection( $comment, $args, $depth ) {
static $instance = 0;
$tag = ( 'div' == $args['style'] ) ? 'div' : 'li';
echo "</{$tag}><!-- #comment-## -->\n";
if ( 0 === $instance % 2 ) {
echo "<{$tag} class=\"comment__ad\">YOUR AD HERE!</{$tag}>";
}
$instance++;
}
```
where we do the counting with the static variable `$instance` that's incremented for each call.
This should inject the defined comment ads, using either `div` or `li` tags, depending on the styling.
By using the end-callback, we don't need to modify the comment callback, if we don't need to, just to inject the ads. So if we need the default comment layout, we can also inject the ads this way.
One could additionally use the comment `depth` to control the ads display.
Note that the callback for both the `callback` and `end-callback` of `wp_list_comments()`, has three input arguments, not four.
The `wp_list_comments_args` filter
----------------------------------
We can then adjust it further and use the `wp_list_comments_args` filter:
```
add_filter( 'wp_list_comments_args', function( $args ) {
if ( ! isset( $args['end-callback'] ) ) {
$args['end-callback'] = 'wpse_comments_ads_injection';
}
return $args;
} );
```
instead of modifying the the `wp_list_comments()` directly.
We can create a plugin for this or add this into the `functions.php` file in the current theme's directory.
Introducing injection's offset, rate and html
---------------------------------------------
Then we can add a support for the injection's *rate*, *offset* and *html*:
```
add_filter( 'wp_list_comments_args', function( $args ) {
if ( ! isset( $args['end-callback'] ) ) {
// Modify this to your needs!
$args['end-callback'] = 'wpse_comments_ads_injection';
$args['_ads_offset'] = 0; // Start injecting after the 1st comment.
$args['_ads_rate'] = 2; // Inject after every second comment.
$args['_ads_html'] = '<img src="http://placekitten.com/g/500/100" />';
}
return $args;
} );
```
where we adjust the end-callback with:
```
/**
* Inject Ads To WordPress Comments - end-callback for wp_list_comments().
*
* The Ads HTML is sanitized through wp_kses_post().
*
* @version 1.0.11
* @see https://wordpress.stackexchange.com/a/328155/26350
*/
function wpse_comments_ads_injection( $comment, $args, $depth ) {
static $instance = 0;
$tag = ( 'div' == $args['style'] ) ? 'div' : 'li';
$ads_rate = isset( $args['_ads_rate' ] ) && $args['_ads_rate' ] > 0
? (int) $args['_ads_rate' ]
: 2;
$ads_offset = isset( $args['_ads_offset' ] ) && $args['_ads_offset' ] > 0
? (int) $args['_ads_offset' ]
: 0;
$ads_html = isset( $args['_ads_html' ] )
? wp_kses_post( $args['_ads_html' ] )
: '';
echo "</{$tag}><!-- #comment-## -->\n";
if ( $ads_offset <= $instance && 0 === ( $instance - $ads_offset ) % $ads_rate && ! empty( $ads_html ) ) {
echo "<{$tag} class=\"comment__ad\">{$ads_html}</{$tag}>";
}
$instance++;
}
```
Here's a [gist](https://gist.github.com/birgire/493f0d646491532e0ed5b0c5549f1a12) for the code to add into the `functions.php` file in the current themes directory.
This is untested, but I hope you can adjust this to your needs! |
328,176 | <p>I have registered a custom post type using <code>register_post_type('myposttype', ...)</code>. On published posts, there is a custom class that gets applied to the whole body of the page, <code>single-myposttype</code>. I apply css rules using this body class to make the post appear differently from non-custom post types posts. </p>
<p>Now that the Gutenberg editor is such a key part of Wordpress, I would like to be able to add a custom body class to the editor when working on these custom post types, so that the same style rules that apply to the published post are applied during editing.</p>
<p>I have seen some answered questions (e.g. <a href="https://wordpress.stackexchange.com/questions/304009/gutenberg-extend-blocks-add-new-class-name">this one</a>) which use javascript, however if I understand correctly they would apply to the editor for <em>all</em> posts and pages, not just custom post types.</p>
| [
{
"answer_id": 328229,
"author": "mtthias",
"author_id": 160740,
"author_profile": "https://wordpress.stackexchange.com/users/160740",
"pm_score": 4,
"selected": true,
"text": "<p>This hook should add a single-[post_type] class to the body of the editor page.</p>\n\n<pre><code>add_filter('admin_body_class', function ($classes) { \n //get current page\n global $pagenow;\n\n //check if the current page is post.php and if the post parameteris set\n if ( $pagenow ==='post.php' && isset($_GET['post']) ) {\n //get the post type via the post id from the URL\n $postType = get_post_type( $_GET['post']);\n //append the new class\n $classes .= 'single-' . $postType;\n } \n //next check if this is a new post\n elseif ( $pagenow ==='post-new.php' ) {\n //check if the post_type parameter is set\n if(isset($_GET['post_type'])) {\n //in this case you can get the post_type directly from the URL\n $classes .= 'single-' . urldecode($_GET['post_type']);\n } else {\n //if post_type is not set, a 'post' is being created\n $classes .= 'single-post';\n }\n\n\n }\n return $classes;\n}); \n</code></pre>\n"
},
{
"answer_id": 328309,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 1,
"selected": false,
"text": "<p>We can use the <em>current screen object</em> to add the <code>single-{post_type}</code> to the <em>admin body class</em> of it's block editor page:</p>\n\n<pre><code>add_filter( 'admin_body_class', function ( $classes ) {\n $screen = get_current_screen();\n return $screen->is_block_editor() && $screen->post_type\n ? $classes . ' single-' . $screen->post_type\n : $classes;\n} );\n</code></pre>\n\n<p>... but ... for <a href=\"https://wordpress.org/gutenberg/handbook/designers-developers/developers/themes/theme-support/\" rel=\"nofollow noreferrer\">editor styles</a>:</p>\n\n<pre><code>add_theme_support( 'editor-styles' );\nadd_editor_style( 'style-editor.css' );\n</code></pre>\n\n<p>the CSS there will be auto prefixed with the <code>.editor-styles-wrapper</code> class selector. Also all <code>body</code> selectors there are replaced with <code>.editor-styles-wrapper</code>. I guess this is to have the editor styles backward compatible, as it was previously loaded within an iframe without any prefixing as mentioned in the <a href=\"https://wordpress.org/gutenberg/handbook/designers-developers/developers/themes/theme-support/#editor-styles\" rel=\"nofollow noreferrer\">handbook</a>.</p>\n\n<p>It's also possible to use the <code>enqueue_block_assets</code> to load a stylesheet on both the editor admin page and the frontend, but if we don't use specific CSS selectors it can mess up the whole admin editor layout. So I would think this would be best used to target specific blocks, rather than generic layout adjustments.</p>\n"
}
] | 2019/02/09 | [
"https://wordpress.stackexchange.com/questions/328176",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/34991/"
] | I have registered a custom post type using `register_post_type('myposttype', ...)`. On published posts, there is a custom class that gets applied to the whole body of the page, `single-myposttype`. I apply css rules using this body class to make the post appear differently from non-custom post types posts.
Now that the Gutenberg editor is such a key part of Wordpress, I would like to be able to add a custom body class to the editor when working on these custom post types, so that the same style rules that apply to the published post are applied during editing.
I have seen some answered questions (e.g. [this one](https://wordpress.stackexchange.com/questions/304009/gutenberg-extend-blocks-add-new-class-name)) which use javascript, however if I understand correctly they would apply to the editor for *all* posts and pages, not just custom post types. | This hook should add a single-[post\_type] class to the body of the editor page.
```
add_filter('admin_body_class', function ($classes) {
//get current page
global $pagenow;
//check if the current page is post.php and if the post parameteris set
if ( $pagenow ==='post.php' && isset($_GET['post']) ) {
//get the post type via the post id from the URL
$postType = get_post_type( $_GET['post']);
//append the new class
$classes .= 'single-' . $postType;
}
//next check if this is a new post
elseif ( $pagenow ==='post-new.php' ) {
//check if the post_type parameter is set
if(isset($_GET['post_type'])) {
//in this case you can get the post_type directly from the URL
$classes .= 'single-' . urldecode($_GET['post_type']);
} else {
//if post_type is not set, a 'post' is being created
$classes .= 'single-post';
}
}
return $classes;
});
``` |
328,194 | <p>I have problem to display custom taxonomy under custom admin menu. Custom post types are displayed properly, but the taxonomy doesn't appear.</p>
<p>I added to custom post types: <strong>'show_in_menu' => 'my-menu'</strong></p>
<p><strong>My Custom Menu</strong></p>
<ul>
<li><strong>Custom Post Type 1</strong></li>
<li><strong>Custom Post Type 2</strong></li>
<li><strong>Custom Post Type 3</strong></li>
<li><strong>Custom Taxonomy that can be used by Post Type 1/2/3</strong></li>
</ul>
<p>What i need to do to display custom taxonomy?</p>
<p><strong>UPDATE</strong></p>
<p>Here's my code:</p>
<pre><code>function create_custom_admin_menu() {
add_menu_page(
'My Menu',
'My Menu',
'read',
'my-menu',
'',
'dashicons-admin-page',
10
);
}
add_action( 'admin_menu', 'create_custom_admin_menu' );
function create_custom_post_type_1() {
$labels = array(
'name' => _x( 'Custom Post 1' ),
'singular_name' => _x( 'Custom Post 1' ),
'menu_name' => __( 'Custom Post 1' ),
);
register_post_type( 'custom-post-type-1', array(
'labels' => $labels,
'has_archive' => false,
'public' => true,
'show_in_menu' => 'my-menu',
'supports' => array( 'title', 'editor', 'auther', 'excerpt', 'custom-fields', 'thumbnail','comments' ),
'taxonomies' => array( 'custom-taxonomy' ),
'exclude_from_search' => false,
'capability_type' => 'post',
)
);
}
add_action( 'init', 'create_custom_post_type_1' );
function register_custom_taxonomy() {
$labels = array(
'name' => _x( 'Custom Taxonomy'),
'singular_name' => _x( 'Custom Taxonomy' ),
'menu_name' => __( 'Custom Taxonomy' ),
);
register_taxonomy( 'custom-taxonomy', 'my-menu', array(
'hierarchical' => true,
'labels' => $labels,
'query_var' => true,
'show_admin_column' => true
) );
}
add_action( 'init', 'register_custom_taxonomy' );
</code></pre>
<p><strong>UPDATE 2</strong></p>
<p>I tried it all and nothing works:</p>
<pre><code>register_taxonomy( 'custom-taxonomy', 'my-menu', [...]
register_taxonomy( 'custom-taxonomy', 'custom-post-type-1', [...]
register_taxonomy( 'custom-taxonomy', array('custom-post-type-1', 'custom-post-type-2', 'custom-post-type-3' ), [...]
</code></pre>
| [
{
"answer_id": 328198,
"author": "Md. Ehsanul Haque Kanan",
"author_id": 75705,
"author_profile": "https://wordpress.stackexchange.com/users/75705",
"pm_score": -1,
"selected": false,
"text": "<p>I think that there is an issue with your plugins. That's why, custom taxonomy is not showing up. </p>\n\n<p>Turn off all the plugins. Then enable them one at a time. In this way, you can find the defective one. You have to remove it and use an alternate option. </p>\n"
},
{
"answer_id": 328201,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>You haven't properly registered the taxonomy for your post type. You register your post type like this:</p>\n\n<pre><code>register_post_type( 'custom-post-type-1',\n</code></pre>\n\n<p>Meaning that your post type is named <code>custom-post-type-1</code>. But when you register the taxonomy, you're registering it for a post type called <code>my-menu</code>\"</p>\n\n<pre><code>register_taxonomy( 'custom-taxonomy', 'my-menu',\n</code></pre>\n\n<p>You need to register your taxonomy for your post type:</p>\n\n<pre><code>register_taxonomy( 'custom-taxonomy', 'custom-post-type-1',\n</code></pre>\n"
}
] | 2019/02/09 | [
"https://wordpress.stackexchange.com/questions/328194",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/138812/"
] | I have problem to display custom taxonomy under custom admin menu. Custom post types are displayed properly, but the taxonomy doesn't appear.
I added to custom post types: **'show\_in\_menu' => 'my-menu'**
**My Custom Menu**
* **Custom Post Type 1**
* **Custom Post Type 2**
* **Custom Post Type 3**
* **Custom Taxonomy that can be used by Post Type 1/2/3**
What i need to do to display custom taxonomy?
**UPDATE**
Here's my code:
```
function create_custom_admin_menu() {
add_menu_page(
'My Menu',
'My Menu',
'read',
'my-menu',
'',
'dashicons-admin-page',
10
);
}
add_action( 'admin_menu', 'create_custom_admin_menu' );
function create_custom_post_type_1() {
$labels = array(
'name' => _x( 'Custom Post 1' ),
'singular_name' => _x( 'Custom Post 1' ),
'menu_name' => __( 'Custom Post 1' ),
);
register_post_type( 'custom-post-type-1', array(
'labels' => $labels,
'has_archive' => false,
'public' => true,
'show_in_menu' => 'my-menu',
'supports' => array( 'title', 'editor', 'auther', 'excerpt', 'custom-fields', 'thumbnail','comments' ),
'taxonomies' => array( 'custom-taxonomy' ),
'exclude_from_search' => false,
'capability_type' => 'post',
)
);
}
add_action( 'init', 'create_custom_post_type_1' );
function register_custom_taxonomy() {
$labels = array(
'name' => _x( 'Custom Taxonomy'),
'singular_name' => _x( 'Custom Taxonomy' ),
'menu_name' => __( 'Custom Taxonomy' ),
);
register_taxonomy( 'custom-taxonomy', 'my-menu', array(
'hierarchical' => true,
'labels' => $labels,
'query_var' => true,
'show_admin_column' => true
) );
}
add_action( 'init', 'register_custom_taxonomy' );
```
**UPDATE 2**
I tried it all and nothing works:
```
register_taxonomy( 'custom-taxonomy', 'my-menu', [...]
register_taxonomy( 'custom-taxonomy', 'custom-post-type-1', [...]
register_taxonomy( 'custom-taxonomy', array('custom-post-type-1', 'custom-post-type-2', 'custom-post-type-3' ), [...]
``` | You haven't properly registered the taxonomy for your post type. You register your post type like this:
```
register_post_type( 'custom-post-type-1',
```
Meaning that your post type is named `custom-post-type-1`. But when you register the taxonomy, you're registering it for a post type called `my-menu`"
```
register_taxonomy( 'custom-taxonomy', 'my-menu',
```
You need to register your taxonomy for your post type:
```
register_taxonomy( 'custom-taxonomy', 'custom-post-type-1',
``` |
328,195 | <p>Since Wordpress 5.x they've removed the thumbnail size option for galleries. Is there a way to activate or build a workaround? I like to build up a classic Lightbox gallery. </p>
<p><a href="https://i.stack.imgur.com/rpbXa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rpbXa.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 328199,
"author": "Md. Ehsanul Haque Kanan",
"author_id": 75705,
"author_profile": "https://wordpress.stackexchange.com/users/75705",
"pm_score": 2,
"selected": false,
"text": "<p>There is a project going on about the image sizes. You can follow it <a href=\"https://github.com/WordPress/gutenberg/issues/6177\" rel=\"nofollow noreferrer\">right here</a>.</p>\n\n<p>Right now, you can try using <strong>shortcode_atts_gallery</strong> filter. Take a look at these codes to get a hint: </p>\n\n<pre><code>/* Register shortcode_atts_gallery filter callback */\nadd_filter( 'shortcode_atts_gallery', 'meks_gallery_atts', 10, 3 );\n\n/* Change attributes of wp gallery to modify image sizes for your needs */\nfunction meks_gallery_atts( $output, $pairs, $atts ) {\n\n/* You can use these sizes:\n- thumbnail\n- medium\n- large\n- full\nor, if your theme/plugin generate additional custom sizes you can use them as well\n*/\n\n$output['size'] = 'medium'; //i.e. This will change all your gallery images to \"medium\" size\n\nreturn $output;\n\n}\n</code></pre>\n\n<p>You can find more information about <strong>shortcode_atts_gallery</strong> <a href=\"https://mekshq.com/change-image-thumbnail-size-in-wordpress-gallery/\" rel=\"nofollow noreferrer\">right here</a>. </p>\n"
},
{
"answer_id": 328200,
"author": "tmdesigned",
"author_id": 28273,
"author_profile": "https://wordpress.stackexchange.com/users/28273",
"pm_score": 1,
"selected": false,
"text": "<p>It's an ongoing process. Right now there is not a way to adjust manually the image sizes on the gallery block. It is being discussed by the WordPress core development community on <a href=\"https://github.com/WordPress/gutenberg/issues/6177\" rel=\"nofollow noreferrer\">this github issue</a>.</p>\n\n<p>Just because the default gutenberg gallery block does not allow you to do it does not mean you cannot install a 3rd party plugin, create a custom block yourself (I recommend using ACF Custom Blocks), or reverting to the classic editor for this specific use.</p>\n"
}
] | 2019/02/09 | [
"https://wordpress.stackexchange.com/questions/328195",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/141935/"
] | Since Wordpress 5.x they've removed the thumbnail size option for galleries. Is there a way to activate or build a workaround? I like to build up a classic Lightbox gallery.
[](https://i.stack.imgur.com/rpbXa.png) | There is a project going on about the image sizes. You can follow it [right here](https://github.com/WordPress/gutenberg/issues/6177).
Right now, you can try using **shortcode\_atts\_gallery** filter. Take a look at these codes to get a hint:
```
/* Register shortcode_atts_gallery filter callback */
add_filter( 'shortcode_atts_gallery', 'meks_gallery_atts', 10, 3 );
/* Change attributes of wp gallery to modify image sizes for your needs */
function meks_gallery_atts( $output, $pairs, $atts ) {
/* You can use these sizes:
- thumbnail
- medium
- large
- full
or, if your theme/plugin generate additional custom sizes you can use them as well
*/
$output['size'] = 'medium'; //i.e. This will change all your gallery images to "medium" size
return $output;
}
```
You can find more information about **shortcode\_atts\_gallery** [right here](https://mekshq.com/change-image-thumbnail-size-in-wordpress-gallery/). |
328,219 | <p>If I make a theme and add hard-coded text using <code>_e()</code>, <code>__()</code>, <code>esc_attr()</code> and so on. Could I do this in polish (or whichever language) and then add English translation po/mo files with the other languages I want to include or is this backwards and bad practice?</p>
| [
{
"answer_id": 328199,
"author": "Md. Ehsanul Haque Kanan",
"author_id": 75705,
"author_profile": "https://wordpress.stackexchange.com/users/75705",
"pm_score": 2,
"selected": false,
"text": "<p>There is a project going on about the image sizes. You can follow it <a href=\"https://github.com/WordPress/gutenberg/issues/6177\" rel=\"nofollow noreferrer\">right here</a>.</p>\n\n<p>Right now, you can try using <strong>shortcode_atts_gallery</strong> filter. Take a look at these codes to get a hint: </p>\n\n<pre><code>/* Register shortcode_atts_gallery filter callback */\nadd_filter( 'shortcode_atts_gallery', 'meks_gallery_atts', 10, 3 );\n\n/* Change attributes of wp gallery to modify image sizes for your needs */\nfunction meks_gallery_atts( $output, $pairs, $atts ) {\n\n/* You can use these sizes:\n- thumbnail\n- medium\n- large\n- full\nor, if your theme/plugin generate additional custom sizes you can use them as well\n*/\n\n$output['size'] = 'medium'; //i.e. This will change all your gallery images to \"medium\" size\n\nreturn $output;\n\n}\n</code></pre>\n\n<p>You can find more information about <strong>shortcode_atts_gallery</strong> <a href=\"https://mekshq.com/change-image-thumbnail-size-in-wordpress-gallery/\" rel=\"nofollow noreferrer\">right here</a>. </p>\n"
},
{
"answer_id": 328200,
"author": "tmdesigned",
"author_id": 28273,
"author_profile": "https://wordpress.stackexchange.com/users/28273",
"pm_score": 1,
"selected": false,
"text": "<p>It's an ongoing process. Right now there is not a way to adjust manually the image sizes on the gallery block. It is being discussed by the WordPress core development community on <a href=\"https://github.com/WordPress/gutenberg/issues/6177\" rel=\"nofollow noreferrer\">this github issue</a>.</p>\n\n<p>Just because the default gutenberg gallery block does not allow you to do it does not mean you cannot install a 3rd party plugin, create a custom block yourself (I recommend using ACF Custom Blocks), or reverting to the classic editor for this specific use.</p>\n"
}
] | 2019/02/09 | [
"https://wordpress.stackexchange.com/questions/328219",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/158034/"
] | If I make a theme and add hard-coded text using `_e()`, `__()`, `esc_attr()` and so on. Could I do this in polish (or whichever language) and then add English translation po/mo files with the other languages I want to include or is this backwards and bad practice? | There is a project going on about the image sizes. You can follow it [right here](https://github.com/WordPress/gutenberg/issues/6177).
Right now, you can try using **shortcode\_atts\_gallery** filter. Take a look at these codes to get a hint:
```
/* Register shortcode_atts_gallery filter callback */
add_filter( 'shortcode_atts_gallery', 'meks_gallery_atts', 10, 3 );
/* Change attributes of wp gallery to modify image sizes for your needs */
function meks_gallery_atts( $output, $pairs, $atts ) {
/* You can use these sizes:
- thumbnail
- medium
- large
- full
or, if your theme/plugin generate additional custom sizes you can use them as well
*/
$output['size'] = 'medium'; //i.e. This will change all your gallery images to "medium" size
return $output;
}
```
You can find more information about **shortcode\_atts\_gallery** [right here](https://mekshq.com/change-image-thumbnail-size-in-wordpress-gallery/). |
328,249 | <p>I found the API reference here: <a href="https://v2.wp-api.org/reference/posts/" rel="nofollow noreferrer">https://v2.wp-api.org/reference/posts/</a></p>
<p>Based on the API reference above, I wrote this Python code:</p>
<pre><code>from urllib.request import Request, urlopen
from datetime import datetime
import json
def create(wordpressUrl, content):
params = {
'date_gmt': datetime.now().replace(microsecond=0).isoformat() + "Z",
'status': 'publish',
'title': 'The Title',
'author': 'The Author',
'content': content
}
postparam = json.dumps(params).encode('utf-8')
req = Request(wordpressUrl + "/wp-json/wp/v2/posts", method='POST', data=postparam)
req.add_header('Content-Type', 'application/json')
r = urlopen(req)
if(r.getcode() != 200):
raise Exception("failed with rc=" + r.getcode())
return json.loads(r.read())
</code></pre>
<p>Why when calling this code, the WP API just returns the site's About page, and does not create a new Post? How else can I create a Post inside of Wordpress, using Python to call the WP API?</p>
| [
{
"answer_id": 328269,
"author": "prathamesh patil",
"author_id": 160954,
"author_profile": "https://wordpress.stackexchange.com/users/160954",
"pm_score": 0,
"selected": false,
"text": "<p>I think you are missing out on the authentication part , check this <a href=\"https://stackoverflow.com/questions/41532738/publish-wordpress-post-with-python-requests-and-rest-api\">https://stackoverflow.com/questions/41532738/publish-wordpress-post-with-python-requests-and-rest-api</a></p>\n"
},
{
"answer_id": 380831,
"author": "crifan",
"author_id": 199778,
"author_profile": "https://wordpress.stackexchange.com/users/199778",
"pm_score": 3,
"selected": true,
"text": "<p>as <code>@prathamesh patil</code> say, you missed the <code>authentication</code> = <code>your jwt token</code></p>\n<h3>how to generate <code>jwt token</code> ?</h3>\n<ul>\n<li>simple = core logic\n<ul>\n<li>install and enable WordPress plugin: <a href=\"https://wordpress.org/plugins/jwt-authentication-for-wp-rest-api/\" rel=\"nofollow noreferrer\">JWT Authentication for WP REST API</a></li>\n<li>wordpress server enable <code>HTTP:Authorization</code>\n<ul>\n<li>purpose: allow to call <code>/wp-json/jwt-auth/v1</code> api</li>\n</ul>\n</li>\n<li>add <code>JWT_AUTH_SECRET_KEY</code> into <code>wp-config.php</code></li>\n<li>call <code>POST https://www.yourWebsite.com/wp-json/jwt-auth/v1/token</code> with wordpress <code>username</code> and <code>password</code>, response contain your expected <strong>jwt token</strong>\n<ul>\n<li>look like: <code>eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvd3d3LmNyaWZhbi5jb20iLCJpYXQiOjE1ODQxMDk4OTAsIm5iZiI6MTU4NDEwOTg5MCwiZXhwIjoxNTg0NzE0NjkwLCJkYXRhIjp7InVzZXIiOnsiaWQiOiIxIn19fQ.YvFzitTfIZaCwtkxKTIjP715795OMAVQowgnD8G3wk0</code></li>\n</ul>\n</li>\n</ul>\n</li>\n<li>detail\n<ul>\n<li>please refer my answer for another post:\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/41532738/publish-wordpress-post-with-python-requests-and-rest-api/65547860#65547860\">Publish WordPress Post with Python Requests and REST API - Stack Overflow</a></li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n<h2>python code to call wordpress REST api to create posts</h2>\n<p>code:</p>\n<pre class=\"lang-python prettyprint-override\"><code> def createPost(self,\n title,\n content,\n dateStr,\n slug,\n categoryNameList=[],\n tagNameList=[],\n status="draft",\n postFormat="standard"\n ):\n """Create wordpress standard post\n by call REST api: POST /wp-json/wp/v2/posts\n\n Args:\n title (str): post title\n content (str): post content of html\n dateStr (str): date string\n slug (str): post slug url\n categoryNameList (list): category name list\n tagNameList (list): tag name list\n status (str): status, default to 'draft'\n postFormat (str): post format, default to 'standard'\n Returns:\n (bool, dict)\n True, uploaded post info\n False, error detail\n Raises:\n """\n curHeaders = {\n "Authorization": self.authorization,\n "Content-Type": "application/json",\n "Accept": "application/json",\n }\n logging.debug("curHeaders=%s", curHeaders)\n\n categoryIdList = []\n tagIdList = []\n\n if categoryNameList:\n # ['Mac']\n categoryIdList = self.getTaxonomyIdList(categoryNameList, taxonomy="category")\n # category nameList=['Mac'] -> taxonomyIdList=[1374]\n\n if tagNameList:\n # ['切换', 'GPU', 'pmset', '显卡模式']\n tagIdList = self.getTaxonomyIdList(tagNameList, taxonomy="post_tag")\n # post_tag nameList=['切换', 'GPU', 'pmset', '显卡模式'] -> taxonomyIdList=[1367, 13224, 13225, 13226]\n\n postDict = {\n "title": title, # '【记录】Mac中用pmset设置GPU显卡切换模式'\n "content": content, # '<html>\\n <div>\\n 折腾:\\n </div>\\n <div>\\n 【已解决】Mac Pro 2018款发热量大很烫非常烫\\n </div>\\n <div>\\n 期间,...performance graphic cards\\n </li>\\n </ul>\\n </ul>\\n </ul>\\n <div>\\n <br/>\\n </div>\\n</html>'\n # "date_gmt": dateStr,\n "date": dateStr, # '2020-08-17T10:16:34'\n "slug": slug, # 'on_mac_pmset_is_used_set_gpu_graphics_card_switching_mode'\n "status": status, # 'draft'\n "format": postFormat, # 'standard'\n "categories": categoryIdList, # [1374]\n "tags": tagIdList, # [1367, 13224, 13225, 13226]\n # TODO: featured_media, excerpt\n }\n logging.debug("postDict=%s", postDict)\n # postDict={'title': '【记录】Mac中用pmset设置GPU显卡切换模式', 'content': '<html>\\n <div>\\n 折腾:\\n </div>\\n <div>\\。。。。<br/>\\n </div>\\n</html>', 'date': '2020-08-17T10:16:34', 'slug': 'on_mac_pmset_is_used_set_gpu_graphics_card_switching_mode', 'status': 'draft', 'format': 'standard', 'categories': [1374], 'tags': [1367, 13224, 13225, 13226]}\n createPostUrl = self.apiPosts\n resp = requests.post(\n createPostUrl,\n proxies=self.requestsProxies,\n headers=curHeaders,\n # data=json.dumps(postDict),\n json=postDict, # internal auto do json.dumps\n )\n logging.info("createPostUrl=%s -> resp=%s", createPostUrl, resp)\n\n isUploadOk, respInfo = crifanWordpress.processCommonResponse(resp)\n return isUploadOk, respInfo\n</code></pre>\n<ul>\n<li>full & latest code please refer:\n<ul>\n<li><code>createPost</code> in <a href=\"https://github.com/crifan/crifanLibPython/blob/master/python3/crifanLib/thirdParty/crifanWordpress.py\" rel=\"nofollow noreferrer\">crifanWordpress.py</a></li>\n</ul>\n</li>\n</ul>\n"
}
] | 2019/02/10 | [
"https://wordpress.stackexchange.com/questions/328249",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145576/"
] | I found the API reference here: <https://v2.wp-api.org/reference/posts/>
Based on the API reference above, I wrote this Python code:
```
from urllib.request import Request, urlopen
from datetime import datetime
import json
def create(wordpressUrl, content):
params = {
'date_gmt': datetime.now().replace(microsecond=0).isoformat() + "Z",
'status': 'publish',
'title': 'The Title',
'author': 'The Author',
'content': content
}
postparam = json.dumps(params).encode('utf-8')
req = Request(wordpressUrl + "/wp-json/wp/v2/posts", method='POST', data=postparam)
req.add_header('Content-Type', 'application/json')
r = urlopen(req)
if(r.getcode() != 200):
raise Exception("failed with rc=" + r.getcode())
return json.loads(r.read())
```
Why when calling this code, the WP API just returns the site's About page, and does not create a new Post? How else can I create a Post inside of Wordpress, using Python to call the WP API? | as `@prathamesh patil` say, you missed the `authentication` = `your jwt token`
### how to generate `jwt token` ?
* simple = core logic
+ install and enable WordPress plugin: [JWT Authentication for WP REST API](https://wordpress.org/plugins/jwt-authentication-for-wp-rest-api/)
+ wordpress server enable `HTTP:Authorization`
- purpose: allow to call `/wp-json/jwt-auth/v1` api
+ add `JWT_AUTH_SECRET_KEY` into `wp-config.php`
+ call `POST https://www.yourWebsite.com/wp-json/jwt-auth/v1/token` with wordpress `username` and `password`, response contain your expected **jwt token**
- look like: `eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvd3d3LmNyaWZhbi5jb20iLCJpYXQiOjE1ODQxMDk4OTAsIm5iZiI6MTU4NDEwOTg5MCwiZXhwIjoxNTg0NzE0NjkwLCJkYXRhIjp7InVzZXIiOnsiaWQiOiIxIn19fQ.YvFzitTfIZaCwtkxKTIjP715795OMAVQowgnD8G3wk0`
* detail
+ please refer my answer for another post:
- [Publish WordPress Post with Python Requests and REST API - Stack Overflow](https://stackoverflow.com/questions/41532738/publish-wordpress-post-with-python-requests-and-rest-api/65547860#65547860)
python code to call wordpress REST api to create posts
------------------------------------------------------
code:
```python
def createPost(self,
title,
content,
dateStr,
slug,
categoryNameList=[],
tagNameList=[],
status="draft",
postFormat="standard"
):
"""Create wordpress standard post
by call REST api: POST /wp-json/wp/v2/posts
Args:
title (str): post title
content (str): post content of html
dateStr (str): date string
slug (str): post slug url
categoryNameList (list): category name list
tagNameList (list): tag name list
status (str): status, default to 'draft'
postFormat (str): post format, default to 'standard'
Returns:
(bool, dict)
True, uploaded post info
False, error detail
Raises:
"""
curHeaders = {
"Authorization": self.authorization,
"Content-Type": "application/json",
"Accept": "application/json",
}
logging.debug("curHeaders=%s", curHeaders)
categoryIdList = []
tagIdList = []
if categoryNameList:
# ['Mac']
categoryIdList = self.getTaxonomyIdList(categoryNameList, taxonomy="category")
# category nameList=['Mac'] -> taxonomyIdList=[1374]
if tagNameList:
# ['切换', 'GPU', 'pmset', '显卡模式']
tagIdList = self.getTaxonomyIdList(tagNameList, taxonomy="post_tag")
# post_tag nameList=['切换', 'GPU', 'pmset', '显卡模式'] -> taxonomyIdList=[1367, 13224, 13225, 13226]
postDict = {
"title": title, # '【记录】Mac中用pmset设置GPU显卡切换模式'
"content": content, # '<html>\n <div>\n 折腾:\n </div>\n <div>\n 【已解决】Mac Pro 2018款发热量大很烫非常烫\n </div>\n <div>\n 期间,...performance graphic cards\n </li>\n </ul>\n </ul>\n </ul>\n <div>\n <br/>\n </div>\n</html>'
# "date_gmt": dateStr,
"date": dateStr, # '2020-08-17T10:16:34'
"slug": slug, # 'on_mac_pmset_is_used_set_gpu_graphics_card_switching_mode'
"status": status, # 'draft'
"format": postFormat, # 'standard'
"categories": categoryIdList, # [1374]
"tags": tagIdList, # [1367, 13224, 13225, 13226]
# TODO: featured_media, excerpt
}
logging.debug("postDict=%s", postDict)
# postDict={'title': '【记录】Mac中用pmset设置GPU显卡切换模式', 'content': '<html>\n <div>\n 折腾:\n </div>\n <div>\。。。。<br/>\n </div>\n</html>', 'date': '2020-08-17T10:16:34', 'slug': 'on_mac_pmset_is_used_set_gpu_graphics_card_switching_mode', 'status': 'draft', 'format': 'standard', 'categories': [1374], 'tags': [1367, 13224, 13225, 13226]}
createPostUrl = self.apiPosts
resp = requests.post(
createPostUrl,
proxies=self.requestsProxies,
headers=curHeaders,
# data=json.dumps(postDict),
json=postDict, # internal auto do json.dumps
)
logging.info("createPostUrl=%s -> resp=%s", createPostUrl, resp)
isUploadOk, respInfo = crifanWordpress.processCommonResponse(resp)
return isUploadOk, respInfo
```
* full & latest code please refer:
+ `createPost` in [crifanWordpress.py](https://github.com/crifan/crifanLibPython/blob/master/python3/crifanLib/thirdParty/crifanWordpress.py) |
328,256 | <p>I wrote a simple plugin which creates a post type named <strong>cryptoevent</strong> and also creates a <strong>metabox</strong> that have some custom fields, I display this post type and fields with <strong>WP_Query</strong>, now I want to display them with a load more button, note this is supposed to be a plugin and I don't want user to have to do changes in his/her theme's <strong>function.php</strong>, here is my code, thank u for your help. and I'm a beginner, by the way, please help me in a simple language.</p>
<pre><code>function cryptoevent_addform( $atts ) {
$args = array( 'post_type' =>'cryptoevent','posts_per_page'=>8);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
echo '<div style="padding:0 15%;"><h2>';
the_title(); ?>
<p><?php echo get_post_meta( get_the_ID(), 'date_add', true ); ?></p>
<p><?php echo get_post_meta( get_the_ID(), 'date_expiration', true ); ?></p>
<?php
echo '</h2></div>';
endwhile;
wp_reset_query();
}
add_shortcode( 'cryptoevent', 'cryptoevent_addform' );
</code></pre>
| [
{
"answer_id": 328274,
"author": "tmdesigned",
"author_id": 28273,
"author_profile": "https://wordpress.stackexchange.com/users/28273",
"pm_score": 1,
"selected": false,
"text": "<p>If you want it to work like a true \"load more\" button, then you are going to have to let the posts load in groups without the user changing pages. This means you have to use an AJAX method. This is much more complicated than the WordPress loop you have right now.</p>\n\n<p>Overall it works like this, with your code split into 2 parts:</p>\n\n<p><strong>A. Code that displays results</strong></p>\n\n<ol>\n<li>Request up to 10 results via AJAX (or another number)</li>\n<li>When they load, show them on the screen.</li>\n<li>If there are more results available, show a \"load more\" button</li>\n<li>If the user hits load more, go back to step 1</li>\n</ol>\n\n<p><strong>B. Code that fetches results</strong></p>\n\n<ol>\n<li>Look at which results were requested (which page)</li>\n<li>Echo out the results </li>\n</ol>\n\n<p>So your code that does <strong>A.</strong> above and your code that does <strong>B.</strong> above live in different places. </p>\n\n<p>The <strong>A</strong> code is more or less what you have in the cryptoevent_addform function you wrote. It would be very different from what you have, but basically that is handling the <em>front-end</em>. The main difference is instead of getting the posts via WP_QUERY and PHP, it would be getting them via a JavaScript AJAX request, through the the WordPress AJAX system, to your <strong>B</strong> code.</p>\n\n<p>The <strong>B</strong> code handles the <em>back-end</em>. It can also live in your plugin, but would need to be registered through the WordPress AJAX API.</p>\n\n<p>Why do we have to do this? The normal flow of a page is (1) Backend (PHP/mySQL/etc), then (2) Frontend (HTML/JavaScript/etc.). But here we have to flip the order. You are letting a user (front-end) fetch posts from your database (back-end), without them having to reload a page. So to flip the order, we have to separate your code into the 2 parts and then use AJAX to start the page flow over.</p>\n\n<p>You'll want to look at how to structure a WordPress AJAX call, which is more than we can cover in a Stack Exchange answer. <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">See the documentation.</a></p>\n"
},
{
"answer_id": 328479,
"author": "hessam hosseinipour",
"author_id": 160944,
"author_profile": "https://wordpress.stackexchange.com/users/160944",
"pm_score": 0,
"selected": false,
"text": "<p>i used paginate instead, and use the code below</p>\n\n<pre><code>$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;\n$data= new WP_Query(array(\n'post_type'=>'cryptoevent', // your post type name\n'posts_per_page' => 3, // post per page\n'paged' => $paged,\n ));\nif($data->have_posts()) :\nwhile($data->have_posts()) : $data->the_post();\nthe_title(); \nphp\nendwhile;\n?><br><?php\n$total_pages = $data->max_num_pages;\nif ($total_pages > 1){\n $current_page = max(1, get_query_var('paged'));\n $big = 99999; // need an unlikely integer\n echo paginate_links(array(\n 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),\n 'format' => '/page/%#%',\n 'current' => $current_page,\n 'total' => $total_pages,\n 'prev_text' => __('« prev'),\n 'next_text' => __('next »'),\n ));\n}\n?>\n<?php else :?>\n<h3><?php _e('404 Error&#58; Not Found', ''); ?></h3>\n<?php endif; ?>\n<?php wp_reset_postdata();\n</code></pre>\n\n<p>it works fine if i set <strong>permalinks</strong> on <strong>plain</strong>, but my site permalinks are set on <strong>post name</strong>, please help me, thank you so much.</p>\n"
}
] | 2019/02/10 | [
"https://wordpress.stackexchange.com/questions/328256",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/160944/"
] | I wrote a simple plugin which creates a post type named **cryptoevent** and also creates a **metabox** that have some custom fields, I display this post type and fields with **WP\_Query**, now I want to display them with a load more button, note this is supposed to be a plugin and I don't want user to have to do changes in his/her theme's **function.php**, here is my code, thank u for your help. and I'm a beginner, by the way, please help me in a simple language.
```
function cryptoevent_addform( $atts ) {
$args = array( 'post_type' =>'cryptoevent','posts_per_page'=>8);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
echo '<div style="padding:0 15%;"><h2>';
the_title(); ?>
<p><?php echo get_post_meta( get_the_ID(), 'date_add', true ); ?></p>
<p><?php echo get_post_meta( get_the_ID(), 'date_expiration', true ); ?></p>
<?php
echo '</h2></div>';
endwhile;
wp_reset_query();
}
add_shortcode( 'cryptoevent', 'cryptoevent_addform' );
``` | If you want it to work like a true "load more" button, then you are going to have to let the posts load in groups without the user changing pages. This means you have to use an AJAX method. This is much more complicated than the WordPress loop you have right now.
Overall it works like this, with your code split into 2 parts:
**A. Code that displays results**
1. Request up to 10 results via AJAX (or another number)
2. When they load, show them on the screen.
3. If there are more results available, show a "load more" button
4. If the user hits load more, go back to step 1
**B. Code that fetches results**
1. Look at which results were requested (which page)
2. Echo out the results
So your code that does **A.** above and your code that does **B.** above live in different places.
The **A** code is more or less what you have in the cryptoevent\_addform function you wrote. It would be very different from what you have, but basically that is handling the *front-end*. The main difference is instead of getting the posts via WP\_QUERY and PHP, it would be getting them via a JavaScript AJAX request, through the the WordPress AJAX system, to your **B** code.
The **B** code handles the *back-end*. It can also live in your plugin, but would need to be registered through the WordPress AJAX API.
Why do we have to do this? The normal flow of a page is (1) Backend (PHP/mySQL/etc), then (2) Frontend (HTML/JavaScript/etc.). But here we have to flip the order. You are letting a user (front-end) fetch posts from your database (back-end), without them having to reload a page. So to flip the order, we have to separate your code into the 2 parts and then use AJAX to start the page flow over.
You'll want to look at how to structure a WordPress AJAX call, which is more than we can cover in a Stack Exchange answer. [See the documentation.](https://codex.wordpress.org/AJAX_in_Plugins) |
328,277 | <p>I'm working on a plugin that defined a custom block for the Gutenberg/Block Editor. The block shows a <code>select</code> box of posts. When you select one, I create HTML with some of the selected post's fields, such as title, date, etc.</p>
<p>When I query my posts in the <code>edit</code> method, my code correctly produces a list of pages (in my case, a custom post type named <code>product</code>), but custom fields, which this post type has, are not included.</p>
<pre><code>var pages = select('core').getEntityRecords('postType', 'product', { per_page: -1 });
</code></pre>
<p>I'm trying to find documentation on <code>getEntityRecords</code> query parameters, but there seems to be none. Is it possible to include custom fields in the query? You would think this should be explained on <a href="https://wordpress.org/gutenberg/handbook/designers-developers/developers/data/data-core/#getentityrecords" rel="noreferrer">https://wordpress.org/gutenberg/handbook/designers-developers/developers/data/data-core/#getentityrecords</a></p>
<p>My only other idea was: when the block is saved ("during" the <code>save</code> method), is it possible to do another query that just selects the single post by ID and retrieves its data, maybe including custom fields? It seems I can't query anything during save.</p>
| [
{
"answer_id": 330953,
"author": "Marc Heiduk",
"author_id": 162686,
"author_profile": "https://wordpress.stackexchange.com/users/162686",
"pm_score": 3,
"selected": false,
"text": "<p>Gutenberg documentation is not finished yet, but there are some unreleased commits in the official Gutenberg Repo. This could help: <a href=\"https://github.com/WordPress/gutenberg/blob/b7ad77d15f32ca234ff2f3df4994e47a5cf2e6d7/packages/editor/src/components/page-attributes/README.md\" rel=\"noreferrer\">https://github.com/WordPress/gutenberg/blob/b7ad77d15f32ca234ff2f3df4994e47a5cf2e6d7/packages/editor/src/components/page-attributes/README.md</a></p>\n\n<pre><code>[...]\n var query = {\n per_page: -1,\n exclude: postId,\n parent_exclude: postId,\n orderby: 'menu_order',\n order: 'asc',\n status: 'publish,future,draft,pending,private',\n };\n return {\n parentItems: isHierarchical ?\n selectCore.getEntityRecords( 'postType', postTypeSlug, query ) :\n []\n };\n[...]\n</code></pre>\n"
},
{
"answer_id": 356391,
"author": "Josh Bradley",
"author_id": 177275,
"author_profile": "https://wordpress.stackexchange.com/users/177275",
"pm_score": 4,
"selected": false,
"text": "<p>If you look into the source code for <code>getEntityRecords</code>, you'll see that the the <code>core/data</code> library creates entities using the Wordpress API in <a href=\"https://github.com/WordPress/gutenberg/blob/master/packages/core-data/src/entities.js\" rel=\"noreferrer\">entities.js</a>.</p>\n\n<p>So you can use any parameter available in the <a href=\"https://developer.wordpress.org/rest-api/reference/\" rel=\"noreferrer\">REST API</a>. Here are options for posts:</p>\n\n<pre><code>context\npage\nper_page\nsearch\nafter\nauthor\nauthor_exclude\nbefore\nexclude\ninclude\noffset\norder\norderby\nslug\nstatus\ncategories\ncategories_exclude\ntags\ntags_exclude\nsticky\n</code></pre>\n"
}
] | 2019/02/10 | [
"https://wordpress.stackexchange.com/questions/328277",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/160955/"
] | I'm working on a plugin that defined a custom block for the Gutenberg/Block Editor. The block shows a `select` box of posts. When you select one, I create HTML with some of the selected post's fields, such as title, date, etc.
When I query my posts in the `edit` method, my code correctly produces a list of pages (in my case, a custom post type named `product`), but custom fields, which this post type has, are not included.
```
var pages = select('core').getEntityRecords('postType', 'product', { per_page: -1 });
```
I'm trying to find documentation on `getEntityRecords` query parameters, but there seems to be none. Is it possible to include custom fields in the query? You would think this should be explained on <https://wordpress.org/gutenberg/handbook/designers-developers/developers/data/data-core/#getentityrecords>
My only other idea was: when the block is saved ("during" the `save` method), is it possible to do another query that just selects the single post by ID and retrieves its data, maybe including custom fields? It seems I can't query anything during save. | If you look into the source code for `getEntityRecords`, you'll see that the the `core/data` library creates entities using the Wordpress API in [entities.js](https://github.com/WordPress/gutenberg/blob/master/packages/core-data/src/entities.js).
So you can use any parameter available in the [REST API](https://developer.wordpress.org/rest-api/reference/). Here are options for posts:
```
context
page
per_page
search
after
author
author_exclude
before
exclude
include
offset
order
orderby
slug
status
categories
categories_exclude
tags
tags_exclude
sticky
``` |
328,283 | <p>I copied this code from a youtuber. It works for him, but not for me. Does the code contain any errors? As soon as I put it in, my WordPress breaks and won’t load. </p>
<pre><code>function gt_custom_post_type() {
register_post_type('project',
array(
'rewrite' => array('slug' => 'projects'),
'labels' => array(
'name' => 'Projects'
'singular_name' => 'Project',
'add_new_item' => 'Add New Project',
'edit_item' => 'Edit Project'
),
'menu-icon' => 'dashicons-media-document',
'public' => true,
'has_archive' => true,
'supports' => array(
'title', 'thumnail', 'editor', 'excerpt', 'comments'
)
)
);
}
add_action('init', 'gt_custom_post_type');
</code></pre>
| [
{
"answer_id": 330953,
"author": "Marc Heiduk",
"author_id": 162686,
"author_profile": "https://wordpress.stackexchange.com/users/162686",
"pm_score": 3,
"selected": false,
"text": "<p>Gutenberg documentation is not finished yet, but there are some unreleased commits in the official Gutenberg Repo. This could help: <a href=\"https://github.com/WordPress/gutenberg/blob/b7ad77d15f32ca234ff2f3df4994e47a5cf2e6d7/packages/editor/src/components/page-attributes/README.md\" rel=\"noreferrer\">https://github.com/WordPress/gutenberg/blob/b7ad77d15f32ca234ff2f3df4994e47a5cf2e6d7/packages/editor/src/components/page-attributes/README.md</a></p>\n\n<pre><code>[...]\n var query = {\n per_page: -1,\n exclude: postId,\n parent_exclude: postId,\n orderby: 'menu_order',\n order: 'asc',\n status: 'publish,future,draft,pending,private',\n };\n return {\n parentItems: isHierarchical ?\n selectCore.getEntityRecords( 'postType', postTypeSlug, query ) :\n []\n };\n[...]\n</code></pre>\n"
},
{
"answer_id": 356391,
"author": "Josh Bradley",
"author_id": 177275,
"author_profile": "https://wordpress.stackexchange.com/users/177275",
"pm_score": 4,
"selected": false,
"text": "<p>If you look into the source code for <code>getEntityRecords</code>, you'll see that the the <code>core/data</code> library creates entities using the Wordpress API in <a href=\"https://github.com/WordPress/gutenberg/blob/master/packages/core-data/src/entities.js\" rel=\"noreferrer\">entities.js</a>.</p>\n\n<p>So you can use any parameter available in the <a href=\"https://developer.wordpress.org/rest-api/reference/\" rel=\"noreferrer\">REST API</a>. Here are options for posts:</p>\n\n<pre><code>context\npage\nper_page\nsearch\nafter\nauthor\nauthor_exclude\nbefore\nexclude\ninclude\noffset\norder\norderby\nslug\nstatus\ncategories\ncategories_exclude\ntags\ntags_exclude\nsticky\n</code></pre>\n"
}
] | 2019/02/10 | [
"https://wordpress.stackexchange.com/questions/328283",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/160967/"
] | I copied this code from a youtuber. It works for him, but not for me. Does the code contain any errors? As soon as I put it in, my WordPress breaks and won’t load.
```
function gt_custom_post_type() {
register_post_type('project',
array(
'rewrite' => array('slug' => 'projects'),
'labels' => array(
'name' => 'Projects'
'singular_name' => 'Project',
'add_new_item' => 'Add New Project',
'edit_item' => 'Edit Project'
),
'menu-icon' => 'dashicons-media-document',
'public' => true,
'has_archive' => true,
'supports' => array(
'title', 'thumnail', 'editor', 'excerpt', 'comments'
)
)
);
}
add_action('init', 'gt_custom_post_type');
``` | If you look into the source code for `getEntityRecords`, you'll see that the the `core/data` library creates entities using the Wordpress API in [entities.js](https://github.com/WordPress/gutenberg/blob/master/packages/core-data/src/entities.js).
So you can use any parameter available in the [REST API](https://developer.wordpress.org/rest-api/reference/). Here are options for posts:
```
context
page
per_page
search
after
author
author_exclude
before
exclude
include
offset
order
orderby
slug
status
categories
categories_exclude
tags
tags_exclude
sticky
``` |
328,318 | <p>Centos 6 sys with php5.3.3, php5.6 and php7.0.<br>
Virtual Host set with php5.3.3
Just installed WP.<br>
Adding a plugin I get: </p>
<blockquote>
<p>Adaptive Images Error — PHP GD image library missing<br>
The PHP GD
image library is not detected in your server. ...</p>
</blockquote>
<pre><code>php -m | grep -i gd
</code></pre>
<blockquote>
<p>gd</p>
</blockquote>
<pre><code>rpm -qa | grep php
</code></pre>
<blockquote>
<p>rh-php70-php-gd-7.0.27-1.el6.x86_64<br>
php-gd-5.3.3-49.el6.x86_64</p>
</blockquote>
<p>I could successfully installed the same plugin in another WP installation (different virtual host, same server and php version) I have long time ago.<br>
I don't realize what's going on.
I created the virtual host using Virtualmin.<br>
Also switched from 5.3.3 to 7.0 php version but GD wasn't found too</p>
| [
{
"answer_id": 330953,
"author": "Marc Heiduk",
"author_id": 162686,
"author_profile": "https://wordpress.stackexchange.com/users/162686",
"pm_score": 3,
"selected": false,
"text": "<p>Gutenberg documentation is not finished yet, but there are some unreleased commits in the official Gutenberg Repo. This could help: <a href=\"https://github.com/WordPress/gutenberg/blob/b7ad77d15f32ca234ff2f3df4994e47a5cf2e6d7/packages/editor/src/components/page-attributes/README.md\" rel=\"noreferrer\">https://github.com/WordPress/gutenberg/blob/b7ad77d15f32ca234ff2f3df4994e47a5cf2e6d7/packages/editor/src/components/page-attributes/README.md</a></p>\n\n<pre><code>[...]\n var query = {\n per_page: -1,\n exclude: postId,\n parent_exclude: postId,\n orderby: 'menu_order',\n order: 'asc',\n status: 'publish,future,draft,pending,private',\n };\n return {\n parentItems: isHierarchical ?\n selectCore.getEntityRecords( 'postType', postTypeSlug, query ) :\n []\n };\n[...]\n</code></pre>\n"
},
{
"answer_id": 356391,
"author": "Josh Bradley",
"author_id": 177275,
"author_profile": "https://wordpress.stackexchange.com/users/177275",
"pm_score": 4,
"selected": false,
"text": "<p>If you look into the source code for <code>getEntityRecords</code>, you'll see that the the <code>core/data</code> library creates entities using the Wordpress API in <a href=\"https://github.com/WordPress/gutenberg/blob/master/packages/core-data/src/entities.js\" rel=\"noreferrer\">entities.js</a>.</p>\n\n<p>So you can use any parameter available in the <a href=\"https://developer.wordpress.org/rest-api/reference/\" rel=\"noreferrer\">REST API</a>. Here are options for posts:</p>\n\n<pre><code>context\npage\nper_page\nsearch\nafter\nauthor\nauthor_exclude\nbefore\nexclude\ninclude\noffset\norder\norderby\nslug\nstatus\ncategories\ncategories_exclude\ntags\ntags_exclude\nsticky\n</code></pre>\n"
}
] | 2019/02/10 | [
"https://wordpress.stackexchange.com/questions/328318",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/66849/"
] | Centos 6 sys with php5.3.3, php5.6 and php7.0.
Virtual Host set with php5.3.3
Just installed WP.
Adding a plugin I get:
>
> Adaptive Images Error — PHP GD image library missing
>
> The PHP GD
> image library is not detected in your server. ...
>
>
>
```
php -m | grep -i gd
```
>
> gd
>
>
>
```
rpm -qa | grep php
```
>
> rh-php70-php-gd-7.0.27-1.el6.x86\_64
>
> php-gd-5.3.3-49.el6.x86\_64
>
>
>
I could successfully installed the same plugin in another WP installation (different virtual host, same server and php version) I have long time ago.
I don't realize what's going on.
I created the virtual host using Virtualmin.
Also switched from 5.3.3 to 7.0 php version but GD wasn't found too | If you look into the source code for `getEntityRecords`, you'll see that the the `core/data` library creates entities using the Wordpress API in [entities.js](https://github.com/WordPress/gutenberg/blob/master/packages/core-data/src/entities.js).
So you can use any parameter available in the [REST API](https://developer.wordpress.org/rest-api/reference/). Here are options for posts:
```
context
page
per_page
search
after
author
author_exclude
before
exclude
include
offset
order
orderby
slug
status
categories
categories_exclude
tags
tags_exclude
sticky
``` |
328,331 | <p>I am trying to insert a new post with a simple ajax form in a wordpress plugin. Visitors will use this form to create posts from frontend.</p>
<p>My form is like this:</p>
<pre><code><script>
jQuery( document ).ready(function() {
jQuery('input[type=submit]').on('click', function() {
var ajaxurl = 'https://example.com/wp-admin/admin-ajax.php';
jQuery.ajax({
type: "POST",
data: jQuery('.event-form').serialize(),
url: ajaxurl,
success: function(result) {
console.log('data sent!');
console.log('sent to: ' + templateDir + loadUrl );
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
});
});
</script>
<form id="msform" name="review_form" class="form-horizontal event-form" action="/create-event" method="POST" enctype="multipart/form-data">
<input type="text" name="title" placeholder="title">
<textarea rows="4" name="desc" placeholder="Description"></textarea>
<select name="category">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<input type="hidden" name="userID" id="userID" value="<?php get_current_user_id(); ?>">
<input type="submit" name="submit" class="submit action-button" value="Submit"/>
</form>
</code></pre>
<p>This is the php ajax function</p>
<pre><code>function save_post () {
ini_set('display_errors', 1);
error_reporting('E_ALL');
$new_post = array(
'post_title' => $_POST['title'],
'post_author' => $_POST['userID'],
'post_content' => $_POST['desc'],
'post_category' => array($_POST['category']),
'post_status' => 'publish',
'post_type' => 'post'
);
$post_id = wp_insert_post($new_post);
}
add_action('wp_ajax_nopriv_save_post','save_post');
add_action('wp_ajax_save_post','save_post');
</code></pre>
<p>I am getting the following error message in the console when I click the submit button:</p>
<pre><code>[object Object] :: error :: Bad Request
</code></pre>
<p>What am I doing wrong?</p>
| [
{
"answer_id": 328339,
"author": "moped",
"author_id": 160324,
"author_profile": "https://wordpress.stackexchange.com/users/160324",
"pm_score": -1,
"selected": false,
"text": "<p>Your form calls action 'create-event', your ajax function is 'save_post'.\nTell your ajax script which action (method/function) to use.\nI think it never reaches 'save_post'.</p>\n"
},
{
"answer_id": 328382,
"author": "GeorgeP",
"author_id": 160985,
"author_profile": "https://wordpress.stackexchange.com/users/160985",
"pm_score": 1,
"selected": true,
"text": "<p>Finally found the problem. The <code>action: save_post</code> was missing from data in ajax call. This code works:</p>\n\n<pre><code> <script>\n jQuery( document ).ready(function() {\n jQuery('input[type=button]').on('click', function() {\n var ajaxurl = \"<?php echo admin_url('admin-ajax.php'); ?>\";\n jQuery.ajax({\n type: \"POST\",\n data: {\n data:jQuery('.event-form').serialize(),\n action: 'save_post'\n },\n url: ajaxurl,\n success: function(result) {\n console.log('data sent!');\n console.log('sent to: ' + templateDir + loadUrl );\n },\n error: function(jqXHR, textStatus, errorThrown) {\n console.log(jqXHR + \" :: \" + textStatus + \" :: \" + errorThrown);\n }\n });\n });\n });\n </script>\n</code></pre>\n"
}
] | 2019/02/11 | [
"https://wordpress.stackexchange.com/questions/328331",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/160985/"
] | I am trying to insert a new post with a simple ajax form in a wordpress plugin. Visitors will use this form to create posts from frontend.
My form is like this:
```
<script>
jQuery( document ).ready(function() {
jQuery('input[type=submit]').on('click', function() {
var ajaxurl = 'https://example.com/wp-admin/admin-ajax.php';
jQuery.ajax({
type: "POST",
data: jQuery('.event-form').serialize(),
url: ajaxurl,
success: function(result) {
console.log('data sent!');
console.log('sent to: ' + templateDir + loadUrl );
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
});
});
</script>
<form id="msform" name="review_form" class="form-horizontal event-form" action="/create-event" method="POST" enctype="multipart/form-data">
<input type="text" name="title" placeholder="title">
<textarea rows="4" name="desc" placeholder="Description"></textarea>
<select name="category">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<input type="hidden" name="userID" id="userID" value="<?php get_current_user_id(); ?>">
<input type="submit" name="submit" class="submit action-button" value="Submit"/>
</form>
```
This is the php ajax function
```
function save_post () {
ini_set('display_errors', 1);
error_reporting('E_ALL');
$new_post = array(
'post_title' => $_POST['title'],
'post_author' => $_POST['userID'],
'post_content' => $_POST['desc'],
'post_category' => array($_POST['category']),
'post_status' => 'publish',
'post_type' => 'post'
);
$post_id = wp_insert_post($new_post);
}
add_action('wp_ajax_nopriv_save_post','save_post');
add_action('wp_ajax_save_post','save_post');
```
I am getting the following error message in the console when I click the submit button:
```
[object Object] :: error :: Bad Request
```
What am I doing wrong? | Finally found the problem. The `action: save_post` was missing from data in ajax call. This code works:
```
<script>
jQuery( document ).ready(function() {
jQuery('input[type=button]').on('click', function() {
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
jQuery.ajax({
type: "POST",
data: {
data:jQuery('.event-form').serialize(),
action: 'save_post'
},
url: ajaxurl,
success: function(result) {
console.log('data sent!');
console.log('sent to: ' + templateDir + loadUrl );
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
});
});
</script>
``` |
328,353 | <p>I'm about to convert my Bootstrap template to a custom Wordpress theme and have a little issue. </p>
<p>I want to display all of my blog posts. So far, it is working well. But here is the thing: Because of my design preferences I want to change the used styles for the displayed posts after a specific post. So let's say for the first three posts I want to use style A (post displayed in a great box with title and excerpt) and after the third I want to display thw following posts with style B (two per row, smaller box, just image and title, no excerpt).</p>
<p>I am just starting out with WP syntax, so I have no idea how to accomplish this. Any suggestions?</p>
<p>Thanks</p>
<p><strong>EDIT</strong></p>
<p>This is the code I am currently using</p>
<pre><code><?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'post-type' => 'post',
'post-per-page' => 8,
'paged' => $paged,
);
$wp_query = new WP_Query($args);
if ($wp_query->have_posts()) : while ($wp_query->have_posts()) : $wp_query->the_post();
?>
<article class="single-post">
<div class="post-thumbnail">
<a href="<?php the_permalink(); ?>">
<img src="<?php echo get_template_directory_uri(); ?>/images/example.jpg">
</a>
</div>
<div class="post-content">
<div class="content-header">
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
</div>
<div class="content-text">
<?php the_excerpt(); ?>
</div>
<div class="read-more">
<a href="<?php the_permalink(); ?>">Read More</a>
</div>
</div>
</article>
<?php endwhile; else: ?>
<p>Sorry, no posts yet.</p>
<?php endif; ?>
</code></pre>
<p>This will result in a list of my current posts, all the same style. I actually want, as I said, that the style will change after the third post. This looks like the following in my current Bootstrap code:</p>
<pre><code><article class="single-post">
// all the stuff above
</article>
<div class="row"> <!-- a new row for smaller post boxes -->
<div class="col-sm-6"> <!-- first box -->
<article class="multiple-post">
// all the stuff here
</article>
</div>
<div class="col-sm-6"> <!-- second box -->
<article class="multiple-post">
// all the stuff here
</article>
</div>
</div>
</code></pre>
<p>So, I want use article with class single-post for the first 3 or so blog posts and after those, the page should use article with class multiple-post INCLUDING the additional div-row. Otherwise I can not use the exact layout because of how Bootstrap works.</p>
<p>Hope this makes it much more clearly to you.</p>
| [
{
"answer_id": 328339,
"author": "moped",
"author_id": 160324,
"author_profile": "https://wordpress.stackexchange.com/users/160324",
"pm_score": -1,
"selected": false,
"text": "<p>Your form calls action 'create-event', your ajax function is 'save_post'.\nTell your ajax script which action (method/function) to use.\nI think it never reaches 'save_post'.</p>\n"
},
{
"answer_id": 328382,
"author": "GeorgeP",
"author_id": 160985,
"author_profile": "https://wordpress.stackexchange.com/users/160985",
"pm_score": 1,
"selected": true,
"text": "<p>Finally found the problem. The <code>action: save_post</code> was missing from data in ajax call. This code works:</p>\n\n<pre><code> <script>\n jQuery( document ).ready(function() {\n jQuery('input[type=button]').on('click', function() {\n var ajaxurl = \"<?php echo admin_url('admin-ajax.php'); ?>\";\n jQuery.ajax({\n type: \"POST\",\n data: {\n data:jQuery('.event-form').serialize(),\n action: 'save_post'\n },\n url: ajaxurl,\n success: function(result) {\n console.log('data sent!');\n console.log('sent to: ' + templateDir + loadUrl );\n },\n error: function(jqXHR, textStatus, errorThrown) {\n console.log(jqXHR + \" :: \" + textStatus + \" :: \" + errorThrown);\n }\n });\n });\n });\n </script>\n</code></pre>\n"
}
] | 2019/02/11 | [
"https://wordpress.stackexchange.com/questions/328353",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/160998/"
] | I'm about to convert my Bootstrap template to a custom Wordpress theme and have a little issue.
I want to display all of my blog posts. So far, it is working well. But here is the thing: Because of my design preferences I want to change the used styles for the displayed posts after a specific post. So let's say for the first three posts I want to use style A (post displayed in a great box with title and excerpt) and after the third I want to display thw following posts with style B (two per row, smaller box, just image and title, no excerpt).
I am just starting out with WP syntax, so I have no idea how to accomplish this. Any suggestions?
Thanks
**EDIT**
This is the code I am currently using
```
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'post-type' => 'post',
'post-per-page' => 8,
'paged' => $paged,
);
$wp_query = new WP_Query($args);
if ($wp_query->have_posts()) : while ($wp_query->have_posts()) : $wp_query->the_post();
?>
<article class="single-post">
<div class="post-thumbnail">
<a href="<?php the_permalink(); ?>">
<img src="<?php echo get_template_directory_uri(); ?>/images/example.jpg">
</a>
</div>
<div class="post-content">
<div class="content-header">
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
</div>
<div class="content-text">
<?php the_excerpt(); ?>
</div>
<div class="read-more">
<a href="<?php the_permalink(); ?>">Read More</a>
</div>
</div>
</article>
<?php endwhile; else: ?>
<p>Sorry, no posts yet.</p>
<?php endif; ?>
```
This will result in a list of my current posts, all the same style. I actually want, as I said, that the style will change after the third post. This looks like the following in my current Bootstrap code:
```
<article class="single-post">
// all the stuff above
</article>
<div class="row"> <!-- a new row for smaller post boxes -->
<div class="col-sm-6"> <!-- first box -->
<article class="multiple-post">
// all the stuff here
</article>
</div>
<div class="col-sm-6"> <!-- second box -->
<article class="multiple-post">
// all the stuff here
</article>
</div>
</div>
```
So, I want use article with class single-post for the first 3 or so blog posts and after those, the page should use article with class multiple-post INCLUDING the additional div-row. Otherwise I can not use the exact layout because of how Bootstrap works.
Hope this makes it much more clearly to you. | Finally found the problem. The `action: save_post` was missing from data in ajax call. This code works:
```
<script>
jQuery( document ).ready(function() {
jQuery('input[type=button]').on('click', function() {
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
jQuery.ajax({
type: "POST",
data: {
data:jQuery('.event-form').serialize(),
action: 'save_post'
},
url: ajaxurl,
success: function(result) {
console.log('data sent!');
console.log('sent to: ' + templateDir + loadUrl );
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
});
});
</script>
``` |
328,354 | <p>So, I was doing some SEO work for my company's website. The website is an online e-shop, where you can learn about their products and make an order. They also got a blog. So far so good.
The set up is Wordpress obviously along with WooCommerce.</p>
<p>What I see is that there is an option to add a product and another option to add a blog article.</p>
<p>When I was doing my SEO, I managed the product tags. I was happy with how I made things work for products.</p>
<p>Here is the deal:
If you want to add tags for a post, you can NOT access tags for products.
All right I get it, it is smart that way. But I don't like the idea of just copy-paste the whole stuff from one tag group to another manually.</p>
<p><em>So, is there a way to duplicate the <strong>product</strong> tags to <strong>blog article tags</strong>, or am I forced to do it manually?</em></p>
<p>I mean some products share a tag, let's say an ingredient. It would also be helpful and nice to got this tag on blog posts about the ingredient, the product or both.</p>
<p>Edit:
Just to clarify, I don't wanna have the product tags shared with blog post tags.
I want the product tags when clicked to show only the products sharing that tag.
But when it comes to blog posts, it would be nice to have the same tags (same text) that can show all the blog postst sharing them. Products can be linked in blog text hyperlings I suppose. </p>
| [
{
"answer_id": 328358,
"author": "Alexander Holsgrove",
"author_id": 48962,
"author_profile": "https://wordpress.stackexchange.com/users/48962",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, you can register the WooCommerce product tags (taxonomy) on your posts. Normally this would be done when you register the post type, but you can use <a href=\"https://developer.wordpress.org/reference/functions/register_taxonomy_for_object_type/\" rel=\"nofollow noreferrer\">register_taxonomy_for_object_type</a> to register the <code>product_tag</code> from WooCommerce against your normal posts:</p>\n\n<pre><code>register_taxonomy_for_object_type( 'product_tag', 'post');\n</code></pre>\n\n<p>You can also change the labels for this, as it will display <code>Tags</code> twice under Posts:</p>\n\n<pre><code>function add_product_tags_to_post() {\n global $wp_taxonomies;\n\n register_taxonomy_for_object_type( 'product_tag', 'post');\n\n $labels = &$wp_taxonomies['product_tag']->labels;\n $labels->name = 'Product Tags';\n $labels->singular_name = 'Product Tag';\n $labels->add_new = 'Add Product Tag';\n $labels->add_new_item = 'Add Product Tag';\n $labels->edit_item = 'Edit Product Tag';\n $labels->new_item = 'Product Tag';\n $labels->view_item = 'View Product Tag';\n $labels->search_items = 'Search Product Tags';\n $labels->not_found = 'No Product Tags found';\n $labels->not_found_in_trash = 'No Product Tags found in Trash';\n $labels->all_items = 'All Product Tags';\n $labels->menu_name = 'Product Tags';\n $labels->name_admin_bar = 'Product Tag';\n}\n\nadd_action('init', 'add_product_tags_to_post');\n</code></pre>\n"
},
{
"answer_id": 328361,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 2,
"selected": true,
"text": "<p>OK, so you can use <code>created_term</code> hook to make the product tags copy themselves automatically to post tags.</p>\n\n<pre><code>function ( $term_id, $tt_id, $taxonomy ) {\n if ( 'product_tag' == $taxonomy ) {\n $term = get_term( $term_id, $taxonomy );\n wp_insert_term( $term->name, 'post_tag' );\n }\n}\nadd_action( 'created_term', 'copy_product_tags_for_blog', 10, 3 );\n</code></pre>\n\n<p>And you’ll have to run a simple loop for tags that are already in DB.</p>\n"
}
] | 2019/02/11 | [
"https://wordpress.stackexchange.com/questions/328354",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159988/"
] | So, I was doing some SEO work for my company's website. The website is an online e-shop, where you can learn about their products and make an order. They also got a blog. So far so good.
The set up is Wordpress obviously along with WooCommerce.
What I see is that there is an option to add a product and another option to add a blog article.
When I was doing my SEO, I managed the product tags. I was happy with how I made things work for products.
Here is the deal:
If you want to add tags for a post, you can NOT access tags for products.
All right I get it, it is smart that way. But I don't like the idea of just copy-paste the whole stuff from one tag group to another manually.
*So, is there a way to duplicate the **product** tags to **blog article tags**, or am I forced to do it manually?*
I mean some products share a tag, let's say an ingredient. It would also be helpful and nice to got this tag on blog posts about the ingredient, the product or both.
Edit:
Just to clarify, I don't wanna have the product tags shared with blog post tags.
I want the product tags when clicked to show only the products sharing that tag.
But when it comes to blog posts, it would be nice to have the same tags (same text) that can show all the blog postst sharing them. Products can be linked in blog text hyperlings I suppose. | OK, so you can use `created_term` hook to make the product tags copy themselves automatically to post tags.
```
function ( $term_id, $tt_id, $taxonomy ) {
if ( 'product_tag' == $taxonomy ) {
$term = get_term( $term_id, $taxonomy );
wp_insert_term( $term->name, 'post_tag' );
}
}
add_action( 'created_term', 'copy_product_tags_for_blog', 10, 3 );
```
And you’ll have to run a simple loop for tags that are already in DB. |
328,384 | <p>Hi trying this code below to get working, but no look so far.
Idea is simple if page template is <strong>page-47.php</strong> display <code><h1>Something</h1></code> else <code><h1>This will show on any other page</h1></code> .</p>
<pre><code><?php if ( is_page_template( 'page-47.php' ) ): ?>
<h1>Something</h1>
<?php else: ?>
<h1>This will show on any other page</h1>
<?php endif ?>
</code></pre>
<p>Thank You</p>
| [
{
"answer_id": 328427,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 5,
"selected": true,
"text": "<p><code>is_page_template()</code> will only tell you if the page is using a <em>custom</em> page template. Meaning a template that was created by adding the <code>Template Name:</code> comment to the file and selecting it from the Template dropdown, as described <a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/#creating-custom-page-templates-for-global-use\" rel=\"noreferrer\">here</a>. The function works by checking the post meta for which template was selected.</p>\n\n<p>If you have created a page template using the slug or ID using the method described <a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/#creating-a-custom-page-template-for-one-specific-page\" rel=\"noreferrer\">here</a>, which you appear to have, then the template being used is not stored in meta, so won't be picked up by the <code>is_page_template()</code> function.</p>\n\n<p>If you want to know the filename of the current template being used, regardless of whether it's a custom template or not, you can use the global <code>$template</code> variable:</p>\n\n<pre><code>global $template;\n\nif ( basename( $template ) === 'page-47.php' ) {\n\n}\n</code></pre>\n"
},
{
"answer_id": 375028,
"author": "Webvd",
"author_id": 194797,
"author_profile": "https://wordpress.stackexchange.com/users/194797",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks to Jacob Peattie! This also solved my problem.</p>\n<pre><code>add_filter( 'woocommerce_currency_symbol', 'change_currency_symbol', 10, 2 );\n\nfunction change_currency_symbol( $symbols, $currency ) {\n \n global $template;\n \n if ( basename( $template ) === 'archive-chiptuning.php' && ( 'EUR' === $currency )) {\n return '';\n }\n return $symbols;\n}\n</code></pre>\n"
}
] | 2019/02/11 | [
"https://wordpress.stackexchange.com/questions/328384",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/153778/"
] | Hi trying this code below to get working, but no look so far.
Idea is simple if page template is **page-47.php** display `<h1>Something</h1>` else `<h1>This will show on any other page</h1>` .
```
<?php if ( is_page_template( 'page-47.php' ) ): ?>
<h1>Something</h1>
<?php else: ?>
<h1>This will show on any other page</h1>
<?php endif ?>
```
Thank You | `is_page_template()` will only tell you if the page is using a *custom* page template. Meaning a template that was created by adding the `Template Name:` comment to the file and selecting it from the Template dropdown, as described [here](https://developer.wordpress.org/themes/template-files-section/page-template-files/#creating-custom-page-templates-for-global-use). The function works by checking the post meta for which template was selected.
If you have created a page template using the slug or ID using the method described [here](https://developer.wordpress.org/themes/template-files-section/page-template-files/#creating-a-custom-page-template-for-one-specific-page), which you appear to have, then the template being used is not stored in meta, so won't be picked up by the `is_page_template()` function.
If you want to know the filename of the current template being used, regardless of whether it's a custom template or not, you can use the global `$template` variable:
```
global $template;
if ( basename( $template ) === 'page-47.php' ) {
}
``` |
328,408 | <p>When viewing a draft page on the frontend, I'd like to see that status right away on the page itself. Currently, there is zero indication. Is there any way to have draft-specific CSS (or even just a header message?)</p>
| [
{
"answer_id": 328412,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 4,
"selected": true,
"text": "<p>There is probably a better way but you could add the following CSS to your stylesheet, which will add a little banner when viewing a page that has a status of draft.</p>\n\n<pre><code>.status-draft.hentry:before {\n content: \"Previewing a Draft\";\n background: #87C5D6 !important;\n display: block;\n text-align: center;\n}\n</code></pre>\n\n<p>You could also use these classes for the different statuses.</p>\n\n<p><code>.status-pending</code></p>\n\n<p><code>.status-publish</code></p>\n\n<p><code>.status-future</code></p>\n\n<p><code>.status-private</code></p>\n\n<p>Works for me.</p>\n\n<p><a href=\"https://i.stack.imgur.com/DBjrr.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/DBjrr.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 328494,
"author": "Derek Illchuk",
"author_id": 161026,
"author_profile": "https://wordpress.stackexchange.com/users/161026",
"pm_score": 1,
"selected": false,
"text": "<p>OP here. If the homepage is set to draft, the CSS class used in the chosen answer is not available. Here's what I'm using now to place a diagonal DRAFT watermark, using \"CSS and Javascript Toolbox\" plugin:</p>\n\n<p>CSS</p>\n\n<pre><code>.draft-watermark{\n position:absolute;\n background:clear;\n display:block;\n min-height:50%; \n min-width:50%;\n color:lightgrey;\n font-size:500%;\n transform:rotate(310deg);\n -webkit-transform:rotate(310deg);\n z-index: 100;\n}\n.draft-watermark:before {\n content: \"DRAFT DRAFT DRAFT DRAFT\";\n}\n</code></pre>\n\n<p>Script in CJToolbox, set to be included on all pages:</p>\n\n<pre><code><?php if (get_post_status(get_the_ID()) == 'draft'): ?>\n<script>\n jQuery(document).ready(function() {\n jQuery('<div class=\"draft-watermark\"></div>').insertBefore(jQuery('div:first'));\n });\n</script>\n<?php endif; ?>\n</code></pre>\n"
}
] | 2019/02/11 | [
"https://wordpress.stackexchange.com/questions/328408",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/161026/"
] | When viewing a draft page on the frontend, I'd like to see that status right away on the page itself. Currently, there is zero indication. Is there any way to have draft-specific CSS (or even just a header message?) | There is probably a better way but you could add the following CSS to your stylesheet, which will add a little banner when viewing a page that has a status of draft.
```
.status-draft.hentry:before {
content: "Previewing a Draft";
background: #87C5D6 !important;
display: block;
text-align: center;
}
```
You could also use these classes for the different statuses.
`.status-pending`
`.status-publish`
`.status-future`
`.status-private`
Works for me.
[](https://i.stack.imgur.com/DBjrr.png) |
328,411 | <p>I'd like to re-order the search results based on post meta and date . The post meta key is <code>_prioritize_s</code> and the value isn't important. So in a "normal" meta query, I'd just write the <code>compare</code> parameters to check EXISTS/NOT EXISTS. While I have experience with meta queries, I've never had to re-order search results until now, so I'd appreciate any help.</p>
<p><strong>This is how I'd like to re-order the search results:</strong></p>
<ul>
<li>Check if posts with post meta <code>_prioritize_s</code> exists within search results</li>
<li>If they do, put those on top of the results in date order (from recent to oldest). After these posts are shown, show the remaining search results underneath in their default order.</li>
<li>If there are no posts with this post meta among the search results, order by whatever is default</li>
</ul>
<p>It looks like I have to use 2 filters, one to join and one to set the order. It seems like it's kind of working, but the order isn't right? Thoughts?</p>
<p><strong>Updated Code from <a href="https://stackoverflow.com/questions/10016568/wordpress-custom-field-search-results-sorted-by-value">this sample</a></strong> </p>
<pre><code> add_filter( 'posts_join', 'modify_search_results_join' );
add_filter( 'posts_orderby', 'modify_search_results_order', 10, 2 );
function modify_search_results_join( $orderby ) {
global $wpdb;
if ( ! is_admin() && is_search() ) {
$orderby .= "LEFT JOIN (
SELECT *
FROM $wpdb->postmeta
WHERE meta_key = '_prioritize_s' ) AS postmeta ON $wpdb->posts.ID = postmeta.post_id";
return $orderby;
}
return $orderby;
}
function modify_search_results_order( $orderby, $query ) {
global $wpdb;
//how do I order the results by _prioritize_s set to 'yes'?
$orderby = "postmeta.meta_value+'' DESC";
return $orderby;
}
</code></pre>
| [
{
"answer_id": 328412,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 4,
"selected": true,
"text": "<p>There is probably a better way but you could add the following CSS to your stylesheet, which will add a little banner when viewing a page that has a status of draft.</p>\n\n<pre><code>.status-draft.hentry:before {\n content: \"Previewing a Draft\";\n background: #87C5D6 !important;\n display: block;\n text-align: center;\n}\n</code></pre>\n\n<p>You could also use these classes for the different statuses.</p>\n\n<p><code>.status-pending</code></p>\n\n<p><code>.status-publish</code></p>\n\n<p><code>.status-future</code></p>\n\n<p><code>.status-private</code></p>\n\n<p>Works for me.</p>\n\n<p><a href=\"https://i.stack.imgur.com/DBjrr.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/DBjrr.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 328494,
"author": "Derek Illchuk",
"author_id": 161026,
"author_profile": "https://wordpress.stackexchange.com/users/161026",
"pm_score": 1,
"selected": false,
"text": "<p>OP here. If the homepage is set to draft, the CSS class used in the chosen answer is not available. Here's what I'm using now to place a diagonal DRAFT watermark, using \"CSS and Javascript Toolbox\" plugin:</p>\n\n<p>CSS</p>\n\n<pre><code>.draft-watermark{\n position:absolute;\n background:clear;\n display:block;\n min-height:50%; \n min-width:50%;\n color:lightgrey;\n font-size:500%;\n transform:rotate(310deg);\n -webkit-transform:rotate(310deg);\n z-index: 100;\n}\n.draft-watermark:before {\n content: \"DRAFT DRAFT DRAFT DRAFT\";\n}\n</code></pre>\n\n<p>Script in CJToolbox, set to be included on all pages:</p>\n\n<pre><code><?php if (get_post_status(get_the_ID()) == 'draft'): ?>\n<script>\n jQuery(document).ready(function() {\n jQuery('<div class=\"draft-watermark\"></div>').insertBefore(jQuery('div:first'));\n });\n</script>\n<?php endif; ?>\n</code></pre>\n"
}
] | 2019/02/11 | [
"https://wordpress.stackexchange.com/questions/328411",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/42783/"
] | I'd like to re-order the search results based on post meta and date . The post meta key is `_prioritize_s` and the value isn't important. So in a "normal" meta query, I'd just write the `compare` parameters to check EXISTS/NOT EXISTS. While I have experience with meta queries, I've never had to re-order search results until now, so I'd appreciate any help.
**This is how I'd like to re-order the search results:**
* Check if posts with post meta `_prioritize_s` exists within search results
* If they do, put those on top of the results in date order (from recent to oldest). After these posts are shown, show the remaining search results underneath in their default order.
* If there are no posts with this post meta among the search results, order by whatever is default
It looks like I have to use 2 filters, one to join and one to set the order. It seems like it's kind of working, but the order isn't right? Thoughts?
**Updated Code from [this sample](https://stackoverflow.com/questions/10016568/wordpress-custom-field-search-results-sorted-by-value)**
```
add_filter( 'posts_join', 'modify_search_results_join' );
add_filter( 'posts_orderby', 'modify_search_results_order', 10, 2 );
function modify_search_results_join( $orderby ) {
global $wpdb;
if ( ! is_admin() && is_search() ) {
$orderby .= "LEFT JOIN (
SELECT *
FROM $wpdb->postmeta
WHERE meta_key = '_prioritize_s' ) AS postmeta ON $wpdb->posts.ID = postmeta.post_id";
return $orderby;
}
return $orderby;
}
function modify_search_results_order( $orderby, $query ) {
global $wpdb;
//how do I order the results by _prioritize_s set to 'yes'?
$orderby = "postmeta.meta_value+'' DESC";
return $orderby;
}
``` | There is probably a better way but you could add the following CSS to your stylesheet, which will add a little banner when viewing a page that has a status of draft.
```
.status-draft.hentry:before {
content: "Previewing a Draft";
background: #87C5D6 !important;
display: block;
text-align: center;
}
```
You could also use these classes for the different statuses.
`.status-pending`
`.status-publish`
`.status-future`
`.status-private`
Works for me.
[](https://i.stack.imgur.com/DBjrr.png) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.