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
|
---|---|---|---|---|---|---|
367,853 | <p>Please i want to ensure only male or female is selected in the dropdown if not fail the form but my validation keeps returning false even if male or female is selected. </p>
<p>Html</p>
<pre class="lang-html prettyprint-override"><code><select name="gender">
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Nonesense" selected>Nonesense</option>
</select>
</code></pre>
<p>Here is the php code</p>
<pre class="lang-php prettyprint-override"><code>if ( isset( $_POST['submit'] ) ) {
if ( $_POST['gender'] != 'Male' || $_POST['gender'] != 'Female' ) {
echo 'sorry it must be either male or female'; return '';
}
}
</code></pre>
| [
{
"answer_id": 367892,
"author": "Himad",
"author_id": 158512,
"author_profile": "https://wordpress.stackexchange.com/users/158512",
"pm_score": -1,
"selected": false,
"text": "<p>I came across this some time ago, I'll try to find time to correctly debug the origin of the issue but in the meantime, try this: </p>\n\n<pre><code>/*\nThis is due to a bug that doesn't grant permission to the post-new.php unless there is a\nsubmenu with the link accesible for the user.\n*/\nglobal $submenu;\n$submenu['your_menu'][] = array(\n 'Hide me', # Do something to hide it or just leave it blank.\n 'create_posts',\n 'post-new.php?post_type=your_post_type',\n); \n</code></pre>\n"
},
{
"answer_id": 367893,
"author": "Mort 1305",
"author_id": 188811,
"author_profile": "https://wordpress.stackexchange.com/users/188811",
"pm_score": 3,
"selected": true,
"text": "<p>The problem is that when the special subscriber tries to <strong>Add New</strong> a sub-cpt post, it is denied permission. However, when the CPT menu is a top-admin-menu, then everything works out fine. The issue is related to the placement of the CPT's UI menu in the back-end: if it's top-level (<code>show_in_menu=TRUE</code>), all is well; if its a submenu (<code>show_in_menu='my-menu-item'</code>), the user can't create the post type unless it has the <code>edit_posts</code> permission (even if it has all the <code>edit_PostType</code> permissions in the world). I've been chasing this stupid thing since the 22nd. Thanks to the pandemic, I haven't had to do much of anything else. After 12-15 hours each of the 8 days, I finally got this little bugger picked.</p>\n\n<p>This issue had something to do with <strong>post-new.php</strong>, as all works out fine when the CPT is edited under the <strong>post.php</strong> script (which is nearly identical). The very first thing that <strong>post-new.php</strong> does is call on <strong>admin.php</strong>. On line <a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/admin.php#L153\" rel=\"nofollow noreferrer\">153</a>, <strong>wp-admin/menu.php</strong> is called in to bat which includes <strong>wp-admin/includes/menu.php</strong> as its <a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/menu.php#L326\" rel=\"nofollow noreferrer\">last execution</a>. On that <strong>includes/menu.php</strong> file's <a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includes/menu.php#L341\" rel=\"nofollow noreferrer\">line 341</a>, the <code>user_can_access_admin_page()</code> returns <code>FALSE</code>, triggering the <code>do_action('admin_page_access_denied')</code> hook to be fired and the <code>wp_die(__('Sorry, you are not allowed to access this page.'), 403)</code> command to kill the whole process.</p>\n\n<p>The <code>user_can_access_admin_page()</code> method is defined on <a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includes/plugin.php#L2042\" rel=\"nofollow noreferrer\">line 2042</a> of the <strong>wp-admin/includes/plugin.php</strong> file. <a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includes/plugin.php#L2064\" rel=\"nofollow noreferrer\">Line 2064</a> passed its check in that <code>get_admin_page_parent()</code> was empty. This is followed by <a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includes/plugin.php#L2078\" rel=\"nofollow noreferrer\">line 2078</a> failing its check in that the variable of <code>$_wp_submenu_nopriv['edit.php']['post-new.php']</code> is set. The combined effect of these checks the <code>FALSE</code> boolean being returned and WordPress dies.</p>\n\n<p>The closest related script known to me is that of <strong>post.php</strong>, as the <strong>admin.php</strong> process is immediately called and runs in an identical manner, including the calling of <code>user_can_access_admin_page()</code>. Debugging demonstrates that the <code>user_can_access_admin_page()</code> is passed in the <strong>post.php</strong> script because, unlike <strong>post-new.php</strong>, none of the <code>$_wp_submenu_nopriv[____][$pagenow]</code> flags were set. So, the question is why this index is being set for <strong>post-new.php</strong> and not set for <strong>post.php</strong>.</p>\n\n<p>The <code>global $_wp_submenu_nopriv</code> is first set on <a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includes/menu.php#L71\" rel=\"nofollow noreferrer\">line 71</a> of <strong>wp-admin/includes/menu.php</strong>, in which that variable is initialized as an empty array. If the <code>current_user_can()</code> test is not passed on <a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includes/menu.php#L79\" rel=\"nofollow noreferrer\">line 79</a>, the flag is set on <a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includes/menu.php#L81\" rel=\"nofollow noreferrer\">line 81</a>. At that point, the <code>global $submenu['edit.php']</code> is initialized to the point of our concern, and contains the array at *index=*10 <em>(\"Add New\", \"edit_posts\", \"post-new.php\")</em>. A review of <a href=\"https://whiteleydesigns.com/editing-wordpress-admin-menus/\" rel=\"nofollow noreferrer\">admin menu positioning</a>) reveals this entry is the <strong>Add New</strong> link made by the system for standard WP posts. The check that occurs tests whether or not the current user has the permission to <code>edit_posts</code>. As the special Subscriber user cannot edit \"posts,\" the check fails and the system breaks. When I learned this, the race was on to unset the <code>$submenu['edit.php']['post-new.php']</code> entry before <a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includes/menu.php#L81\" rel=\"nofollow noreferrer\">line 81</a> of <strong>wp-admin/includes/menu.php</strong> was executed. If one worked backwards from that line into <strong>wp-admin/menu.php</strong>, it would be found that the flag at issue is set on <a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/menu.php#L170\" rel=\"nofollow noreferrer\">line 170</a> with the execution of <code>$submenu[$ptype_file][10] = array($ptype_obj->labels->add_new, $ptype_obj->cap->create_posts, $post_new_file)</code>. So, the hooks fired between these two points in the code will allow us to interject and unset the flag that has caused me so much strife.</p>\n\n<p>The first function called with an available hook after this setting is <code>current_user_can('switch_themes')</code> on <a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/menu.php#L185\" rel=\"nofollow noreferrer\">line 185</a>. A check in the subsequently called <code>user_has_cap</code> for this squirmy flag will occur more times than one can count, so its not really the best hook to use. Following this, the only direct hooks available are those of <code>_network_admin_menu</code>, <code>_user_admin_menu</code>, or <code>_admin_menu</code> found in <strong>/wp-admin/includes/menu.php</strong> straight away at the very top of <a href=\"https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includes/menu.php#L9\" rel=\"nofollow noreferrer\">the file</a> (only one of them will fire depending on if the request is for the network administration interface, user administration interface, or neither). Since calling a filter from an unrelated function is a heck of a round-about way of doing things, I chose to make use of these hooks, like so:</p>\n\n<pre>\nadd_action('_network_admin_menu', 'pick_out_the_little_bugger');\nadd_action('_user_admin_menu', 'pick_out_the_little_bugger');\nadd_action('_admin_menu', 'pick_out_the_little_bugger');\nfunction pick_out_the_little_bugger() {\n // If the current user can not edit posts, unset the post menu\n if(!current_user_can('edit_posts')) {\n global $submenu;\n $problem_child = remove_menu_page('edit.php'); // Kill its parent and get its lineage.\n unset($submenu[$problem_child[2]]); // \"unset\" is just too nice for this wormy thing.\n }\n}\n</pre>\n\n<p>Jeezers this was a shot in the dark and wayyyy to much work for less than a dozen lines of code! Since I found a bunch of people with this same problem, I <a href=\"https://core.trac.wordpress.org/ticket/50284#ticket\" rel=\"nofollow noreferrer\">opened a ticket</a> to modify the WordPress Core.</p>\n"
},
{
"answer_id": 397952,
"author": "Dave S",
"author_id": 213761,
"author_profile": "https://wordpress.stackexchange.com/users/213761",
"pm_score": 0,
"selected": false,
"text": "<p>After debugging this same problem for an hour I was grateful to find this and realize it is a known bug. I took a slightly different approach to getting around it.</p>\n<p>This bug occurs when the CPT UI is a submenu page, the CPT has custom capabilities or capability type, and the current user does not have 'edit_posts' capability. I created a custom menu page to contain several custom post types and taxonomies and avoid cluttering the admin menu. But when the user does not have 'edit_posts' capability I only need to show one or two CPTs so I don't really need the custom menu page. So to get around the problem, I check if the current user can edit_posts and assign show_in_menu based on that.</p>\n<pre><code>class Admin_Menu_Page {\n const MENU_SLUG = 'my-menu-slug';\n // ...\n public static function get_CPT_show_in_menu() {\n if ( current_user_can( 'edit_posts' ) ) {\n $result = self::MENU_SLUG;\n } else {\n $result = TRUE;\n }\n return $result;\n }\n public static function create_menu() {\n if ( self::get_CPT_show_in_menu() === self::MENU_SLUG ) {\n // Create my custom menu page\n }\n }\n}\n\nclass My_CPT {\n const POST_TYPE = 'my-post-type';\n // ...\n public static function register() {\n $args = array(\n // ...\n 'show_in_menu' => Admin_Menu_Page::get_CPT_show_in_menu(),\n // ...\n );\n register_post_type( self::POST_TYPE, $args );\n }\n}\n</code></pre>\n"
}
] | 2020/05/29 | [
"https://wordpress.stackexchange.com/questions/367853",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/152456/"
] | Please i want to ensure only male or female is selected in the dropdown if not fail the form but my validation keeps returning false even if male or female is selected.
Html
```html
<select name="gender">
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Nonesense" selected>Nonesense</option>
</select>
```
Here is the php code
```php
if ( isset( $_POST['submit'] ) ) {
if ( $_POST['gender'] != 'Male' || $_POST['gender'] != 'Female' ) {
echo 'sorry it must be either male or female'; return '';
}
}
``` | The problem is that when the special subscriber tries to **Add New** a sub-cpt post, it is denied permission. However, when the CPT menu is a top-admin-menu, then everything works out fine. The issue is related to the placement of the CPT's UI menu in the back-end: if it's top-level (`show_in_menu=TRUE`), all is well; if its a submenu (`show_in_menu='my-menu-item'`), the user can't create the post type unless it has the `edit_posts` permission (even if it has all the `edit_PostType` permissions in the world). I've been chasing this stupid thing since the 22nd. Thanks to the pandemic, I haven't had to do much of anything else. After 12-15 hours each of the 8 days, I finally got this little bugger picked.
This issue had something to do with **post-new.php**, as all works out fine when the CPT is edited under the **post.php** script (which is nearly identical). The very first thing that **post-new.php** does is call on **admin.php**. On line [153](https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/admin.php#L153), **wp-admin/menu.php** is called in to bat which includes **wp-admin/includes/menu.php** as its [last execution](https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/menu.php#L326). On that **includes/menu.php** file's [line 341](https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includes/menu.php#L341), the `user_can_access_admin_page()` returns `FALSE`, triggering the `do_action('admin_page_access_denied')` hook to be fired and the `wp_die(__('Sorry, you are not allowed to access this page.'), 403)` command to kill the whole process.
The `user_can_access_admin_page()` method is defined on [line 2042](https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includes/plugin.php#L2042) of the **wp-admin/includes/plugin.php** file. [Line 2064](https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includes/plugin.php#L2064) passed its check in that `get_admin_page_parent()` was empty. This is followed by [line 2078](https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includes/plugin.php#L2078) failing its check in that the variable of `$_wp_submenu_nopriv['edit.php']['post-new.php']` is set. The combined effect of these checks the `FALSE` boolean being returned and WordPress dies.
The closest related script known to me is that of **post.php**, as the **admin.php** process is immediately called and runs in an identical manner, including the calling of `user_can_access_admin_page()`. Debugging demonstrates that the `user_can_access_admin_page()` is passed in the **post.php** script because, unlike **post-new.php**, none of the `$_wp_submenu_nopriv[____][$pagenow]` flags were set. So, the question is why this index is being set for **post-new.php** and not set for **post.php**.
The `global $_wp_submenu_nopriv` is first set on [line 71](https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includes/menu.php#L71) of **wp-admin/includes/menu.php**, in which that variable is initialized as an empty array. If the `current_user_can()` test is not passed on [line 79](https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includes/menu.php#L79), the flag is set on [line 81](https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includes/menu.php#L81). At that point, the `global $submenu['edit.php']` is initialized to the point of our concern, and contains the array at \*index=\*10 *("Add New", "edit\_posts", "post-new.php")*. A review of [admin menu positioning](https://whiteleydesigns.com/editing-wordpress-admin-menus/)) reveals this entry is the **Add New** link made by the system for standard WP posts. The check that occurs tests whether or not the current user has the permission to `edit_posts`. As the special Subscriber user cannot edit "posts," the check fails and the system breaks. When I learned this, the race was on to unset the `$submenu['edit.php']['post-new.php']` entry before [line 81](https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includes/menu.php#L81) of **wp-admin/includes/menu.php** was executed. If one worked backwards from that line into **wp-admin/menu.php**, it would be found that the flag at issue is set on [line 170](https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/menu.php#L170) with the execution of `$submenu[$ptype_file][10] = array($ptype_obj->labels->add_new, $ptype_obj->cap->create_posts, $post_new_file)`. So, the hooks fired between these two points in the code will allow us to interject and unset the flag that has caused me so much strife.
The first function called with an available hook after this setting is `current_user_can('switch_themes')` on [line 185](https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/menu.php#L185). A check in the subsequently called `user_has_cap` for this squirmy flag will occur more times than one can count, so its not really the best hook to use. Following this, the only direct hooks available are those of `_network_admin_menu`, `_user_admin_menu`, or `_admin_menu` found in **/wp-admin/includes/menu.php** straight away at the very top of [the file](https://core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includes/menu.php#L9) (only one of them will fire depending on if the request is for the network administration interface, user administration interface, or neither). Since calling a filter from an unrelated function is a heck of a round-about way of doing things, I chose to make use of these hooks, like so:
```
add_action('_network_admin_menu', 'pick_out_the_little_bugger');
add_action('_user_admin_menu', 'pick_out_the_little_bugger');
add_action('_admin_menu', 'pick_out_the_little_bugger');
function pick_out_the_little_bugger() {
// If the current user can not edit posts, unset the post menu
if(!current_user_can('edit_posts')) {
global $submenu;
$problem_child = remove_menu_page('edit.php'); // Kill its parent and get its lineage.
unset($submenu[$problem_child[2]]); // "unset" is just too nice for this wormy thing.
}
}
```
Jeezers this was a shot in the dark and wayyyy to much work for less than a dozen lines of code! Since I found a bunch of people with this same problem, I [opened a ticket](https://core.trac.wordpress.org/ticket/50284#ticket) to modify the WordPress Core. |
367,886 | <p>I using the InnerBlocks tag to allow for nested blocks, within my custom block. I am trying to use the 'allowedBlocks' argument to restrict the blocks allowed to only specific ones. However, if I put anything inside the InnerBlocks tag, the block does not load and just spins.</p>
<p>I am using acf_register_block for my block registry, as what we are doing heavily ties in with ACF.
I have enabled <code>'__experimental_jsx' => true</code> in all the blocks I am working with.</p>
<p>This works</p>
<pre><code><div>
<InnerBlocks />
</div>
</code></pre>
<p>This does not work</p>
<pre><code><div>
<InnerBlocks allowedBlocks={ 'acf/orange-carousel' } />
</div>
</code></pre>
<p>It also doesn't work if I pass an array instead of a string for the allowed blocks.</p>
<p>I am using ACF Pro Beta 5.9</p>
<p>Any help is appreciated!</p>
| [
{
"answer_id": 367901,
"author": "Garrett ",
"author_id": 189094,
"author_profile": "https://wordpress.stackexchange.com/users/189094",
"pm_score": 0,
"selected": false,
"text": "<p>Is <code>acf</code> the correct namespace? if so, this should work in your edit function.</p>\n\n<pre><code>const ALLOWED_BLOCKS = [\n 'acf/orange-carousel',\n]\n\nreturn (\n <div className={className}>\n <InnerBlocks\n allowedBlocks={ ALLOWED_BLOCKS }\n />\n </div>\n);\n</code></pre>\n"
},
{
"answer_id": 388025,
"author": "dowen121",
"author_id": 206262,
"author_profile": "https://wordpress.stackexchange.com/users/206262",
"pm_score": 2,
"selected": false,
"text": "<p>A late reply but I thought I would include a snippet that worked for me.</p>\n<p>Update <code>$allowed_inner_blocks</code> with your own "block_types" and place the following code inside the parent block template;</p>\n<pre><code><?php $allowed_inner_blocks = ['acf/logos']; ?>\n<InnerBlocks allowedBlocks="<?php echo esc_attr(wp_json_encode($allowed_inner_blocks)); ?>" />\n</code></pre>\n"
}
] | 2020/05/29 | [
"https://wordpress.stackexchange.com/questions/367886",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/168656/"
] | I using the InnerBlocks tag to allow for nested blocks, within my custom block. I am trying to use the 'allowedBlocks' argument to restrict the blocks allowed to only specific ones. However, if I put anything inside the InnerBlocks tag, the block does not load and just spins.
I am using acf\_register\_block for my block registry, as what we are doing heavily ties in with ACF.
I have enabled `'__experimental_jsx' => true` in all the blocks I am working with.
This works
```
<div>
<InnerBlocks />
</div>
```
This does not work
```
<div>
<InnerBlocks allowedBlocks={ 'acf/orange-carousel' } />
</div>
```
It also doesn't work if I pass an array instead of a string for the allowed blocks.
I am using ACF Pro Beta 5.9
Any help is appreciated! | A late reply but I thought I would include a snippet that worked for me.
Update `$allowed_inner_blocks` with your own "block\_types" and place the following code inside the parent block template;
```
<?php $allowed_inner_blocks = ['acf/logos']; ?>
<InnerBlocks allowedBlocks="<?php echo esc_attr(wp_json_encode($allowed_inner_blocks)); ?>" />
``` |
367,904 | <p>My previous blog author using his font-family and size on every sentence of blog post. I want apply new css rule to post but it cant overide these in-line styles.</p>
<p>I tried searching around and found this one:</p>
<pre><code>add_filter( 'the_content', function( $content ){
return str_replace( ' style="', ' data-style="', $content);
});
</code></pre>
<p>But it removing style of whole website. I just want remove style that used on single post's content only.</p>
| [
{
"answer_id": 367906,
"author": "Sabry Suleiman",
"author_id": 174580,
"author_profile": "https://wordpress.stackexchange.com/users/174580",
"pm_score": 1,
"selected": false,
"text": "<p>You can try this code it works better</p>\n\n<pre><code>add_filter('the_content', function( $content ){\n $content = preg_replace('/ style=(\"|\\')(.*?)(\"|\\')/','',$content);\n return $content;\n}, 20);\n</code></pre>\n"
},
{
"answer_id": 367908,
"author": "Behemoth",
"author_id": 188582,
"author_profile": "https://wordpress.stackexchange.com/users/188582",
"pm_score": 3,
"selected": true,
"text": "<p>You want to remove the style from single post. And the \"single post\" term is confusing.\nWhether you need it for a single post or the single post template. </p>\n\n<p>In either case you have to use your code with conditional and your code may look like this. </p>\n\n<p><strong><em>If you want to remove from all posts(not pages but including custom post types).</em></strong> </p>\n\n<pre><code>add_filter( 'the_content', function( $content ){\n\n if(is_single()){\n\n return str_replace( ' style=\"', ' data-style=\"', $content); \n\n }\n\n else{\n\n return $content;\n\n }\n\n}); \n</code></pre>\n\n<p><strong><em>If you want to remove from all posts(only WordPress post, not custom post type or pages).</em></strong></p>\n\n<pre><code>add_filter( 'the_content', function( $content ){\n\n if (is_singular('post')) {\n\n return str_replace( ' style=\"', ' data-style=\"', $content);\n\n } \n else{\n\n return $content;\n\n }\n}); \n</code></pre>\n\n<p><code>is_singular</code> is the WordPress API conditional to check post types.\n<a href=\"https://developer.wordpress.org/reference/functions/is_singular/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/is_singular/</a> </p>\n\n<p><strong><em>If you want to remove from only one particular post.</em></strong></p>\n\n<pre><code>add_filter( 'the_content', function( $content ){\n\n if(is_single([POST-ID])){\n\n return str_replace( ' style=\"', ' data-style=\"', $content);\n\n }\n else{\n\n return $content;\n\n }\n}); \n</code></pre>\n"
}
] | 2020/05/30 | [
"https://wordpress.stackexchange.com/questions/367904",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/153513/"
] | My previous blog author using his font-family and size on every sentence of blog post. I want apply new css rule to post but it cant overide these in-line styles.
I tried searching around and found this one:
```
add_filter( 'the_content', function( $content ){
return str_replace( ' style="', ' data-style="', $content);
});
```
But it removing style of whole website. I just want remove style that used on single post's content only. | You want to remove the style from single post. And the "single post" term is confusing.
Whether you need it for a single post or the single post template.
In either case you have to use your code with conditional and your code may look like this.
***If you want to remove from all posts(not pages but including custom post types).***
```
add_filter( 'the_content', function( $content ){
if(is_single()){
return str_replace( ' style="', ' data-style="', $content);
}
else{
return $content;
}
});
```
***If you want to remove from all posts(only WordPress post, not custom post type or pages).***
```
add_filter( 'the_content', function( $content ){
if (is_singular('post')) {
return str_replace( ' style="', ' data-style="', $content);
}
else{
return $content;
}
});
```
`is_singular` is the WordPress API conditional to check post types.
<https://developer.wordpress.org/reference/functions/is_singular/>
***If you want to remove from only one particular post.***
```
add_filter( 'the_content', function( $content ){
if(is_single([POST-ID])){
return str_replace( ' style="', ' data-style="', $content);
}
else{
return $content;
}
});
``` |
367,932 | <p>The documentation for InnerBlock has a prop <a href="https://github.com/WordPress/gutenberg/tree/master/packages/block-editor/src/components/inner-blocks#example-usage" rel="nofollow noreferrer">renderAppender</a> which can be used to add a custom button. In the example:</p>
<pre><code>// Fully custom
<InnerBlocks
renderAppender={ () => (
<button className="bespoke-appender" type="button">Some Special Appender</button>
) }
/>
</code></pre>
<p>the custom button does nothing on click. How can open the Block Picker Menu on click of the custom button?</p>
| [
{
"answer_id": 368098,
"author": "Welcher",
"author_id": 27210,
"author_profile": "https://wordpress.stackexchange.com/users/27210",
"pm_score": 2,
"selected": false,
"text": "<p>Custom <code>renderAppenders</code> require that you create all of the functionality of inserting blocks yourself. This is one I created a little while ago to only allow a single block to be inserted, you could modify the code as needed for your purposes.</p>\n\n<pre><code>/**\n * WordPress Imports\n */\nconst { createBlock } = wp.blocks;\nconst { Button } = wp.components;\nconst { withSelect, withDispatch } = wp.data;\nconst { compose } = wp.compose;\nconst { __ } = wp.i18n;\n\n\n/**\n * Custom Appender meant to be used when there is only one type of block that can be inserted to an InnerBlocks instance.\n *\n * @param buttonText\n * @param onClick\n * @param clientId\n * @param allowedBlock\n * @param innerBlocks\n * @param {Object} props\n */\nconst SingleBlockTypeAppender = ( { buttonText = __( 'Add Item' ), onClick, clientId, allowedBlock, innerBlocks, ...props } ) => {\n return(\n <Button onClick={ onClick } { ...props} >\n {buttonText}\n </Button>\n );\n};\n\n\nexport default compose( [\n withSelect( ( select, ownProps ) => {\n return {\n innerBlocks: select( 'core/block-editor' ).getBlock( ownProps.clientId ).innerBlocks\n };\n } ),\n withDispatch( ( dispatch, ownProps ) => {\n return {\n onClick() {\n const newBlock = createBlock( ownProps.allowedBlock );\n dispatch( 'core/block-editor' ).insertBlock( newBlock, ownProps.innerBlocks.length, ownProps.clientId );\n }\n };\n } )\n] )( SingleBlockTypeAppender );\n</code></pre>\n\n<p>You can then use it like this:</p>\n\n<pre><code><InnerBlocks\n renderAppender={\n () =>\n <SingleBlockTypeAppender\n isDefault\n isLarge\n buttonText=\"Add Block\"\n allowedBlock=\"block/slug\"\n clientId={ this.props.clientId }\n />\n }\n/>\n</code></pre>\n\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 368156,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": true,
"text": "<p>So I'm answering the following: <strong>How to open the <em>block picker menu</em> via a <em>custom button</em>.</strong> I.e. Without using <code>InnerBlocks.ButtonBlockAppender</code>. :)</p>\n\n<blockquote>\n <p>How can I open the Block Picker Menu on click of the custom button?</p>\n</blockquote>\n\n<p>There's no (as of writing) \"standard\" function (like <code>alert()</code>) that you can simply call which then opens the <em>block picker menu</em>; however, you can wrap your button in a <a href=\"https://github.com/WordPress/gutenberg/blob/master/packages/block-editor/src/components/inserter/index.js\" rel=\"nofollow noreferrer\"><code>Inserter</code> component</a> (<code>wp.blockEditor.Inserter</code>) and call it's <code>onToggle</code> method/function on clicking your button.</p>\n\n<p>Here's a simplified example based on <a href=\"https://github.com/WordPress/gutenberg/blob/v8.2.1/packages/block-editor/src/components/button-block-appender/index.js\" rel=\"nofollow noreferrer\"><code>ButtonBlockAppender</code></a> (the <em>base component</em> that's used by <code>InnerBlocks.ButtonBlockAppender</code>) for the Gutenberg <em>plugin</em> version 8.2.1.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>// WordPress dependencies.\nimport { Inserter, InnerBlocks } from '@wordpress/block-editor';\nimport { IconButton } from '@wordpress/components';\nimport { registerBlockType } from '@wordpress/blocks';\n\nfunction MyButtonBlockAppender( { rootClientId } ) {\n return (\n <Inserter\n rootClientId={ rootClientId }\n renderToggle={ ( { onToggle, disabled } ) => (\n <IconButton\n className=\"my-button-block-appender\"\n onClick={ onToggle }\n disabled={ disabled }\n label=\"Add a Block\"\n icon=\"plus\"\n />\n ) }\n isAppender\n />\n );\n}\n\nregisterBlockType( 'my-plugin/my-block', {\n title: 'My Block',\n category: 'common',\n\n edit( { className, clientId } ) {\n return (\n <div className={ className }>\n Click the button to add your 1st image/paragraph.\n <InnerBlocks\n allowedBlocks={ [ 'core/image', 'core/paragraph' ] }\n renderAppender={ () => (\n <MyButtonBlockAppender rootClientId={ clientId } />\n ) }\n />\n </div>\n );\n },\n\n save() {\n return (\n <div>\n <InnerBlocks.Content />\n </div>\n );\n },\n} );\n</code></pre>\n\n<p>So as I said, that's a simplified example. You can just copy the original <code>ButtonBlockAppender</code> component and modify it to tailor your requirements.</p>\n\n<p>Happy coding!</p>\n"
}
] | 2020/05/30 | [
"https://wordpress.stackexchange.com/questions/367932",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67538/"
] | The documentation for InnerBlock has a prop [renderAppender](https://github.com/WordPress/gutenberg/tree/master/packages/block-editor/src/components/inner-blocks#example-usage) which can be used to add a custom button. In the example:
```
// Fully custom
<InnerBlocks
renderAppender={ () => (
<button className="bespoke-appender" type="button">Some Special Appender</button>
) }
/>
```
the custom button does nothing on click. How can open the Block Picker Menu on click of the custom button? | So I'm answering the following: **How to open the *block picker menu* via a *custom button*.** I.e. Without using `InnerBlocks.ButtonBlockAppender`. :)
>
> How can I open the Block Picker Menu on click of the custom button?
>
>
>
There's no (as of writing) "standard" function (like `alert()`) that you can simply call which then opens the *block picker menu*; however, you can wrap your button in a [`Inserter` component](https://github.com/WordPress/gutenberg/blob/master/packages/block-editor/src/components/inserter/index.js) (`wp.blockEditor.Inserter`) and call it's `onToggle` method/function on clicking your button.
Here's a simplified example based on [`ButtonBlockAppender`](https://github.com/WordPress/gutenberg/blob/v8.2.1/packages/block-editor/src/components/button-block-appender/index.js) (the *base component* that's used by `InnerBlocks.ButtonBlockAppender`) for the Gutenberg *plugin* version 8.2.1.
```js
// WordPress dependencies.
import { Inserter, InnerBlocks } from '@wordpress/block-editor';
import { IconButton } from '@wordpress/components';
import { registerBlockType } from '@wordpress/blocks';
function MyButtonBlockAppender( { rootClientId } ) {
return (
<Inserter
rootClientId={ rootClientId }
renderToggle={ ( { onToggle, disabled } ) => (
<IconButton
className="my-button-block-appender"
onClick={ onToggle }
disabled={ disabled }
label="Add a Block"
icon="plus"
/>
) }
isAppender
/>
);
}
registerBlockType( 'my-plugin/my-block', {
title: 'My Block',
category: 'common',
edit( { className, clientId } ) {
return (
<div className={ className }>
Click the button to add your 1st image/paragraph.
<InnerBlocks
allowedBlocks={ [ 'core/image', 'core/paragraph' ] }
renderAppender={ () => (
<MyButtonBlockAppender rootClientId={ clientId } />
) }
/>
</div>
);
},
save() {
return (
<div>
<InnerBlocks.Content />
</div>
);
},
} );
```
So as I said, that's a simplified example. You can just copy the original `ButtonBlockAppender` component and modify it to tailor your requirements.
Happy coding! |
367,934 | <p>I have a list of emails I have fetched from the Wordpress database. </p>
<p>I would like to programmatically send emails to these emails using the contact form 7.</p>
<p>this is my code</p>
<pre><code>function benson_call_before_form_submit( $wpcf7 ){
$submission = WPCF7_Submission::get_instance();
if ( $submission ) {
$posted_data = $submission->get_posted_data();
}
if( $wpcf7->id() == 2216 || $wpcf7->id() == "2216" ) {
//$wpcf->skip_mail = true;
// we can now send the email here
$emails = get_mod_and_admin_emails(); // these are emails
// how do I send email inside here from contact form 7
// ?????????????????
}
}
add_action( 'wpcf7_before_send_mail', 'benson_call_before_form_submit' );
function get_mod_and_admin_emails( ){
global $bp;
$users = get_users( array( 'fields' => array( 'ID', 'user_email' ) ) );
$emails = "";
foreach($users as $key => $user){
$user_id = $user->ID;
if( groups_is_user_mod( $user_id, $bp->groups->current_group->id ) || groups_is_user_admin( $user_id, $bp->groups->current_group->id ) ){
$email = $user->user_email;
$emails .=$email.",";
}
}
return $emails;
}
</code></pre>
| [
{
"answer_id": 372158,
"author": "Aurovrata",
"author_id": 52120,
"author_profile": "https://wordpress.stackexchange.com/users/52120",
"pm_score": 1,
"selected": false,
"text": "<p>There is 2 way to achieve this, either</p>\n<p>1 use the 'wpcf7_mail_components' hook, to modify the email recipient or cc list,</p>\n<pre><code>add_filter( 'wpcf7_mail_components', 'change_email_address',10,3);\nfunction change_email_address($components, $form, $mailobj){\n //get the $users....\n foreach($users as $key => $user){\n $email = $user->user_email;\n //either as in the recipient list,\n $components['recipient'].=','.$email;\n //or add in cc\n $cc=$email.',';\n }\n $components['additional_headers']='cc:'.$cc;\n return $components;\n}\n</code></pre>\n<p>2 use the 'wpcf7_additional_mail' to create additional emails,</p>\n<pre><code>add_filter( 'wpcf7_additional_mail', 'send_additional_mails',10,2);\nfunction send_additional_mails($mails, $form){\n //$mails will container the maail_2 template if you have enabled it.\n //reset it if you don't want to send mail_2, but just using it as an additional mail template. \n $mails = array(); \n //get the $users....\n foreach($users as $key => $user){\n $email = $user->user_email;\n //copy your mail template\n $template = $form->prop('mail');\n //or if you have enabled mail 2 template, you can use that instead.\n $template = $form->prop('mail_2');\n //add the mail to the recipient list...\n $template['recipient'] = $email ;\n $mails[$email] = $template;\n }\n return $mails;\n}\n</code></pre>\n<p>Once you have set the templates, you can hook 'wpcf7_mail_components' to further filter your additional mails.</p>\n"
},
{
"answer_id": 378401,
"author": "Geza Gog",
"author_id": 143893,
"author_profile": "https://wordpress.stackexchange.com/users/143893",
"pm_score": 2,
"selected": false,
"text": "<p>You can manipulate recipients just before sending out the emails with the hook wpcf7_before_send_mail.</p>\n<p>Here is a simple script that adds an extra recipient:</p>\n<pre><code>add_action( 'wpcf7_before_send_mail', 'add_my_second_recipient', 10, 1 );\n\nfunction add_my_second_recipient($instance) {\n $properites = $instance->get_properties();\n // use below part if you want to add recipient based on the submitted data\n /*\n $submission = WPCF7_Submission::get_instance();\n $data = $submission->get_posted_data();\n */\n $additional_recipent = '[email protected]';\n $properites['mail']['recipient'] .= ', ' . $additional_recipent;\n \n $instance->set_properties($properites);\n return ($instance);\n}\n</code></pre>\n"
}
] | 2020/05/30 | [
"https://wordpress.stackexchange.com/questions/367934",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/153444/"
] | I have a list of emails I have fetched from the Wordpress database.
I would like to programmatically send emails to these emails using the contact form 7.
this is my code
```
function benson_call_before_form_submit( $wpcf7 ){
$submission = WPCF7_Submission::get_instance();
if ( $submission ) {
$posted_data = $submission->get_posted_data();
}
if( $wpcf7->id() == 2216 || $wpcf7->id() == "2216" ) {
//$wpcf->skip_mail = true;
// we can now send the email here
$emails = get_mod_and_admin_emails(); // these are emails
// how do I send email inside here from contact form 7
// ?????????????????
}
}
add_action( 'wpcf7_before_send_mail', 'benson_call_before_form_submit' );
function get_mod_and_admin_emails( ){
global $bp;
$users = get_users( array( 'fields' => array( 'ID', 'user_email' ) ) );
$emails = "";
foreach($users as $key => $user){
$user_id = $user->ID;
if( groups_is_user_mod( $user_id, $bp->groups->current_group->id ) || groups_is_user_admin( $user_id, $bp->groups->current_group->id ) ){
$email = $user->user_email;
$emails .=$email.",";
}
}
return $emails;
}
``` | You can manipulate recipients just before sending out the emails with the hook wpcf7\_before\_send\_mail.
Here is a simple script that adds an extra recipient:
```
add_action( 'wpcf7_before_send_mail', 'add_my_second_recipient', 10, 1 );
function add_my_second_recipient($instance) {
$properites = $instance->get_properties();
// use below part if you want to add recipient based on the submitted data
/*
$submission = WPCF7_Submission::get_instance();
$data = $submission->get_posted_data();
*/
$additional_recipent = '[email protected]';
$properites['mail']['recipient'] .= ', ' . $additional_recipent;
$instance->set_properties($properites);
return ($instance);
}
``` |
368,016 | <p>I am conditionally showing menu items. All is fine but want to remove parent item if returning no child items. </p>
<p>For example if I have a parent menu (it will always be a custom link with #) called <strong>More</strong> and it has multiple child items (mostly one level). Now if I am hiding child items based on user roles and for some roles no child items available, in that case, I want to remove <strong>More</strong> menu items also since it has no child.</p>
<p>I am trying with the following code but since <code>$item</code> is an object, <code>array_search</code> won't work. So how can I check for child-parent and remove the menu item if it has no child?</p>
<pre><code>array_search( $item[ 'ID' ], array_column( $item, 'menu_item_parent' ) )
</code></pre>
<p>Below is the working code that hides menu item based on user roles.</p>
<pre><code>public static function exclude_menu_items( $items, $menu, $args ) {
if ( current_user_can( 'administrator' ) ) {
return $items;
}
foreach ( $items as $key => $item ) {
if ( $page = get_post( $item->object_id ) ) {
if ( $page->post_type == 'page' ) {
$template = get_post_meta( $page->ID, '_wp_page_template', TRUE );
$post_type = self::get_cpt_for_template( $template );
if ( $post_type && ( ! current_user_can( 'cp_access_' . $post_type ) || ! ( new self() )->is_current_user_granted_for_module( $post_type ) ) ) {
unset( $items[ $key ] );
}
}
}
}
return $items;
}
</code></pre>
| [
{
"answer_id": 368153,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": true,
"text": "<p>If you want to use the <code>wp_get_nav_menu_items</code> hook, then try the function below which should be hooked <em>after</em> the <code>exclude_menu_items</code> function:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>// Example when NOT using a class: (you already defined the exclude_menu_items function)\nadd_filter( 'wp_get_nav_menu_items', 'exclude_menu_items', 10, 3 );\nadd_filter( 'wp_get_nav_menu_items', 'exclude_menu_items2' );\n\nfunction exclude_menu_items2( $items ) {\n if ( current_user_can( 'administrator' ) ) {\n return $items;\n }\n\n $mores = [];\n $parents = [];\n foreach ( $items as $key => $item ) {\n if ( '#' === $item->url && 'More' === $item->title ) {\n $mores[] = $item->ID;\n }\n\n if ( ! in_array( $item->menu_item_parent, $parents ) ) {\n $parents[] = $item->menu_item_parent;\n }\n }\n\n $mores = array_diff( $mores, $parents );\n foreach ( $items as $i => $item ) {\n if ( in_array( $item->ID, $mores ) ) {\n unset( $items[ $i ] );\n }\n }\n\n return $items;\n}\n</code></pre>\n\n<p>Just make sure to run the appropriate validation so that the menu items don't get messed, e.g. on the Menus admin screen.</p>\n\n<p>And the two functions can also be <em>combined</em>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function exclude_menu_items( $items, $menu, $args ) {\n if ( current_user_can( 'administrator' ) ) {\n return $items;\n }\n\n $mores = [];\n $parents = [];\n foreach ( $items as $key => $item ) {\n if ( $page = get_post( $item->object_id ) ) {\n // ... your code here.\n }\n\n if ( ! empty( $items[ $key ] ) ) {\n if ( '#' === $item->url && 'More' === $item->title ) {\n $mores[] = $item->ID;\n }\n\n if ( ! in_array( $item->menu_item_parent, $parents ) ) {\n $parents[] = $item->menu_item_parent;\n }\n }\n }\n\n $mores = array_diff( $mores, $parents );\n foreach ( $items as $i => $item ) {\n if ( in_array( $item->ID, $mores ) ) {\n unset( $items[ $i ] );\n }\n }\n\n return $items;\n}\n</code></pre>\n\n<p>And actually — when <code>wp_nav_menu()</code> is called — with the <a href=\"https://developer.wordpress.org/reference/hooks/wp_nav_menu_objects/\" rel=\"nofollow noreferrer\"><code>wp_nav_menu_objects</code> hook</a>, it's simpler to remove the \"More\" items which have no children:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'wp_nav_menu_objects', function ( $items ) {\n if ( is_admin() ) { // sample validation..\n return $items;\n }\n\n return array_filter( $items, function ( $item ) {\n return ! ( '#' === $item->url && 'More' === $item->title &&\n ! in_array( 'menu-item-has-children', $item->classes )\n );\n } );\n} );\n</code></pre>\n"
},
{
"answer_id": 388791,
"author": "dimitrisv",
"author_id": 206979,
"author_profile": "https://wordpress.stackexchange.com/users/206979",
"pm_score": 0,
"selected": false,
"text": "<p>Here you may find a more in depth approach on dealing with the limitations of the wp_get_nav_menu_items</p>\n<p>It uses SQL to determine the children but provides far more flexibility in order to achieve full control of what you are actually want to do:</p>\n<pre><code> //this query produces all you need to have for the children at any depth. It is explained on the readme and will spare you the add on walkers. \n $query = "SELECT e.id, e.post_title, CASE WHEN c.meta_value='custom' THEN ( d.meta_value) ELSE concat ('/', e.post_name ,'/') END as linkurl, b.post_id \n FROM wp_postmeta a FORCE INDEX (post_id)\n JOIN wp_postmeta b FORCE INDEX (post_id) ON a.post_id=b.post_id\n JOIN wp_postmeta c FORCE INDEX (post_id) ON c.post_id=b.post_id\n JOIN wp_postmeta d FORCE INDEX (post_id) ON d.post_id=b.post_id\n JOIN wp_posts e ON e.id=b.meta_value\n WHERE d.meta_key='_menu_item_url' AND c.meta_key='_menu_item_object' AND b.meta_key='_menu_item_object_id' \n AND a.meta_key='_menu_item_menu_item_parent' AND a.meta_value='" . $submenu->ID . "'";\n\n $resultsData = $wpdb->get_results($query);\n\n foreach ($resultsData as $childrenData) {\n\n $menu_html_s .= '<!-- Lets print each of the children -->';\n $menu_html_s .= '<div class="menu-sub menu-sub-accordion menu-active-bg">';\n $menu_html_s .= '<div class="menu-item">';\n $menu_html_s .= '<a class="menu-link" href="' . $childrenData->linkurl . '">';\n $menu_html_s .= '<span class="menu-bullet">';\n $menu_html_s .= '<span class="bullet bullet-dot"></span>';\n $menu_html_s .= '</span>';\n $menu_html_s .= '<span class="menu-title">' . $childrenData->post_title . '</span>';\n $menu_html_s .= '</a>';\n $menu_html_s .= '</div>';\n $menu_html_s .= '</div>';\n</code></pre>\n<p>More details here:</p>\n<p><a href=\"https://github.com/exonianp/wp-bootstrap5-accordeon-vertical-menu\" rel=\"nofollow noreferrer\">https://github.com/exonianp/wp-bootstrap5-accordeon-vertical-menu</a></p>\n"
}
] | 2020/06/01 | [
"https://wordpress.stackexchange.com/questions/368016",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/9821/"
] | I am conditionally showing menu items. All is fine but want to remove parent item if returning no child items.
For example if I have a parent menu (it will always be a custom link with #) called **More** and it has multiple child items (mostly one level). Now if I am hiding child items based on user roles and for some roles no child items available, in that case, I want to remove **More** menu items also since it has no child.
I am trying with the following code but since `$item` is an object, `array_search` won't work. So how can I check for child-parent and remove the menu item if it has no child?
```
array_search( $item[ 'ID' ], array_column( $item, 'menu_item_parent' ) )
```
Below is the working code that hides menu item based on user roles.
```
public static function exclude_menu_items( $items, $menu, $args ) {
if ( current_user_can( 'administrator' ) ) {
return $items;
}
foreach ( $items as $key => $item ) {
if ( $page = get_post( $item->object_id ) ) {
if ( $page->post_type == 'page' ) {
$template = get_post_meta( $page->ID, '_wp_page_template', TRUE );
$post_type = self::get_cpt_for_template( $template );
if ( $post_type && ( ! current_user_can( 'cp_access_' . $post_type ) || ! ( new self() )->is_current_user_granted_for_module( $post_type ) ) ) {
unset( $items[ $key ] );
}
}
}
}
return $items;
}
``` | If you want to use the `wp_get_nav_menu_items` hook, then try the function below which should be hooked *after* the `exclude_menu_items` function:
```php
// Example when NOT using a class: (you already defined the exclude_menu_items function)
add_filter( 'wp_get_nav_menu_items', 'exclude_menu_items', 10, 3 );
add_filter( 'wp_get_nav_menu_items', 'exclude_menu_items2' );
function exclude_menu_items2( $items ) {
if ( current_user_can( 'administrator' ) ) {
return $items;
}
$mores = [];
$parents = [];
foreach ( $items as $key => $item ) {
if ( '#' === $item->url && 'More' === $item->title ) {
$mores[] = $item->ID;
}
if ( ! in_array( $item->menu_item_parent, $parents ) ) {
$parents[] = $item->menu_item_parent;
}
}
$mores = array_diff( $mores, $parents );
foreach ( $items as $i => $item ) {
if ( in_array( $item->ID, $mores ) ) {
unset( $items[ $i ] );
}
}
return $items;
}
```
Just make sure to run the appropriate validation so that the menu items don't get messed, e.g. on the Menus admin screen.
And the two functions can also be *combined*:
```php
function exclude_menu_items( $items, $menu, $args ) {
if ( current_user_can( 'administrator' ) ) {
return $items;
}
$mores = [];
$parents = [];
foreach ( $items as $key => $item ) {
if ( $page = get_post( $item->object_id ) ) {
// ... your code here.
}
if ( ! empty( $items[ $key ] ) ) {
if ( '#' === $item->url && 'More' === $item->title ) {
$mores[] = $item->ID;
}
if ( ! in_array( $item->menu_item_parent, $parents ) ) {
$parents[] = $item->menu_item_parent;
}
}
}
$mores = array_diff( $mores, $parents );
foreach ( $items as $i => $item ) {
if ( in_array( $item->ID, $mores ) ) {
unset( $items[ $i ] );
}
}
return $items;
}
```
And actually — when `wp_nav_menu()` is called — with the [`wp_nav_menu_objects` hook](https://developer.wordpress.org/reference/hooks/wp_nav_menu_objects/), it's simpler to remove the "More" items which have no children:
```php
add_filter( 'wp_nav_menu_objects', function ( $items ) {
if ( is_admin() ) { // sample validation..
return $items;
}
return array_filter( $items, function ( $item ) {
return ! ( '#' === $item->url && 'More' === $item->title &&
! in_array( 'menu-item-has-children', $item->classes )
);
} );
} );
``` |
368,033 | <p>I am creating a plugin to redirect all sign in attempts to a dedicated page rather than using the builting wordpress page<br>
so i created this hook action for the admin_init with the highest priority over other callbacks </p>
<pre><code>add_action( 'admin_init', 'redirect_callback', 1)
</code></pre>
<p>the callback function will then make sure the user is not signed in already to make the redirect </p>
<pre><code>function redirect_callback() {
if ( ! is_user_logged_in() ) {
wp_redirect( /* my link */ );
exit;
}
}
</code></pre>
<p>and of course the <code>is_user_logged_in()</code> needs this dependency</p>
<pre><code>include(ABSPATH."wp-includes/pluggable.php")
</code></pre>
<p>visiting this link: <code>url/wp-admin</code> still doesn't redirect anywhere, it still pulls up the wordpress press sign in page.<br>
anyone can help ?</p>
| [
{
"answer_id": 368153,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": true,
"text": "<p>If you want to use the <code>wp_get_nav_menu_items</code> hook, then try the function below which should be hooked <em>after</em> the <code>exclude_menu_items</code> function:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>// Example when NOT using a class: (you already defined the exclude_menu_items function)\nadd_filter( 'wp_get_nav_menu_items', 'exclude_menu_items', 10, 3 );\nadd_filter( 'wp_get_nav_menu_items', 'exclude_menu_items2' );\n\nfunction exclude_menu_items2( $items ) {\n if ( current_user_can( 'administrator' ) ) {\n return $items;\n }\n\n $mores = [];\n $parents = [];\n foreach ( $items as $key => $item ) {\n if ( '#' === $item->url && 'More' === $item->title ) {\n $mores[] = $item->ID;\n }\n\n if ( ! in_array( $item->menu_item_parent, $parents ) ) {\n $parents[] = $item->menu_item_parent;\n }\n }\n\n $mores = array_diff( $mores, $parents );\n foreach ( $items as $i => $item ) {\n if ( in_array( $item->ID, $mores ) ) {\n unset( $items[ $i ] );\n }\n }\n\n return $items;\n}\n</code></pre>\n\n<p>Just make sure to run the appropriate validation so that the menu items don't get messed, e.g. on the Menus admin screen.</p>\n\n<p>And the two functions can also be <em>combined</em>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function exclude_menu_items( $items, $menu, $args ) {\n if ( current_user_can( 'administrator' ) ) {\n return $items;\n }\n\n $mores = [];\n $parents = [];\n foreach ( $items as $key => $item ) {\n if ( $page = get_post( $item->object_id ) ) {\n // ... your code here.\n }\n\n if ( ! empty( $items[ $key ] ) ) {\n if ( '#' === $item->url && 'More' === $item->title ) {\n $mores[] = $item->ID;\n }\n\n if ( ! in_array( $item->menu_item_parent, $parents ) ) {\n $parents[] = $item->menu_item_parent;\n }\n }\n }\n\n $mores = array_diff( $mores, $parents );\n foreach ( $items as $i => $item ) {\n if ( in_array( $item->ID, $mores ) ) {\n unset( $items[ $i ] );\n }\n }\n\n return $items;\n}\n</code></pre>\n\n<p>And actually — when <code>wp_nav_menu()</code> is called — with the <a href=\"https://developer.wordpress.org/reference/hooks/wp_nav_menu_objects/\" rel=\"nofollow noreferrer\"><code>wp_nav_menu_objects</code> hook</a>, it's simpler to remove the \"More\" items which have no children:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'wp_nav_menu_objects', function ( $items ) {\n if ( is_admin() ) { // sample validation..\n return $items;\n }\n\n return array_filter( $items, function ( $item ) {\n return ! ( '#' === $item->url && 'More' === $item->title &&\n ! in_array( 'menu-item-has-children', $item->classes )\n );\n } );\n} );\n</code></pre>\n"
},
{
"answer_id": 388791,
"author": "dimitrisv",
"author_id": 206979,
"author_profile": "https://wordpress.stackexchange.com/users/206979",
"pm_score": 0,
"selected": false,
"text": "<p>Here you may find a more in depth approach on dealing with the limitations of the wp_get_nav_menu_items</p>\n<p>It uses SQL to determine the children but provides far more flexibility in order to achieve full control of what you are actually want to do:</p>\n<pre><code> //this query produces all you need to have for the children at any depth. It is explained on the readme and will spare you the add on walkers. \n $query = "SELECT e.id, e.post_title, CASE WHEN c.meta_value='custom' THEN ( d.meta_value) ELSE concat ('/', e.post_name ,'/') END as linkurl, b.post_id \n FROM wp_postmeta a FORCE INDEX (post_id)\n JOIN wp_postmeta b FORCE INDEX (post_id) ON a.post_id=b.post_id\n JOIN wp_postmeta c FORCE INDEX (post_id) ON c.post_id=b.post_id\n JOIN wp_postmeta d FORCE INDEX (post_id) ON d.post_id=b.post_id\n JOIN wp_posts e ON e.id=b.meta_value\n WHERE d.meta_key='_menu_item_url' AND c.meta_key='_menu_item_object' AND b.meta_key='_menu_item_object_id' \n AND a.meta_key='_menu_item_menu_item_parent' AND a.meta_value='" . $submenu->ID . "'";\n\n $resultsData = $wpdb->get_results($query);\n\n foreach ($resultsData as $childrenData) {\n\n $menu_html_s .= '<!-- Lets print each of the children -->';\n $menu_html_s .= '<div class="menu-sub menu-sub-accordion menu-active-bg">';\n $menu_html_s .= '<div class="menu-item">';\n $menu_html_s .= '<a class="menu-link" href="' . $childrenData->linkurl . '">';\n $menu_html_s .= '<span class="menu-bullet">';\n $menu_html_s .= '<span class="bullet bullet-dot"></span>';\n $menu_html_s .= '</span>';\n $menu_html_s .= '<span class="menu-title">' . $childrenData->post_title . '</span>';\n $menu_html_s .= '</a>';\n $menu_html_s .= '</div>';\n $menu_html_s .= '</div>';\n</code></pre>\n<p>More details here:</p>\n<p><a href=\"https://github.com/exonianp/wp-bootstrap5-accordeon-vertical-menu\" rel=\"nofollow noreferrer\">https://github.com/exonianp/wp-bootstrap5-accordeon-vertical-menu</a></p>\n"
}
] | 2020/06/01 | [
"https://wordpress.stackexchange.com/questions/368033",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] | I am creating a plugin to redirect all sign in attempts to a dedicated page rather than using the builting wordpress page
so i created this hook action for the admin\_init with the highest priority over other callbacks
```
add_action( 'admin_init', 'redirect_callback', 1)
```
the callback function will then make sure the user is not signed in already to make the redirect
```
function redirect_callback() {
if ( ! is_user_logged_in() ) {
wp_redirect( /* my link */ );
exit;
}
}
```
and of course the `is_user_logged_in()` needs this dependency
```
include(ABSPATH."wp-includes/pluggable.php")
```
visiting this link: `url/wp-admin` still doesn't redirect anywhere, it still pulls up the wordpress press sign in page.
anyone can help ? | If you want to use the `wp_get_nav_menu_items` hook, then try the function below which should be hooked *after* the `exclude_menu_items` function:
```php
// Example when NOT using a class: (you already defined the exclude_menu_items function)
add_filter( 'wp_get_nav_menu_items', 'exclude_menu_items', 10, 3 );
add_filter( 'wp_get_nav_menu_items', 'exclude_menu_items2' );
function exclude_menu_items2( $items ) {
if ( current_user_can( 'administrator' ) ) {
return $items;
}
$mores = [];
$parents = [];
foreach ( $items as $key => $item ) {
if ( '#' === $item->url && 'More' === $item->title ) {
$mores[] = $item->ID;
}
if ( ! in_array( $item->menu_item_parent, $parents ) ) {
$parents[] = $item->menu_item_parent;
}
}
$mores = array_diff( $mores, $parents );
foreach ( $items as $i => $item ) {
if ( in_array( $item->ID, $mores ) ) {
unset( $items[ $i ] );
}
}
return $items;
}
```
Just make sure to run the appropriate validation so that the menu items don't get messed, e.g. on the Menus admin screen.
And the two functions can also be *combined*:
```php
function exclude_menu_items( $items, $menu, $args ) {
if ( current_user_can( 'administrator' ) ) {
return $items;
}
$mores = [];
$parents = [];
foreach ( $items as $key => $item ) {
if ( $page = get_post( $item->object_id ) ) {
// ... your code here.
}
if ( ! empty( $items[ $key ] ) ) {
if ( '#' === $item->url && 'More' === $item->title ) {
$mores[] = $item->ID;
}
if ( ! in_array( $item->menu_item_parent, $parents ) ) {
$parents[] = $item->menu_item_parent;
}
}
}
$mores = array_diff( $mores, $parents );
foreach ( $items as $i => $item ) {
if ( in_array( $item->ID, $mores ) ) {
unset( $items[ $i ] );
}
}
return $items;
}
```
And actually — when `wp_nav_menu()` is called — with the [`wp_nav_menu_objects` hook](https://developer.wordpress.org/reference/hooks/wp_nav_menu_objects/), it's simpler to remove the "More" items which have no children:
```php
add_filter( 'wp_nav_menu_objects', function ( $items ) {
if ( is_admin() ) { // sample validation..
return $items;
}
return array_filter( $items, function ( $item ) {
return ! ( '#' === $item->url && 'More' === $item->title &&
! in_array( 'menu-item-has-children', $item->classes )
);
} );
} );
``` |
368,122 | <p>I'm tryng without success to create a custom backend based on user ID, if user id is different the 1 or different then 2 show custom backend.</p>
<p>This is my code but it doesn't work, any help would be very appreciate it.</p>
<pre><code>if ($current_user_id != 1 || $current_user_id != 2){ show custom backend
</code></pre>
<p>Thank you</p>
| [
{
"answer_id": 368123,
"author": "shanebp",
"author_id": 16575,
"author_profile": "https://wordpress.stackexchange.com/users/16575",
"pm_score": 0,
"selected": false,
"text": "<p>Use: <code>get_current_user_id()</code></p>\n\n<pre><code>$current_user_id = get_current_user_id();\nif ($current_user_id != 1 && $current_user_id != 2){ \n //show custom backend\n}\n</code></pre>\n"
},
{
"answer_id": 368124,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<p>You do not want an OR, you want an AND.</p>\n\n<p>Follow it through and substitute the values. If we are user 1, then it's true because we are not user 2, and true OR false resolves to true. Only one of them needs to be true for an OR to be true. If we are user 2, then it's true because we are not user 1, and false OR true also resolves to true.</p>\n\n<p>Remember, <code>a or b</code> is true if A, B, or both are true. I know what you meant, but the computer does not, and you have to be extremely exact.</p>\n\n<p>When you say I do not want A or B, what you really meant was I do not want A <strong><em>and</em></strong> I do not want B.</p>\n\n<p>so replace this:</p>\n\n<pre><code>if user is not 1 or user is not 2\n</code></pre>\n\n<p>with:</p>\n\n<pre><code>if user is not 1 and user is not 2\n</code></pre>\n\n<p>Or better yet:</p>\n\n<pre><code>if user is not in this array [ 1, 2]\n</code></pre>\n"
}
] | 2020/06/02 | [
"https://wordpress.stackexchange.com/questions/368122",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107630/"
] | I'm tryng without success to create a custom backend based on user ID, if user id is different the 1 or different then 2 show custom backend.
This is my code but it doesn't work, any help would be very appreciate it.
```
if ($current_user_id != 1 || $current_user_id != 2){ show custom backend
```
Thank you | You do not want an OR, you want an AND.
Follow it through and substitute the values. If we are user 1, then it's true because we are not user 2, and true OR false resolves to true. Only one of them needs to be true for an OR to be true. If we are user 2, then it's true because we are not user 1, and false OR true also resolves to true.
Remember, `a or b` is true if A, B, or both are true. I know what you meant, but the computer does not, and you have to be extremely exact.
When you say I do not want A or B, what you really meant was I do not want A ***and*** I do not want B.
so replace this:
```
if user is not 1 or user is not 2
```
with:
```
if user is not 1 and user is not 2
```
Or better yet:
```
if user is not in this array [ 1, 2]
``` |
368,169 | <p>Please i need assistance in converting objects that is returned from $wpdb->get_results into arrays so that i can call them values like $query['username'] instead of using $Query->username <br><br> because my method of doing it is not flexible enough and it makes me write many codes by manually creating those column as array just like this code below <br> <code>$data = array('username = $query->username, email = $query->email');</code> <br> but i believe there is a simple way to do this automatically without having to retype all column names one by one </p>
| [
{
"answer_id": 368170,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 2,
"selected": true,
"text": "<p><a href=\"https://developer.wordpress.org/reference/classes/wpdb/get_results/\" rel=\"nofollow noreferrer\"><code>$wpdb->get_results</code></a> has a second parameter that lets you specify what kind of return value you want:</p>\n\n<p>For example:</p>\n\n<pre><code>$data = $wpdb->get_results( $query, ARRAY_A );\n</code></pre>\n\n<p>Here you get an associative array back.</p>\n"
},
{
"answer_id": 368173,
"author": "Baikare Sandeep",
"author_id": 99404,
"author_profile": "https://wordpress.stackexchange.com/users/99404",
"pm_score": 0,
"selected": false,
"text": "<p>Hey you can try this to use the Object in array format:</p>\n\n<pre><code>global $wpdb;\n$data = $wpdb->get_results( \"SELECT * FROM {$wpdb->prefix}users\", OBJECT );\n$data = json_decode( json_encode($data), true );\necho $data[0]['user_email'];\n</code></pre>\n\n<p>Also, you can use the <code>unset()</code> method to remove unwanted columns from the array.\nBy using this way you can achieve. </p>\n"
},
{
"answer_id": 368180,
"author": "pandglobal",
"author_id": 152456,
"author_profile": "https://wordpress.stackexchange.com/users/152456",
"pm_score": 1,
"selected": false,
"text": "<pre><code>global $wpdb;\n$data = $wpdb->get_results( \"SELECT * FROM {$wpdb->prefix}users\", ARRAY_A );\n\nforeach($data as $user){ \n$deuser = $user;\n}\n\necho $deuser['username'];`\n</code></pre>\n"
}
] | 2020/06/03 | [
"https://wordpress.stackexchange.com/questions/368169",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/152456/"
] | Please i need assistance in converting objects that is returned from $wpdb->get\_results into arrays so that i can call them values like $query['username'] instead of using $Query->username
because my method of doing it is not flexible enough and it makes me write many codes by manually creating those column as array just like this code below
`$data = array('username = $query->username, email = $query->email');`
but i believe there is a simple way to do this automatically without having to retype all column names one by one | [`$wpdb->get_results`](https://developer.wordpress.org/reference/classes/wpdb/get_results/) has a second parameter that lets you specify what kind of return value you want:
For example:
```
$data = $wpdb->get_results( $query, ARRAY_A );
```
Here you get an associative array back. |
368,194 | <p>Having a perplexing issue... ...for a custom post-type called 'Resources' I used the 'Featured Image' or 'thumbnail' function within WordPress to allow users to attach documents to 'Resources'. The process itself works exactly as expected and anticipated.</p>
<p>However, setting the site up, someone made a mistake and uploaded two documents and assigned them to the wrong 'Resources'. So <code>Resource A -> Document B</code> and <code>Resource B -> Document A</code>.</p>
<p>When attempting to switch them and clicking 'Edit Featured Image' you are unable to see any of the documents. They clicked 'Remove Featured Image' and then 'Set Featured Image' and when the dialogue opens, still no documents.</p>
<p>In the Wordpress Media Library all of the uploaded and attached documents are there. Visible, with previews, etc. As expected. Here's the first two rows of the Media Library. You can see tons of PDFs that have been successfully uploaded.
<a href="https://i.stack.imgur.com/Ud8rF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ud8rF.png" alt="Media Library"></a></p>
<p>The only place where this issue appears is that in the actual 'Featured Image' media dialogue box, WordPress will not display any PDFs.</p>
<p>Here's the CPT supports segment:</p>
<pre><code>$rsc_supports = array(
'title',
'editor',
'thumbnail',
'page-attributes'
);
</code></pre>
<p>Like I said, everything works perfectly - even uploading and attaching PDFs as 'thumbnails' to be associated as attachments with the CPT. When a PDF is attached and you 'Click to edit' the dialogue opens up and you can see the attached PDF in the list.
The only failing is that the 'Featured Image' modal/pop-up/dialogue box that loads, is designed to filter out everything except images.
This is what that dialogue box looks like on a 'Resource' with nothing attached.
<a href="https://i.stack.imgur.com/QbYLX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QbYLX.png" alt="Featured Image Dialogue"></a></p>
<p>However, if you view another Resource that does have a PDF already attached, you get this:
<a href="https://i.stack.imgur.com/jvZne.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jvZne.png" alt="With PDF Attached"></a></p>
<p>I have tried the filtering and date dropdown and they don't address this.</p>
<p>I believe this is by design. So my question is, <strong>"How do I modify that dialogue box to display all files rather than just images?"</strong></p>
| [
{
"answer_id": 368759,
"author": "Ahmad Wael",
"author_id": 115635,
"author_profile": "https://wordpress.stackexchange.com/users/115635",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried this plugin <a href=\"https://wordpress.org/plugins/pdf-thumbnails/\" rel=\"nofollow noreferrer\">PDF Thumbnails</a> ?</p>\n\n<p>This plugin generates a thumbnail from the first page in the\nuploaded document and names it as PDFNAME-thumbnail, then you can use this image as a featured image. this plugin is outdated, about 4 years ago so be sure for testing and compatibility.</p>\n"
},
{
"answer_id": 368772,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": true,
"text": "<h1>So this may be hacky..</h1>\n\n<p>I mean, compared to <a href=\"https://github.com/WordPress/gutenberg/tree/master/packages/editor/src/components/post-featured-image\" rel=\"nofollow noreferrer\">overriding the default Featured Image panel/component in the Gutenberg block editor</a>, which is not exactly hard, but this one is much simpler and basically just needs a few lines of custom coding. (read till the end to see what I mean)</p>\n\n<p>And I've also tried & tested it working (with both the old/classic editor and the Gutenberg block editor) on WordPress 5.4.2 (the latest release as of writing) as well as WordPress 5.4.1.</p>\n\n<p>So for what you're trying to do, you can override <code>wp.media.model.Query.prototype.sync()</code> (defined in <a href=\"https://build.trac.wordpress.org/browser/tags/5.4.2/wp-includes/js/media-models.js#L1214\" rel=\"nofollow noreferrer\"><code>wp-includes/js/media-models.js</code></a>) which is the function used by the default Featured Image modal for querying attachments via AJAX (<code>admin-ajax.php?action=query-attachments</code>).</p>\n\n<h2>Full (JS) Code</h2>\n\n<pre class=\"lang-js prettyprint-override\"><code>wp.media.model.Query.prototype.sync = function( method, model, options ) {\n var args, fallback;\n\n // Overload the read method so Attachment.fetch() functions correctly.\n if ( 'read' === method ) {\n options = options || {};\n options.context = this;\n options.data = _.extend( options.data || {}, {\n action: 'query-attachments',\n post_id: wp.media.model.settings.post.id\n });\n\n // Clone the args so manipulation is non-destructive.\n args = _.clone( this.args );\n\n // Determine which page to query.\n if ( -1 !== args.posts_per_page ) {\n args.paged = Math.round( this.length / args.posts_per_page ) + 1;\n }\n\n if ( wp.media.frame && 'featured-image' === wp.media.frame.options.state ) {\n // Here I'm allowing image and PDF files only.\n args.post_mime_type = 'image, application/pdf';\n }\n\n options.data.query = args;\n return wp.media.ajax( options );\n\n // Otherwise, fall back to `Backbone.sync()`.\n } else {\n /**\n * Call wp.media.model.Attachments.sync or Backbone.sync\n */\n fallback = Attachments.prototype.sync ? Attachments.prototype : Backbone;\n return fallback.sync.apply( this, arguments );\n }\n};\n</code></pre>\n\n<p><em>But the only thing I added there is this conditional block:</em></p>\n\n<pre class=\"lang-js prettyprint-override\"><code>if ( wp.media.frame && 'featured-image' === wp.media.frame.options.state ) {\n // Here I'm allowing image and PDF files only.\n args.post_mime_type = 'image, application/pdf';\n}\n</code></pre>\n\n<p>Which checks if the currently opened modal is the featured image modal and if so, then we modify the <a href=\"https://developer.wordpress.org/reference/classes/wp_query/parse_query/#parameters\" rel=\"nofollow noreferrer\"><code>post_mime_type</code> argument</a> which defines the MIME type(s) of the attachments being queried.</p>\n\n<p>And that's how you can use this approach to force the Featured Image modal to include files <em>other than images</em>.</p>\n\n<h2>Sample PHP Code</h2>\n\n<blockquote>\n <p><em>Update Jun 13<sup>th</sup> (to other readers):</em> Just to clarify why should we check for the <code>media-models</code> script, which is because we're\n overriding something in that script, so if the script is not being\n loaded on the current page, then there's no need to echo/enqueue our\n custom script. :)</p>\n</blockquote>\n\n<p>The following is the PHP code I used to <em>echo the script in the footer</em> on the post editing screen for the default <code>post</code> and <code>page</code> post types:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'admin_print_footer_scripts', function () {\n $screen_ids = [ 'post', 'page' ];\n if ( in_array( get_current_screen()->id, $screen_ids ) &&\n wp_script_is( 'media-models' ) // check if media-models.js was enqueued\n ) :\n ?>\n <script>\n // See/copy the FULL code above and place it here..\n </script>\n <?php\n endif;\n} );\n</code></pre>\n\n<p>And if you put the script in an <em>external JS file</em>, you should also ensure that the <code>media-models</code> script has been enqueued:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'admin_enqueue_scripts', function () {\n $screen_ids = [ 'post', 'page' ];\n if ( in_array( get_current_screen()->id, $screen_ids ) &&\n wp_script_is( 'media-models' ) // check if media-models.js was enqueued\n ) {\n wp_enqueue_script( 'my-script', '/path/to/my-script.js', [], '', true );\n }\n} );\n</code></pre>\n"
}
] | 2020/06/03 | [
"https://wordpress.stackexchange.com/questions/368194",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/60844/"
] | Having a perplexing issue... ...for a custom post-type called 'Resources' I used the 'Featured Image' or 'thumbnail' function within WordPress to allow users to attach documents to 'Resources'. The process itself works exactly as expected and anticipated.
However, setting the site up, someone made a mistake and uploaded two documents and assigned them to the wrong 'Resources'. So `Resource A -> Document B` and `Resource B -> Document A`.
When attempting to switch them and clicking 'Edit Featured Image' you are unable to see any of the documents. They clicked 'Remove Featured Image' and then 'Set Featured Image' and when the dialogue opens, still no documents.
In the Wordpress Media Library all of the uploaded and attached documents are there. Visible, with previews, etc. As expected. Here's the first two rows of the Media Library. You can see tons of PDFs that have been successfully uploaded.
[](https://i.stack.imgur.com/Ud8rF.png)
The only place where this issue appears is that in the actual 'Featured Image' media dialogue box, WordPress will not display any PDFs.
Here's the CPT supports segment:
```
$rsc_supports = array(
'title',
'editor',
'thumbnail',
'page-attributes'
);
```
Like I said, everything works perfectly - even uploading and attaching PDFs as 'thumbnails' to be associated as attachments with the CPT. When a PDF is attached and you 'Click to edit' the dialogue opens up and you can see the attached PDF in the list.
The only failing is that the 'Featured Image' modal/pop-up/dialogue box that loads, is designed to filter out everything except images.
This is what that dialogue box looks like on a 'Resource' with nothing attached.
[](https://i.stack.imgur.com/QbYLX.png)
However, if you view another Resource that does have a PDF already attached, you get this:
[](https://i.stack.imgur.com/jvZne.png)
I have tried the filtering and date dropdown and they don't address this.
I believe this is by design. So my question is, **"How do I modify that dialogue box to display all files rather than just images?"** | So this may be hacky..
======================
I mean, compared to [overriding the default Featured Image panel/component in the Gutenberg block editor](https://github.com/WordPress/gutenberg/tree/master/packages/editor/src/components/post-featured-image), which is not exactly hard, but this one is much simpler and basically just needs a few lines of custom coding. (read till the end to see what I mean)
And I've also tried & tested it working (with both the old/classic editor and the Gutenberg block editor) on WordPress 5.4.2 (the latest release as of writing) as well as WordPress 5.4.1.
So for what you're trying to do, you can override `wp.media.model.Query.prototype.sync()` (defined in [`wp-includes/js/media-models.js`](https://build.trac.wordpress.org/browser/tags/5.4.2/wp-includes/js/media-models.js#L1214)) which is the function used by the default Featured Image modal for querying attachments via AJAX (`admin-ajax.php?action=query-attachments`).
Full (JS) Code
--------------
```js
wp.media.model.Query.prototype.sync = function( method, model, options ) {
var args, fallback;
// Overload the read method so Attachment.fetch() functions correctly.
if ( 'read' === method ) {
options = options || {};
options.context = this;
options.data = _.extend( options.data || {}, {
action: 'query-attachments',
post_id: wp.media.model.settings.post.id
});
// Clone the args so manipulation is non-destructive.
args = _.clone( this.args );
// Determine which page to query.
if ( -1 !== args.posts_per_page ) {
args.paged = Math.round( this.length / args.posts_per_page ) + 1;
}
if ( wp.media.frame && 'featured-image' === wp.media.frame.options.state ) {
// Here I'm allowing image and PDF files only.
args.post_mime_type = 'image, application/pdf';
}
options.data.query = args;
return wp.media.ajax( options );
// Otherwise, fall back to `Backbone.sync()`.
} else {
/**
* Call wp.media.model.Attachments.sync or Backbone.sync
*/
fallback = Attachments.prototype.sync ? Attachments.prototype : Backbone;
return fallback.sync.apply( this, arguments );
}
};
```
*But the only thing I added there is this conditional block:*
```js
if ( wp.media.frame && 'featured-image' === wp.media.frame.options.state ) {
// Here I'm allowing image and PDF files only.
args.post_mime_type = 'image, application/pdf';
}
```
Which checks if the currently opened modal is the featured image modal and if so, then we modify the [`post_mime_type` argument](https://developer.wordpress.org/reference/classes/wp_query/parse_query/#parameters) which defines the MIME type(s) of the attachments being queried.
And that's how you can use this approach to force the Featured Image modal to include files *other than images*.
Sample PHP Code
---------------
>
> *Update Jun 13th (to other readers):* Just to clarify why should we check for the `media-models` script, which is because we're
> overriding something in that script, so if the script is not being
> loaded on the current page, then there's no need to echo/enqueue our
> custom script. :)
>
>
>
The following is the PHP code I used to *echo the script in the footer* on the post editing screen for the default `post` and `page` post types:
```php
add_action( 'admin_print_footer_scripts', function () {
$screen_ids = [ 'post', 'page' ];
if ( in_array( get_current_screen()->id, $screen_ids ) &&
wp_script_is( 'media-models' ) // check if media-models.js was enqueued
) :
?>
<script>
// See/copy the FULL code above and place it here..
</script>
<?php
endif;
} );
```
And if you put the script in an *external JS file*, you should also ensure that the `media-models` script has been enqueued:
```php
add_action( 'admin_enqueue_scripts', function () {
$screen_ids = [ 'post', 'page' ];
if ( in_array( get_current_screen()->id, $screen_ids ) &&
wp_script_is( 'media-models' ) // check if media-models.js was enqueued
) {
wp_enqueue_script( 'my-script', '/path/to/my-script.js', [], '', true );
}
} );
``` |
368,247 | <p>I am using WooCommerce for the eCommerce part of my WordPress site. </p>
<p>When using the <code>add_to_cart</code> button I want it to say "read more" on a specific webpage only.</p>
<p>So far I have found the code to change the button text: </p>
<pre><code>add_filter('woocommerce_product_single_add_to_cart_text', 'woo_custom_cart_button_text');
function woo_custom_cart_button_text() {
return__('Read More','woocommerce'); }
</code></pre>
<p>The question is, how do I make this apply to the appearance of the <code>add_to_cart</code> button on a single page of my website? The page is not a shop page. It is a normal webpage where is have the description of products and the associated treatment. The button is there to take them to the product page.</p>
| [
{
"answer_id": 368759,
"author": "Ahmad Wael",
"author_id": 115635,
"author_profile": "https://wordpress.stackexchange.com/users/115635",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried this plugin <a href=\"https://wordpress.org/plugins/pdf-thumbnails/\" rel=\"nofollow noreferrer\">PDF Thumbnails</a> ?</p>\n\n<p>This plugin generates a thumbnail from the first page in the\nuploaded document and names it as PDFNAME-thumbnail, then you can use this image as a featured image. this plugin is outdated, about 4 years ago so be sure for testing and compatibility.</p>\n"
},
{
"answer_id": 368772,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": true,
"text": "<h1>So this may be hacky..</h1>\n\n<p>I mean, compared to <a href=\"https://github.com/WordPress/gutenberg/tree/master/packages/editor/src/components/post-featured-image\" rel=\"nofollow noreferrer\">overriding the default Featured Image panel/component in the Gutenberg block editor</a>, which is not exactly hard, but this one is much simpler and basically just needs a few lines of custom coding. (read till the end to see what I mean)</p>\n\n<p>And I've also tried & tested it working (with both the old/classic editor and the Gutenberg block editor) on WordPress 5.4.2 (the latest release as of writing) as well as WordPress 5.4.1.</p>\n\n<p>So for what you're trying to do, you can override <code>wp.media.model.Query.prototype.sync()</code> (defined in <a href=\"https://build.trac.wordpress.org/browser/tags/5.4.2/wp-includes/js/media-models.js#L1214\" rel=\"nofollow noreferrer\"><code>wp-includes/js/media-models.js</code></a>) which is the function used by the default Featured Image modal for querying attachments via AJAX (<code>admin-ajax.php?action=query-attachments</code>).</p>\n\n<h2>Full (JS) Code</h2>\n\n<pre class=\"lang-js prettyprint-override\"><code>wp.media.model.Query.prototype.sync = function( method, model, options ) {\n var args, fallback;\n\n // Overload the read method so Attachment.fetch() functions correctly.\n if ( 'read' === method ) {\n options = options || {};\n options.context = this;\n options.data = _.extend( options.data || {}, {\n action: 'query-attachments',\n post_id: wp.media.model.settings.post.id\n });\n\n // Clone the args so manipulation is non-destructive.\n args = _.clone( this.args );\n\n // Determine which page to query.\n if ( -1 !== args.posts_per_page ) {\n args.paged = Math.round( this.length / args.posts_per_page ) + 1;\n }\n\n if ( wp.media.frame && 'featured-image' === wp.media.frame.options.state ) {\n // Here I'm allowing image and PDF files only.\n args.post_mime_type = 'image, application/pdf';\n }\n\n options.data.query = args;\n return wp.media.ajax( options );\n\n // Otherwise, fall back to `Backbone.sync()`.\n } else {\n /**\n * Call wp.media.model.Attachments.sync or Backbone.sync\n */\n fallback = Attachments.prototype.sync ? Attachments.prototype : Backbone;\n return fallback.sync.apply( this, arguments );\n }\n};\n</code></pre>\n\n<p><em>But the only thing I added there is this conditional block:</em></p>\n\n<pre class=\"lang-js prettyprint-override\"><code>if ( wp.media.frame && 'featured-image' === wp.media.frame.options.state ) {\n // Here I'm allowing image and PDF files only.\n args.post_mime_type = 'image, application/pdf';\n}\n</code></pre>\n\n<p>Which checks if the currently opened modal is the featured image modal and if so, then we modify the <a href=\"https://developer.wordpress.org/reference/classes/wp_query/parse_query/#parameters\" rel=\"nofollow noreferrer\"><code>post_mime_type</code> argument</a> which defines the MIME type(s) of the attachments being queried.</p>\n\n<p>And that's how you can use this approach to force the Featured Image modal to include files <em>other than images</em>.</p>\n\n<h2>Sample PHP Code</h2>\n\n<blockquote>\n <p><em>Update Jun 13<sup>th</sup> (to other readers):</em> Just to clarify why should we check for the <code>media-models</code> script, which is because we're\n overriding something in that script, so if the script is not being\n loaded on the current page, then there's no need to echo/enqueue our\n custom script. :)</p>\n</blockquote>\n\n<p>The following is the PHP code I used to <em>echo the script in the footer</em> on the post editing screen for the default <code>post</code> and <code>page</code> post types:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'admin_print_footer_scripts', function () {\n $screen_ids = [ 'post', 'page' ];\n if ( in_array( get_current_screen()->id, $screen_ids ) &&\n wp_script_is( 'media-models' ) // check if media-models.js was enqueued\n ) :\n ?>\n <script>\n // See/copy the FULL code above and place it here..\n </script>\n <?php\n endif;\n} );\n</code></pre>\n\n<p>And if you put the script in an <em>external JS file</em>, you should also ensure that the <code>media-models</code> script has been enqueued:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'admin_enqueue_scripts', function () {\n $screen_ids = [ 'post', 'page' ];\n if ( in_array( get_current_screen()->id, $screen_ids ) &&\n wp_script_is( 'media-models' ) // check if media-models.js was enqueued\n ) {\n wp_enqueue_script( 'my-script', '/path/to/my-script.js', [], '', true );\n }\n} );\n</code></pre>\n"
}
] | 2020/06/04 | [
"https://wordpress.stackexchange.com/questions/368247",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/189372/"
] | I am using WooCommerce for the eCommerce part of my WordPress site.
When using the `add_to_cart` button I want it to say "read more" on a specific webpage only.
So far I have found the code to change the button text:
```
add_filter('woocommerce_product_single_add_to_cart_text', 'woo_custom_cart_button_text');
function woo_custom_cart_button_text() {
return__('Read More','woocommerce'); }
```
The question is, how do I make this apply to the appearance of the `add_to_cart` button on a single page of my website? The page is not a shop page. It is a normal webpage where is have the description of products and the associated treatment. The button is there to take them to the product page. | So this may be hacky..
======================
I mean, compared to [overriding the default Featured Image panel/component in the Gutenberg block editor](https://github.com/WordPress/gutenberg/tree/master/packages/editor/src/components/post-featured-image), which is not exactly hard, but this one is much simpler and basically just needs a few lines of custom coding. (read till the end to see what I mean)
And I've also tried & tested it working (with both the old/classic editor and the Gutenberg block editor) on WordPress 5.4.2 (the latest release as of writing) as well as WordPress 5.4.1.
So for what you're trying to do, you can override `wp.media.model.Query.prototype.sync()` (defined in [`wp-includes/js/media-models.js`](https://build.trac.wordpress.org/browser/tags/5.4.2/wp-includes/js/media-models.js#L1214)) which is the function used by the default Featured Image modal for querying attachments via AJAX (`admin-ajax.php?action=query-attachments`).
Full (JS) Code
--------------
```js
wp.media.model.Query.prototype.sync = function( method, model, options ) {
var args, fallback;
// Overload the read method so Attachment.fetch() functions correctly.
if ( 'read' === method ) {
options = options || {};
options.context = this;
options.data = _.extend( options.data || {}, {
action: 'query-attachments',
post_id: wp.media.model.settings.post.id
});
// Clone the args so manipulation is non-destructive.
args = _.clone( this.args );
// Determine which page to query.
if ( -1 !== args.posts_per_page ) {
args.paged = Math.round( this.length / args.posts_per_page ) + 1;
}
if ( wp.media.frame && 'featured-image' === wp.media.frame.options.state ) {
// Here I'm allowing image and PDF files only.
args.post_mime_type = 'image, application/pdf';
}
options.data.query = args;
return wp.media.ajax( options );
// Otherwise, fall back to `Backbone.sync()`.
} else {
/**
* Call wp.media.model.Attachments.sync or Backbone.sync
*/
fallback = Attachments.prototype.sync ? Attachments.prototype : Backbone;
return fallback.sync.apply( this, arguments );
}
};
```
*But the only thing I added there is this conditional block:*
```js
if ( wp.media.frame && 'featured-image' === wp.media.frame.options.state ) {
// Here I'm allowing image and PDF files only.
args.post_mime_type = 'image, application/pdf';
}
```
Which checks if the currently opened modal is the featured image modal and if so, then we modify the [`post_mime_type` argument](https://developer.wordpress.org/reference/classes/wp_query/parse_query/#parameters) which defines the MIME type(s) of the attachments being queried.
And that's how you can use this approach to force the Featured Image modal to include files *other than images*.
Sample PHP Code
---------------
>
> *Update Jun 13th (to other readers):* Just to clarify why should we check for the `media-models` script, which is because we're
> overriding something in that script, so if the script is not being
> loaded on the current page, then there's no need to echo/enqueue our
> custom script. :)
>
>
>
The following is the PHP code I used to *echo the script in the footer* on the post editing screen for the default `post` and `page` post types:
```php
add_action( 'admin_print_footer_scripts', function () {
$screen_ids = [ 'post', 'page' ];
if ( in_array( get_current_screen()->id, $screen_ids ) &&
wp_script_is( 'media-models' ) // check if media-models.js was enqueued
) :
?>
<script>
// See/copy the FULL code above and place it here..
</script>
<?php
endif;
} );
```
And if you put the script in an *external JS file*, you should also ensure that the `media-models` script has been enqueued:
```php
add_action( 'admin_enqueue_scripts', function () {
$screen_ids = [ 'post', 'page' ];
if ( in_array( get_current_screen()->id, $screen_ids ) &&
wp_script_is( 'media-models' ) // check if media-models.js was enqueued
) {
wp_enqueue_script( 'my-script', '/path/to/my-script.js', [], '', true );
}
} );
``` |
368,291 | <p>In custom post type book I have several books published
I just want to show data obtained from metabox field but I have not been able to help me the code that I am showing does not work</p>
<pre><code> <?php $book=get_post_meta( get_the_ID(), 'name_ebook', true ); ?> return name ebook Paintree
<?php
$loop_args = array(
'post_type' => 'book',
'order' => 'ASC',
'meta_key' => '$book',
'orderby' => 'meta_value',
); ?>
</code></pre>
<p>show only search Paintree ebook</p>
| [
{
"answer_id": 368759,
"author": "Ahmad Wael",
"author_id": 115635,
"author_profile": "https://wordpress.stackexchange.com/users/115635",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried this plugin <a href=\"https://wordpress.org/plugins/pdf-thumbnails/\" rel=\"nofollow noreferrer\">PDF Thumbnails</a> ?</p>\n\n<p>This plugin generates a thumbnail from the first page in the\nuploaded document and names it as PDFNAME-thumbnail, then you can use this image as a featured image. this plugin is outdated, about 4 years ago so be sure for testing and compatibility.</p>\n"
},
{
"answer_id": 368772,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": true,
"text": "<h1>So this may be hacky..</h1>\n\n<p>I mean, compared to <a href=\"https://github.com/WordPress/gutenberg/tree/master/packages/editor/src/components/post-featured-image\" rel=\"nofollow noreferrer\">overriding the default Featured Image panel/component in the Gutenberg block editor</a>, which is not exactly hard, but this one is much simpler and basically just needs a few lines of custom coding. (read till the end to see what I mean)</p>\n\n<p>And I've also tried & tested it working (with both the old/classic editor and the Gutenberg block editor) on WordPress 5.4.2 (the latest release as of writing) as well as WordPress 5.4.1.</p>\n\n<p>So for what you're trying to do, you can override <code>wp.media.model.Query.prototype.sync()</code> (defined in <a href=\"https://build.trac.wordpress.org/browser/tags/5.4.2/wp-includes/js/media-models.js#L1214\" rel=\"nofollow noreferrer\"><code>wp-includes/js/media-models.js</code></a>) which is the function used by the default Featured Image modal for querying attachments via AJAX (<code>admin-ajax.php?action=query-attachments</code>).</p>\n\n<h2>Full (JS) Code</h2>\n\n<pre class=\"lang-js prettyprint-override\"><code>wp.media.model.Query.prototype.sync = function( method, model, options ) {\n var args, fallback;\n\n // Overload the read method so Attachment.fetch() functions correctly.\n if ( 'read' === method ) {\n options = options || {};\n options.context = this;\n options.data = _.extend( options.data || {}, {\n action: 'query-attachments',\n post_id: wp.media.model.settings.post.id\n });\n\n // Clone the args so manipulation is non-destructive.\n args = _.clone( this.args );\n\n // Determine which page to query.\n if ( -1 !== args.posts_per_page ) {\n args.paged = Math.round( this.length / args.posts_per_page ) + 1;\n }\n\n if ( wp.media.frame && 'featured-image' === wp.media.frame.options.state ) {\n // Here I'm allowing image and PDF files only.\n args.post_mime_type = 'image, application/pdf';\n }\n\n options.data.query = args;\n return wp.media.ajax( options );\n\n // Otherwise, fall back to `Backbone.sync()`.\n } else {\n /**\n * Call wp.media.model.Attachments.sync or Backbone.sync\n */\n fallback = Attachments.prototype.sync ? Attachments.prototype : Backbone;\n return fallback.sync.apply( this, arguments );\n }\n};\n</code></pre>\n\n<p><em>But the only thing I added there is this conditional block:</em></p>\n\n<pre class=\"lang-js prettyprint-override\"><code>if ( wp.media.frame && 'featured-image' === wp.media.frame.options.state ) {\n // Here I'm allowing image and PDF files only.\n args.post_mime_type = 'image, application/pdf';\n}\n</code></pre>\n\n<p>Which checks if the currently opened modal is the featured image modal and if so, then we modify the <a href=\"https://developer.wordpress.org/reference/classes/wp_query/parse_query/#parameters\" rel=\"nofollow noreferrer\"><code>post_mime_type</code> argument</a> which defines the MIME type(s) of the attachments being queried.</p>\n\n<p>And that's how you can use this approach to force the Featured Image modal to include files <em>other than images</em>.</p>\n\n<h2>Sample PHP Code</h2>\n\n<blockquote>\n <p><em>Update Jun 13<sup>th</sup> (to other readers):</em> Just to clarify why should we check for the <code>media-models</code> script, which is because we're\n overriding something in that script, so if the script is not being\n loaded on the current page, then there's no need to echo/enqueue our\n custom script. :)</p>\n</blockquote>\n\n<p>The following is the PHP code I used to <em>echo the script in the footer</em> on the post editing screen for the default <code>post</code> and <code>page</code> post types:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'admin_print_footer_scripts', function () {\n $screen_ids = [ 'post', 'page' ];\n if ( in_array( get_current_screen()->id, $screen_ids ) &&\n wp_script_is( 'media-models' ) // check if media-models.js was enqueued\n ) :\n ?>\n <script>\n // See/copy the FULL code above and place it here..\n </script>\n <?php\n endif;\n} );\n</code></pre>\n\n<p>And if you put the script in an <em>external JS file</em>, you should also ensure that the <code>media-models</code> script has been enqueued:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'admin_enqueue_scripts', function () {\n $screen_ids = [ 'post', 'page' ];\n if ( in_array( get_current_screen()->id, $screen_ids ) &&\n wp_script_is( 'media-models' ) // check if media-models.js was enqueued\n ) {\n wp_enqueue_script( 'my-script', '/path/to/my-script.js', [], '', true );\n }\n} );\n</code></pre>\n"
}
] | 2020/06/04 | [
"https://wordpress.stackexchange.com/questions/368291",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/189413/"
] | In custom post type book I have several books published
I just want to show data obtained from metabox field but I have not been able to help me the code that I am showing does not work
```
<?php $book=get_post_meta( get_the_ID(), 'name_ebook', true ); ?> return name ebook Paintree
<?php
$loop_args = array(
'post_type' => 'book',
'order' => 'ASC',
'meta_key' => '$book',
'orderby' => 'meta_value',
); ?>
```
show only search Paintree ebook | So this may be hacky..
======================
I mean, compared to [overriding the default Featured Image panel/component in the Gutenberg block editor](https://github.com/WordPress/gutenberg/tree/master/packages/editor/src/components/post-featured-image), which is not exactly hard, but this one is much simpler and basically just needs a few lines of custom coding. (read till the end to see what I mean)
And I've also tried & tested it working (with both the old/classic editor and the Gutenberg block editor) on WordPress 5.4.2 (the latest release as of writing) as well as WordPress 5.4.1.
So for what you're trying to do, you can override `wp.media.model.Query.prototype.sync()` (defined in [`wp-includes/js/media-models.js`](https://build.trac.wordpress.org/browser/tags/5.4.2/wp-includes/js/media-models.js#L1214)) which is the function used by the default Featured Image modal for querying attachments via AJAX (`admin-ajax.php?action=query-attachments`).
Full (JS) Code
--------------
```js
wp.media.model.Query.prototype.sync = function( method, model, options ) {
var args, fallback;
// Overload the read method so Attachment.fetch() functions correctly.
if ( 'read' === method ) {
options = options || {};
options.context = this;
options.data = _.extend( options.data || {}, {
action: 'query-attachments',
post_id: wp.media.model.settings.post.id
});
// Clone the args so manipulation is non-destructive.
args = _.clone( this.args );
// Determine which page to query.
if ( -1 !== args.posts_per_page ) {
args.paged = Math.round( this.length / args.posts_per_page ) + 1;
}
if ( wp.media.frame && 'featured-image' === wp.media.frame.options.state ) {
// Here I'm allowing image and PDF files only.
args.post_mime_type = 'image, application/pdf';
}
options.data.query = args;
return wp.media.ajax( options );
// Otherwise, fall back to `Backbone.sync()`.
} else {
/**
* Call wp.media.model.Attachments.sync or Backbone.sync
*/
fallback = Attachments.prototype.sync ? Attachments.prototype : Backbone;
return fallback.sync.apply( this, arguments );
}
};
```
*But the only thing I added there is this conditional block:*
```js
if ( wp.media.frame && 'featured-image' === wp.media.frame.options.state ) {
// Here I'm allowing image and PDF files only.
args.post_mime_type = 'image, application/pdf';
}
```
Which checks if the currently opened modal is the featured image modal and if so, then we modify the [`post_mime_type` argument](https://developer.wordpress.org/reference/classes/wp_query/parse_query/#parameters) which defines the MIME type(s) of the attachments being queried.
And that's how you can use this approach to force the Featured Image modal to include files *other than images*.
Sample PHP Code
---------------
>
> *Update Jun 13th (to other readers):* Just to clarify why should we check for the `media-models` script, which is because we're
> overriding something in that script, so if the script is not being
> loaded on the current page, then there's no need to echo/enqueue our
> custom script. :)
>
>
>
The following is the PHP code I used to *echo the script in the footer* on the post editing screen for the default `post` and `page` post types:
```php
add_action( 'admin_print_footer_scripts', function () {
$screen_ids = [ 'post', 'page' ];
if ( in_array( get_current_screen()->id, $screen_ids ) &&
wp_script_is( 'media-models' ) // check if media-models.js was enqueued
) :
?>
<script>
// See/copy the FULL code above and place it here..
</script>
<?php
endif;
} );
```
And if you put the script in an *external JS file*, you should also ensure that the `media-models` script has been enqueued:
```php
add_action( 'admin_enqueue_scripts', function () {
$screen_ids = [ 'post', 'page' ];
if ( in_array( get_current_screen()->id, $screen_ids ) &&
wp_script_is( 'media-models' ) // check if media-models.js was enqueued
) {
wp_enqueue_script( 'my-script', '/path/to/my-script.js', [], '', true );
}
} );
``` |
368,293 | <p>I want <code>testFunction()</code> to call <code>check()</code> that i created in my plugin php when i click <strong>My Button</strong>. How do i make it work ?</p>
<pre><code><?php
function createButton()
{
echo '<button onclick="testFunction()">My Button</button>';
}
function check()
{
alert("Works");
}
function my_php_function()
{
echo '<script>
function testFunction() {
check();
}
</script>';
}
add_action( 'wp_footer', 'my_php_function' );
</code></pre>
| [
{
"answer_id": 368759,
"author": "Ahmad Wael",
"author_id": 115635,
"author_profile": "https://wordpress.stackexchange.com/users/115635",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried this plugin <a href=\"https://wordpress.org/plugins/pdf-thumbnails/\" rel=\"nofollow noreferrer\">PDF Thumbnails</a> ?</p>\n\n<p>This plugin generates a thumbnail from the first page in the\nuploaded document and names it as PDFNAME-thumbnail, then you can use this image as a featured image. this plugin is outdated, about 4 years ago so be sure for testing and compatibility.</p>\n"
},
{
"answer_id": 368772,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": true,
"text": "<h1>So this may be hacky..</h1>\n\n<p>I mean, compared to <a href=\"https://github.com/WordPress/gutenberg/tree/master/packages/editor/src/components/post-featured-image\" rel=\"nofollow noreferrer\">overriding the default Featured Image panel/component in the Gutenberg block editor</a>, which is not exactly hard, but this one is much simpler and basically just needs a few lines of custom coding. (read till the end to see what I mean)</p>\n\n<p>And I've also tried & tested it working (with both the old/classic editor and the Gutenberg block editor) on WordPress 5.4.2 (the latest release as of writing) as well as WordPress 5.4.1.</p>\n\n<p>So for what you're trying to do, you can override <code>wp.media.model.Query.prototype.sync()</code> (defined in <a href=\"https://build.trac.wordpress.org/browser/tags/5.4.2/wp-includes/js/media-models.js#L1214\" rel=\"nofollow noreferrer\"><code>wp-includes/js/media-models.js</code></a>) which is the function used by the default Featured Image modal for querying attachments via AJAX (<code>admin-ajax.php?action=query-attachments</code>).</p>\n\n<h2>Full (JS) Code</h2>\n\n<pre class=\"lang-js prettyprint-override\"><code>wp.media.model.Query.prototype.sync = function( method, model, options ) {\n var args, fallback;\n\n // Overload the read method so Attachment.fetch() functions correctly.\n if ( 'read' === method ) {\n options = options || {};\n options.context = this;\n options.data = _.extend( options.data || {}, {\n action: 'query-attachments',\n post_id: wp.media.model.settings.post.id\n });\n\n // Clone the args so manipulation is non-destructive.\n args = _.clone( this.args );\n\n // Determine which page to query.\n if ( -1 !== args.posts_per_page ) {\n args.paged = Math.round( this.length / args.posts_per_page ) + 1;\n }\n\n if ( wp.media.frame && 'featured-image' === wp.media.frame.options.state ) {\n // Here I'm allowing image and PDF files only.\n args.post_mime_type = 'image, application/pdf';\n }\n\n options.data.query = args;\n return wp.media.ajax( options );\n\n // Otherwise, fall back to `Backbone.sync()`.\n } else {\n /**\n * Call wp.media.model.Attachments.sync or Backbone.sync\n */\n fallback = Attachments.prototype.sync ? Attachments.prototype : Backbone;\n return fallback.sync.apply( this, arguments );\n }\n};\n</code></pre>\n\n<p><em>But the only thing I added there is this conditional block:</em></p>\n\n<pre class=\"lang-js prettyprint-override\"><code>if ( wp.media.frame && 'featured-image' === wp.media.frame.options.state ) {\n // Here I'm allowing image and PDF files only.\n args.post_mime_type = 'image, application/pdf';\n}\n</code></pre>\n\n<p>Which checks if the currently opened modal is the featured image modal and if so, then we modify the <a href=\"https://developer.wordpress.org/reference/classes/wp_query/parse_query/#parameters\" rel=\"nofollow noreferrer\"><code>post_mime_type</code> argument</a> which defines the MIME type(s) of the attachments being queried.</p>\n\n<p>And that's how you can use this approach to force the Featured Image modal to include files <em>other than images</em>.</p>\n\n<h2>Sample PHP Code</h2>\n\n<blockquote>\n <p><em>Update Jun 13<sup>th</sup> (to other readers):</em> Just to clarify why should we check for the <code>media-models</code> script, which is because we're\n overriding something in that script, so if the script is not being\n loaded on the current page, then there's no need to echo/enqueue our\n custom script. :)</p>\n</blockquote>\n\n<p>The following is the PHP code I used to <em>echo the script in the footer</em> on the post editing screen for the default <code>post</code> and <code>page</code> post types:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'admin_print_footer_scripts', function () {\n $screen_ids = [ 'post', 'page' ];\n if ( in_array( get_current_screen()->id, $screen_ids ) &&\n wp_script_is( 'media-models' ) // check if media-models.js was enqueued\n ) :\n ?>\n <script>\n // See/copy the FULL code above and place it here..\n </script>\n <?php\n endif;\n} );\n</code></pre>\n\n<p>And if you put the script in an <em>external JS file</em>, you should also ensure that the <code>media-models</code> script has been enqueued:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'admin_enqueue_scripts', function () {\n $screen_ids = [ 'post', 'page' ];\n if ( in_array( get_current_screen()->id, $screen_ids ) &&\n wp_script_is( 'media-models' ) // check if media-models.js was enqueued\n ) {\n wp_enqueue_script( 'my-script', '/path/to/my-script.js', [], '', true );\n }\n} );\n</code></pre>\n"
}
] | 2020/06/05 | [
"https://wordpress.stackexchange.com/questions/368293",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/189146/"
] | I want `testFunction()` to call `check()` that i created in my plugin php when i click **My Button**. How do i make it work ?
```
<?php
function createButton()
{
echo '<button onclick="testFunction()">My Button</button>';
}
function check()
{
alert("Works");
}
function my_php_function()
{
echo '<script>
function testFunction() {
check();
}
</script>';
}
add_action( 'wp_footer', 'my_php_function' );
``` | So this may be hacky..
======================
I mean, compared to [overriding the default Featured Image panel/component in the Gutenberg block editor](https://github.com/WordPress/gutenberg/tree/master/packages/editor/src/components/post-featured-image), which is not exactly hard, but this one is much simpler and basically just needs a few lines of custom coding. (read till the end to see what I mean)
And I've also tried & tested it working (with both the old/classic editor and the Gutenberg block editor) on WordPress 5.4.2 (the latest release as of writing) as well as WordPress 5.4.1.
So for what you're trying to do, you can override `wp.media.model.Query.prototype.sync()` (defined in [`wp-includes/js/media-models.js`](https://build.trac.wordpress.org/browser/tags/5.4.2/wp-includes/js/media-models.js#L1214)) which is the function used by the default Featured Image modal for querying attachments via AJAX (`admin-ajax.php?action=query-attachments`).
Full (JS) Code
--------------
```js
wp.media.model.Query.prototype.sync = function( method, model, options ) {
var args, fallback;
// Overload the read method so Attachment.fetch() functions correctly.
if ( 'read' === method ) {
options = options || {};
options.context = this;
options.data = _.extend( options.data || {}, {
action: 'query-attachments',
post_id: wp.media.model.settings.post.id
});
// Clone the args so manipulation is non-destructive.
args = _.clone( this.args );
// Determine which page to query.
if ( -1 !== args.posts_per_page ) {
args.paged = Math.round( this.length / args.posts_per_page ) + 1;
}
if ( wp.media.frame && 'featured-image' === wp.media.frame.options.state ) {
// Here I'm allowing image and PDF files only.
args.post_mime_type = 'image, application/pdf';
}
options.data.query = args;
return wp.media.ajax( options );
// Otherwise, fall back to `Backbone.sync()`.
} else {
/**
* Call wp.media.model.Attachments.sync or Backbone.sync
*/
fallback = Attachments.prototype.sync ? Attachments.prototype : Backbone;
return fallback.sync.apply( this, arguments );
}
};
```
*But the only thing I added there is this conditional block:*
```js
if ( wp.media.frame && 'featured-image' === wp.media.frame.options.state ) {
// Here I'm allowing image and PDF files only.
args.post_mime_type = 'image, application/pdf';
}
```
Which checks if the currently opened modal is the featured image modal and if so, then we modify the [`post_mime_type` argument](https://developer.wordpress.org/reference/classes/wp_query/parse_query/#parameters) which defines the MIME type(s) of the attachments being queried.
And that's how you can use this approach to force the Featured Image modal to include files *other than images*.
Sample PHP Code
---------------
>
> *Update Jun 13th (to other readers):* Just to clarify why should we check for the `media-models` script, which is because we're
> overriding something in that script, so if the script is not being
> loaded on the current page, then there's no need to echo/enqueue our
> custom script. :)
>
>
>
The following is the PHP code I used to *echo the script in the footer* on the post editing screen for the default `post` and `page` post types:
```php
add_action( 'admin_print_footer_scripts', function () {
$screen_ids = [ 'post', 'page' ];
if ( in_array( get_current_screen()->id, $screen_ids ) &&
wp_script_is( 'media-models' ) // check if media-models.js was enqueued
) :
?>
<script>
// See/copy the FULL code above and place it here..
</script>
<?php
endif;
} );
```
And if you put the script in an *external JS file*, you should also ensure that the `media-models` script has been enqueued:
```php
add_action( 'admin_enqueue_scripts', function () {
$screen_ids = [ 'post', 'page' ];
if ( in_array( get_current_screen()->id, $screen_ids ) &&
wp_script_is( 'media-models' ) // check if media-models.js was enqueued
) {
wp_enqueue_script( 'my-script', '/path/to/my-script.js', [], '', true );
}
} );
``` |
368,299 | <p>I have two custom post types </p>
<ol>
<li>case</li>
<li>client </li>
</ol>
<p>In case post type I have a ACF custom field to choose a client, so each case have a single client.</p>
<p>Now what is working:
I am displaying all cases on a page and able to filter them using a client Id.</p>
<p>Whats I want:
I want to get a list of cases (of all clients) and the order by sorting should be a client title ASC.</p>
<hr>
<p>I am able to apply order by using client Id but I want order by client title.</p>
<p>Please suggest an solution for this.</p>
<pre><code>$args = array(
'post_type' => 'case',
'post_status' => 'publish',
'orderby' => 'meta_value_num',
'meta_key' => 'client',
'posts_per_page' => 9
);
</code></pre>
| [
{
"answer_id": 368301,
"author": "Baikare Sandeep",
"author_id": 99404,
"author_profile": "https://wordpress.stackexchange.com/users/99404",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the <code>order</code> and <code>orderby</code> param in <code>WP_Query</code> argument like below:</p>\n\n<pre><code>$args = array(\n 'post_type' => 'case',\n 'post_status' => 'publish',\n 'meta_key' => 'client',\n 'posts_per_page' => 9,\n 'orderby' => 'title',\n 'order' => 'ASC',\n);\n$query = new WP_Query( $args );\n</code></pre>\n\n<p>It will list out your posts by title. For more information check official <a href=\"https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters\" rel=\"nofollow noreferrer\">WordPress document</a></p>\n"
},
{
"answer_id": 368314,
"author": "Rod",
"author_id": 189357,
"author_profile": "https://wordpress.stackexchange.com/users/189357",
"pm_score": 1,
"selected": false,
"text": "<p>You can try this:</p>\n\n<pre><code>$args = array(\n 'post_type' => 'case',\n 'post_status' => 'publish',\n 'orderby' => 'meta_value',\n 'order' => ASC,\n 'meta_key' => 'client',\n 'posts_per_page' => 9\n);\n</code></pre>\n\n<p>More information of <a href=\"https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters\" rel=\"nofollow noreferrer\">orderby parameters</a></p>\n"
}
] | 2020/06/05 | [
"https://wordpress.stackexchange.com/questions/368299",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/149954/"
] | I have two custom post types
1. case
2. client
In case post type I have a ACF custom field to choose a client, so each case have a single client.
Now what is working:
I am displaying all cases on a page and able to filter them using a client Id.
Whats I want:
I want to get a list of cases (of all clients) and the order by sorting should be a client title ASC.
---
I am able to apply order by using client Id but I want order by client title.
Please suggest an solution for this.
```
$args = array(
'post_type' => 'case',
'post_status' => 'publish',
'orderby' => 'meta_value_num',
'meta_key' => 'client',
'posts_per_page' => 9
);
``` | You can use the `order` and `orderby` param in `WP_Query` argument like below:
```
$args = array(
'post_type' => 'case',
'post_status' => 'publish',
'meta_key' => 'client',
'posts_per_page' => 9,
'orderby' => 'title',
'order' => 'ASC',
);
$query = new WP_Query( $args );
```
It will list out your posts by title. For more information check official [WordPress document](https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters) |
368,327 | <p>I'm having a heck of a time with the ServerSideRender component for a Gutenberg block I'm developing. I'm seeing this error in the (non-)rendered block: <code>Error loading block: The response is not a valid JSON response.</code>
But where can I see the actual JSON response?</p>
<p>In the Chrome Inspector Tools I see:</p>
<blockquote>
<p>Failed to load resource: the server responded with a status of 502 ()</p>
</blockquote>
<p>along with the request that was sent, with all the block attributes:</p>
<pre><code>https://www.bibleget.io/wp-json/wp/v2/block-renderer/bibleget/bible-quote?context=edit&attributes%5BPARAGRAPHSTYLES_FONTFAMILY%5D=Times%20New%20Roman&attributes%5BPARAGRAPHSTYLES_LINEHEIGHT%5D=1.5&attributes%5BPARAGRAPHSTYLES_PADDINGTOPBOTTOM%5D=8&attributes%5BPARAGRAPHSTYLES_PADDINGLEFTRIGHT%5D=17&attributes%5BPARAGRAPHSTYLES_MARGINTOPBOTTOM%5D=24&attributes%5BPARAGRAPHSTYLES_MARGINLEFTRIGHT%5D=14&attributes%5BPARAGRAPHSTYLES_MARGINLEFTRIGHTUNIT%5D=auto&attributes%5BPARAGRAPHSTYLES_PARAGRAPHALIGN%5D=4&attributes%5BPARAGRAPHSTYLES_WIDTH%5D=85&attributes%5BPARAGRAPHSTYLES_NOVERSIONFORMATTING%5D=false&attributes%5BPARAGRAPHSTYLES_BORDERWIDTH%5D=4&attributes%5BPARAGRAPHSTYLES_BORDERCOLOR%5D=%230b02ac&attributes%5BPARAGRAPHSTYLES_BORDERSTYLE%5D=3&attributes%5BPARAGRAPHSTYLES_BORDERRADIUS%5D=12&attributes%5BPARAGRAPHSTYLES_BACKGROUNDCOLOR%5D=%23fdfbf7&attributes%5BVERSIONSTYLES_BOLD%5D=true&attributes%5BVERSIONSTYLES_ITALIC%5D=true&attributes%5BVERSIONSTYLES_UNDERLINE%5D=false&attributes%5BVERSIONSTYLES_STRIKETHROUGH%5D=false&attributes%5BVERSIONSTYLES_TEXTCOLOR%5D=%23000096&attributes%5BVERSIONSTYLES_FONTSIZE%5D=9&attributes%5BVERSIONSTYLES_FONTSIZEUNIT%5D=inherit&attributes%5BVERSIONSTYLES_VALIGN%5D=3&attributes%5BBOOKCHAPTERSTYLES_BOLD%5D=true&attributes%5BBOOKCHAPTERSTYLES_ITALIC%5D=false&attributes%5BBOOKCHAPTERSTYLES_UNDERLINE%5D=false&attributes%5BBOOKCHAPTERSTYLES_STRIKETHROUGH%5D=false&attributes%5BBOOKCHAPTERSTYLES_TEXTCOLOR%5D=%2302813d&attributes%5BBOOKCHAPTERSTYLES_FONTSIZE%5D=9&attributes%5BBOOKCHAPTERSTYLES_FONTSIZEUNIT%5D=em&attributes%5BBOOKCHAPTERSTYLES_VALIGN%5D=3&attributes%5BVERSENUMBERSTYLES_BOLD%5D=false&attributes%5BVERSENUMBERSTYLES_ITALIC%5D=false&attributes%5BVERSENUMBERSTYLES_UNDERLINE%5D=false&attributes%5BVERSENUMBERSTYLES_STRIKETHROUGH%5D=false&attributes%5BVERSENUMBERSTYLES_TEXTCOLOR%5D=%23ee0000&attributes%5BVERSENUMBERSTYLES_FONTSIZE%5D=7&attributes%5BVERSENUMBERSTYLES_FONTSIZEUNIT%5D=em&attributes%5BVERSENUMBERSTYLES_VALIGN%5D=1&attributes%5BVERSETEXTSTYLES_BOLD%5D=false&attributes%5BVERSETEXTSTYLES_ITALIC%5D=false&attributes%5BVERSETEXTSTYLES_UNDERLINE%5D=false&attributes%5BVERSETEXTSTYLES_STRIKETHROUGH%5D=false&attributes%5BVERSETEXTSTYLES_TEXTCOLOR%5D=%23706e6e&attributes%5BVERSETEXTSTYLES_FONTSIZE%5D=8&attributes%5BVERSETEXTSTYLES_FONTSIZEUNIT%5D=em&attributes%5BVERSETEXTSTYLES_VALIGN%5D=3&attributes%5BLAYOUTPREFS_SHOWBIBLEVERSION%5D=true&attributes%5BLAYOUTPREFS_BIBLEVERSIONALIGNMENT%5D=2&attributes%5BLAYOUTPREFS_BIBLEVERSIONPOSITION%5D=1&attributes%5BLAYOUTPREFS_BIBLEVERSIONWRAP%5D=2&attributes%5BLAYOUTPREFS_BOOKCHAPTERALIGNMENT%5D=1&attributes%5BLAYOUTPREFS_BOOKCHAPTERPOSITION%5D=1&attributes%5BLAYOUTPREFS_BOOKCHAPTERWRAP%5D=1&attributes%5BLAYOUTPREFS_BOOKCHAPTERFORMAT%5D=3&attributes%5BLAYOUTPREFS_BOOKCHAPTERFULLQUERY%5D=false&attributes%5BLAYOUTPREFS_SHOWVERSENUMBERS%5D=true&attributes%5BVERSION%5D%5B0%5D=LUZZI&attributes%5BVERSION%5D%5B1%5D=NVBSE&attributes%5BQUERY%5D=Lc10%2C1-16&attributes%5BPOPUP%5D=false&attributes%5BFORCEVERSION%5D=false&attributes%5BFORCECOPYRIGHT%5D=false&post_id=1178&lang=it&_locale=user
</code></pre>
<p>All the attributes look correct, and how they're handled in the PHP render callback is looking correct. I had the <code>ServerSideRender</code> working until yesterday, and now suddenly this "non valid JSON response error" is popping up.</p>
<p>I haven't made any changes to my render callback in PHP. I have even stepped through the render callback PHP function to make sure it was receiving all the attributes correctly and handling them correctly, and I have verified that that is the case. I have a function that will write to a debug.txt file, and I have stepped through the render callback making sure that each condition is working correctly. I can even see the final output that the render callback is returning, and it is correct. And yet, I am seeing this error on the Gutenberg block side. It would be helpful to have a more significant error message rather than "not a valid JSON response".</p>
<p>Looking at the Network tab of the Chrome Inspector Tools I am seeing that the actual response from the request posted above is <code>502 Bad Gateway - nginx</code>.</p>
<p>I have no idea what this is supposed to mean, because the request from the block is being sent to the server callback, the server callback is processing the request and returning a correct response. Something is happening somewhere between the response that is returned from the callback and the client side rendering of the block. Any ideas what could possibly be going on?</p>
| [
{
"answer_id": 368418,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 0,
"selected": false,
"text": "<p>The problem is that your block has a lot of attributes, and when they're turned into a <code>GET</code> url the HTTP headers are larger than your Nginx setup is configured to handle.</p>\n\n<p>This is why you get a 502 Gateway error, it isn't a WP error, WP doesn't even get loaded.</p>\n\n<p>There are 5 possible solutions:</p>\n\n<ul>\n<li>require nginx configuration changes in order to use your code, to support the super long URLs</li>\n<li>reduce the number of attributes passed to the server, perhaps by breaking up the block, or relying on block editor features such as block styles rather than dedicated attributes</li>\n<li>re-implement using javascript, and use an API to interact with PHP yourself, allowing you to do the necessary PHP bits then apply the attributes yourself in JS</li>\n<li>Break this block apart into multiple blocks, it sounds like it does a lot and might benefit from composability</li>\n</ul>\n\n<p>But the final one:</p>\n\n<ul>\n<li>Don't rely on serverside rendering to display both the saved output, and the edit output. They don't have to be the same. You don't even need to use server side rendering in the edit function of your block, you could make it render a placeholder in the edit screen, or implement something completely different</li>\n</ul>\n"
},
{
"answer_id": 368563,
"author": "JohnRDOrazio",
"author_id": 60906,
"author_profile": "https://wordpress.stackexchange.com/users/60906",
"pm_score": 2,
"selected": true,
"text": "<p>After discovering the exact problem in this case, the request headers being too large because ServerSideRender sending too many attributes in a GET request, I <a href=\"https://github.com/WordPress/gutenberg/issues/23004\" rel=\"nofollow noreferrer\">opened a ticket</a> on the Gutenberg development repository proposing a few possible solutions for this issue. And the issue had actually already been addressed because I wasn't the first one to have this problem, so there is currently a <a href=\"https://github.com/WordPress/gutenberg/pull/21068\" rel=\"nofollow noreferrer\">pull request to solve this by allowing POST request to be made instead of GET requests</a>.</p>\n\n<p>As for the initial question of getting a more significant response from the ServerSideRender when there is an error, that still stands. It would be helpful to see something more than <code>Error loading block: The response is not a valid JSON response.</code> Perhaps seeing what the exact http status code from the response is, instead of having to dig for it in the Network requests of the browser's Inspector Tools...</p>\n"
}
] | 2020/06/05 | [
"https://wordpress.stackexchange.com/questions/368327",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/60906/"
] | I'm having a heck of a time with the ServerSideRender component for a Gutenberg block I'm developing. I'm seeing this error in the (non-)rendered block: `Error loading block: The response is not a valid JSON response.`
But where can I see the actual JSON response?
In the Chrome Inspector Tools I see:
>
> Failed to load resource: the server responded with a status of 502 ()
>
>
>
along with the request that was sent, with all the block attributes:
```
https://www.bibleget.io/wp-json/wp/v2/block-renderer/bibleget/bible-quote?context=edit&attributes%5BPARAGRAPHSTYLES_FONTFAMILY%5D=Times%20New%20Roman&attributes%5BPARAGRAPHSTYLES_LINEHEIGHT%5D=1.5&attributes%5BPARAGRAPHSTYLES_PADDINGTOPBOTTOM%5D=8&attributes%5BPARAGRAPHSTYLES_PADDINGLEFTRIGHT%5D=17&attributes%5BPARAGRAPHSTYLES_MARGINTOPBOTTOM%5D=24&attributes%5BPARAGRAPHSTYLES_MARGINLEFTRIGHT%5D=14&attributes%5BPARAGRAPHSTYLES_MARGINLEFTRIGHTUNIT%5D=auto&attributes%5BPARAGRAPHSTYLES_PARAGRAPHALIGN%5D=4&attributes%5BPARAGRAPHSTYLES_WIDTH%5D=85&attributes%5BPARAGRAPHSTYLES_NOVERSIONFORMATTING%5D=false&attributes%5BPARAGRAPHSTYLES_BORDERWIDTH%5D=4&attributes%5BPARAGRAPHSTYLES_BORDERCOLOR%5D=%230b02ac&attributes%5BPARAGRAPHSTYLES_BORDERSTYLE%5D=3&attributes%5BPARAGRAPHSTYLES_BORDERRADIUS%5D=12&attributes%5BPARAGRAPHSTYLES_BACKGROUNDCOLOR%5D=%23fdfbf7&attributes%5BVERSIONSTYLES_BOLD%5D=true&attributes%5BVERSIONSTYLES_ITALIC%5D=true&attributes%5BVERSIONSTYLES_UNDERLINE%5D=false&attributes%5BVERSIONSTYLES_STRIKETHROUGH%5D=false&attributes%5BVERSIONSTYLES_TEXTCOLOR%5D=%23000096&attributes%5BVERSIONSTYLES_FONTSIZE%5D=9&attributes%5BVERSIONSTYLES_FONTSIZEUNIT%5D=inherit&attributes%5BVERSIONSTYLES_VALIGN%5D=3&attributes%5BBOOKCHAPTERSTYLES_BOLD%5D=true&attributes%5BBOOKCHAPTERSTYLES_ITALIC%5D=false&attributes%5BBOOKCHAPTERSTYLES_UNDERLINE%5D=false&attributes%5BBOOKCHAPTERSTYLES_STRIKETHROUGH%5D=false&attributes%5BBOOKCHAPTERSTYLES_TEXTCOLOR%5D=%2302813d&attributes%5BBOOKCHAPTERSTYLES_FONTSIZE%5D=9&attributes%5BBOOKCHAPTERSTYLES_FONTSIZEUNIT%5D=em&attributes%5BBOOKCHAPTERSTYLES_VALIGN%5D=3&attributes%5BVERSENUMBERSTYLES_BOLD%5D=false&attributes%5BVERSENUMBERSTYLES_ITALIC%5D=false&attributes%5BVERSENUMBERSTYLES_UNDERLINE%5D=false&attributes%5BVERSENUMBERSTYLES_STRIKETHROUGH%5D=false&attributes%5BVERSENUMBERSTYLES_TEXTCOLOR%5D=%23ee0000&attributes%5BVERSENUMBERSTYLES_FONTSIZE%5D=7&attributes%5BVERSENUMBERSTYLES_FONTSIZEUNIT%5D=em&attributes%5BVERSENUMBERSTYLES_VALIGN%5D=1&attributes%5BVERSETEXTSTYLES_BOLD%5D=false&attributes%5BVERSETEXTSTYLES_ITALIC%5D=false&attributes%5BVERSETEXTSTYLES_UNDERLINE%5D=false&attributes%5BVERSETEXTSTYLES_STRIKETHROUGH%5D=false&attributes%5BVERSETEXTSTYLES_TEXTCOLOR%5D=%23706e6e&attributes%5BVERSETEXTSTYLES_FONTSIZE%5D=8&attributes%5BVERSETEXTSTYLES_FONTSIZEUNIT%5D=em&attributes%5BVERSETEXTSTYLES_VALIGN%5D=3&attributes%5BLAYOUTPREFS_SHOWBIBLEVERSION%5D=true&attributes%5BLAYOUTPREFS_BIBLEVERSIONALIGNMENT%5D=2&attributes%5BLAYOUTPREFS_BIBLEVERSIONPOSITION%5D=1&attributes%5BLAYOUTPREFS_BIBLEVERSIONWRAP%5D=2&attributes%5BLAYOUTPREFS_BOOKCHAPTERALIGNMENT%5D=1&attributes%5BLAYOUTPREFS_BOOKCHAPTERPOSITION%5D=1&attributes%5BLAYOUTPREFS_BOOKCHAPTERWRAP%5D=1&attributes%5BLAYOUTPREFS_BOOKCHAPTERFORMAT%5D=3&attributes%5BLAYOUTPREFS_BOOKCHAPTERFULLQUERY%5D=false&attributes%5BLAYOUTPREFS_SHOWVERSENUMBERS%5D=true&attributes%5BVERSION%5D%5B0%5D=LUZZI&attributes%5BVERSION%5D%5B1%5D=NVBSE&attributes%5BQUERY%5D=Lc10%2C1-16&attributes%5BPOPUP%5D=false&attributes%5BFORCEVERSION%5D=false&attributes%5BFORCECOPYRIGHT%5D=false&post_id=1178&lang=it&_locale=user
```
All the attributes look correct, and how they're handled in the PHP render callback is looking correct. I had the `ServerSideRender` working until yesterday, and now suddenly this "non valid JSON response error" is popping up.
I haven't made any changes to my render callback in PHP. I have even stepped through the render callback PHP function to make sure it was receiving all the attributes correctly and handling them correctly, and I have verified that that is the case. I have a function that will write to a debug.txt file, and I have stepped through the render callback making sure that each condition is working correctly. I can even see the final output that the render callback is returning, and it is correct. And yet, I am seeing this error on the Gutenberg block side. It would be helpful to have a more significant error message rather than "not a valid JSON response".
Looking at the Network tab of the Chrome Inspector Tools I am seeing that the actual response from the request posted above is `502 Bad Gateway - nginx`.
I have no idea what this is supposed to mean, because the request from the block is being sent to the server callback, the server callback is processing the request and returning a correct response. Something is happening somewhere between the response that is returned from the callback and the client side rendering of the block. Any ideas what could possibly be going on? | After discovering the exact problem in this case, the request headers being too large because ServerSideRender sending too many attributes in a GET request, I [opened a ticket](https://github.com/WordPress/gutenberg/issues/23004) on the Gutenberg development repository proposing a few possible solutions for this issue. And the issue had actually already been addressed because I wasn't the first one to have this problem, so there is currently a [pull request to solve this by allowing POST request to be made instead of GET requests](https://github.com/WordPress/gutenberg/pull/21068).
As for the initial question of getting a more significant response from the ServerSideRender when there is an error, that still stands. It would be helpful to see something more than `Error loading block: The response is not a valid JSON response.` Perhaps seeing what the exact http status code from the response is, instead of having to dig for it in the Network requests of the browser's Inspector Tools... |
368,332 | <p>when I try to upload a theme I have uploaded on a free host and it is the first time I upload a theme on a host, I got this error failed because
The style.css stylesheet doesn’t contain a valid theme header.</p>
<p>then I put this on my styles.css , but still getting this error , although the theme works very well on the localhost.
what should I do, please?</p>
<pre><code>/*
Theme Name: shah
Author: shah
Author URI: http://shah.gq
Description: Wordpress Theme
Version: 1.0
*/
</code></pre>
| [
{
"answer_id": 368348,
"author": "Sabbir Hasan",
"author_id": 76587,
"author_profile": "https://wordpress.stackexchange.com/users/76587",
"pm_score": 1,
"selected": false,
"text": "<p>Remove the extra space from the header. Try like below:</p>\n<pre><code>/*\nTheme Name: shah\nTheme URI: \nAuthor: shah\nAuthor URI: http://shah.gq\nDescription: Wordpress Theme\nVersion: 1.0\n*/\n</code></pre>\n"
},
{
"answer_id": 382697,
"author": "Sachin Hamal",
"author_id": 201350,
"author_profile": "https://wordpress.stackexchange.com/users/201350",
"pm_score": -1,
"selected": false,
"text": "<p>use same name for theme and also for your folder</p>\n"
}
] | 2020/06/05 | [
"https://wordpress.stackexchange.com/questions/368332",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/188733/"
] | when I try to upload a theme I have uploaded on a free host and it is the first time I upload a theme on a host, I got this error failed because
The style.css stylesheet doesn’t contain a valid theme header.
then I put this on my styles.css , but still getting this error , although the theme works very well on the localhost.
what should I do, please?
```
/*
Theme Name: shah
Author: shah
Author URI: http://shah.gq
Description: Wordpress Theme
Version: 1.0
*/
``` | Remove the extra space from the header. Try like below:
```
/*
Theme Name: shah
Theme URI:
Author: shah
Author URI: http://shah.gq
Description: Wordpress Theme
Version: 1.0
*/
``` |
368,342 | <h1>Context</h1>
<p>I'm developping a plugin showing geolocated posts on a leaflet map. <strong>I want to add a shortcode parameter to show a map with only the current loop posts' markers.</strong> That feature would be great on the search result page for exemple!</p>
<h1>Question</h1>
<p><strong>Is there a way to get the current page WP_Query arguments?</strong> I want to get those arguments to create a new WP_Query and add some more to filter only geolocated posts.</p>
<p>I don't know if it's possible at all, I always create new WP_query objects from scratch.</p>
<p>Thank you!</p>
| [
{
"answer_id": 368346,
"author": "Michelle",
"author_id": 16,
"author_profile": "https://wordpress.stackexchange.com/users/16",
"pm_score": 1,
"selected": false,
"text": "<p>I believe you can use <code>rewind_posts()</code> to get the posts from the current query, then amend from there:</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/rewind_posts/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/rewind_posts/</a></p>\n\n<p>This article has a good explanation of <code>rewind_posts()</code>, differentiating it from <code>wp_reset_postdata()</code> and <code>wp_reset_query()</code> : <a href=\"https://digwp.com/2011/09/3-ways-to-reset-the-wordpress-loop/\" rel=\"nofollow noreferrer\">https://digwp.com/2011/09/3-ways-to-reset-the-wordpress-loop/</a></p>\n"
},
{
"answer_id": 368350,
"author": "jannp",
"author_id": 189304,
"author_profile": "https://wordpress.stackexchange.com/users/189304",
"pm_score": 4,
"selected": true,
"text": "<p>Have you tried using <code>$wp_query</code> ?</p>\n\n<pre><code>global $wp_query;\nvar_dump($wp_query->query_vars);\n</code></pre>\n\n<p>For a single variable, you can use <a href=\"https://developer.wordpress.org/reference/functions/get_query_var/\" rel=\"noreferrer\">get_query_var</a></p>\n\n<p>Or you could try just dumping the <code>$_POST</code> , <code>var_dump( $_POST );</code></p>\n\n<p>Or maybe <code>var_dump( $GLOBALS['post'] );</code></p>\n"
},
{
"answer_id": 397088,
"author": "Carl Brubaker",
"author_id": 201820,
"author_profile": "https://wordpress.stackexchange.com/users/201820",
"pm_score": 0,
"selected": false,
"text": "<p>Another alternative is to get it from the <code>query</code> args directly. You can access all of the <code>$args</code> this way.</p>\n<pre class=\"lang-php prettyprint-override\"><code>$query = new WP_Query( $args );\n\n// paged\n$paged_arg = $query->query['paged'];\n</code></pre>\n"
}
] | 2020/06/05 | [
"https://wordpress.stackexchange.com/questions/368342",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140435/"
] | Context
=======
I'm developping a plugin showing geolocated posts on a leaflet map. **I want to add a shortcode parameter to show a map with only the current loop posts' markers.** That feature would be great on the search result page for exemple!
Question
========
**Is there a way to get the current page WP\_Query arguments?** I want to get those arguments to create a new WP\_Query and add some more to filter only geolocated posts.
I don't know if it's possible at all, I always create new WP\_query objects from scratch.
Thank you! | Have you tried using `$wp_query` ?
```
global $wp_query;
var_dump($wp_query->query_vars);
```
For a single variable, you can use [get\_query\_var](https://developer.wordpress.org/reference/functions/get_query_var/)
Or you could try just dumping the `$_POST` , `var_dump( $_POST );`
Or maybe `var_dump( $GLOBALS['post'] );` |
368,369 | <p>I am looking to use the rest API to use WordPress as a headless CMS, but I am curious as to how best to get a page using the path.</p>
<p>Example, if Wordpress is hosted at cms.example.com and my frontend is at example.com. If I create a page at cms.example.com/services/service-a I would want it accessible on the frontend at example.com/services/service-a. If my front end takes 'services/service-a' how can I find the right page?</p>
<p>My first thought was using the slug, until I realized the slug only matches the last part. In this example the slug would be 'service-a' not 'service\service-a'. I can specify a slug and a parent ID but this would require a a call for each level or hierarchy to work up the tree to get the parent id.</p>
<p><s>I have also briefly considered ignoring all previous levels of hierarchy and just looking at the last part of the path to use the slug, but I am not sure if that would have any unintended consequences.</s> EDIT: Thinking about it more I am decidedly against this method as it is possible for two pages at different areas of hierarchy to have the same slug resulting in a different path.</p>
<p>I was thinking to setup a custom endpoint to take the path, run it through the get_page_by_path() function then return the id. But that means each page load would require 2 API calls, or at least each page load that isn't at the first level of hierarchy. </p>
<p>But wanting to limit each request to a single API call I am thinking either if possible add a custom argument to the pages API endpoint to specify a full path to search by for the response, or else if that is not explicitly possible creating my own endpoint to accept the path argument then return the matching page object. Obviously in this case my preference would be for the former over the latter as that should require less work for a plugin and make the most out of the existing code in WordPress.</p>
<p>Is it possible to add a custom option to an existing endpoint? Is there a better method to do this with a single API call?</p>
| [
{
"answer_id": 368346,
"author": "Michelle",
"author_id": 16,
"author_profile": "https://wordpress.stackexchange.com/users/16",
"pm_score": 1,
"selected": false,
"text": "<p>I believe you can use <code>rewind_posts()</code> to get the posts from the current query, then amend from there:</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/rewind_posts/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/rewind_posts/</a></p>\n\n<p>This article has a good explanation of <code>rewind_posts()</code>, differentiating it from <code>wp_reset_postdata()</code> and <code>wp_reset_query()</code> : <a href=\"https://digwp.com/2011/09/3-ways-to-reset-the-wordpress-loop/\" rel=\"nofollow noreferrer\">https://digwp.com/2011/09/3-ways-to-reset-the-wordpress-loop/</a></p>\n"
},
{
"answer_id": 368350,
"author": "jannp",
"author_id": 189304,
"author_profile": "https://wordpress.stackexchange.com/users/189304",
"pm_score": 4,
"selected": true,
"text": "<p>Have you tried using <code>$wp_query</code> ?</p>\n\n<pre><code>global $wp_query;\nvar_dump($wp_query->query_vars);\n</code></pre>\n\n<p>For a single variable, you can use <a href=\"https://developer.wordpress.org/reference/functions/get_query_var/\" rel=\"noreferrer\">get_query_var</a></p>\n\n<p>Or you could try just dumping the <code>$_POST</code> , <code>var_dump( $_POST );</code></p>\n\n<p>Or maybe <code>var_dump( $GLOBALS['post'] );</code></p>\n"
},
{
"answer_id": 397088,
"author": "Carl Brubaker",
"author_id": 201820,
"author_profile": "https://wordpress.stackexchange.com/users/201820",
"pm_score": 0,
"selected": false,
"text": "<p>Another alternative is to get it from the <code>query</code> args directly. You can access all of the <code>$args</code> this way.</p>\n<pre class=\"lang-php prettyprint-override\"><code>$query = new WP_Query( $args );\n\n// paged\n$paged_arg = $query->query['paged'];\n</code></pre>\n"
}
] | 2020/06/06 | [
"https://wordpress.stackexchange.com/questions/368369",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/189477/"
] | I am looking to use the rest API to use WordPress as a headless CMS, but I am curious as to how best to get a page using the path.
Example, if Wordpress is hosted at cms.example.com and my frontend is at example.com. If I create a page at cms.example.com/services/service-a I would want it accessible on the frontend at example.com/services/service-a. If my front end takes 'services/service-a' how can I find the right page?
My first thought was using the slug, until I realized the slug only matches the last part. In this example the slug would be 'service-a' not 'service\service-a'. I can specify a slug and a parent ID but this would require a a call for each level or hierarchy to work up the tree to get the parent id.
~~I have also briefly considered ignoring all previous levels of hierarchy and just looking at the last part of the path to use the slug, but I am not sure if that would have any unintended consequences.~~ EDIT: Thinking about it more I am decidedly against this method as it is possible for two pages at different areas of hierarchy to have the same slug resulting in a different path.
I was thinking to setup a custom endpoint to take the path, run it through the get\_page\_by\_path() function then return the id. But that means each page load would require 2 API calls, or at least each page load that isn't at the first level of hierarchy.
But wanting to limit each request to a single API call I am thinking either if possible add a custom argument to the pages API endpoint to specify a full path to search by for the response, or else if that is not explicitly possible creating my own endpoint to accept the path argument then return the matching page object. Obviously in this case my preference would be for the former over the latter as that should require less work for a plugin and make the most out of the existing code in WordPress.
Is it possible to add a custom option to an existing endpoint? Is there a better method to do this with a single API call? | Have you tried using `$wp_query` ?
```
global $wp_query;
var_dump($wp_query->query_vars);
```
For a single variable, you can use [get\_query\_var](https://developer.wordpress.org/reference/functions/get_query_var/)
Or you could try just dumping the `$_POST` , `var_dump( $_POST );`
Or maybe `var_dump( $GLOBALS['post'] );` |
368,389 | <p>I've added the following code to
<strong>remove some checkout fields</strong> in case a <strong>particular shipping method</strong> is chosen and also make it work when you <strong>change the shipping method on the checkout page</strong>. </p>
<pre><code>add_filter( 'woocommerce_checkout_fields', 'xa_remove_billing_checkout_fields' );
function xa_remove_billing_checkout_fields( $fields ) {
// change below for the method
$shipping_method ='local_pickup:1'; // Here I want to specify an array of shipping methods
// change below for the list of fields
$hide_fields = array( 'billing_address_1', 'billing_address_2', 'billing_city', 'billing_state', 'billing_postcode' );
$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
// uncomment below line and reload checkout page to check current $chosen_methods
// print_r($chosen_methods);
$chosen_shipping = $chosen_methods[0];
foreach($hide_fields as $field ) {
if ($chosen_shipping == $shipping_method) {
$fields['billing'][$field]['required'] = false;
$fields['billing'][$field]['class'][] = 'hide';
}
$fields['billing'][$field]['class'][] = 'billing-dynamic';
}
return $fields;
}
add_action( 'wp_footer', 'cart_update_script', 999 );
function cart_update_script() {
if (is_checkout()) :
?>
<style>
.hide {display: none!important;}
</style>
<script>
jQuery( function( $ ) {
// woocommerce_params is required to continue, ensure the object exists
if ( typeof woocommerce_params === 'undefined' ) {
return false;
}
$(document).on( 'change', '#shipping_method input[type="radio"]', function() {
// change local_pickup:1 accordingly
$('.billing-dynamic').toggleClass('hide', this.value == 'local_pickup:1');
});
});
</script>
<?php
endif;
}
</code></pre>
<p>I was wondering how to make this work for an <strong>array of shipping methods</strong>. Suppose I want to make this work for flat_rate:2 as well, how could I elegantly loop the array to hide the fields an all shipping method of the array. </p>
| [
{
"answer_id": 368392,
"author": "Falz",
"author_id": 188264,
"author_profile": "https://wordpress.stackexchange.com/users/188264",
"pm_score": 1,
"selected": false,
"text": "<p>Sorry Not really a great answer. However, I haven't got enough Reputation points to add a comment yet :(</p>\n\n<p>I was just reading <a href=\"https://businessbloomer.com/woocommerce-hide-checkout-billing-fields-if-virtual-product-cart/\" rel=\"nofollow noreferrer\">this site</a>, and I saw the following snippet that could be useful for what you are trying to do.</p>\n\n<p>(this is not my code I use this page for a lot of great ideas & tips)</p>\n\n<pre>\n/**\n * @snippet Simplify Checkout if Only Virtual Products\n * @how-to Get CustomizeWoo.com FREE\n * @sourcecode https://businessbloomer.com/?p=78351\n * @author Rodolfo Melogli\n * @compatible WooCommerce 3.5.4\n * @donate $9 https://businessbloomer.com/bloomer-armada/\n */\n\nadd_filter( 'woocommerce_checkout_fields' , 'bbloomer_simplify_checkout_virtual' );\n\nfunction bbloomer_simplify_checkout_virtual( $fields ) {\n\n $only_virtual = true;\n\n foreach( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {\n // Check if there are non-virtual products\n if ( ! $cart_item['data']->is_virtual() ) $only_virtual = false; \n }\n\n if( $only_virtual ) {\n unset($fields['billing']['billing_company']);\n unset($fields['billing']['billing_address_1']);\n unset($fields['billing']['billing_address_2']);\n unset($fields['billing']['billing_city']);\n unset($fields['billing']['billing_postcode']);\n unset($fields['billing']['billing_country']);\n unset($fields['billing']['billing_state']);\n unset($fields['billing']['billing_phone']);\n add_filter( 'woocommerce_enable_order_notes_field', '__return_false' );\n }\n\n return $fields;\n}\n\n</pre>\n\n<p>I hope you find it useful :)</p>\n"
},
{
"answer_id": 369024,
"author": "BarrieO",
"author_id": 129008,
"author_profile": "https://wordpress.stackexchange.com/users/129008",
"pm_score": 1,
"selected": true,
"text": "<p>I came up with the following code for my problem:</p>\n<pre><code>/* HIDE "POSTKANTOOR" FIELD WHEN NON-POSTKANTOOR SHIPPING OPTION IS SELECTED */\n/* --- */\nadd_filter( 'woocommerce_checkout_fields', 'remove_billing_checkout_fields' );\nfunction remove_billing_checkout_fields( $fields ) {\n // Postkantoor shipping methods\n $shipping_method = array( 'flat_rate:6','flat_rate:7','flat_rate:8' ); \n // Fields to hide if not postkantoor shipping method\n $hide_fields = array( 'postkantoor' );\n\n $chosen_methods = WC()->session->get( 'chosen_shipping_methods' );\n // uncomment below line and reload checkout page to check current $chosen_methods\n // print_r($chosen_methods);\n $chosen_shipping = $chosen_methods[0];\n\n foreach( $hide_fields as $field ) {\n if ( ! in_array ($chosen_shipping , $shipping_method) ) {\n $fields['billing'][$field]['required'] = false;\n $fields['billing'][$field]['class'][] = 'hide';\n }\n $fields['billing'][$field]['class'][] = 'billing-dynamic';\n }\n\n return $fields;\n}\n\nadd_action( 'wp_footer', 'cart_update_script', 999 );\nfunction cart_update_script() {\n if (is_checkout()) :\n ?>\n <style>\n .hide {display: none!important;}\n </style>\n <script>\n jQuery( function( $ ) {\n\n // woocommerce_params is required to continue, ensure the object exists\n if ( typeof woocommerce_params === 'undefined' ) {\n return false;\n }\n\n // Postkantoor shipping methods\n var show = ['flat_rate:6','flat_rate:7','flat_rate:8'];\n\n $(document).on( 'change', '#shipping_method input[type="radio"]', function() {\n // console.log($.inArray($(this).val(), show));\n if ($.inArray($(this).val(), show) > -1) { // >-1 if found in array \n $('.billing-dynamic').removeClass('hide');\n // console.log('show');\n } else {\n $('.billing-dynamic').addClass('hide');\n // console.log('hide');\n }\n });\n\n });\n </script>\n <?php\n endif;\n}\n</code></pre>\n"
}
] | 2020/06/06 | [
"https://wordpress.stackexchange.com/questions/368389",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/129008/"
] | I've added the following code to
**remove some checkout fields** in case a **particular shipping method** is chosen and also make it work when you **change the shipping method on the checkout page**.
```
add_filter( 'woocommerce_checkout_fields', 'xa_remove_billing_checkout_fields' );
function xa_remove_billing_checkout_fields( $fields ) {
// change below for the method
$shipping_method ='local_pickup:1'; // Here I want to specify an array of shipping methods
// change below for the list of fields
$hide_fields = array( 'billing_address_1', 'billing_address_2', 'billing_city', 'billing_state', 'billing_postcode' );
$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
// uncomment below line and reload checkout page to check current $chosen_methods
// print_r($chosen_methods);
$chosen_shipping = $chosen_methods[0];
foreach($hide_fields as $field ) {
if ($chosen_shipping == $shipping_method) {
$fields['billing'][$field]['required'] = false;
$fields['billing'][$field]['class'][] = 'hide';
}
$fields['billing'][$field]['class'][] = 'billing-dynamic';
}
return $fields;
}
add_action( 'wp_footer', 'cart_update_script', 999 );
function cart_update_script() {
if (is_checkout()) :
?>
<style>
.hide {display: none!important;}
</style>
<script>
jQuery( function( $ ) {
// woocommerce_params is required to continue, ensure the object exists
if ( typeof woocommerce_params === 'undefined' ) {
return false;
}
$(document).on( 'change', '#shipping_method input[type="radio"]', function() {
// change local_pickup:1 accordingly
$('.billing-dynamic').toggleClass('hide', this.value == 'local_pickup:1');
});
});
</script>
<?php
endif;
}
```
I was wondering how to make this work for an **array of shipping methods**. Suppose I want to make this work for flat\_rate:2 as well, how could I elegantly loop the array to hide the fields an all shipping method of the array. | I came up with the following code for my problem:
```
/* HIDE "POSTKANTOOR" FIELD WHEN NON-POSTKANTOOR SHIPPING OPTION IS SELECTED */
/* --- */
add_filter( 'woocommerce_checkout_fields', 'remove_billing_checkout_fields' );
function remove_billing_checkout_fields( $fields ) {
// Postkantoor shipping methods
$shipping_method = array( 'flat_rate:6','flat_rate:7','flat_rate:8' );
// Fields to hide if not postkantoor shipping method
$hide_fields = array( 'postkantoor' );
$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
// uncomment below line and reload checkout page to check current $chosen_methods
// print_r($chosen_methods);
$chosen_shipping = $chosen_methods[0];
foreach( $hide_fields as $field ) {
if ( ! in_array ($chosen_shipping , $shipping_method) ) {
$fields['billing'][$field]['required'] = false;
$fields['billing'][$field]['class'][] = 'hide';
}
$fields['billing'][$field]['class'][] = 'billing-dynamic';
}
return $fields;
}
add_action( 'wp_footer', 'cart_update_script', 999 );
function cart_update_script() {
if (is_checkout()) :
?>
<style>
.hide {display: none!important;}
</style>
<script>
jQuery( function( $ ) {
// woocommerce_params is required to continue, ensure the object exists
if ( typeof woocommerce_params === 'undefined' ) {
return false;
}
// Postkantoor shipping methods
var show = ['flat_rate:6','flat_rate:7','flat_rate:8'];
$(document).on( 'change', '#shipping_method input[type="radio"]', function() {
// console.log($.inArray($(this).val(), show));
if ($.inArray($(this).val(), show) > -1) { // >-1 if found in array
$('.billing-dynamic').removeClass('hide');
// console.log('show');
} else {
$('.billing-dynamic').addClass('hide');
// console.log('hide');
}
});
});
</script>
<?php
endif;
}
``` |
368,427 | <p>In the default wordpress rss feed the element <code><pubDate></code> is </p>
<p><code><pubDate><?php echo mysql2date( 'D, d M Y H:i:s +0000', get_post_time( 'Y-m-d H:i:s', true ), false ); ?></pubDate></code></p>
<p>and gives a result of <code><pubDate>Tue, 12 May 2020 12:39:03 +0000</pubDate></code></p>
<p>how can i change this line to give a result of <code><pubDate>12/05/2020 12:39:03 +0000</pubDate></code> (d/m/Y) or <code><pubDate>12-05-2020 12:39:03 +0000</pubDate></code> (d-m-Y) but to be valid with RFC-822 ? </p>
<p>I tried many variations <code><pubDate><?php echo mysql2date('r', get_the_time('Y-m-d H:i:s')); ?></pubDate></code> or <code><pubDate><?php echo get_post_time( 'd/m/Y H:i:s O', true ); ?></pubDate></code> but they dont validate.</p>
<p>Any ideas would be appreciated. </p>
| [
{
"answer_id": 368392,
"author": "Falz",
"author_id": 188264,
"author_profile": "https://wordpress.stackexchange.com/users/188264",
"pm_score": 1,
"selected": false,
"text": "<p>Sorry Not really a great answer. However, I haven't got enough Reputation points to add a comment yet :(</p>\n\n<p>I was just reading <a href=\"https://businessbloomer.com/woocommerce-hide-checkout-billing-fields-if-virtual-product-cart/\" rel=\"nofollow noreferrer\">this site</a>, and I saw the following snippet that could be useful for what you are trying to do.</p>\n\n<p>(this is not my code I use this page for a lot of great ideas & tips)</p>\n\n<pre>\n/**\n * @snippet Simplify Checkout if Only Virtual Products\n * @how-to Get CustomizeWoo.com FREE\n * @sourcecode https://businessbloomer.com/?p=78351\n * @author Rodolfo Melogli\n * @compatible WooCommerce 3.5.4\n * @donate $9 https://businessbloomer.com/bloomer-armada/\n */\n\nadd_filter( 'woocommerce_checkout_fields' , 'bbloomer_simplify_checkout_virtual' );\n\nfunction bbloomer_simplify_checkout_virtual( $fields ) {\n\n $only_virtual = true;\n\n foreach( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {\n // Check if there are non-virtual products\n if ( ! $cart_item['data']->is_virtual() ) $only_virtual = false; \n }\n\n if( $only_virtual ) {\n unset($fields['billing']['billing_company']);\n unset($fields['billing']['billing_address_1']);\n unset($fields['billing']['billing_address_2']);\n unset($fields['billing']['billing_city']);\n unset($fields['billing']['billing_postcode']);\n unset($fields['billing']['billing_country']);\n unset($fields['billing']['billing_state']);\n unset($fields['billing']['billing_phone']);\n add_filter( 'woocommerce_enable_order_notes_field', '__return_false' );\n }\n\n return $fields;\n}\n\n</pre>\n\n<p>I hope you find it useful :)</p>\n"
},
{
"answer_id": 369024,
"author": "BarrieO",
"author_id": 129008,
"author_profile": "https://wordpress.stackexchange.com/users/129008",
"pm_score": 1,
"selected": true,
"text": "<p>I came up with the following code for my problem:</p>\n<pre><code>/* HIDE "POSTKANTOOR" FIELD WHEN NON-POSTKANTOOR SHIPPING OPTION IS SELECTED */\n/* --- */\nadd_filter( 'woocommerce_checkout_fields', 'remove_billing_checkout_fields' );\nfunction remove_billing_checkout_fields( $fields ) {\n // Postkantoor shipping methods\n $shipping_method = array( 'flat_rate:6','flat_rate:7','flat_rate:8' ); \n // Fields to hide if not postkantoor shipping method\n $hide_fields = array( 'postkantoor' );\n\n $chosen_methods = WC()->session->get( 'chosen_shipping_methods' );\n // uncomment below line and reload checkout page to check current $chosen_methods\n // print_r($chosen_methods);\n $chosen_shipping = $chosen_methods[0];\n\n foreach( $hide_fields as $field ) {\n if ( ! in_array ($chosen_shipping , $shipping_method) ) {\n $fields['billing'][$field]['required'] = false;\n $fields['billing'][$field]['class'][] = 'hide';\n }\n $fields['billing'][$field]['class'][] = 'billing-dynamic';\n }\n\n return $fields;\n}\n\nadd_action( 'wp_footer', 'cart_update_script', 999 );\nfunction cart_update_script() {\n if (is_checkout()) :\n ?>\n <style>\n .hide {display: none!important;}\n </style>\n <script>\n jQuery( function( $ ) {\n\n // woocommerce_params is required to continue, ensure the object exists\n if ( typeof woocommerce_params === 'undefined' ) {\n return false;\n }\n\n // Postkantoor shipping methods\n var show = ['flat_rate:6','flat_rate:7','flat_rate:8'];\n\n $(document).on( 'change', '#shipping_method input[type="radio"]', function() {\n // console.log($.inArray($(this).val(), show));\n if ($.inArray($(this).val(), show) > -1) { // >-1 if found in array \n $('.billing-dynamic').removeClass('hide');\n // console.log('show');\n } else {\n $('.billing-dynamic').addClass('hide');\n // console.log('hide');\n }\n });\n\n });\n </script>\n <?php\n endif;\n}\n</code></pre>\n"
}
] | 2020/06/07 | [
"https://wordpress.stackexchange.com/questions/368427",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/129972/"
] | In the default wordpress rss feed the element `<pubDate>` is
`<pubDate><?php echo mysql2date( 'D, d M Y H:i:s +0000', get_post_time( 'Y-m-d H:i:s', true ), false ); ?></pubDate>`
and gives a result of `<pubDate>Tue, 12 May 2020 12:39:03 +0000</pubDate>`
how can i change this line to give a result of `<pubDate>12/05/2020 12:39:03 +0000</pubDate>` (d/m/Y) or `<pubDate>12-05-2020 12:39:03 +0000</pubDate>` (d-m-Y) but to be valid with RFC-822 ?
I tried many variations `<pubDate><?php echo mysql2date('r', get_the_time('Y-m-d H:i:s')); ?></pubDate>` or `<pubDate><?php echo get_post_time( 'd/m/Y H:i:s O', true ); ?></pubDate>` but they dont validate.
Any ideas would be appreciated. | I came up with the following code for my problem:
```
/* HIDE "POSTKANTOOR" FIELD WHEN NON-POSTKANTOOR SHIPPING OPTION IS SELECTED */
/* --- */
add_filter( 'woocommerce_checkout_fields', 'remove_billing_checkout_fields' );
function remove_billing_checkout_fields( $fields ) {
// Postkantoor shipping methods
$shipping_method = array( 'flat_rate:6','flat_rate:7','flat_rate:8' );
// Fields to hide if not postkantoor shipping method
$hide_fields = array( 'postkantoor' );
$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
// uncomment below line and reload checkout page to check current $chosen_methods
// print_r($chosen_methods);
$chosen_shipping = $chosen_methods[0];
foreach( $hide_fields as $field ) {
if ( ! in_array ($chosen_shipping , $shipping_method) ) {
$fields['billing'][$field]['required'] = false;
$fields['billing'][$field]['class'][] = 'hide';
}
$fields['billing'][$field]['class'][] = 'billing-dynamic';
}
return $fields;
}
add_action( 'wp_footer', 'cart_update_script', 999 );
function cart_update_script() {
if (is_checkout()) :
?>
<style>
.hide {display: none!important;}
</style>
<script>
jQuery( function( $ ) {
// woocommerce_params is required to continue, ensure the object exists
if ( typeof woocommerce_params === 'undefined' ) {
return false;
}
// Postkantoor shipping methods
var show = ['flat_rate:6','flat_rate:7','flat_rate:8'];
$(document).on( 'change', '#shipping_method input[type="radio"]', function() {
// console.log($.inArray($(this).val(), show));
if ($.inArray($(this).val(), show) > -1) { // >-1 if found in array
$('.billing-dynamic').removeClass('hide');
// console.log('show');
} else {
$('.billing-dynamic').addClass('hide');
// console.log('hide');
}
});
});
</script>
<?php
endif;
}
``` |
368,489 | <p>I have a site developed by a third party using wordpress however we could not log in the Admin page currently due to change of IP address recently.</p>
<p>The login page <a href="https://domain/wp-admin" rel="nofollow noreferrer">https://domain/wp-admin</a> has directed me to "Forbidden" error page instead.</p>
<p>I also do not have the database file to do further amendments.</p>
<p>Can anyone help on this? Thanks.</p>
| [
{
"answer_id": 368491,
"author": "Botond Vajna",
"author_id": 163786,
"author_profile": "https://wordpress.stackexchange.com/users/163786",
"pm_score": 2,
"selected": false,
"text": "<p>You may try changing the site url in wp-config.php with:</p>\n\n<pre><code>define( 'WP_HOME', 'http://example.com' );\ndefine( 'WP_SITEURL', 'http://example.com' );\n\n</code></pre>\n\n<p>you may also check if you have http, or https.</p>\n"
},
{
"answer_id": 383271,
"author": "ACE-CM",
"author_id": 200678,
"author_profile": "https://wordpress.stackexchange.com/users/200678",
"pm_score": 0,
"selected": false,
"text": "<p>Had same issue when accessing the /WP-admin from an IP address in another country. The hosting company had blocked entry from IP addresses in other locations. Please contact your host to fix.</p>\n"
}
] | 2020/06/08 | [
"https://wordpress.stackexchange.com/questions/368489",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/189570/"
] | I have a site developed by a third party using wordpress however we could not log in the Admin page currently due to change of IP address recently.
The login page <https://domain/wp-admin> has directed me to "Forbidden" error page instead.
I also do not have the database file to do further amendments.
Can anyone help on this? Thanks. | You may try changing the site url in wp-config.php with:
```
define( 'WP_HOME', 'http://example.com' );
define( 'WP_SITEURL', 'http://example.com' );
```
you may also check if you have http, or https. |
368,498 | <p>I use the Contact Form 7 plugin on my site, now I have a task to send a confirmation email after sending the data. But I can not find in the documentation how to do this without creating an extra field.</p>
<p><strong>My solution:</strong> </p>
<ol>
<li>I created an additional field "Confirm email"</li>
<li>In the plugin settings, turned on Mail (2) and configured so that the email was sent</li>
</ol>
<p>everything works perfectly. But is it possible to make it so that without an additional field sends a email? with different text? </p>
<p>"Thanks for your reply"</p>
| [
{
"answer_id": 368499,
"author": "Juan Cullen",
"author_id": 189571,
"author_profile": "https://wordpress.stackexchange.com/users/189571",
"pm_score": 0,
"selected": false,
"text": "<p>You could redirect to another URL after the form is submitted. See: <a href=\"https://contactform7.com/redirecting-to-another-url-after-submissions/\" rel=\"nofollow noreferrer\">https://contactform7.com/redirecting-to-another-url-after-submissions/</a></p>\n\n<p>Here, you could run your own custom script that sends out a custom email.</p>\n"
},
{
"answer_id": 368503,
"author": "Abhik",
"author_id": 26991,
"author_profile": "https://wordpress.stackexchange.com/users/26991",
"pm_score": 1,
"selected": false,
"text": "<p>Hook into <code>wpcf7_mail_sent</code> action, it fires after the mail is successfully sent.</p>\n\n<pre><code>function wpse_368498_cf7_mail_sent( $contact_form ) {\n\n //Your confirmation code here\n\n}\nadd_action( 'wpcf7_mail_sent', 'wpse_368498_cf7_mail_sent' );\n</code></pre>\n"
}
] | 2020/06/08 | [
"https://wordpress.stackexchange.com/questions/368498",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/189574/"
] | I use the Contact Form 7 plugin on my site, now I have a task to send a confirmation email after sending the data. But I can not find in the documentation how to do this without creating an extra field.
**My solution:**
1. I created an additional field "Confirm email"
2. In the plugin settings, turned on Mail (2) and configured so that the email was sent
everything works perfectly. But is it possible to make it so that without an additional field sends a email? with different text?
"Thanks for your reply" | Hook into `wpcf7_mail_sent` action, it fires after the mail is successfully sent.
```
function wpse_368498_cf7_mail_sent( $contact_form ) {
//Your confirmation code here
}
add_action( 'wpcf7_mail_sent', 'wpse_368498_cf7_mail_sent' );
``` |
368,511 | <p>Gutenberg is still relative new concept, so I lack experiences (and the Internet lacks good tutorials). My goal it to wrap all heading titles generated by Gutenberg's "Heading" block with the <code><span></code> tag. So instead following code</p>
<pre><code><h2>Tips and trics</h2>
</code></pre>
<p>it renders this way</p>
<pre><code><h2><span>Tips and trics</span></h2>
</code></pre>
<p>How to start? It's JS or PHP job? Is there any filter family? What documentation search for on Wordpress.org?</p>
| [
{
"answer_id": 368499,
"author": "Juan Cullen",
"author_id": 189571,
"author_profile": "https://wordpress.stackexchange.com/users/189571",
"pm_score": 0,
"selected": false,
"text": "<p>You could redirect to another URL after the form is submitted. See: <a href=\"https://contactform7.com/redirecting-to-another-url-after-submissions/\" rel=\"nofollow noreferrer\">https://contactform7.com/redirecting-to-another-url-after-submissions/</a></p>\n\n<p>Here, you could run your own custom script that sends out a custom email.</p>\n"
},
{
"answer_id": 368503,
"author": "Abhik",
"author_id": 26991,
"author_profile": "https://wordpress.stackexchange.com/users/26991",
"pm_score": 1,
"selected": false,
"text": "<p>Hook into <code>wpcf7_mail_sent</code> action, it fires after the mail is successfully sent.</p>\n\n<pre><code>function wpse_368498_cf7_mail_sent( $contact_form ) {\n\n //Your confirmation code here\n\n}\nadd_action( 'wpcf7_mail_sent', 'wpse_368498_cf7_mail_sent' );\n</code></pre>\n"
}
] | 2020/06/08 | [
"https://wordpress.stackexchange.com/questions/368511",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/50021/"
] | Gutenberg is still relative new concept, so I lack experiences (and the Internet lacks good tutorials). My goal it to wrap all heading titles generated by Gutenberg's "Heading" block with the `<span>` tag. So instead following code
```
<h2>Tips and trics</h2>
```
it renders this way
```
<h2><span>Tips and trics</span></h2>
```
How to start? It's JS or PHP job? Is there any filter family? What documentation search for on Wordpress.org? | Hook into `wpcf7_mail_sent` action, it fires after the mail is successfully sent.
```
function wpse_368498_cf7_mail_sent( $contact_form ) {
//Your confirmation code here
}
add_action( 'wpcf7_mail_sent', 'wpse_368498_cf7_mail_sent' );
``` |
368,535 | <p>I have created two post types, events and registrations and would like to be able to loop through the events and then fetch the registrations for each event, but WP_Query seems not to be working.</p>
<p>The data is setup for 9 events and 3 registrations, two for one event and one for another</p>
<p>It seems to not fetch the registration data correctly.</p>
<pre><code>
$events = new WP_Query(Array(
'posts_per_page' => -1,
'post_type' => 'event'
));
if ($events->have_Posts()){
while($events->have_posts()){
$events->the_post();
echo "<p>Event " . get_the_title() . '</p>';
$eventID = $events->get_the_ID();
echo $eventID;
$args = array(
'post_type' => 'registration',
'meta_key' => 'event_id',
'meta_value' => $eventID,
'meta_compare' => '='
);
$registrations = new WP_Query($args);
while ($registrations->have_posts()){
$registrations->the_post();
echo "<p>The registrations list " . get_the_title() . "</p>";
}
}
}
</code></pre>
<p>I get the following results</p>
<pre><code>Event 1
Event 2
Event 3
Event 4
Event 5
Event 6
Event 7
Event 8
Event 9
</code></pre>
<p>If I change the line <code>'meta_compare' => '='</code> to <code>'meta_compare' => '!='</code>
I get the following</p>
<pre><code>Event 1
The registrations list for Evnt 1
The registrations list for Evnt 2
The registrations list for Evnt 1
Event 2
The registrations list for Evnt 1
The registrations list for Evnt 2
The registrations list for Evnt 1
Event 3
The registrations list for Evnt 1
The registrations list for Evnt 2
The registrations list for Evnt 1
Event 4
The registrations list for Evnt 1
The registrations list for Evnt 2
The registrations list for Evnt 1
Event 5
The registrations list for Evnt 1
The registrations list for Evnt 2
The registrations list for Evnt 1
Event 6r Registration
The registrations list for Evnt 1
The registrations list for Evnt 2
The registrations list for Evnt 1
Event 7
The registrations list for Evnt 1
The registrations list for Evnt 2
The registrations list for Evnt 1
Event 8
The registrations list for Evnt 1
The registrations list for Evnt 2
The registrations list for Evnt 1
Event 9
The registrations list for Evnt 1
The registrations list for Evnt 2
The registrations list for Evnt 1
</code></pre>
<p>Not sure why this is proving to be so hard, maybe it's because they're both posts, just different types, from the same table.</p>
<p>Can anyone help please?</p>
| [
{
"answer_id": 368499,
"author": "Juan Cullen",
"author_id": 189571,
"author_profile": "https://wordpress.stackexchange.com/users/189571",
"pm_score": 0,
"selected": false,
"text": "<p>You could redirect to another URL after the form is submitted. See: <a href=\"https://contactform7.com/redirecting-to-another-url-after-submissions/\" rel=\"nofollow noreferrer\">https://contactform7.com/redirecting-to-another-url-after-submissions/</a></p>\n\n<p>Here, you could run your own custom script that sends out a custom email.</p>\n"
},
{
"answer_id": 368503,
"author": "Abhik",
"author_id": 26991,
"author_profile": "https://wordpress.stackexchange.com/users/26991",
"pm_score": 1,
"selected": false,
"text": "<p>Hook into <code>wpcf7_mail_sent</code> action, it fires after the mail is successfully sent.</p>\n\n<pre><code>function wpse_368498_cf7_mail_sent( $contact_form ) {\n\n //Your confirmation code here\n\n}\nadd_action( 'wpcf7_mail_sent', 'wpse_368498_cf7_mail_sent' );\n</code></pre>\n"
}
] | 2020/06/08 | [
"https://wordpress.stackexchange.com/questions/368535",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/189611/"
] | I have created two post types, events and registrations and would like to be able to loop through the events and then fetch the registrations for each event, but WP\_Query seems not to be working.
The data is setup for 9 events and 3 registrations, two for one event and one for another
It seems to not fetch the registration data correctly.
```
$events = new WP_Query(Array(
'posts_per_page' => -1,
'post_type' => 'event'
));
if ($events->have_Posts()){
while($events->have_posts()){
$events->the_post();
echo "<p>Event " . get_the_title() . '</p>';
$eventID = $events->get_the_ID();
echo $eventID;
$args = array(
'post_type' => 'registration',
'meta_key' => 'event_id',
'meta_value' => $eventID,
'meta_compare' => '='
);
$registrations = new WP_Query($args);
while ($registrations->have_posts()){
$registrations->the_post();
echo "<p>The registrations list " . get_the_title() . "</p>";
}
}
}
```
I get the following results
```
Event 1
Event 2
Event 3
Event 4
Event 5
Event 6
Event 7
Event 8
Event 9
```
If I change the line `'meta_compare' => '='` to `'meta_compare' => '!='`
I get the following
```
Event 1
The registrations list for Evnt 1
The registrations list for Evnt 2
The registrations list for Evnt 1
Event 2
The registrations list for Evnt 1
The registrations list for Evnt 2
The registrations list for Evnt 1
Event 3
The registrations list for Evnt 1
The registrations list for Evnt 2
The registrations list for Evnt 1
Event 4
The registrations list for Evnt 1
The registrations list for Evnt 2
The registrations list for Evnt 1
Event 5
The registrations list for Evnt 1
The registrations list for Evnt 2
The registrations list for Evnt 1
Event 6r Registration
The registrations list for Evnt 1
The registrations list for Evnt 2
The registrations list for Evnt 1
Event 7
The registrations list for Evnt 1
The registrations list for Evnt 2
The registrations list for Evnt 1
Event 8
The registrations list for Evnt 1
The registrations list for Evnt 2
The registrations list for Evnt 1
Event 9
The registrations list for Evnt 1
The registrations list for Evnt 2
The registrations list for Evnt 1
```
Not sure why this is proving to be so hard, maybe it's because they're both posts, just different types, from the same table.
Can anyone help please? | Hook into `wpcf7_mail_sent` action, it fires after the mail is successfully sent.
```
function wpse_368498_cf7_mail_sent( $contact_form ) {
//Your confirmation code here
}
add_action( 'wpcf7_mail_sent', 'wpse_368498_cf7_mail_sent' );
``` |
368,587 | <p>I have a form where users will submit a timecard.<br /><br /><ul><li>All entries to this form will be from users who are logged in (this part I have figured out).</li><li>Users will enter their name, the amount of hours, and select the date for the timecard (week ending).</li><li><strong>The issue I'm encountering</strong> is how to limit the form so that each user can only submit the form once for each week ending (the date field).</li><li>Every user should be able to submit a form for the same date, but only once per user.</li><li>I'm not limiting per time period, because perhaps they forgot a timecard for last week and and so they should be able to enter two form submissions back to back, one for this week and one for last week, but only one form submission per user, per date selected in the date field.</li></ul>
<p>Any assistance would be greatly appreciated!</p>
| [
{
"answer_id": 368499,
"author": "Juan Cullen",
"author_id": 189571,
"author_profile": "https://wordpress.stackexchange.com/users/189571",
"pm_score": 0,
"selected": false,
"text": "<p>You could redirect to another URL after the form is submitted. See: <a href=\"https://contactform7.com/redirecting-to-another-url-after-submissions/\" rel=\"nofollow noreferrer\">https://contactform7.com/redirecting-to-another-url-after-submissions/</a></p>\n\n<p>Here, you could run your own custom script that sends out a custom email.</p>\n"
},
{
"answer_id": 368503,
"author": "Abhik",
"author_id": 26991,
"author_profile": "https://wordpress.stackexchange.com/users/26991",
"pm_score": 1,
"selected": false,
"text": "<p>Hook into <code>wpcf7_mail_sent</code> action, it fires after the mail is successfully sent.</p>\n\n<pre><code>function wpse_368498_cf7_mail_sent( $contact_form ) {\n\n //Your confirmation code here\n\n}\nadd_action( 'wpcf7_mail_sent', 'wpse_368498_cf7_mail_sent' );\n</code></pre>\n"
}
] | 2020/06/09 | [
"https://wordpress.stackexchange.com/questions/368587",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/189655/"
] | I have a form where users will submit a timecard.
* All entries to this form will be from users who are logged in (this part I have figured out).
* Users will enter their name, the amount of hours, and select the date for the timecard (week ending).
* **The issue I'm encountering** is how to limit the form so that each user can only submit the form once for each week ending (the date field).
* Every user should be able to submit a form for the same date, but only once per user.
* I'm not limiting per time period, because perhaps they forgot a timecard for last week and and so they should be able to enter two form submissions back to back, one for this week and one for last week, but only one form submission per user, per date selected in the date field.
Any assistance would be greatly appreciated! | Hook into `wpcf7_mail_sent` action, it fires after the mail is successfully sent.
```
function wpse_368498_cf7_mail_sent( $contact_form ) {
//Your confirmation code here
}
add_action( 'wpcf7_mail_sent', 'wpse_368498_cf7_mail_sent' );
``` |
368,627 | <p>I am having an issue:</p>
<ul>
<li><a href="https://developer.wordpress.org/reference/functions/get_the_author_meta/" rel="nofollow noreferrer">get_the_author_meta()</a> returns the meta</li>
<li><a href="https://developer.wordpress.org/reference/functions/get_user_meta/" rel="nofollow noreferrer">get_user_meta()</a> returns <em>false</em> for the same meta key</li>
</ul>
<p>I don't know why this happens.</p>
<p>Regarding user metadata, when should I use one or the other?</p>
<p><strong>I tried this</strong>:</p>
<pre><code>get_the_author_meta('afzfp_user_status', $user->ID);
get_user_meta('afzfp_user_status', $user->ID, true);
</code></pre>
<p><strong>It returns</strong>:</p>
<pre><code>String "the meta value"
bool (false)
</code></pre>
<p><strong>UPDATE</strong>:</p>
<p>(As pointed by <a href="https://wordpress.stackexchange.com/users/16575/shanebp">@shanebp</a>) - The parameters order is different, that is why my code is not working as expected:</p>
<pre><code>get_the_author_meta('afzfp_user_status', $user->ID);
get_user_meta($user->ID, 'afzfp_user_status', true);
</code></pre>
<p><strong>The question itself still remains</strong>: What is the difference between them and when is it recommended to use one or the other?</p>
| [
{
"answer_id": 368634,
"author": "shanebp",
"author_id": 16575,
"author_profile": "https://wordpress.stackexchange.com/users/16575",
"pm_score": 2,
"selected": false,
"text": "<p>Your parameter order is wrong for <a href=\"https://developer.wordpress.org/reference/functions/get_user_meta/\" rel=\"nofollow noreferrer\">get_user_meta</a>. \nThe user id should be first. </p>\n\n<p>Try: <code>var_dump(get_user_meta( $user->ID, 'afzfp_user_status', true));</code></p>\n"
},
{
"answer_id": 413829,
"author": "Thiago Santos",
"author_id": 158367,
"author_profile": "https://wordpress.stackexchange.com/users/158367",
"pm_score": 2,
"selected": true,
"text": "<p><strong><a href=\"https://developer.wordpress.org/reference/functions/get_the_author_meta/\" rel=\"nofollow noreferrer\"><code>get_the_author_meta</code></a></strong>: retrieves the requested data of the author of the current post.</p>\n<ul>\n<li>Parameters: ( string <strong>$field = ''</strong>, int|false <strong>$user_id = false</strong> )</li>\n</ul>\n<p><strong><a href=\"https://developer.wordpress.org/reference/functions/get_user_meta/\" rel=\"nofollow noreferrer\"><code>get_user_meta</code></a></strong>: retrieves user meta field for a user.</p>\n<ul>\n<li>Parameters: ( int <strong>$user_id</strong>, string <strong>$key = ''</strong>, bool <strong>$single = false</strong> )</li>\n</ul>\n<hr />\n<p><strong>Example</strong>:</p>\n<p>John is an logged in user reading a post written by Mary.</p>\n<ul>\n<li><strong><code>get_the_author_meta</code></strong> will return the value of a field (string) related to Mary, the author.</li>\n<li><strong><code>get_user_meta</code></strong> will return the value of one (string) or more (array) meta data fields related to John.</li>\n</ul>\n<hr />\n<p><strong>Snippets:</strong></p>\n<p><strong><code>get_the_author_meta</code></strong></p>\n<p>Get the email address for the author of the current post<b>*</b> and store it in the <code>$author_email</code> variable for further use:</p>\n<pre><code>$author_email = get_the_author_meta( 'author_email' );\n</code></pre>\n<p><b>*</b>If used within The Loop, the user ID need not be specified, it defaults to current post author. A user ID must be specified if used outside The Loop.</p>\n<p><strong><code>get_user_meta</code></strong></p>\n<p>Get the last name for user id 2 and store it in the <code>$user_last</code> variable:</p>\n<pre><code>$user_last = get_user_meta( 2, 'last_name', true );\n</code></pre>\n<hr />\n<p><strong>Reference:</strong></p>\n<p><strong><code>get_the_author_meta</code></strong>: <a href=\"https://developer.wordpress.org/reference/functions/get_the_author_meta/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_the_author_meta/</a></p>\n<p><strong><code>get_user_meta</code></strong>: <a href=\"https://developer.wordpress.org/reference/functions/get_user_meta/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_user_meta/</a></p>\n"
}
] | 2020/06/09 | [
"https://wordpress.stackexchange.com/questions/368627",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/155394/"
] | I am having an issue:
* [get\_the\_author\_meta()](https://developer.wordpress.org/reference/functions/get_the_author_meta/) returns the meta
* [get\_user\_meta()](https://developer.wordpress.org/reference/functions/get_user_meta/) returns *false* for the same meta key
I don't know why this happens.
Regarding user metadata, when should I use one or the other?
**I tried this**:
```
get_the_author_meta('afzfp_user_status', $user->ID);
get_user_meta('afzfp_user_status', $user->ID, true);
```
**It returns**:
```
String "the meta value"
bool (false)
```
**UPDATE**:
(As pointed by [@shanebp](https://wordpress.stackexchange.com/users/16575/shanebp)) - The parameters order is different, that is why my code is not working as expected:
```
get_the_author_meta('afzfp_user_status', $user->ID);
get_user_meta($user->ID, 'afzfp_user_status', true);
```
**The question itself still remains**: What is the difference between them and when is it recommended to use one or the other? | **[`get_the_author_meta`](https://developer.wordpress.org/reference/functions/get_the_author_meta/)**: retrieves the requested data of the author of the current post.
* Parameters: ( string **$field = ''**, int|false **$user\_id = false** )
**[`get_user_meta`](https://developer.wordpress.org/reference/functions/get_user_meta/)**: retrieves user meta field for a user.
* Parameters: ( int **$user\_id**, string **$key = ''**, bool **$single = false** )
---
**Example**:
John is an logged in user reading a post written by Mary.
* **`get_the_author_meta`** will return the value of a field (string) related to Mary, the author.
* **`get_user_meta`** will return the value of one (string) or more (array) meta data fields related to John.
---
**Snippets:**
**`get_the_author_meta`**
Get the email address for the author of the current post**\*** and store it in the `$author_email` variable for further use:
```
$author_email = get_the_author_meta( 'author_email' );
```
**\***If used within The Loop, the user ID need not be specified, it defaults to current post author. A user ID must be specified if used outside The Loop.
**`get_user_meta`**
Get the last name for user id 2 and store it in the `$user_last` variable:
```
$user_last = get_user_meta( 2, 'last_name', true );
```
---
**Reference:**
**`get_the_author_meta`**: <https://developer.wordpress.org/reference/functions/get_the_author_meta/>
**`get_user_meta`**: <https://developer.wordpress.org/reference/functions/get_user_meta/> |
368,696 | <p>Im trying to set a custom post title with a custom field instead of typing the title im setting it with a custom field it works good if I use a type text custom field but once I use a relationship field Im getting nothing I guess because that field return a array, my relationship field is "route_affected_by_this_alert"</p>
<pre><code>// Auto fill Title and Slug for CPT's - 'alerts'
function lh_acf_save_post( $post_id ) {
// Don't do this on the ACF post type
// if ( get_post_type( $post_id ) == 'project' ) {
// return;
// }
$new_title = '';
$new_slug = '';
</code></pre>
<p>// Get title from 'alerts' CPT acf field 'route_affected_by_this_alert'
if ( get_post_type( $post_id ) == 'alerts' ) {
$new_title = get_field( 'route_affected_by_this_alert', $post_id );
$new_slug = sanitize_title( $new_title );
}</p>
<pre><code> // Prevent iInfinite looping...
remove_action( 'acf/save_post', 'lh_acf_save_post' );
// Grab post data
$post = array(
'ID' => $post_id,
'post_title' => $new_title,
'post_name' => $new_slug,
);
// Update the Post
wp_update_post( $post );
// Continue save action
add_action( 'acf/save_post', 'lh_save_post' );
// Set the return URL in case of 'new' post
$_POST['return'] = add_query_arg( 'updated', 'true', get_permalink( $post_id ) );
}
add_action( 'acf/save_post', 'lh_acf_save_post', 10, 1 );
</code></pre>
<p>I want to assign those names to the post title</p>
<p><a href="https://i.stack.imgur.com/QMICE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QMICE.png" alt="Want to get those names in the post title" /></a></p>
<p>This is what im getting:</p>
<pre><code>
Array ( [0] => WP_Post Object ( [ID] => 4009 [post_author] => 1 [post_date] => 2020-05-22 11:29:55 [post_date_gmt] => 2020-05-22 15:29:55 [post_content] =>
Route 49 schedule - Effective 1/17/15
Kennedy Plaza Bus Stop Locations
[post_title] => Camp St/Miriam Hospital [post_excerpt] => [post_status] => publish [comment_status] => open [ping_status] => closed [post_password] => [post_name] => 49 [to_ping] => [pinged] => [post_modified] => 2020-05-27 14:44:24 [post_modified_gmt] => 2020-05-27 18:44:24 [post_content_filtered] => [post_parent] => 0 [guid] => https://mypage.com/?post_type=routes&p=4009 [menu_order] => 0 [post_type] => routes [post_mime_type] => [comment_count] => 0 [filter] => raw ) [1] => WP_Post Object ( [ID] => 4000 [post_author] => 1 [post_date] => 2020-05-22 10:59:15 [post_date_gmt] => 2020-05-22 14:59:15 [post_content] =>
Route 60 schedule - Effective 1/19/19
Kennedy Plaza Bus Stop Locations
Newport Visitors Center Bus Stop Locations
All inbound and outbound trips service Bay View Apartments.
[post_title] => Providence/Newport [post_excerpt] => [post_status] => publish [comment_status] => open [ping_status] => closed [post_password] => [post_name] => 60 [to_ping] => [pinged] => [post_modified] => 2020-06-08 11:02:14 [post_modified_gmt] => 2020-06-08 15:02:14 [post_content_filtered] => [post_parent] => 0 [guid] => https://mypage.com/?post_type=routes&p=4000 [menu_order] => 0 [post_type] => routes [post_mime_type] => [comment_count] => 0 [filter] => raw ) )
</code>
</pre>
<p>This is what im getting to make it work with the alerts CPT:
after: // generate our post title</p>
<pre><code>
// Code to get the title from a repeater field
function create_relationship_title($posts)
{
// set empty net title array
$new_title = [];
// if posts is not an array then return false
if (!is_array($posts)) return false;
// loop through each post
foreach ($posts as $post) {
// add the current post title to new title array
$new_title[] = $post->post_title;
}
// join all the related post titles together separated by a comma
$new_title = implode(' AND ', $new_title);
// return the new title
return $new_title;
}
function lh_acf_save_post($post_id ) {
$new_title = '';
// Get title from 'alerts' CPT acf field 'route_affected_by_this_alert'
if ( get_post_type( $post_id ) == 'alerts' ) {
$relationships = get_field( 'route_affected_by_this_alert', $post_id );
$new_title = create_relationship_title($relationships);
}
// get our product object
$post = get_post($post_id);
// generate our post title
if(get_post_type( $post_id ) == 'alerts') {
// remove the action
remove_action('acf/save_post', 'lh_acf_save_post', 20);
// update the post object
$post->post_title = $new_title;
$post->post_name = sanitize_title($new_title);
// update post
wp_update_post($post);
// re add the action
add_action('acf/save_post', 'lh_acf_save_post', 20);
}
// finally, return
return;
}
// construct your action here
add_action( 'acf/save_post', 'lh_acf_save_post', 20 );
</code>
</pre>
| [
{
"answer_id": 368715,
"author": "joshmoto",
"author_id": 111152,
"author_profile": "https://wordpress.stackexchange.com/users/111152",
"pm_score": 1,
"selected": true,
"text": "<p>Updated version...</p>\n<pre><code><?php\n\n/**\n * @param $posts array\n * @return false|string\n */\nfunction create_relationship_title($posts)\n{\n\n // set empty net title array\n $new_title = [];\n\n // if posts is not an array then return false\n if (!is_array($posts)) return false;\n\n // loop through each post\n foreach ($posts as $post) {\n\n // add the current post title to new title array\n $new_title[] = $post->post_title;\n\n }\n\n // join all the related post titles together separated by a comma\n $new_title = implode(', ', $new_title);\n\n // return the new title\n return $new_title;\n\n}\n\n/**\n * @param $post_id int\n */\nfunction lh_acf_save_post($post_id ) {\n\n // check we are on the correct post type\n if(get_post_type($post_id) <> 'alerts') return;\n\n $new_title = '';\n\n // Get title from 'companies' CPT acf field 'company_name'\n if ( get_post_type( $post_id ) == 'alerts' ) {\n $relationships = get_field( 'route_affected_by_this_alert', $post_id );\n $new_title = create_relationship_title($relationships);\n }\n\n // get our product object\n $post = get_post($post_id);\n\n // generate our post title\n if($post->post_status == 'publish' || $post->post_status == 'draft') {\n\n // remove the action\n remove_action('acf/save_post', 'lh_acf_save_post', 20);\n\n // update the post object\n $post->post_title = $new_title;\n $post->post_name = sanitize_title($new_title);\n\n // update post\n wp_update_post($post);\n\n // re add the action\n add_action('acf/save_post', 'lh_acf_save_post', 20);\n\n }\n\n // finally, return\n return;\n\n}\n\n// construct your action here\nadd_action( 'acf/save_post', 'lh_acf_save_post', 20 );\n</code></pre>\n"
},
{
"answer_id": 408185,
"author": "Julien",
"author_id": 224553,
"author_profile": "https://wordpress.stackexchange.com/users/224553",
"pm_score": 1,
"selected": false,
"text": "<p>you don't need a function...</p>\n<pre><code>$my_query = get_posts(array(\n 'post_type' => 'post_type_name',\n 'meta_query' => array(\n array(\n 'key' => 'relationship_field_name', \n 'value' => get_the_ID(), \n 'compare' => 'LIKE'\n )\n )\n));\n\nforeach( $my_query as $object ):\n print_r($object); //you'll see everything about the single post\n \n $object_title = $object->post_title; //title\n $object_acf_field = get_field('acf_field_name',$object->ID); //any ACF field\nendforeach;\n</code></pre>\n"
}
] | 2020/06/10 | [
"https://wordpress.stackexchange.com/questions/368696",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/181226/"
] | Im trying to set a custom post title with a custom field instead of typing the title im setting it with a custom field it works good if I use a type text custom field but once I use a relationship field Im getting nothing I guess because that field return a array, my relationship field is "route\_affected\_by\_this\_alert"
```
// Auto fill Title and Slug for CPT's - 'alerts'
function lh_acf_save_post( $post_id ) {
// Don't do this on the ACF post type
// if ( get_post_type( $post_id ) == 'project' ) {
// return;
// }
$new_title = '';
$new_slug = '';
```
// Get title from 'alerts' CPT acf field 'route\_affected\_by\_this\_alert'
if ( get\_post\_type( $post\_id ) == 'alerts' ) {
$new\_title = get\_field( 'route\_affected\_by\_this\_alert', $post\_id );
$new\_slug = sanitize\_title( $new\_title );
}
```
// Prevent iInfinite looping...
remove_action( 'acf/save_post', 'lh_acf_save_post' );
// Grab post data
$post = array(
'ID' => $post_id,
'post_title' => $new_title,
'post_name' => $new_slug,
);
// Update the Post
wp_update_post( $post );
// Continue save action
add_action( 'acf/save_post', 'lh_save_post' );
// Set the return URL in case of 'new' post
$_POST['return'] = add_query_arg( 'updated', 'true', get_permalink( $post_id ) );
}
add_action( 'acf/save_post', 'lh_acf_save_post', 10, 1 );
```
I want to assign those names to the post title
[](https://i.stack.imgur.com/QMICE.png)
This is what im getting:
```
Array ( [0] => WP_Post Object ( [ID] => 4009 [post_author] => 1 [post_date] => 2020-05-22 11:29:55 [post_date_gmt] => 2020-05-22 15:29:55 [post_content] =>
Route 49 schedule - Effective 1/17/15
Kennedy Plaza Bus Stop Locations
[post_title] => Camp St/Miriam Hospital [post_excerpt] => [post_status] => publish [comment_status] => open [ping_status] => closed [post_password] => [post_name] => 49 [to_ping] => [pinged] => [post_modified] => 2020-05-27 14:44:24 [post_modified_gmt] => 2020-05-27 18:44:24 [post_content_filtered] => [post_parent] => 0 [guid] => https://mypage.com/?post_type=routes&p=4009 [menu_order] => 0 [post_type] => routes [post_mime_type] => [comment_count] => 0 [filter] => raw ) [1] => WP_Post Object ( [ID] => 4000 [post_author] => 1 [post_date] => 2020-05-22 10:59:15 [post_date_gmt] => 2020-05-22 14:59:15 [post_content] =>
Route 60 schedule - Effective 1/19/19
Kennedy Plaza Bus Stop Locations
Newport Visitors Center Bus Stop Locations
All inbound and outbound trips service Bay View Apartments.
[post_title] => Providence/Newport [post_excerpt] => [post_status] => publish [comment_status] => open [ping_status] => closed [post_password] => [post_name] => 60 [to_ping] => [pinged] => [post_modified] => 2020-06-08 11:02:14 [post_modified_gmt] => 2020-06-08 15:02:14 [post_content_filtered] => [post_parent] => 0 [guid] => https://mypage.com/?post_type=routes&p=4000 [menu_order] => 0 [post_type] => routes [post_mime_type] => [comment_count] => 0 [filter] => raw ) )
```
This is what im getting to make it work with the alerts CPT:
after: // generate our post title
```
// Code to get the title from a repeater field
function create_relationship_title($posts)
{
// set empty net title array
$new_title = [];
// if posts is not an array then return false
if (!is_array($posts)) return false;
// loop through each post
foreach ($posts as $post) {
// add the current post title to new title array
$new_title[] = $post->post_title;
}
// join all the related post titles together separated by a comma
$new_title = implode(' AND ', $new_title);
// return the new title
return $new_title;
}
function lh_acf_save_post($post_id ) {
$new_title = '';
// Get title from 'alerts' CPT acf field 'route_affected_by_this_alert'
if ( get_post_type( $post_id ) == 'alerts' ) {
$relationships = get_field( 'route_affected_by_this_alert', $post_id );
$new_title = create_relationship_title($relationships);
}
// get our product object
$post = get_post($post_id);
// generate our post title
if(get_post_type( $post_id ) == 'alerts') {
// remove the action
remove_action('acf/save_post', 'lh_acf_save_post', 20);
// update the post object
$post->post_title = $new_title;
$post->post_name = sanitize_title($new_title);
// update post
wp_update_post($post);
// re add the action
add_action('acf/save_post', 'lh_acf_save_post', 20);
}
// finally, return
return;
}
// construct your action here
add_action( 'acf/save_post', 'lh_acf_save_post', 20 );
``` | Updated version...
```
<?php
/**
* @param $posts array
* @return false|string
*/
function create_relationship_title($posts)
{
// set empty net title array
$new_title = [];
// if posts is not an array then return false
if (!is_array($posts)) return false;
// loop through each post
foreach ($posts as $post) {
// add the current post title to new title array
$new_title[] = $post->post_title;
}
// join all the related post titles together separated by a comma
$new_title = implode(', ', $new_title);
// return the new title
return $new_title;
}
/**
* @param $post_id int
*/
function lh_acf_save_post($post_id ) {
// check we are on the correct post type
if(get_post_type($post_id) <> 'alerts') return;
$new_title = '';
// Get title from 'companies' CPT acf field 'company_name'
if ( get_post_type( $post_id ) == 'alerts' ) {
$relationships = get_field( 'route_affected_by_this_alert', $post_id );
$new_title = create_relationship_title($relationships);
}
// get our product object
$post = get_post($post_id);
// generate our post title
if($post->post_status == 'publish' || $post->post_status == 'draft') {
// remove the action
remove_action('acf/save_post', 'lh_acf_save_post', 20);
// update the post object
$post->post_title = $new_title;
$post->post_name = sanitize_title($new_title);
// update post
wp_update_post($post);
// re add the action
add_action('acf/save_post', 'lh_acf_save_post', 20);
}
// finally, return
return;
}
// construct your action here
add_action( 'acf/save_post', 'lh_acf_save_post', 20 );
``` |
368,805 | <p>I use the wordpress theme Sensible WP. When I do a search this is what appears as the URL:</p>
<p><a href="https://www.example.com/?s=my+search+text" rel="nofollow noreferrer">https://www.example.com/?s=my+search+text</a></p>
<p>I need to modify the CSS for this page only, not all pages, but I can't find how to do it.</p>
| [
{
"answer_id": 368806,
"author": "Jarod Thornton",
"author_id": 44017,
"author_profile": "https://wordpress.stackexchange.com/users/44017",
"pm_score": -1,
"selected": false,
"text": "<pre><code>if ( is_search() ) {\n echo ‘<style>.class{color:red;}</style>’;\n}\n</code></pre>\n"
},
{
"answer_id": 407707,
"author": "Kai",
"author_id": 200326,
"author_profile": "https://wordpress.stackexchange.com/users/200326",
"pm_score": 1,
"selected": false,
"text": "<p>I was looking for this and found the solution:</p>\n<p>Just add</p>\n<blockquote>\n<p>.search-results</p>\n</blockquote>\n<p>to your class. ie:</p>\n<pre><code>.search-results .title {\ncolor: red;\n}\n</code></pre>\n<p>Hope this is useful.</p>\n"
}
] | 2020/06/12 | [
"https://wordpress.stackexchange.com/questions/368805",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/189834/"
] | I use the wordpress theme Sensible WP. When I do a search this is what appears as the URL:
<https://www.example.com/?s=my+search+text>
I need to modify the CSS for this page only, not all pages, but I can't find how to do it. | I was looking for this and found the solution:
Just add
>
> .search-results
>
>
>
to your class. ie:
```
.search-results .title {
color: red;
}
```
Hope this is useful. |
368,872 | <p>I want to display the "ratingValue" and "ratingCount" values generated by the <a href="https://id.wordpress.org/plugins/kk-star-ratings/" rel="nofollow noreferrer">KK Star Ratings plugin</a> (<a href="https://github.com/kamalkhan/kk-star-ratings" rel="nofollow noreferrer">Github</a>).</p>
<p>I made a JSON-LD SoftwareAplication and here is the code I use in function.php:</p>
<pre><code>add_action('wp_head', 'add_jsonld_head', 1);
function add_jsonld_head() {
if ( is_single() ) {
?>
<script type="application/ld+json">
{
"@context": "http://schema.org/",
"@type": "SoftwareApplication",
"@id": "<?php echo get_permalink( get_option( 'page_for_posts' ) ); ?>",
"softwareVersion": "<?php the_field('versi_terbaru'); ?>",
"operatingSystem": "Windows",
"applicationCategory": "<?php the_field('kategori'); ?>",
"dateModified": "<?php the_modified_time('c'); ?>",
"name": "<?php the_title(); ?>",
"aggregateRating": {
"@type": "AggregateRating",
"name": "<?php the_title(); ?>",
"ratingValue": "",
"ratingCount": "",
"bestRating": "5",
},
"publisher": {
"@type": "organization",
"name": "<?php the_title(); ?>"
},
"offers": {
"@type": "Offer",
"price": "0",
"priceCurrency": "IDR"
},
"image":{
"@type": "ImageObject",
"url": "<?php the_post_thumbnail_url(); ?>",
"width": "100",
"height": "100"
}
}
</script>
<?php
}
}
</code></pre>
<p>How do I get the ratingValue and ratingCount values from KK Star Ratings?</p>
<p>I have played around with this plugins but sadly my coding skills are not that good so I couldn't figure out how to modify it. I would really appreciate any help I can get on this.</p>
| [
{
"answer_id": 368952,
"author": "Sabbir Hasan",
"author_id": 76587,
"author_profile": "https://wordpress.stackexchange.com/users/76587",
"pm_score": 2,
"selected": true,
"text": "<p>Here is what I found that might help you. I did some test by myself and here is snippets for you to use. Add the following code to functions.php file:</p>\n\n<pre><code>//Getter methods\n\n//this will return the base best score like 5 or 10.\nfunction get_best_rating(){\n return max((int) get_option('kksr_stars'), 1);\n}\n\n\n//This will return the rating vote count\nfunction get_rating_count($id){\n return count_filter(null, $id, null);\n}\n\n//This will return the rating score value\nfunction get_rating_score($id){\n return score_filter(null, $best, $id, null);\n}\n\n//Helper Functions\nfunction count_filter($count, $id, $slug){\n if ($slug) {\n return $count;\n }\n\n $count = (int) get_post_meta($id, '_kksr_casts', true);\n\n return max($count, 0);\n}\n\nfunction score_filter($score, $best, $id, $slug){\n if ($slug) {\n return $score;\n }\n\n $count = count_filter(null, $id, null);\n $counter = (float) get_post_meta($id, '_kksr_ratings', true);\n\n if (! $count) {\n return 0;\n }\n\n $score = $counter / $count / 5 * $best;\n $score = round($score, 1, PHP_ROUND_HALF_DOWN);\n\n return min(max($score, 0), $best);\n}\n</code></pre>\n\n<p>Now you can call the getter function like this:</p>\n\n<pre><code>$best = get_best_rating();\n$count = get_rating_count(get_the_id()); //You must provide post id as param\n$score = get_rating_score(get_the_id()); //You must provide post id as param\n</code></pre>\n\n<p>Let me know if it helps you.</p>\n"
},
{
"answer_id": 369000,
"author": "R.M. Reza",
"author_id": 159482,
"author_profile": "https://wordpress.stackexchange.com/users/159482",
"pm_score": 0,
"selected": false,
"text": "<p>This is the code I used:</p>\n<pre><code>$best = get_option('kksr_stars');\n$score = get_post_meta(get_the_ID(), '_kksr_ratings', true) ? ((int) get_post_meta(get_the_ID(), '_kksr_ratings', true)) : 0;\n$votes = get_post_meta(get_the_ID(), '_kksr_casts', true) ? ((int) get_post_meta(get_the_ID(), '_kksr_casts', true)) : 0;\n$avg = $score && $votes ? round((float)(($score/$votes)*($best/5)), 1) : 0;\n</code></pre>\n<p>Call:</p>\n<pre><code><?php echo $avg; ?>\n<?php echo $votes; ?> \n</code></pre>\n"
}
] | 2020/06/13 | [
"https://wordpress.stackexchange.com/questions/368872",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159482/"
] | I want to display the "ratingValue" and "ratingCount" values generated by the [KK Star Ratings plugin](https://id.wordpress.org/plugins/kk-star-ratings/) ([Github](https://github.com/kamalkhan/kk-star-ratings)).
I made a JSON-LD SoftwareAplication and here is the code I use in function.php:
```
add_action('wp_head', 'add_jsonld_head', 1);
function add_jsonld_head() {
if ( is_single() ) {
?>
<script type="application/ld+json">
{
"@context": "http://schema.org/",
"@type": "SoftwareApplication",
"@id": "<?php echo get_permalink( get_option( 'page_for_posts' ) ); ?>",
"softwareVersion": "<?php the_field('versi_terbaru'); ?>",
"operatingSystem": "Windows",
"applicationCategory": "<?php the_field('kategori'); ?>",
"dateModified": "<?php the_modified_time('c'); ?>",
"name": "<?php the_title(); ?>",
"aggregateRating": {
"@type": "AggregateRating",
"name": "<?php the_title(); ?>",
"ratingValue": "",
"ratingCount": "",
"bestRating": "5",
},
"publisher": {
"@type": "organization",
"name": "<?php the_title(); ?>"
},
"offers": {
"@type": "Offer",
"price": "0",
"priceCurrency": "IDR"
},
"image":{
"@type": "ImageObject",
"url": "<?php the_post_thumbnail_url(); ?>",
"width": "100",
"height": "100"
}
}
</script>
<?php
}
}
```
How do I get the ratingValue and ratingCount values from KK Star Ratings?
I have played around with this plugins but sadly my coding skills are not that good so I couldn't figure out how to modify it. I would really appreciate any help I can get on this. | Here is what I found that might help you. I did some test by myself and here is snippets for you to use. Add the following code to functions.php file:
```
//Getter methods
//this will return the base best score like 5 or 10.
function get_best_rating(){
return max((int) get_option('kksr_stars'), 1);
}
//This will return the rating vote count
function get_rating_count($id){
return count_filter(null, $id, null);
}
//This will return the rating score value
function get_rating_score($id){
return score_filter(null, $best, $id, null);
}
//Helper Functions
function count_filter($count, $id, $slug){
if ($slug) {
return $count;
}
$count = (int) get_post_meta($id, '_kksr_casts', true);
return max($count, 0);
}
function score_filter($score, $best, $id, $slug){
if ($slug) {
return $score;
}
$count = count_filter(null, $id, null);
$counter = (float) get_post_meta($id, '_kksr_ratings', true);
if (! $count) {
return 0;
}
$score = $counter / $count / 5 * $best;
$score = round($score, 1, PHP_ROUND_HALF_DOWN);
return min(max($score, 0), $best);
}
```
Now you can call the getter function like this:
```
$best = get_best_rating();
$count = get_rating_count(get_the_id()); //You must provide post id as param
$score = get_rating_score(get_the_id()); //You must provide post id as param
```
Let me know if it helps you. |
368,875 | <p>I've pulling pulling my hair for the last 2 days with this and searching did not result in any solution to the issue I am having. </p>
<p>I wanted to use <strong><serverSideRender /></strong> to load dynamic content in the front-end as well as see the generated content in the Gutenberg editor. I tested it with the simple example given on the <a href="https://developer.wordpress.org/block-editor/tutorials/block-tutorial/creating-dynamic-blocks/" rel="nofollow noreferrer">Gutenberg doc page</a>. </p>
<p>Here is the JS code:</p>
<pre><code>const { registerBlockType } = wp.blocks;
const { serverSideRender } = wp.serverSideRender
registerBlockType( 'gutenberg-examples/example-dynamic', {
title: 'Example: last post',
icon: 'megaphone',
category: 'widgets',
edit: function( props ) {
return [
<p>serverSideRender should appear here:</p>,
<serverSideRender
block="gutenberg-examples/example-dynamic"
attributes={ props.attributes }
/>
];
},
} );
</code></pre>
<p>PHP Code:</p>
<pre><code>function gutenberg_examples_dynamic_render_callback( $attributes, $content ) {
$recent_posts = wp_get_recent_posts( array(
'numberposts' => 1,
'post_status' => 'publish',
) );
if ( count( $recent_posts ) === 0 ) {
return 'No posts';
}
$post = $recent_posts[ 0 ];
$post_id = $post['ID'];
return sprintf(
'<a class="wp-block-my-plugin-latest-post" href="%1$s">%2$s</a>',
esc_url( get_permalink( $post_id ) ),
esc_html( get_the_title( $post_id ) )
);
}
function gutenberg_examples_dynamic() {
register_block_type( 'gutenberg-examples/example-dynamic', array(
'render_callback' => 'gutenberg_examples_dynamic_render_callback'
) );
}
add_action( 'init', 'gutenberg_examples_dynamic' );
</code></pre>
<p>The front-end displays the post as intended. Screenshot below:</p>
<p><a href="https://i.stack.imgur.com/ldjeX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ldjeX.png" alt="enter image description here"></a></p>
<p>But in Gutenberg the block does not show the dynamic content. In theory I should see the same thing as the front-end right? Or am I missing something?</p>
<p>This is what I see in Gutenberg:</p>
<p><a href="https://i.stack.imgur.com/RUROB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RUROB.png" alt="enter image description here"></a></p>
<p>As you can see, none of the dynamic content is rendered and there aren't any errors in the console either.</p>
<p>What am I doing wrong? Any help would be much appreciated.</p>
<p>Thanks in advance</p>
| [
{
"answer_id": 368892,
"author": "Welcher",
"author_id": 27210,
"author_profile": "https://wordpress.stackexchange.com/users/27210",
"pm_score": 0,
"selected": false,
"text": "<p>You’ll have to alias serverSideRender to use it in JSX.</p>\n\n<pre><code>const { serverSiderRender: ServerSideRender } = wp.serverSideRender\n</code></pre>\n"
},
{
"answer_id": 368902,
"author": "Woody",
"author_id": 189887,
"author_profile": "https://wordpress.stackexchange.com/users/189887",
"pm_score": 2,
"selected": false,
"text": "<p>Ok, after spending the whole day searching and reading I found the solution. It seems that <code>ServerSideRender</code> should be de-structured from <code>wp.components</code> and <strong>NOT</strong> from <code>wp.serverSideRender</code></p>\n\n<p>After replacing</p>\n\n<pre><code>const { serverSiderRender: ServerSideRender } = wp.serverSideRender;\n</code></pre>\n\n<p>with</p>\n\n<pre><code>const { ServerSideRender } = wp.components;\n</code></pre>\n\n<p>And</p>\n\n<pre><code>// <serverSideRender\n<ServerSideRender \n block=\"gutenberg-examples/example-dynamic\"\n attributes={ props.attributes }\n/>\n</code></pre>\n\n<p>All works fine now</p>\n\n<p><a href=\"https://i.stack.imgur.com/bOLKe.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/bOLKe.png\" alt=\"enter image description here\"></a></p>\n\n<p>Hope this helps someone. Thanks</p>\n"
}
] | 2020/06/13 | [
"https://wordpress.stackexchange.com/questions/368875",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/189887/"
] | I've pulling pulling my hair for the last 2 days with this and searching did not result in any solution to the issue I am having.
I wanted to use **<serverSideRender />** to load dynamic content in the front-end as well as see the generated content in the Gutenberg editor. I tested it with the simple example given on the [Gutenberg doc page](https://developer.wordpress.org/block-editor/tutorials/block-tutorial/creating-dynamic-blocks/).
Here is the JS code:
```
const { registerBlockType } = wp.blocks;
const { serverSideRender } = wp.serverSideRender
registerBlockType( 'gutenberg-examples/example-dynamic', {
title: 'Example: last post',
icon: 'megaphone',
category: 'widgets',
edit: function( props ) {
return [
<p>serverSideRender should appear here:</p>,
<serverSideRender
block="gutenberg-examples/example-dynamic"
attributes={ props.attributes }
/>
];
},
} );
```
PHP Code:
```
function gutenberg_examples_dynamic_render_callback( $attributes, $content ) {
$recent_posts = wp_get_recent_posts( array(
'numberposts' => 1,
'post_status' => 'publish',
) );
if ( count( $recent_posts ) === 0 ) {
return 'No posts';
}
$post = $recent_posts[ 0 ];
$post_id = $post['ID'];
return sprintf(
'<a class="wp-block-my-plugin-latest-post" href="%1$s">%2$s</a>',
esc_url( get_permalink( $post_id ) ),
esc_html( get_the_title( $post_id ) )
);
}
function gutenberg_examples_dynamic() {
register_block_type( 'gutenberg-examples/example-dynamic', array(
'render_callback' => 'gutenberg_examples_dynamic_render_callback'
) );
}
add_action( 'init', 'gutenberg_examples_dynamic' );
```
The front-end displays the post as intended. Screenshot below:
[](https://i.stack.imgur.com/ldjeX.png)
But in Gutenberg the block does not show the dynamic content. In theory I should see the same thing as the front-end right? Or am I missing something?
This is what I see in Gutenberg:
[](https://i.stack.imgur.com/RUROB.png)
As you can see, none of the dynamic content is rendered and there aren't any errors in the console either.
What am I doing wrong? Any help would be much appreciated.
Thanks in advance | Ok, after spending the whole day searching and reading I found the solution. It seems that `ServerSideRender` should be de-structured from `wp.components` and **NOT** from `wp.serverSideRender`
After replacing
```
const { serverSiderRender: ServerSideRender } = wp.serverSideRender;
```
with
```
const { ServerSideRender } = wp.components;
```
And
```
// <serverSideRender
<ServerSideRender
block="gutenberg-examples/example-dynamic"
attributes={ props.attributes }
/>
```
All works fine now
[](https://i.stack.imgur.com/bOLKe.png)
Hope this helps someone. Thanks |
368,890 | <p>Hi I'm building up a WordPress rest API's custom endpoint on my project. I'm using the following code to get the single response from the website.</p>
<pre><code>function get_single_post( $request ) {
$response = array();
$args = [
'id' => $request['id'],
'post_type' => 'payment',
];
$post = get_posts($args);
$metas = get_post_meta($request['id'],'');
$post_id = $post->ID;
$response[$post_id]['response'] = $post[0];
$response[$post_id]['metas'] = $metas;
return $response;
}
add_action('rest_api_init', function(){
register_rest_route('booking/v1', 'posts',[
'methods'=> 'GET',
'callback' => 'booking_posts',
]);
register_rest_route('booking/v1','/posts/(?P<id>\d+)',[
'methods' => 'GET',
// Register the callback for the endpoint.
'callback' => 'get_single_post',
]);
});
</code></pre>
<p>I'm not getting the post with the posts/ in my response. Kindly advise what I'm doing wrong here?</p>
<p>Here's my response:</p>
<pre><code>{
"": {
"response": {
"ID": 12042,
"post_author": "10",
"post_date": "2020-06-12 15:15:42",
"post_date_gmt": "2020-06-12 14:15:42",
"post_content": "",
"post_title": "xxxxxxxxxxxxxxx",
"post_excerpt": "",
"post_status": "publish",
"comment_status": "closed",
"ping_status": "closed",
"post_password": "",
"post_name": "xxxxxxxxxxx",
"to_ping": "",
"pinged": "",
"post_modified": "2020-06-12 15:15:42",
"post_modified_gmt": "2020-06-12 14:15:42",
"post_content_filtered": "",
"post_parent": 0,
"guid": "https://xxxxxxxx/payment/xxxxxxxxxx/",
"menu_order": 0,
"post_type": "payment",
"post_mime_type": "",
"comment_count": "0",
"filter": "raw"
},
"metas": {
"chauffeur_payment_status": [
"Unpaid"
],
"chauffeur_payment_num_passengers": [
"1"
],
"chauffeur_payment_num_bags": [
"0"
],
"chauffeur_payment_first_name": [
"xxxxxxx"
],
"chauffeur_payment_last_name": [
"xxxxxxxx"
],
"chauffeur_payment_email": [
"xxxxxxxxx"
],
"chauffeur_payment_phone_num": [
"xxxxxx"
],
"chauffeur_payment_flight_number": [
""
],
"chauffeur_payment_additional_info": [
""
],
"chauffeur_payment_pickup_address": [
"xxxxxxx"
],
"chauffeur_payment_dropoff_address": [
"xxxxxxxx"
],
"chauffeur_payment_pickup_date": [
"12/06/2020"
],
"chauffeur_payment_pickup_time": [
"12:00"
],
"chauffeur_payment_trip_distance": [
"3,907 km"
],
"chauffeur_payment_trip_time": [
"1 day 12 hours"
],
"chauffeur_payment_item_name": [
"Standard-size taxi"
],
"chauffeur_payment_trip_type": [
"one_way"
],
"chauffeur_payment_return_journey": [
"One Way"
],
"chauffeur_payment_num_hours": [
""
],
"chauffeur_payment_amount": [
"xxxx"
],
"chauffeur_payment_full_pickup_address": [
""
],
"chauffeur_payment_pickup_instructions": [
""
],
"chauffeur_payment_full_dropoff_address": [
""
],
"chauffeur_payment_dropoff_instructions": [
""
]
}
}
}
</code></pre>
<p>The id of response->ID should be same as posts/. It's not.</p>
| [
{
"answer_id": 368893,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": true,
"text": "<p>You're getting that mismatched values because you're using the wrong argument for the post ID in your <code>$args</code> array (i.e. the query args for <code>WP_Query</code>). And the correct argument is <code>p</code> (lowercase <code>P</code>) and not <code>id</code>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$args = [\n// 'id' => $request['id'], // wrong argument name - 'id'\n 'p' => $request['id'], // and the correct one is 'p'\n 'post_type' => 'payment',\n];\n</code></pre>\n\n<p>And in addition to that main issue, another one I noticed is the <code>$post_id = $post->ID;</code> whereby that <code>$post</code> is an array and not object. So did you mean to use <code>$post_id = $post[0]->ID;</code> ?</p>\n\n<p>Also, why do you have to use <code>get_posts()</code>? Why not just use <code>get_post()</code> — <code>$post = get_post( $request['id'] );</code> ? That way, the above <code>$post_id = $post->ID;</code> would be valid. So for example, this is how your code would look like when using <code>get_post()</code>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>if ( ! $post = get_post( $request['id'] ) ) {\n return new WP_Error( 'your_error_code_here', 'Please define a valid post ID.' );\n}\n\n$metas = get_post_meta( $request['id'] );\n$post_id = $post->ID;\n\n$response[ $post_id ]['response'] = $post;\n</code></pre>\n"
},
{
"answer_id": 392267,
"author": "Cameron",
"author_id": 209262,
"author_profile": "https://wordpress.stackexchange.com/users/209262",
"pm_score": 0,
"selected": false,
"text": "<p>Hope this helps someone, this uses ACF Custom Fields as well:</p>\n<p><strong>routes/site-route.php</strong></p>\n<pre><code><?php\n\nclass SiteRestRouter\n{\n\n public function __construct()\n {\n $this->register_routes();\n }\n\n public function get_site($request)\n {\n $args = array(\n 'p' => $request['id'],\n 'post_type' => 'site',\n );\n\n if ( ! $post = get_post( $request['id'] ) ) {\n return new WP_Error( 'invalid_id', 'Please define a valid post ID.' );\n }\n\n $query = new WP_Query($args);\n\n if ($query -> have_posts()) {\n $query->the_post();\n $post = get_post(get_the_ID());\n $id = get_the_ID();\n $title = $post->post_title;\n $last_updated = get_field('last_updated');\n $deployment_location = get_field('location');\n $git_location = get_field('git_location');\n $database_location = get_field('database_location');\n $host = get_field('host');\n $protected_by_cloudflare = get_field('cloudflare');\n $maintenance = get_field('maintenance');\n $php_version = get_field('php_version');\n $wordpress_version = get_field('wordpress_version');\n $assigned_to = get_field('assigned_to');\n $notes = get_field('notes');\n $logs = get_field('logs');\n\n $response['id'] = $id;\n $response['title'] = $title;\n $response['last_updated'] = $last_updated;\n $response['deployment_location'] = $deployment_location;\n $response['git_location'] = $git_location;\n $response['database_location'] = $database_location;\n $response['host'] = $host;\n $response['protected_by_cloudflare'] = $protected_by_cloudflare;\n $response['maintenance'] = $maintenance;\n $response['php_version'] = $php_version;\n $response['wordpress_version'] = $wordpress_version;\n $response['assigned_to'] = $assigned_to->post_title;\n $response['notes'] = $notes;\n $response['logs'] = $logs;\n }\n\n wp_reset_postdata();\n\n return $response;\n }\n\n protected function register_routes()\n {\n add_action('rest_api_init', function () {\n $namespace = 'api/v1/';\n\n register_rest_route($namespace, '/sites/(?P<id>\\d+)', array(\n 'methods' => 'GET',\n 'callback' => array( $this, 'get_site' ),\n ));\n });\n }\n}\n\nnew SiteRestRouter();\n</code></pre>\n<p><strong>Add this to functions.php</strong></p>\n<pre><code>require_once 'routes/site-route.php';\n</code></pre>\n"
}
] | 2020/06/13 | [
"https://wordpress.stackexchange.com/questions/368890",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/189621/"
] | Hi I'm building up a WordPress rest API's custom endpoint on my project. I'm using the following code to get the single response from the website.
```
function get_single_post( $request ) {
$response = array();
$args = [
'id' => $request['id'],
'post_type' => 'payment',
];
$post = get_posts($args);
$metas = get_post_meta($request['id'],'');
$post_id = $post->ID;
$response[$post_id]['response'] = $post[0];
$response[$post_id]['metas'] = $metas;
return $response;
}
add_action('rest_api_init', function(){
register_rest_route('booking/v1', 'posts',[
'methods'=> 'GET',
'callback' => 'booking_posts',
]);
register_rest_route('booking/v1','/posts/(?P<id>\d+)',[
'methods' => 'GET',
// Register the callback for the endpoint.
'callback' => 'get_single_post',
]);
});
```
I'm not getting the post with the posts/ in my response. Kindly advise what I'm doing wrong here?
Here's my response:
```
{
"": {
"response": {
"ID": 12042,
"post_author": "10",
"post_date": "2020-06-12 15:15:42",
"post_date_gmt": "2020-06-12 14:15:42",
"post_content": "",
"post_title": "xxxxxxxxxxxxxxx",
"post_excerpt": "",
"post_status": "publish",
"comment_status": "closed",
"ping_status": "closed",
"post_password": "",
"post_name": "xxxxxxxxxxx",
"to_ping": "",
"pinged": "",
"post_modified": "2020-06-12 15:15:42",
"post_modified_gmt": "2020-06-12 14:15:42",
"post_content_filtered": "",
"post_parent": 0,
"guid": "https://xxxxxxxx/payment/xxxxxxxxxx/",
"menu_order": 0,
"post_type": "payment",
"post_mime_type": "",
"comment_count": "0",
"filter": "raw"
},
"metas": {
"chauffeur_payment_status": [
"Unpaid"
],
"chauffeur_payment_num_passengers": [
"1"
],
"chauffeur_payment_num_bags": [
"0"
],
"chauffeur_payment_first_name": [
"xxxxxxx"
],
"chauffeur_payment_last_name": [
"xxxxxxxx"
],
"chauffeur_payment_email": [
"xxxxxxxxx"
],
"chauffeur_payment_phone_num": [
"xxxxxx"
],
"chauffeur_payment_flight_number": [
""
],
"chauffeur_payment_additional_info": [
""
],
"chauffeur_payment_pickup_address": [
"xxxxxxx"
],
"chauffeur_payment_dropoff_address": [
"xxxxxxxx"
],
"chauffeur_payment_pickup_date": [
"12/06/2020"
],
"chauffeur_payment_pickup_time": [
"12:00"
],
"chauffeur_payment_trip_distance": [
"3,907 km"
],
"chauffeur_payment_trip_time": [
"1 day 12 hours"
],
"chauffeur_payment_item_name": [
"Standard-size taxi"
],
"chauffeur_payment_trip_type": [
"one_way"
],
"chauffeur_payment_return_journey": [
"One Way"
],
"chauffeur_payment_num_hours": [
""
],
"chauffeur_payment_amount": [
"xxxx"
],
"chauffeur_payment_full_pickup_address": [
""
],
"chauffeur_payment_pickup_instructions": [
""
],
"chauffeur_payment_full_dropoff_address": [
""
],
"chauffeur_payment_dropoff_instructions": [
""
]
}
}
}
```
The id of response->ID should be same as posts/. It's not. | You're getting that mismatched values because you're using the wrong argument for the post ID in your `$args` array (i.e. the query args for `WP_Query`). And the correct argument is `p` (lowercase `P`) and not `id`:
```php
$args = [
// 'id' => $request['id'], // wrong argument name - 'id'
'p' => $request['id'], // and the correct one is 'p'
'post_type' => 'payment',
];
```
And in addition to that main issue, another one I noticed is the `$post_id = $post->ID;` whereby that `$post` is an array and not object. So did you mean to use `$post_id = $post[0]->ID;` ?
Also, why do you have to use `get_posts()`? Why not just use `get_post()` — `$post = get_post( $request['id'] );` ? That way, the above `$post_id = $post->ID;` would be valid. So for example, this is how your code would look like when using `get_post()`:
```php
if ( ! $post = get_post( $request['id'] ) ) {
return new WP_Error( 'your_error_code_here', 'Please define a valid post ID.' );
}
$metas = get_post_meta( $request['id'] );
$post_id = $post->ID;
$response[ $post_id ]['response'] = $post;
``` |
368,897 | <p>I've just started making my own WordPress widgets and don't have a very good understanding of good practices with PHP or HTML. To add html to a widget I have seen two different methods, the first being inside the PHP using <code>echo</code> and the second being closing off the PHP with <code>?></code> , writing some HTML then reopening the PHP with a <code><?php</code> tag.</p>
<p>For my widget I have found it much easier to use the second method but I am concerned about whether doing this is bad practice and could lead to problems later on. Is this something that just happens to work and wasn't intended to be used this way so could be broken in future updates?</p>
| [
{
"answer_id": 368910,
"author": "Mort 1305",
"author_id": 188811,
"author_profile": "https://wordpress.stackexchange.com/users/188811",
"pm_score": 2,
"selected": false,
"text": "<p>\"Practice\" is a matter of personal preference. The opening and closing PHP tags (<code><?php</code> and <code>?></code>) are there as a matter of convenience. Basically, try to write your code in context. In example,</p>\n\n<pre>\n// PHP code here\n?><a href=\"<?php the_permalink() ?>\"><?php the_title() ?></a><?php\n// PHP code here\n</pre>\n\n<p>looks (to me) like HTML code plopped right in the middle of a PHP code block (like in a function of the <strong>functions.php</strong> file), so I will write the display of this HTML link in that context as</p>\n\n<pre>\n// PHP code here\necho '<a href=\"'. get_the_permalink() .'\">'. get_the_title() .'</a>';\n// PHP code here\n</pre>\n\n<p>But, if I am in a HTML code block (like in the <strong>single.php</strong> file of a template), I will write the display of this link in HTML context (as opposed to PHP context above). So, I will not use</p>\n\n<pre>\n// HTML code here\n<?php echo '<a href=\"'. get_the_permalink() .'\">'. get_the_title() .'</a>'; ?>\n// HTML code here\n</pre>\n\n<p>but instead will code the display of the link as</p>\n\n<pre>\n// HTML code here\n<a href=\"<?php the_permalink() ?>\"><?php the_title() ?></a>\n// HTML code here\n</pre>\n"
},
{
"answer_id": 368913,
"author": "mozboz",
"author_id": 176814,
"author_profile": "https://wordpress.stackexchange.com/users/176814",
"pm_score": 0,
"selected": false,
"text": "<p>It's good practice to try and separate out code and presentation as much as possible. The best way to achieve this is to keep all your HTML in a 'template' and all your code in a PHP file somewhere.</p>\n\n<p>In practice, lots of PHP developers don't do this, and you get a mix of code and HTML which is often hard to read.</p>\n\n<p>I would suggest wherever you can, put all your PHP in one part of the file, and then drop the results of the PHP into the HTML using as short pieces of PHP as possible. Here's an example:</p>\n\n<pre><code><?php\n// do some complicated stuff here and keep all the code logic in one place:\n$a = complicated_function();\n$b = work_something_out();\n$c = $a + $b;\nif ($c = \"hello\") {\n $d = \"this\";\n}\n// etc etc\n?>\n\n<!-- now put all that in your HTML using shortest PHP tags possible -->\n<div><p><?php echo $a; ?></p></div>\n<h1><?php echo $b; ?></h1>\n....\n<div class=\"<?php echo $c; ?>\"><?php echo $d; ?><?div>\n</code></pre>\n\n<p>So here the code and the HTML are as separated as possible and it's much easier to see what the code is doing in one place and what the presentation is doing in the second place</p>\n\n<p>If you have a lot of PHP, pull it out into a separate class / file as much as possible.</p>\n"
}
] | 2020/06/13 | [
"https://wordpress.stackexchange.com/questions/368897",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/189907/"
] | I've just started making my own WordPress widgets and don't have a very good understanding of good practices with PHP or HTML. To add html to a widget I have seen two different methods, the first being inside the PHP using `echo` and the second being closing off the PHP with `?>` , writing some HTML then reopening the PHP with a `<?php` tag.
For my widget I have found it much easier to use the second method but I am concerned about whether doing this is bad practice and could lead to problems later on. Is this something that just happens to work and wasn't intended to be used this way so could be broken in future updates? | "Practice" is a matter of personal preference. The opening and closing PHP tags (`<?php` and `?>`) are there as a matter of convenience. Basically, try to write your code in context. In example,
```
// PHP code here
?><a href="<?php the_permalink() ?>"><?php the_title() ?></a><?php
// PHP code here
```
looks (to me) like HTML code plopped right in the middle of a PHP code block (like in a function of the **functions.php** file), so I will write the display of this HTML link in that context as
```
// PHP code here
echo '<a href="'. get_the_permalink() .'">'. get_the_title() .'</a>';
// PHP code here
```
But, if I am in a HTML code block (like in the **single.php** file of a template), I will write the display of this link in HTML context (as opposed to PHP context above). So, I will not use
```
// HTML code here
<?php echo '<a href="'. get_the_permalink() .'">'. get_the_title() .'</a>'; ?>
// HTML code here
```
but instead will code the display of the link as
```
// HTML code here
<a href="<?php the_permalink() ?>"><?php the_title() ?></a>
// HTML code here
``` |
368,903 | <p>I have an external api which takes json body as payload. I am trying to send multiple parallel requests. So I am not using <code>wp_remote_post()</code></p>
<p>The wp_remote_post() version of my code works perfectly.</p>
<h1>Sending JSON payload using <code>wp_remote_post()</code></h1>
<p>This works!</p>
<pre><code> $response = wp_remote_post($url, [
'body' => json_encode($registrants), // requried keys [firstName, lastName, email]
'headers' => [
'Authorization' => 'Bearer ' . $accessToken,
'Content-Type' => 'application/json; charset=utf-8'
],
'data_format' => 'body',
'timeout' => 10,
]);
return json_decode(wp_remote_retrieve_body($response));
</code></pre>
<p>Now I am trying to do the same with <a href="https://developer.wordpress.org/reference/classes/requests/request_multiple/" rel="nofollow noreferrer"><code>Request::request_multiple()</code></a> But data isn't sending as json body.</p>
<h1>Sending JSON payload using <code>Request::request_multiple()</code></h1>
<p>Does not work!</p>
<pre><code> $requests[] = [
'url' => $url,
'type' => 'POST',
'body' => json_encode($registrant), // requried keys [firstName, lastName, email]
'headers' => [
'Authorization' => 'Bearer ' . $accessToken,
'Content-Type' => 'application/json; charset=utf-8'
],
'data_format' => 'body',
'timeout' => 30,
];
$options = [
'data_format' => 'body'
];
$resp = Requests::request_multiple($requests, $options);
foreach($resp as $response){
var_dump($response);
$responses[] = json_decode($response->body);
}
</code></pre>
<p>The error I am getting from API is very specific and throws when it doesn't get JSON body payload.</p>
| [
{
"answer_id": 368914,
"author": "mozboz",
"author_id": 176814,
"author_profile": "https://wordpress.stackexchange.com/users/176814",
"pm_score": 0,
"selected": false,
"text": "<p>Did you notice that the $registrant variable is spelled differently in the two cases?</p>\n\n<p>If this is not a problem try printing out the value of <code>json_encode($registrant)</code> before you send it and see if it looks right.</p>\n"
},
{
"answer_id": 369001,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": true,
"text": "<p><strong>You can't.</strong></p>\n<p>The requests library that comes bundled in WordPress doesn't support this. The reason for this is that the <code>request_multiple</code> function only accepts these parameters:</p>\n<pre><code>* @param array $requests Request data (array of 'url', 'headers', 'data', 'options') as per {@see Requests_Transport::request}\n</code></pre>\n<p><code>body</code> is not one of those parameters, which explains why your request is failing. A reading of the code confirms this is the case down to the fsock/curl levels of the library.</p>\n<p>Instead:</p>\n<ul>\n<li>Perform non-parallel requests if you intend to continue using the <code>Requests</code> library</li>\n<li>Switch to an alternative library such as Guzzle</li>\n</ul>\n<p>I'd also recommend opening issues on GitHub, there doesn't appear to be any technical reason it couldn't be changed to support the <code>body</code> parameter other than that nobody added it when those interfaces were written</p>\n"
}
] | 2020/06/13 | [
"https://wordpress.stackexchange.com/questions/368903",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3094/"
] | I have an external api which takes json body as payload. I am trying to send multiple parallel requests. So I am not using `wp_remote_post()`
The wp\_remote\_post() version of my code works perfectly.
Sending JSON payload using `wp_remote_post()`
=============================================
This works!
```
$response = wp_remote_post($url, [
'body' => json_encode($registrants), // requried keys [firstName, lastName, email]
'headers' => [
'Authorization' => 'Bearer ' . $accessToken,
'Content-Type' => 'application/json; charset=utf-8'
],
'data_format' => 'body',
'timeout' => 10,
]);
return json_decode(wp_remote_retrieve_body($response));
```
Now I am trying to do the same with [`Request::request_multiple()`](https://developer.wordpress.org/reference/classes/requests/request_multiple/) But data isn't sending as json body.
Sending JSON payload using `Request::request_multiple()`
========================================================
Does not work!
```
$requests[] = [
'url' => $url,
'type' => 'POST',
'body' => json_encode($registrant), // requried keys [firstName, lastName, email]
'headers' => [
'Authorization' => 'Bearer ' . $accessToken,
'Content-Type' => 'application/json; charset=utf-8'
],
'data_format' => 'body',
'timeout' => 30,
];
$options = [
'data_format' => 'body'
];
$resp = Requests::request_multiple($requests, $options);
foreach($resp as $response){
var_dump($response);
$responses[] = json_decode($response->body);
}
```
The error I am getting from API is very specific and throws when it doesn't get JSON body payload. | **You can't.**
The requests library that comes bundled in WordPress doesn't support this. The reason for this is that the `request_multiple` function only accepts these parameters:
```
* @param array $requests Request data (array of 'url', 'headers', 'data', 'options') as per {@see Requests_Transport::request}
```
`body` is not one of those parameters, which explains why your request is failing. A reading of the code confirms this is the case down to the fsock/curl levels of the library.
Instead:
* Perform non-parallel requests if you intend to continue using the `Requests` library
* Switch to an alternative library such as Guzzle
I'd also recommend opening issues on GitHub, there doesn't appear to be any technical reason it couldn't be changed to support the `body` parameter other than that nobody added it when those interfaces were written |
368,948 | <p>I want to make the page classes changed dynamic depend on time or anything else to force the type of scraper that depend on my site classes</p>
<p>or the classes like content, entry-content .. etc.</p>
<p>How can I do that? and how I control with the new classes name to get the style from old classes?!</p>
<p><strong>Old class</strong></p>
<pre><code>.entry-content{
color:red;
font-size:12pt;
}
</code></pre>
<p><strong>new class</strong></p>
<pre><code>.timeNowis46421sdf{
color:red;
font-size:12pt;
}
</code></pre>
| [
{
"answer_id": 368982,
"author": "Tony Djukic",
"author_id": 60844,
"author_profile": "https://wordpress.stackexchange.com/users/60844",
"pm_score": 1,
"selected": false,
"text": "<p>As per my comment, I'm not sure why you'd want to do this, but it is possible.</p>\n\n<p>You would use something like this for your CSS:</p>\n\n<pre><code>[class*='random-']{\n color:red;\n font-size:12pt;\n}\n</code></pre>\n\n<p>That's just your stylesheet targeting any class that starts with <code>random-</code>. You could change that to be whatever you want it to be, say <code>entry-</code> or whatever. You'll just need to match it with the jQuery below.</p>\n\n<p>Now, in your primary/main JS file, you'd want something like this, or take this entire code, make a new file and paste everything below into it. You'd have to enqueue that file though.</p>\n\n<pre><code>(function( $ ) {\n 'use strict';\n $( document ).ready( function() {\n if( $( '.entry-content' ).length > 0 ) {\n var newClassName = 'random-'+Math.floor( ( new Date() ).getTime() / 1000 );\n $( '.entry-content' ).addClass( newClassName ).removeClass( 'entry-content' );\n }\n } );\n} )( jQuery );\n</code></pre>\n\n<p>First thing we're doing is checking if there is an <code>.entry-content</code> on the page - I generally always run a check like this first because I don't want to bother executing anything unless there's something on the page to be effected.</p>\n\n<p>Then we're generating a new class as a jQuery variable by combining <code>random-</code> with a string of numbers using the current date/time.</p>\n\n<p>Lastly we're searching for the <code>.entry-content</code> class, adding the <code>random-1592183945</code> that we generated as a the <code>newClassName</code> variable, and then removing the <code>.entry-content</code> class.</p>\n\n<p>And that's it. Your CSS selector will recognize the class and apply style rules to it and each page load will generate a different class name every second, so scrapers should see them as being different. </p>\n"
},
{
"answer_id": 401251,
"author": "WP Developer",
"author_id": 217831,
"author_profile": "https://wordpress.stackexchange.com/users/217831",
"pm_score": 0,
"selected": false,
"text": "<p>Please use this</p>\n<pre><code><div class="entry-content random-<?php echo time(); ?>">\n<style>\n[class*='random-']{\n color:red;\n font-size:12pt;\n}\n</style>\n</code></pre>\n"
}
] | 2020/06/14 | [
"https://wordpress.stackexchange.com/questions/368948",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82877/"
] | I want to make the page classes changed dynamic depend on time or anything else to force the type of scraper that depend on my site classes
or the classes like content, entry-content .. etc.
How can I do that? and how I control with the new classes name to get the style from old classes?!
**Old class**
```
.entry-content{
color:red;
font-size:12pt;
}
```
**new class**
```
.timeNowis46421sdf{
color:red;
font-size:12pt;
}
``` | As per my comment, I'm not sure why you'd want to do this, but it is possible.
You would use something like this for your CSS:
```
[class*='random-']{
color:red;
font-size:12pt;
}
```
That's just your stylesheet targeting any class that starts with `random-`. You could change that to be whatever you want it to be, say `entry-` or whatever. You'll just need to match it with the jQuery below.
Now, in your primary/main JS file, you'd want something like this, or take this entire code, make a new file and paste everything below into it. You'd have to enqueue that file though.
```
(function( $ ) {
'use strict';
$( document ).ready( function() {
if( $( '.entry-content' ).length > 0 ) {
var newClassName = 'random-'+Math.floor( ( new Date() ).getTime() / 1000 );
$( '.entry-content' ).addClass( newClassName ).removeClass( 'entry-content' );
}
} );
} )( jQuery );
```
First thing we're doing is checking if there is an `.entry-content` on the page - I generally always run a check like this first because I don't want to bother executing anything unless there's something on the page to be effected.
Then we're generating a new class as a jQuery variable by combining `random-` with a string of numbers using the current date/time.
Lastly we're searching for the `.entry-content` class, adding the `random-1592183945` that we generated as a the `newClassName` variable, and then removing the `.entry-content` class.
And that's it. Your CSS selector will recognize the class and apply style rules to it and each page load will generate a different class name every second, so scrapers should see them as being different. |
369,026 | <p>I have a small problem when attempting to query some posts by author.
I have events and registrations. Currently I have 4 registrations, all created by User2 with the wp-admin showing that correctly. If I run the following code with a user logged on it works. User2 shows all and User1 shows none.
However, if no-one is logged on it returns all of the registrations. The user_id is being shown as 0 so it shouldn't find any of the registrations but it finds all of them, those for user 1 and those for user 2. Is there anyway I could stop this without having to check is_user_logged_in() each time.</p>
<p>Thanks</p>
<pre><code>$reg_count=0;
//if (is_user_logged_in()){
echo "looking for registrations with author id of " . get_current_user_id();
$registrations = new WP_Query(Array(
'posts_per_page' => -1,
'post_type' => "registration",
'author' => get_current_user_id(),
'meta_key' => 'first_name',
'orderby' => 'meta_value',
'order' => 'ASC',
'meta_query' => array(
array(
'key'=> 'event_id',
'compare' => 'LIKE',
'value' => '"' . get_the_id() . '"'
)
)
));
$reg_count = $registrations->found_posts;
echo "found " . $reg_count . " registrations wih author id of " . get_current_user_id();
//}
?>
</code></pre>
| [
{
"answer_id": 369028,
"author": "dnwjn",
"author_id": 182963,
"author_profile": "https://wordpress.stackexchange.com/users/182963",
"pm_score": 2,
"selected": false,
"text": "<p>An <code>author</code> value of <code>0</code> results in the query skipping that parameter. See <a href=\"https://wordpress.stackexchange.com/questions/329805/how-to-get-posts-without-author\">this question</a> and specifically <a href=\"https://wordpress.stackexchange.com/questions/329805/how-to-get-posts-without-author/329811#329811\">this answer</a>.</p>\n<p>Checking if the user is logged in would still be your best bet, since that would prevent unnecessary database queries from running.</p>\n"
},
{
"answer_id": 369030,
"author": "jdm2112",
"author_id": 45202,
"author_profile": "https://wordpress.stackexchange.com/users/45202",
"pm_score": 1,
"selected": true,
"text": "<p>Welcome to WPSE. The condition you want to prevent is a ID of 0 so only run the query if it does not.</p>\n<p>Also, DRY - don't repeat yourself. Rather than call <code>get_current_user_id()</code> multiple times, call it once and store it.</p>\n<pre><code>$reg_count= 0;\n$user_id = get_current_user_id();\nif ( 0 !== $user_id ) {\n\n echo "looking for registrations with author id of $user_id"; //PHP will output var value in double quotes\n\n $registrations = new WP_Query(\n array(\n 'posts_per_page' => -1,\n 'post_type' => "registration",\n 'author' => $user_id,\n 'meta_key' => 'first_name',\n 'orderby' => 'meta_value',\n 'order' => 'ASC',\n 'meta_query' => array(\n array(\n 'key' => 'event_id',\n 'compare' => 'LIKE',\n 'value' => '"' . get_the_id() . '"' //Why not just get_the_id()?\n ),\n ),\n ));\n \n echo "found $registrations->found_posts registrations with author id of $user_id";\n}\n</code></pre>\n<p>NOTE: Not at my desk - the code above is untested. Comment here if there is a problem.</p>\n<p>EDIT: added missing closing bracket for <code>IF</code> statement.</p>\n"
}
] | 2020/06/15 | [
"https://wordpress.stackexchange.com/questions/369026",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/189611/"
] | I have a small problem when attempting to query some posts by author.
I have events and registrations. Currently I have 4 registrations, all created by User2 with the wp-admin showing that correctly. If I run the following code with a user logged on it works. User2 shows all and User1 shows none.
However, if no-one is logged on it returns all of the registrations. The user\_id is being shown as 0 so it shouldn't find any of the registrations but it finds all of them, those for user 1 and those for user 2. Is there anyway I could stop this without having to check is\_user\_logged\_in() each time.
Thanks
```
$reg_count=0;
//if (is_user_logged_in()){
echo "looking for registrations with author id of " . get_current_user_id();
$registrations = new WP_Query(Array(
'posts_per_page' => -1,
'post_type' => "registration",
'author' => get_current_user_id(),
'meta_key' => 'first_name',
'orderby' => 'meta_value',
'order' => 'ASC',
'meta_query' => array(
array(
'key'=> 'event_id',
'compare' => 'LIKE',
'value' => '"' . get_the_id() . '"'
)
)
));
$reg_count = $registrations->found_posts;
echo "found " . $reg_count . " registrations wih author id of " . get_current_user_id();
//}
?>
``` | Welcome to WPSE. The condition you want to prevent is a ID of 0 so only run the query if it does not.
Also, DRY - don't repeat yourself. Rather than call `get_current_user_id()` multiple times, call it once and store it.
```
$reg_count= 0;
$user_id = get_current_user_id();
if ( 0 !== $user_id ) {
echo "looking for registrations with author id of $user_id"; //PHP will output var value in double quotes
$registrations = new WP_Query(
array(
'posts_per_page' => -1,
'post_type' => "registration",
'author' => $user_id,
'meta_key' => 'first_name',
'orderby' => 'meta_value',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'event_id',
'compare' => 'LIKE',
'value' => '"' . get_the_id() . '"' //Why not just get_the_id()?
),
),
));
echo "found $registrations->found_posts registrations with author id of $user_id";
}
```
NOTE: Not at my desk - the code above is untested. Comment here if there is a problem.
EDIT: added missing closing bracket for `IF` statement. |
369,094 | <p>I want to show page items in my wordpress theme and this is the code:</p>
<pre><code><section id="two">
<div class="inner">
<?php
$pagesargs = array(
'posts_per_page'=> 2,
'offset'=> 0,
'category' => '',
'category_name' => '',
'orderby' => 'post_date' ,
'order' => 'DESC',
'include' => '',
'exclude' => '',
'meta_key' => '',
'meta_value' => '',
'post_type' => 'page',
'post_mime_type' => '',
'post_parent' => '',
'post_status' => 'publish',
'suppress_filters' => true,
);
$my_pages = get_pages($pagesargs);
foreach ($my_pages as $page){
?>
<article>
<div class="content">
<header>
<h3><?php the_title() ?></h3>
</header>
<div class="image fit">
<img src="<?php bloginfo('template_url')?>/style/images/pic01.jpg" alt="" />
</div>
<p><?php the_excerpt(); ?></p>
</div>
</article>
<?php } ?>
</div>
</section>
</code></pre>
<p>but in index just show posts!!how can I change it and show posts?</p>
| [
{
"answer_id": 369099,
"author": "mozboz",
"author_id": 176814,
"author_profile": "https://wordpress.stackexchange.com/users/176814",
"pm_score": -1,
"selected": false,
"text": "<p>Yes, those custom folders and files go inside the theme you're using. Wordpress groups files like HTML and CSS together in themes. What you should do is pop this CSS file in the directory of the theme you're using, and link to it there. Then it will definitely never get deleted, and then you have your own theme that you can apply to any Wordpress website.</p>\n<p>So if your theme is called 'Nice Theme', you'll find a directory something like:</p>\n<pre><code>wp-content/themes/nice-theme\n</code></pre>\n<p>If there is a css directory in there, put your CSS in there, otherwise put it where it looks like it makes most sense, and update the point you refer to the CSS to include the extra part of the URL, e.g. if before the URL you used to load your CSS was:</p>\n<pre><code>https://yoursite.com/mycss.css\n</code></pre>\n<p>Then now it should be:</p>\n<pre><code>https://yoursite.com/wp-content/themes/nice-theme/mycss.css\n</code></pre>\n"
},
{
"answer_id": 369160,
"author": "mozboz",
"author_id": 176814,
"author_profile": "https://wordpress.stackexchange.com/users/176814",
"pm_score": 0,
"selected": false,
"text": "<p>Taken from <a href=\"https://themes.artbees.net/blog/add-external-css-or-javascript-to-wordpress/\" rel=\"nofollow noreferrer\">this link</a> there are several other options for adding your own CSS, if you don't want to put it in the theme:</p>\n<ol>\n<li>Use Theme Options and paste in CSS</li>\n<li>Use a plugin to insert CSS/JS. You could also write your own plugin to 'host' the CSS file neatly in wp-content/plugins/ somewhere.</li>\n<li>Use a child theme, which will maintain your changes if your theme changes.</li>\n</ol>\n<p>More info on each of these is in the link</p>\n"
},
{
"answer_id": 369161,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 0,
"selected": false,
"text": "<p>To answer your question directly. No the files won't get deleted when WordPress is updated. They will remain intact.</p>\n"
}
] | 2020/06/16 | [
"https://wordpress.stackexchange.com/questions/369094",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/188679/"
] | I want to show page items in my wordpress theme and this is the code:
```
<section id="two">
<div class="inner">
<?php
$pagesargs = array(
'posts_per_page'=> 2,
'offset'=> 0,
'category' => '',
'category_name' => '',
'orderby' => 'post_date' ,
'order' => 'DESC',
'include' => '',
'exclude' => '',
'meta_key' => '',
'meta_value' => '',
'post_type' => 'page',
'post_mime_type' => '',
'post_parent' => '',
'post_status' => 'publish',
'suppress_filters' => true,
);
$my_pages = get_pages($pagesargs);
foreach ($my_pages as $page){
?>
<article>
<div class="content">
<header>
<h3><?php the_title() ?></h3>
</header>
<div class="image fit">
<img src="<?php bloginfo('template_url')?>/style/images/pic01.jpg" alt="" />
</div>
<p><?php the_excerpt(); ?></p>
</div>
</article>
<?php } ?>
</div>
</section>
```
but in index just show posts!!how can I change it and show posts? | Taken from [this link](https://themes.artbees.net/blog/add-external-css-or-javascript-to-wordpress/) there are several other options for adding your own CSS, if you don't want to put it in the theme:
1. Use Theme Options and paste in CSS
2. Use a plugin to insert CSS/JS. You could also write your own plugin to 'host' the CSS file neatly in wp-content/plugins/ somewhere.
3. Use a child theme, which will maintain your changes if your theme changes.
More info on each of these is in the link |
369,143 | <p>I've looked at the Settings API codex page, <a href="https://codex.wordpress.org/Settings_API" rel="nofollow noreferrer">https://codex.wordpress.org/Settings_API</a>, and I can't find anything related to setting <code>autoload</code> to <code>no</code> for any options using the Settings API.</p>
<p>Is there any way to achieve this using the Setttings API? Asking because I have many DB table <code>options</code> entries that were created using <code>register_setting</code> and all of the <code>options</code> have <code>autoload</code> set to <code>yes</code>.</p>
<p>I need to optimize this because hundreds of entries are being loaded on every page load unecessarily.</p>
| [
{
"answer_id": 369392,
"author": "Mark Barnes",
"author_id": 19528,
"author_profile": "https://wordpress.stackexchange.com/users/19528",
"pm_score": 3,
"selected": true,
"text": "<p>The only way to accomplish this is to add the option to the database yourself before the Settings API does so. To do this, add a 'sanitize_callback' to the register_settings function:</p>\n<p><code>register_setting ('my_options', 'my_option_name', array ('type' => 'string', 'sanitize_callback' => 'my_function_name'));</code></p>\n<p>Then, in your function, update the option yourself:</p>\n<pre><code>function my_function_name ($value) {\n update_option ('my_option_name', $value, false);\n return $value;\n}\n</code></pre>\n<p>`</p>\n"
},
{
"answer_id": 412135,
"author": "Victor Crespo",
"author_id": 228361,
"author_profile": "https://wordpress.stackexchange.com/users/228361",
"pm_score": 0,
"selected": false,
"text": "<p>After trying many possible solutions (most of them go into an infinite loop) this one is working for me.</p>\n<p>I use the add_option_{$option} hook and then I do the following:</p>\n<pre><code>public function change_autoload_to_no( $option, $value )\n{\n\n update_option( $option, '', 'no' );\n update_option( $option, $value, 'no' );\n\n}\n</code></pre>\n<p>This might not be the most "elegant" solution but it works. I guess other option is to modify the value directly with sql.</p>\n"
}
] | 2020/06/16 | [
"https://wordpress.stackexchange.com/questions/369143",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/190079/"
] | I've looked at the Settings API codex page, <https://codex.wordpress.org/Settings_API>, and I can't find anything related to setting `autoload` to `no` for any options using the Settings API.
Is there any way to achieve this using the Setttings API? Asking because I have many DB table `options` entries that were created using `register_setting` and all of the `options` have `autoload` set to `yes`.
I need to optimize this because hundreds of entries are being loaded on every page load unecessarily. | The only way to accomplish this is to add the option to the database yourself before the Settings API does so. To do this, add a 'sanitize\_callback' to the register\_settings function:
`register_setting ('my_options', 'my_option_name', array ('type' => 'string', 'sanitize_callback' => 'my_function_name'));`
Then, in your function, update the option yourself:
```
function my_function_name ($value) {
update_option ('my_option_name', $value, false);
return $value;
}
```
` |
369,151 | <p>I have a weird problem with a wordpress site I'm working on, when we share links for it on discord shared link contains my login name and a link to author posts page (index is a page not a blog page) but when I look at the source there is not a single reference to my login name on the page, also facebook and other social media sites don't have this as there is no metadata about it but somehow discord fetches my username (probably because I'm the creator of it) but I'm unable to find how it does that and remove that from links. Any ideas?</p>
<p>Page in question:
angelicthegame.com/</p>
<p>Discord link preview:</p>
<p><a href="https://i.stack.imgur.com/hosKP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hosKP.png" alt="Discord link preview with author name" /></a></p>
<p>Erdi is the author name displayed and links to <a href="https://angelicthegame.com/author/erdi/" rel="nofollow noreferrer">https://angelicthegame.com/author/erdi/</a></p>
| [
{
"answer_id": 369619,
"author": "John A.",
"author_id": 190483,
"author_profile": "https://wordpress.stackexchange.com/users/190483",
"pm_score": 0,
"selected": false,
"text": "<p>Just ran into this issue myself, you are the author of that page so it shows on a Discord link. The best work-around I have found that i'm using is simply changing the author to the Websites Name. So when it shows in discord it shows as the Author is the domain and not a person!</p>\n"
},
{
"answer_id": 369620,
"author": "Sabbir Hasan",
"author_id": 76587,
"author_profile": "https://wordpress.stackexchange.com/users/76587",
"pm_score": 3,
"selected": true,
"text": "<p>This might help you. Add this script to functions.php. It will unset author from oembed preview. Remember Discord might already cached your URL. You may not get immediate result.</p>\n<pre><code>add_filter( 'oembed_response_data', 'disable_embeds_filter_oembed_response_data_' );\nfunction disable_embeds_filter_oembed_response_data_( $data ) {\n unset($data['author_url']);\n unset($data['author_name']);\n return $data;\n}\n</code></pre>\n<p>for more explanation head over <a href=\"https://stackoverflow.com/a/56547051/5448954\">here</a></p>\n"
}
] | 2020/06/16 | [
"https://wordpress.stackexchange.com/questions/369151",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/190091/"
] | I have a weird problem with a wordpress site I'm working on, when we share links for it on discord shared link contains my login name and a link to author posts page (index is a page not a blog page) but when I look at the source there is not a single reference to my login name on the page, also facebook and other social media sites don't have this as there is no metadata about it but somehow discord fetches my username (probably because I'm the creator of it) but I'm unable to find how it does that and remove that from links. Any ideas?
Page in question:
angelicthegame.com/
Discord link preview:
[](https://i.stack.imgur.com/hosKP.png)
Erdi is the author name displayed and links to <https://angelicthegame.com/author/erdi/> | This might help you. Add this script to functions.php. It will unset author from oembed preview. Remember Discord might already cached your URL. You may not get immediate result.
```
add_filter( 'oembed_response_data', 'disable_embeds_filter_oembed_response_data_' );
function disable_embeds_filter_oembed_response_data_( $data ) {
unset($data['author_url']);
unset($data['author_name']);
return $data;
}
```
for more explanation head over [here](https://stackoverflow.com/a/56547051/5448954) |
369,187 | <p>I've already saw the question some times here, but sadly nothing helped me out yet.</p>
<p>Right now I've got following code:</p>
<pre><code><h2 class="title_bar">Videos</h2>
<ul class="vlist">
<?php $args = array( 'numberposts' => 60, 'orderby' => 'rand' );
$rand_posts = get_posts( $args );
foreach( $rand_posts as $post ) : ?>
<li class="video" id="video_<?php the_ID(); ?>">
<a href="<?php the_permalink() ?>" title="<?php the_title(); ?>">
<?php $thumb = tube_getcustomfield('wtp_thumb_url',get_the_ID()); if(!empty($thumb)) { ?>
<img src="<?php echo $thumb; ?>" alt="<?php the_title_attribute(); ?>" title="<?php the_title_attribute(); ?>" width="240p" height="180" class="thumb" /> <?php } else { ?>
<img src="<?php bloginfo('template_url') ?>/images/pic_post1.jpg" alt="<?php the_title_attribute(); ?>" title="<?php the_title_attribute(); ?>" class="thumb"/><?php } ?>
<i></i>
<span class="box">
<span class="views"><?php if(function_exists('the_views')) { the_views(); } ?></span>
<span class="time"><?php echo time_ago(); ?></span>
</span>
<strong><?php short_title('...', '34'); ?></strong> </a>
</li>
<?php endforeach; ?>
</ul>
<div class="clear"></div>
</code></pre>
<p>I'm not sure what exactly I'm doing wrong, since "featured image" is active and I've also setted up my single.php file. Instead of the thumbnail the title is there 2x instead of the title + thumbnail etc. - Title + Thumbnail for a post would be my goal for now :)!</p>
<p>I would appreatiate it, if someone could take a look and tell me what I've done wrong or how to fix it :/</p>
<p>PS: I'm using the latest official version of WordPress.</p>
| [
{
"answer_id": 369184,
"author": "Zayd Bhyat",
"author_id": 93537,
"author_profile": "https://wordpress.stackexchange.com/users/93537",
"pm_score": 2,
"selected": false,
"text": "<p>It seems as though you dont have the required permissions to install this PHP extension. This is often the case when youre using shared hosting. The best option is to contact your hosting provider and ask them to install this php extension. However if they provide you with a cpanel dashboard you may be able to do it yourself, heres how:</p>\n<ol>\n<li><p>Log into your cpanel<a href=\"https://i.stack.imgur.com/aW9dr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/aW9dr.png\" alt=\"Cpanel Login\" /></a></p>\n</li>\n<li><p>Select your php version, usually under the software section of cpanel<a href=\"https://i.stack.imgur.com/Fb9CH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Fb9CH.png\" alt=\"Select PHP Version\" /></a></p>\n</li>\n<li><p>Select the imagick option and then your options should be saved<a href=\"https://i.stack.imgur.com/eRwBx.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/eRwBx.png\" alt=\"Select Imagick\" /></a></p>\n</li>\n</ol>\n<p>And that's the last step. If you don't have cPanel your best solution is to contact your hosting provider. If it is a self hosted server you will need to contact the server admin to install the php extension for you. I hope this helps!!</p>\n"
},
{
"answer_id": 389066,
"author": "Free Radical",
"author_id": 206326,
"author_profile": "https://wordpress.stackexchange.com/users/206326",
"pm_score": 0,
"selected": false,
"text": "<p>You need to install imagick and reload Apache2.</p>\n<p>On Debian/Ubuntu, do the following:</p>\n<pre><code>$ sudo apt install php-imagick\n$ sudo systemctl reload apache2\n</code></pre>\n<p>If you run the PHP-FPM service, you also need to restart PHP-FPM service for Apache.</p>\n<p>There is a more extensive treatment, covering other environments (including cPanel), in the <a href=\"https://wordpress.org/support/topic/php-imagick-module-not-installed-or-disabled-message/\" rel=\"nofollow noreferrer\">WordPress.org support forum</a>.</p>\n"
}
] | 2020/06/17 | [
"https://wordpress.stackexchange.com/questions/369187",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/190116/"
] | I've already saw the question some times here, but sadly nothing helped me out yet.
Right now I've got following code:
```
<h2 class="title_bar">Videos</h2>
<ul class="vlist">
<?php $args = array( 'numberposts' => 60, 'orderby' => 'rand' );
$rand_posts = get_posts( $args );
foreach( $rand_posts as $post ) : ?>
<li class="video" id="video_<?php the_ID(); ?>">
<a href="<?php the_permalink() ?>" title="<?php the_title(); ?>">
<?php $thumb = tube_getcustomfield('wtp_thumb_url',get_the_ID()); if(!empty($thumb)) { ?>
<img src="<?php echo $thumb; ?>" alt="<?php the_title_attribute(); ?>" title="<?php the_title_attribute(); ?>" width="240p" height="180" class="thumb" /> <?php } else { ?>
<img src="<?php bloginfo('template_url') ?>/images/pic_post1.jpg" alt="<?php the_title_attribute(); ?>" title="<?php the_title_attribute(); ?>" class="thumb"/><?php } ?>
<i></i>
<span class="box">
<span class="views"><?php if(function_exists('the_views')) { the_views(); } ?></span>
<span class="time"><?php echo time_ago(); ?></span>
</span>
<strong><?php short_title('...', '34'); ?></strong> </a>
</li>
<?php endforeach; ?>
</ul>
<div class="clear"></div>
```
I'm not sure what exactly I'm doing wrong, since "featured image" is active and I've also setted up my single.php file. Instead of the thumbnail the title is there 2x instead of the title + thumbnail etc. - Title + Thumbnail for a post would be my goal for now :)!
I would appreatiate it, if someone could take a look and tell me what I've done wrong or how to fix it :/
PS: I'm using the latest official version of WordPress. | It seems as though you dont have the required permissions to install this PHP extension. This is often the case when youre using shared hosting. The best option is to contact your hosting provider and ask them to install this php extension. However if they provide you with a cpanel dashboard you may be able to do it yourself, heres how:
1. Log into your cpanel[](https://i.stack.imgur.com/aW9dr.png)
2. Select your php version, usually under the software section of cpanel[](https://i.stack.imgur.com/Fb9CH.png)
3. Select the imagick option and then your options should be saved[](https://i.stack.imgur.com/eRwBx.png)
And that's the last step. If you don't have cPanel your best solution is to contact your hosting provider. If it is a self hosted server you will need to contact the server admin to install the php extension for you. I hope this helps!! |
369,211 | <p>I developed a custom plugin with the following structure in my folders:</p>
<pre><code>wp-content
--- plugins
------ my-plugin
--------- languages
------------ po and mo files
--------- my-plugin.php
</code></pre>
<p>I internationalized it, and the translations all worked successfully. Now, I need that plugin to be a must-use plugin, by using the following structure:</p>
<pre><code>wp-content
--- mu-plugins
------ my-plugin
--------- languages
------------ po and mo files
------ my-plugin.php
</code></pre>
<p>(The main plugin file has to be placed directly into the mu-plugins directory to be executed, from what I learned).</p>
<p>I now corrected all the paths in my main plugin file, due to the slight change of the location of the main plugin file (not inside the <code>my-plugin</code> folder anymore, but inside the <code>wp-content/mu-plugins</code> folder, as explained above), and all my functionalities are working, except from the programmed internationalization. I don't get what I'm still missing. Below's what I did:</p>
<p>Code in main plugin file when it was still a normal plugin, with localizations working:</p>
<pre><code>// Callback loading the textdomain 'my-plugin', defined as such in header of main plugin file
public function my_plugin_load_plugin_textdomain() {
load_plugin_textdomain(
'my-plugin',
false,
basename( dirname( __FILE__ ) ).'//languages/'
);
}
// Hook of it
add_action(
'plugins_loaded',
array( $this, 'my_plugin_load_plugin_textdomain' )
);
</code></pre>
<p>Here everything worked without any problem (I coded my whole main plugin file inside a class, that's why you have <code>array( $this, callback )</code> above). When switching to a mu-plugin, I tried:</p>
<pre><code>// Callback loading the textdomain 'my-plugin', defined as such in header of main plugin file
public function my_plugin_load_muplugin_textdomain() {
load_muplugin_textdomain(
'my-plugin',
'my-plugin/languages'
);
}
// Hook of it
add_action(
'muplugins_loaded',
array( $this, 'my_plugin_load_muplugin_textdomain' )
);
</code></pre>
<p>I.E.:</p>
<ol>
<li><p>changed the function called in the callback from <code>load_plugin_textdomain()</code> to <code>load_muplugin_textdomain()</code>, and adapted parameters as above.</p>
</li>
<li><p>Changed action hook from <code>plugins_loaded</code> to <code>muplugins_loaded</code></p>
</li>
<li><p>Changed Domain Path in main plugin file header from <code>/languages</code> to <code>/my-muplugin/languages</code></p>
</li>
</ol>
<p>Yet, the localization of my mu plugin is still not working. I rechecked the locales as well, and I'm using the correct ones (for example, when I change the users language in the wp admin from german to english(UK), my translation file named <code>my-plugin-en_GB.mo</code> is not applied, and everything still appears in german).</p>
<p>Help??</p>
| [
{
"answer_id": 369184,
"author": "Zayd Bhyat",
"author_id": 93537,
"author_profile": "https://wordpress.stackexchange.com/users/93537",
"pm_score": 2,
"selected": false,
"text": "<p>It seems as though you dont have the required permissions to install this PHP extension. This is often the case when youre using shared hosting. The best option is to contact your hosting provider and ask them to install this php extension. However if they provide you with a cpanel dashboard you may be able to do it yourself, heres how:</p>\n<ol>\n<li><p>Log into your cpanel<a href=\"https://i.stack.imgur.com/aW9dr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/aW9dr.png\" alt=\"Cpanel Login\" /></a></p>\n</li>\n<li><p>Select your php version, usually under the software section of cpanel<a href=\"https://i.stack.imgur.com/Fb9CH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Fb9CH.png\" alt=\"Select PHP Version\" /></a></p>\n</li>\n<li><p>Select the imagick option and then your options should be saved<a href=\"https://i.stack.imgur.com/eRwBx.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/eRwBx.png\" alt=\"Select Imagick\" /></a></p>\n</li>\n</ol>\n<p>And that's the last step. If you don't have cPanel your best solution is to contact your hosting provider. If it is a self hosted server you will need to contact the server admin to install the php extension for you. I hope this helps!!</p>\n"
},
{
"answer_id": 389066,
"author": "Free Radical",
"author_id": 206326,
"author_profile": "https://wordpress.stackexchange.com/users/206326",
"pm_score": 0,
"selected": false,
"text": "<p>You need to install imagick and reload Apache2.</p>\n<p>On Debian/Ubuntu, do the following:</p>\n<pre><code>$ sudo apt install php-imagick\n$ sudo systemctl reload apache2\n</code></pre>\n<p>If you run the PHP-FPM service, you also need to restart PHP-FPM service for Apache.</p>\n<p>There is a more extensive treatment, covering other environments (including cPanel), in the <a href=\"https://wordpress.org/support/topic/php-imagick-module-not-installed-or-disabled-message/\" rel=\"nofollow noreferrer\">WordPress.org support forum</a>.</p>\n"
}
] | 2020/06/17 | [
"https://wordpress.stackexchange.com/questions/369211",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/188571/"
] | I developed a custom plugin with the following structure in my folders:
```
wp-content
--- plugins
------ my-plugin
--------- languages
------------ po and mo files
--------- my-plugin.php
```
I internationalized it, and the translations all worked successfully. Now, I need that plugin to be a must-use plugin, by using the following structure:
```
wp-content
--- mu-plugins
------ my-plugin
--------- languages
------------ po and mo files
------ my-plugin.php
```
(The main plugin file has to be placed directly into the mu-plugins directory to be executed, from what I learned).
I now corrected all the paths in my main plugin file, due to the slight change of the location of the main plugin file (not inside the `my-plugin` folder anymore, but inside the `wp-content/mu-plugins` folder, as explained above), and all my functionalities are working, except from the programmed internationalization. I don't get what I'm still missing. Below's what I did:
Code in main plugin file when it was still a normal plugin, with localizations working:
```
// Callback loading the textdomain 'my-plugin', defined as such in header of main plugin file
public function my_plugin_load_plugin_textdomain() {
load_plugin_textdomain(
'my-plugin',
false,
basename( dirname( __FILE__ ) ).'//languages/'
);
}
// Hook of it
add_action(
'plugins_loaded',
array( $this, 'my_plugin_load_plugin_textdomain' )
);
```
Here everything worked without any problem (I coded my whole main plugin file inside a class, that's why you have `array( $this, callback )` above). When switching to a mu-plugin, I tried:
```
// Callback loading the textdomain 'my-plugin', defined as such in header of main plugin file
public function my_plugin_load_muplugin_textdomain() {
load_muplugin_textdomain(
'my-plugin',
'my-plugin/languages'
);
}
// Hook of it
add_action(
'muplugins_loaded',
array( $this, 'my_plugin_load_muplugin_textdomain' )
);
```
I.E.:
1. changed the function called in the callback from `load_plugin_textdomain()` to `load_muplugin_textdomain()`, and adapted parameters as above.
2. Changed action hook from `plugins_loaded` to `muplugins_loaded`
3. Changed Domain Path in main plugin file header from `/languages` to `/my-muplugin/languages`
Yet, the localization of my mu plugin is still not working. I rechecked the locales as well, and I'm using the correct ones (for example, when I change the users language in the wp admin from german to english(UK), my translation file named `my-plugin-en_GB.mo` is not applied, and everything still appears in german).
Help?? | It seems as though you dont have the required permissions to install this PHP extension. This is often the case when youre using shared hosting. The best option is to contact your hosting provider and ask them to install this php extension. However if they provide you with a cpanel dashboard you may be able to do it yourself, heres how:
1. Log into your cpanel[](https://i.stack.imgur.com/aW9dr.png)
2. Select your php version, usually under the software section of cpanel[](https://i.stack.imgur.com/Fb9CH.png)
3. Select the imagick option and then your options should be saved[](https://i.stack.imgur.com/eRwBx.png)
And that's the last step. If you don't have cPanel your best solution is to contact your hosting provider. If it is a self hosted server you will need to contact the server admin to install the php extension for you. I hope this helps!! |
369,289 | <p><strong>What I'm NOT trying to do:</strong></p>
<ul>
<li>Remove or hide checkout (billing/shipping) country fields</li>
</ul>
<p><strong>What I'm trying do to:</strong></p>
<ul>
<li>Show only ONE country in checkout (billing/shipping) country fields, depending on geolocation (geolocation is already done)</li>
<li>OR, Remove countries I don't want to show to user from checkout (billing/shipping) country fields</li>
</ul>
<p><strong>Facts:</strong></p>
<ul>
<li>My Woocommerce Selling Location(s) settings are: Germany, Andorra, Austria, Bulgaria, Belgium, Croatia, Denmark, Slovakia, Slovenia, Spain, Estonia, Finland, France, Greece, Hungary, Ireland, Latvia, Lithuania, Luxembourg, Monaco, Netherlands, Poland, Portugal, United Kingdom (UK), Czech Republic, Romania, Sweden and Switzerland</li>
<li>I want to sell to all of these countries, so removing countries from Selling Location(s) list is not a solution.</li>
<li>I need a hook/filter solution, please.</li>
</ul>
<p><strong>What have I've done so far:</strong></p>
<ul>
<li>I've tried out several hooks/filters to achieve that: <code>woocommerce_checkout_get_value</code>, <code>woocommerce_shipping_fields</code>, <code>woocommerce_billing_fields</code>, <code>woocommerce_default_address_fields</code> and <code>woocommerce_checkout_fields</code>. None of them seems to work...</li>
</ul>
<p><strong>Code I've written:</strong></p>
<pre><code>// NOT WORKING! SHOWS ALL Selling Location(s) (allowed countries)
function override_checkout_fields( $fields ) {
$fields['shipping']['shipping_country'] = array(
'type' => 'country',
'label' => __( 'Country / Region', 'woocommerce' ),
'required' => true,
'class' => array( 'form-row-wide', 'address-field', 'update_totals_on_change' ),
'autocomplete' => 'country',
'priority' => 40,
'options' => array( $user_country_code => __( $user_country_name, 'woocommerce' ) )
);
//Same for billing_country...
return $fields;
}
add_filter( 'woocommerce_checkout_fields' , 'override_checkout_fields', 10, 1 );
// NOT WORKING! SHOWS ALL Selling Location(s) (allowed countries)
function edit_billing_fields( $fields ) {
$fields['billing']['billing_country'] = array(
'type' => 'country',
'label' => __( 'Country / Region', 'woocommerce' ),
'required' => true,
'class' => array( 'form-row-wide', 'address-field', 'update_totals_on_change' ),
'autocomplete' => 'country',
'priority' => 40,
'options' => array( $user_country_code => __( $user_country_name, 'woocommerce' ) )
);
return $fields;
}
add_filter( 'woocommerce_billing_fields', 'edit_billing_fields' );
... And more
</code></pre>
<p><strong>NOTE:</strong> If I change <code>'type' => 'country'</code> by <code>'type' => 'select'</code> it works, but then if I change country (showing two countries for testing), the state dropdown do not update whith the states for that new selected country. Also the dropdown is shown without Select2 appeareance.</p>
<p><strong>Further Explanation:</strong>
I am selling now to 28 countries. For example, if a user is accessing the web from France, when the user arrives at checkout form, I only want to let you send the product to France. This is the reason why I want to show only the user country (previously geolocated) in the (billing/shipping) country dropdown.</p>
<p>I would appreciate your help! Thanks</p>
| [
{
"answer_id": 369437,
"author": "ViralP",
"author_id": 163113,
"author_profile": "https://wordpress.stackexchange.com/users/163113",
"pm_score": 1,
"selected": false,
"text": "<p>If <code>'type' => 'select'</code> works for you then to solve state selection, you can try <code>woocommerce_states</code> and <code>woocommerce_countries_allowed_country_states</code> filter to list states only for the user's country.</p>\n<p>Reference : <a href=\"https://wordpress.stackexchange.com/a/320548/163113\">https://wordpress.stackexchange.com/a/320548/163113</a></p>\n"
},
{
"answer_id": 369753,
"author": "hormigaz",
"author_id": 180696,
"author_profile": "https://wordpress.stackexchange.com/users/180696",
"pm_score": 0,
"selected": false,
"text": "<p>I've managed to fix it by focusing to a different filter, one that doesn't have to do with the checkout directly. The filter in question is <code>woocommerce_countries_allowed_countries</code>. This filter is in the <code>get_allowed_countries()</code> function and gets the countries the store sells to. So limiting the countries the store sells to, I fix the country listing problem at checkout. In this way, a french user will only see France in the country dropdown, an australian user will only see Australia in the country dropdown and so on... Here is the code:</p>\n<pre><code>/**\n * @param array $countries\n * @return array\n */\nfunction custom_update_allowed_countries( $countries ) {\n\n // Only on frontend\n if( is_admin() ) return $countries;\n\n if( class_exists( 'WC_Geolocation' ) ) {\n $location = WC_Geolocation::geolocate_ip();\n\n if ( isset( $location['country'] ) ) {\n $countryCode = $location['country'];\n } else {\n // If there is no country, then return allowed countries\n return $countries;\n }\n } else {\n // If you can't geolocate user country by IP, then return allowed countries\n return $countries;\n }\n\n // If everything went ok then I filter user country in the allowed countries array\n $user_country_code_array = array( countryCode );\n\n $intersect_countries = array_intersect_key( $countries, array_flip( $user_country_code_array ) );\n\n return $intersect_countries;\n}\nadd_filter( 'woocommerce_countries_allowed_countries', 'custom_update_allowed_countries', 30, 1 );\n</code></pre>\n"
}
] | 2020/06/18 | [
"https://wordpress.stackexchange.com/questions/369289",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180696/"
] | **What I'm NOT trying to do:**
* Remove or hide checkout (billing/shipping) country fields
**What I'm trying do to:**
* Show only ONE country in checkout (billing/shipping) country fields, depending on geolocation (geolocation is already done)
* OR, Remove countries I don't want to show to user from checkout (billing/shipping) country fields
**Facts:**
* My Woocommerce Selling Location(s) settings are: Germany, Andorra, Austria, Bulgaria, Belgium, Croatia, Denmark, Slovakia, Slovenia, Spain, Estonia, Finland, France, Greece, Hungary, Ireland, Latvia, Lithuania, Luxembourg, Monaco, Netherlands, Poland, Portugal, United Kingdom (UK), Czech Republic, Romania, Sweden and Switzerland
* I want to sell to all of these countries, so removing countries from Selling Location(s) list is not a solution.
* I need a hook/filter solution, please.
**What have I've done so far:**
* I've tried out several hooks/filters to achieve that: `woocommerce_checkout_get_value`, `woocommerce_shipping_fields`, `woocommerce_billing_fields`, `woocommerce_default_address_fields` and `woocommerce_checkout_fields`. None of them seems to work...
**Code I've written:**
```
// NOT WORKING! SHOWS ALL Selling Location(s) (allowed countries)
function override_checkout_fields( $fields ) {
$fields['shipping']['shipping_country'] = array(
'type' => 'country',
'label' => __( 'Country / Region', 'woocommerce' ),
'required' => true,
'class' => array( 'form-row-wide', 'address-field', 'update_totals_on_change' ),
'autocomplete' => 'country',
'priority' => 40,
'options' => array( $user_country_code => __( $user_country_name, 'woocommerce' ) )
);
//Same for billing_country...
return $fields;
}
add_filter( 'woocommerce_checkout_fields' , 'override_checkout_fields', 10, 1 );
// NOT WORKING! SHOWS ALL Selling Location(s) (allowed countries)
function edit_billing_fields( $fields ) {
$fields['billing']['billing_country'] = array(
'type' => 'country',
'label' => __( 'Country / Region', 'woocommerce' ),
'required' => true,
'class' => array( 'form-row-wide', 'address-field', 'update_totals_on_change' ),
'autocomplete' => 'country',
'priority' => 40,
'options' => array( $user_country_code => __( $user_country_name, 'woocommerce' ) )
);
return $fields;
}
add_filter( 'woocommerce_billing_fields', 'edit_billing_fields' );
... And more
```
**NOTE:** If I change `'type' => 'country'` by `'type' => 'select'` it works, but then if I change country (showing two countries for testing), the state dropdown do not update whith the states for that new selected country. Also the dropdown is shown without Select2 appeareance.
**Further Explanation:**
I am selling now to 28 countries. For example, if a user is accessing the web from France, when the user arrives at checkout form, I only want to let you send the product to France. This is the reason why I want to show only the user country (previously geolocated) in the (billing/shipping) country dropdown.
I would appreciate your help! Thanks | If `'type' => 'select'` works for you then to solve state selection, you can try `woocommerce_states` and `woocommerce_countries_allowed_country_states` filter to list states only for the user's country.
Reference : <https://wordpress.stackexchange.com/a/320548/163113> |
369,307 | <p>I have a Wordpress based website that uses gravity forms. I have the gravity form loading in a jquery model window. My issue is the form seems to work except for after submission the form just stays on the screen and I see the below error in the console.</p>
<pre><code>Uncaught DOMException: Failed to set the 'href' property on 'Location': 'http://' is not a valid URL.
</code></pre>
<p>I am not sure why this error would occur and how http:// not be a valid url</p>
| [
{
"answer_id": 369437,
"author": "ViralP",
"author_id": 163113,
"author_profile": "https://wordpress.stackexchange.com/users/163113",
"pm_score": 1,
"selected": false,
"text": "<p>If <code>'type' => 'select'</code> works for you then to solve state selection, you can try <code>woocommerce_states</code> and <code>woocommerce_countries_allowed_country_states</code> filter to list states only for the user's country.</p>\n<p>Reference : <a href=\"https://wordpress.stackexchange.com/a/320548/163113\">https://wordpress.stackexchange.com/a/320548/163113</a></p>\n"
},
{
"answer_id": 369753,
"author": "hormigaz",
"author_id": 180696,
"author_profile": "https://wordpress.stackexchange.com/users/180696",
"pm_score": 0,
"selected": false,
"text": "<p>I've managed to fix it by focusing to a different filter, one that doesn't have to do with the checkout directly. The filter in question is <code>woocommerce_countries_allowed_countries</code>. This filter is in the <code>get_allowed_countries()</code> function and gets the countries the store sells to. So limiting the countries the store sells to, I fix the country listing problem at checkout. In this way, a french user will only see France in the country dropdown, an australian user will only see Australia in the country dropdown and so on... Here is the code:</p>\n<pre><code>/**\n * @param array $countries\n * @return array\n */\nfunction custom_update_allowed_countries( $countries ) {\n\n // Only on frontend\n if( is_admin() ) return $countries;\n\n if( class_exists( 'WC_Geolocation' ) ) {\n $location = WC_Geolocation::geolocate_ip();\n\n if ( isset( $location['country'] ) ) {\n $countryCode = $location['country'];\n } else {\n // If there is no country, then return allowed countries\n return $countries;\n }\n } else {\n // If you can't geolocate user country by IP, then return allowed countries\n return $countries;\n }\n\n // If everything went ok then I filter user country in the allowed countries array\n $user_country_code_array = array( countryCode );\n\n $intersect_countries = array_intersect_key( $countries, array_flip( $user_country_code_array ) );\n\n return $intersect_countries;\n}\nadd_filter( 'woocommerce_countries_allowed_countries', 'custom_update_allowed_countries', 30, 1 );\n</code></pre>\n"
}
] | 2020/06/18 | [
"https://wordpress.stackexchange.com/questions/369307",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115581/"
] | I have a Wordpress based website that uses gravity forms. I have the gravity form loading in a jquery model window. My issue is the form seems to work except for after submission the form just stays on the screen and I see the below error in the console.
```
Uncaught DOMException: Failed to set the 'href' property on 'Location': 'http://' is not a valid URL.
```
I am not sure why this error would occur and how http:// not be a valid url | If `'type' => 'select'` works for you then to solve state selection, you can try `woocommerce_states` and `woocommerce_countries_allowed_country_states` filter to list states only for the user's country.
Reference : <https://wordpress.stackexchange.com/a/320548/163113> |
369,370 | <p>I am trying to find out what impact setting a custom stucture prefix in permalinks has on 404's</p>
<p>I have a custom structure of:</p>
<p><code>/news-opinion/%postname%/</code></p>
<p>This is working as expected if you tried to go to a page: <code>domain.com/news-opinion/non-existing-url</code> I will get a 404 as expected.</p>
<p>However if I use: <code>domain.com/non-existing-url</code> this will redirect a user back to the homepage and not 404.</p>
<p>Am I missing somthing here I should have accounted for?</p>
<p>This is a Bedrock / Composer based install and this is the list of plugins in use if any of these are known to cause this issue:</p>
<pre><code>"wpackagist-plugin/cache-enabler": "^1.3.4",
"wpackagist-plugin/classic-editor": "1.5",
"wpackagist-plugin/relevanssi": "4.2.0",
"wpackagist-plugin/safe-svg": "1.9.4",
"wpackagist-plugin/wp-mail-smtp": "^1.8",
"wpackagist-plugin/instant-images": "4.2.0",
"wpackagist-plugin/shortpixel-image-optimiser": "4.16.1",
"deliciousbrains-plugin/wp-migrate-db-pro": "^1.9",
"humanmade/s3-uploads": "^2.1",
"custom-repo/advanced-custom-fields-pro": "^5.7.0",
"custom-repo/gravityforms": "^2.4.0",
"wpackagist-plugin/duplicate-post": "3.2.4",
"wpackagist-plugin/filebird": "2.7.1",
"wpackagist-plugin/crop-thumbnails": "1.2.6",
"wpackagist-plugin/redirection": "4.7.1",
"wpackagist-plugin/advanced-cron-manager": "2.3.10",
"wpackagist-plugin/wp-seopress": "3.8.4",
"wpackagist-plugin/cookie-bar": "1.8.7",
"custom-repo/vcaching": "^1.8.0",
"wpackagist-plugin/wordpress-importer": "0.7",
"wpackagist-plugin/export-media-with-selected-content": "2.0",
"wpackagist-plugin/user-roles-and-capabilities":"^1.2.3",
"wpackagist-plugin/wp-all-export": "1.2.5"
</code></pre>
<p>If I can provide any more information that may be pertanent to this please let me know.</p>
<p>Any help with this would be apperciated.</p>
| [
{
"answer_id": 383759,
"author": "korkut ozkan",
"author_id": 202249,
"author_profile": "https://wordpress.stackexchange.com/users/202249",
"pm_score": 0,
"selected": false,
"text": "<p>you should install "URL Rewrite" module and restart the server not only iis service. then reconfigure "Permalink Settings".</p>\n"
},
{
"answer_id": 398971,
"author": "hatted",
"author_id": 215622,
"author_profile": "https://wordpress.stackexchange.com/users/215622",
"pm_score": 2,
"selected": false,
"text": "<p>Download IIS Rewrite from <a href=\"https://www.iis.net/downloads/microsoft/url-rewrite\" rel=\"nofollow noreferrer\">https://www.iis.net/downloads/microsoft/url-rewrite</a>.\nInstall and restart IIS</p>\n<p>Then modify the web.config\nEdit web.config, add the rewrite code.</p>\n<pre><code><?xml version="1.0" encoding="UTF-8"?>\n<configuration>\n <system.webServer>\n <defaultDocument>\n <files>\n <add value="index.php" />\n </files>\n </defaultDocument>\n\n <rewrite>\n <rules>\n <rule name="Main Rule" stopProcessing="true">\n <match url=".*" />\n <conditions logicalGrouping="MatchAll">\n <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />\n <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />\n </conditions>\n <action type="Rewrite" url="index.php" />\n </rule>\n </rules>\n </rewrite>\n\n </system.webServer>\n</configuration>\n</code></pre>\n"
},
{
"answer_id": 398985,
"author": "STing",
"author_id": 32393,
"author_profile": "https://wordpress.stackexchange.com/users/32393",
"pm_score": 1,
"selected": true,
"text": "<p>I believe this issue is fixed in more recent WP versions and not sure which it was fixed in. But in older versions of WP the rule name="RULENAME" was always the same. The name must be unique or the IIS mod goes nuts.</p>\n<p>You would also run into this if you are copying a complete site for backup or dev.</p>\n"
}
] | 2020/06/19 | [
"https://wordpress.stackexchange.com/questions/369370",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/33236/"
] | I am trying to find out what impact setting a custom stucture prefix in permalinks has on 404's
I have a custom structure of:
`/news-opinion/%postname%/`
This is working as expected if you tried to go to a page: `domain.com/news-opinion/non-existing-url` I will get a 404 as expected.
However if I use: `domain.com/non-existing-url` this will redirect a user back to the homepage and not 404.
Am I missing somthing here I should have accounted for?
This is a Bedrock / Composer based install and this is the list of plugins in use if any of these are known to cause this issue:
```
"wpackagist-plugin/cache-enabler": "^1.3.4",
"wpackagist-plugin/classic-editor": "1.5",
"wpackagist-plugin/relevanssi": "4.2.0",
"wpackagist-plugin/safe-svg": "1.9.4",
"wpackagist-plugin/wp-mail-smtp": "^1.8",
"wpackagist-plugin/instant-images": "4.2.0",
"wpackagist-plugin/shortpixel-image-optimiser": "4.16.1",
"deliciousbrains-plugin/wp-migrate-db-pro": "^1.9",
"humanmade/s3-uploads": "^2.1",
"custom-repo/advanced-custom-fields-pro": "^5.7.0",
"custom-repo/gravityforms": "^2.4.0",
"wpackagist-plugin/duplicate-post": "3.2.4",
"wpackagist-plugin/filebird": "2.7.1",
"wpackagist-plugin/crop-thumbnails": "1.2.6",
"wpackagist-plugin/redirection": "4.7.1",
"wpackagist-plugin/advanced-cron-manager": "2.3.10",
"wpackagist-plugin/wp-seopress": "3.8.4",
"wpackagist-plugin/cookie-bar": "1.8.7",
"custom-repo/vcaching": "^1.8.0",
"wpackagist-plugin/wordpress-importer": "0.7",
"wpackagist-plugin/export-media-with-selected-content": "2.0",
"wpackagist-plugin/user-roles-and-capabilities":"^1.2.3",
"wpackagist-plugin/wp-all-export": "1.2.5"
```
If I can provide any more information that may be pertanent to this please let me know.
Any help with this would be apperciated. | I believe this issue is fixed in more recent WP versions and not sure which it was fixed in. But in older versions of WP the rule name="RULENAME" was always the same. The name must be unique or the IIS mod goes nuts.
You would also run into this if you are copying a complete site for backup or dev. |
369,501 | <p>I have a question.</p>
<p>I use the following code to output the image URLs of a wordpress post. The image URLs are related to the "attached images" of a wordpress post and not the ones that are actually used in the post.</p>
<p>If you added an image to a post 2 years ago, but currently don't use the image anymore, the old unused Image Url will still be output via the code. I would like to avoid this.</p>
<p>What i need to do to adjust the code to output only those Image URLs that are really in the source code of the post or really actually used in the post? That can be also Images that are attached to another wordpress post.</p>
<pre><code><?php
if( is_single() ) {
global $post;
$args = array( 'post_type' => 'attachment', 'numberposts' => -1, 'post_mime_type' => 'image', 'post_status' => null, 'post_parent' => $post->ID );
$attachments = get_posts($args);
if ($attachments) {
foreach ( $attachments as $attachment ) {
$img_title = $attachment->post_excerpt;
$metadata = wp_get_attachment_metadata($attachment->ID);
$width = $metadata['width'];
$height = $metadata['height'];
echo '<meta property="og:image" content="'.$attachment->guid.'"/>';
echo '<meta property="og:image:type" content="image/jpeg" />';
echo '<meta property="og:image:width" content="'.$width.'"/>';
echo '<meta property="og:image:height" content="'.$height.'"/>';
}
}
}
?>
</code></pre>
| [
{
"answer_id": 383759,
"author": "korkut ozkan",
"author_id": 202249,
"author_profile": "https://wordpress.stackexchange.com/users/202249",
"pm_score": 0,
"selected": false,
"text": "<p>you should install "URL Rewrite" module and restart the server not only iis service. then reconfigure "Permalink Settings".</p>\n"
},
{
"answer_id": 398971,
"author": "hatted",
"author_id": 215622,
"author_profile": "https://wordpress.stackexchange.com/users/215622",
"pm_score": 2,
"selected": false,
"text": "<p>Download IIS Rewrite from <a href=\"https://www.iis.net/downloads/microsoft/url-rewrite\" rel=\"nofollow noreferrer\">https://www.iis.net/downloads/microsoft/url-rewrite</a>.\nInstall and restart IIS</p>\n<p>Then modify the web.config\nEdit web.config, add the rewrite code.</p>\n<pre><code><?xml version="1.0" encoding="UTF-8"?>\n<configuration>\n <system.webServer>\n <defaultDocument>\n <files>\n <add value="index.php" />\n </files>\n </defaultDocument>\n\n <rewrite>\n <rules>\n <rule name="Main Rule" stopProcessing="true">\n <match url=".*" />\n <conditions logicalGrouping="MatchAll">\n <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />\n <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />\n </conditions>\n <action type="Rewrite" url="index.php" />\n </rule>\n </rules>\n </rewrite>\n\n </system.webServer>\n</configuration>\n</code></pre>\n"
},
{
"answer_id": 398985,
"author": "STing",
"author_id": 32393,
"author_profile": "https://wordpress.stackexchange.com/users/32393",
"pm_score": 1,
"selected": true,
"text": "<p>I believe this issue is fixed in more recent WP versions and not sure which it was fixed in. But in older versions of WP the rule name="RULENAME" was always the same. The name must be unique or the IIS mod goes nuts.</p>\n<p>You would also run into this if you are copying a complete site for backup or dev.</p>\n"
}
] | 2020/06/22 | [
"https://wordpress.stackexchange.com/questions/369501",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/190385/"
] | I have a question.
I use the following code to output the image URLs of a wordpress post. The image URLs are related to the "attached images" of a wordpress post and not the ones that are actually used in the post.
If you added an image to a post 2 years ago, but currently don't use the image anymore, the old unused Image Url will still be output via the code. I would like to avoid this.
What i need to do to adjust the code to output only those Image URLs that are really in the source code of the post or really actually used in the post? That can be also Images that are attached to another wordpress post.
```
<?php
if( is_single() ) {
global $post;
$args = array( 'post_type' => 'attachment', 'numberposts' => -1, 'post_mime_type' => 'image', 'post_status' => null, 'post_parent' => $post->ID );
$attachments = get_posts($args);
if ($attachments) {
foreach ( $attachments as $attachment ) {
$img_title = $attachment->post_excerpt;
$metadata = wp_get_attachment_metadata($attachment->ID);
$width = $metadata['width'];
$height = $metadata['height'];
echo '<meta property="og:image" content="'.$attachment->guid.'"/>';
echo '<meta property="og:image:type" content="image/jpeg" />';
echo '<meta property="og:image:width" content="'.$width.'"/>';
echo '<meta property="og:image:height" content="'.$height.'"/>';
}
}
}
?>
``` | I believe this issue is fixed in more recent WP versions and not sure which it was fixed in. But in older versions of WP the rule name="RULENAME" was always the same. The name must be unique or the IIS mod goes nuts.
You would also run into this if you are copying a complete site for backup or dev. |
369,537 | <p>I can't seem to find an answer/solution to this. If there is one out there, please post a link.</p>
<p>My understanding is that in a <code>wp_query</code>, <code>offset</code> refers to the results of the query. So if I set <code>'offset' => 4</code>, it will ignore the first 4 posts that match the arguments.</p>
<p>What I'm interested in is ignoring the most recent - let's say - 4 posts and only run the query and check for posts that match the arguments starting with the 5th post.</p>
<p>Is this even possible?</p>
<p>Thank you</p>
<p>EDIT:</p>
<p>Let's say I have 10 posts (from newest to oldest):</p>
<ul>
<li>Post 10</li>
<li>Post 9</li>
<li>Post 8</li>
<li>Post 7</li>
<li>Post 6</li>
<li>Post 5</li>
<li>Post 4</li>
<li>Post 3</li>
<li>Post 2</li>
<li>Post 1</li>
</ul>
<p>Let's assume my query WITHOUT ANY OFFSETTING generates a list of 5 posts:</p>
<ul>
<li>Post 9</li>
<li>Post 6</li>
<li>Post 4</li>
<li>Post 3</li>
<li>Post 1</li>
</ul>
<p>Regardless of how I order my results, if I offset them by 4 (again, based on my understanding of how <code>offset</code> works), I am now left with 1 post. Let's say I leave them ordered by default. Offsetting them gives me a list with only Post 1.</p>
<p>However, if I manage to skip the very first 4 posts before I even "run" the query (that would be Post 10, Post 9, Post 8, and Post 7) and only after that run the query and not offset the results at all (all other arguments remaining the same), I now get a list of 4 posts: Post 6, Post 4, Post 3, and Post 1.</p>
<p>And this is what I'd like to accomplish.</p>
| [
{
"answer_id": 369544,
"author": "mozboz",
"author_id": 176814,
"author_profile": "https://wordpress.stackexchange.com/users/176814",
"pm_score": 1,
"selected": false,
"text": "<p>Sure! There are tons of parameters for WP-Query that can probably do what you want.</p>\n<p>Offset is usually used when your data is ordered. So if you want to ignore the two most recent ones you need to order it by date descending first, then set offset = 2. It doesn't matter if you apply any other query parameters you have before or after the date thing - you don't need to do the offset first and then do a second query with other parameters.</p>\n<p>You can also add other arguments to the same query if you want it to do something more complicated at the same time, which will apply to all of the results (before and after the offset, which is ok). E.g. search for a search time or choose something in particular category or anything else. But <strong>ordering by date</strong> is what will help you skip past e.g. the 2 most recent.</p>\n<p>Here's how you do that:</p>\n<pre><code>$args = array(\n // order by date\n 'orderby' => 'date',\n 'order' => 'DESC', // descending dates will give you most recent first\n\n // any extra stuff you want, e.g. search for posts with 'car' but not 'red'\n 's' => 'car -red',\n\n // display posts from the 3rd one onwards, so with date order this will skip two most recent\n 'offset' => 2\n);\n\n$query = new WP_Query( $args );\n</code></pre>\n<p>If you have a more complicated query you want to do please post more details!</p>\n"
},
{
"answer_id": 369556,
"author": "mozboz",
"author_id": 176814,
"author_profile": "https://wordpress.stackexchange.com/users/176814",
"pm_score": 0,
"selected": false,
"text": "<p>So adding another answer now I understand your case better. There may be a way to do this with SQL, but probably with WP_Query is neater and inside WP way of doing things:</p>\n<pre><code>$excludeArgs = array(\n 'orderby' => 'date',\n 'order' => 'DESC', // descending dates will give you most recent first \n);\n\n$queryExclude = new WP_Query( $excludeArgs );\n$excludeThisMany = 4;\n$countExclusions = 0;\n\n$excludeIDs = [];\n\nwhile ($queryExclude->havePosts() && ($countExclusions < $excludeThisMany)) {\n $queryExclude->thePost();\n $excludeIDs[] = the_ID();\n $countExclusions++;\n}\n\n$matchArgs = array(\n // whatever you want to match on\n s => 'unicorns -rainbows'\n);\n\n$queryMatch = new WP_Query( $matchArgs );\n\nwhile ($queryMatch->havePosts()) {\n $queryMatch->thePost();\n if (!in_array(the_ID(), $excludeIDs)) {\n // only get here if it's not one of the first exclusions\n // render this stuff\n }\n}\n</code></pre>\n<p>That will do it. I can't test this, but hopefully you get the idea and can fix it if it's not exactly right for you. Remember to add a <code>wp_reset_postdata();</code> after if you need it to get back to the main post's data.</p>\n"
}
] | 2020/06/22 | [
"https://wordpress.stackexchange.com/questions/369537",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/190420/"
] | I can't seem to find an answer/solution to this. If there is one out there, please post a link.
My understanding is that in a `wp_query`, `offset` refers to the results of the query. So if I set `'offset' => 4`, it will ignore the first 4 posts that match the arguments.
What I'm interested in is ignoring the most recent - let's say - 4 posts and only run the query and check for posts that match the arguments starting with the 5th post.
Is this even possible?
Thank you
EDIT:
Let's say I have 10 posts (from newest to oldest):
* Post 10
* Post 9
* Post 8
* Post 7
* Post 6
* Post 5
* Post 4
* Post 3
* Post 2
* Post 1
Let's assume my query WITHOUT ANY OFFSETTING generates a list of 5 posts:
* Post 9
* Post 6
* Post 4
* Post 3
* Post 1
Regardless of how I order my results, if I offset them by 4 (again, based on my understanding of how `offset` works), I am now left with 1 post. Let's say I leave them ordered by default. Offsetting them gives me a list with only Post 1.
However, if I manage to skip the very first 4 posts before I even "run" the query (that would be Post 10, Post 9, Post 8, and Post 7) and only after that run the query and not offset the results at all (all other arguments remaining the same), I now get a list of 4 posts: Post 6, Post 4, Post 3, and Post 1.
And this is what I'd like to accomplish. | Sure! There are tons of parameters for WP-Query that can probably do what you want.
Offset is usually used when your data is ordered. So if you want to ignore the two most recent ones you need to order it by date descending first, then set offset = 2. It doesn't matter if you apply any other query parameters you have before or after the date thing - you don't need to do the offset first and then do a second query with other parameters.
You can also add other arguments to the same query if you want it to do something more complicated at the same time, which will apply to all of the results (before and after the offset, which is ok). E.g. search for a search time or choose something in particular category or anything else. But **ordering by date** is what will help you skip past e.g. the 2 most recent.
Here's how you do that:
```
$args = array(
// order by date
'orderby' => 'date',
'order' => 'DESC', // descending dates will give you most recent first
// any extra stuff you want, e.g. search for posts with 'car' but not 'red'
's' => 'car -red',
// display posts from the 3rd one onwards, so with date order this will skip two most recent
'offset' => 2
);
$query = new WP_Query( $args );
```
If you have a more complicated query you want to do please post more details! |
369,547 | <p>I have a shortcode that works to display posts from specific categories, or a single post based on the post slug. I'm having trouble figuring out how to get it to display multiple posts based on their slugs though. I know I need to use explode, but I can't seem to get it right.</p>
<p>Here's the current working code:</p>
<pre><code>add_shortcode( 'latest_post', 'latest_post_query_shortcode' );
function latest_post_query_shortcode( $atts ) {
ob_start();
$atts = shortcode_atts( array(
'posts_per_page' => '',
'category' => '',
'offset' => '',
'post' => '',
), $atts );
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page'=> $atts['posts_per_page'],
'offset' => $atts['offset'],
);
// Add category if not empty
if ( ! empty ( $atts['category'] ) ) {
$args['tax_query'] = array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => $atts['category'],
),
);
}
// Add post if not empty
if ( ! empty ( $atts['post'] ) ) {
$args['name'] = $atts['post'];
}
$string = '';
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) { ?>
<section class="recent-posts clear">
<?php while ( $query->have_posts() ) : $query->the_post() ; ?>
<article id="post-<?php the_ID(); ?>" <?php post_class( 'left' ); ?>>
<? echo '<a href="' . get_permalink( $_post->ID ) . '" title="' . esc_attr( $_post->post_title ) . '">';
echo get_the_post_thumbnail( $_post->ID, 'large' );
echo '</a>';
echo '<h2><a href="' . get_permalink( $_post->ID ) . '" title="' . esc_attr( $_post->post_title ) . '">';
echo get_the_title( $_post->ID);
echo '</a></h2>';
?>
</article>
<?php endwhile;
wp_reset_postdata();?>
</section>
<?php
$clean = ob_get_clean();
return $clean;
}
}
</code></pre>
<p>I tried adding:</p>
<pre><code>'name' => explode( ', ', $post),
</code></pre>
<p>inside</p>
<pre><code>$args = array(
</code></pre>
<p>but that didn't return anything when I tried specifying two slugs, for example:
[latest_post post="almond-cake, coconut-pie"] (If I use either one of those, it works, but not both.)</p>
<p>Additionally once I added the explode, it game me this warning everywhere <em>else</em> the shortcode was used:</p>
<p>Warning: trim() expects parameter 1 to be string, array given...</p>
| [
{
"answer_id": 369551,
"author": "Michelle",
"author_id": 16,
"author_profile": "https://wordpress.stackexchange.com/users/16",
"pm_score": 0,
"selected": false,
"text": "<p>This works for me:</p>\n<pre><code>add_shortcode( 'latest_post', 'latest_post_query_shortcode' );\nfunction latest_post_query_shortcode( $atts ) {\n ob_start();\n $atts = shortcode_atts( array(\n 'posts_per_page' => '',\n 'category' => array(), // defined as array here\n 'offset' => '',\n 'post' => '',\n ), $atts );\n\n $args = array(\n 'post_type' => 'post',\n 'post_status' => 'publish',\n 'posts_per_page'=> $atts['posts_per_page'],\n 'offset' => $atts['offset'],\n );\n\n \n // Add category if not empty\n if ( !empty( $atts['category'] ) ) {\n $terms = str_replace(' ', '', $atts['category']); // strip whitespace so admins don't have to remember whether or not to put a space after each comma\n $terms = explode(',', $atts['category']); // then get the array\n $args['tax_query'] = array( \n array(\n 'taxonomy' => 'category',\n 'field' => 'slug',\n 'terms' => $terms,\n ), \n ); \n }\n \n // Add post if not empty\n if ( ! empty ( $atts['post'] ) ) {\n $args['name'] = $atts['post'];\n }\n $string = '';\n \n // The Query\n $query = new WP_Query( $args ); \n\n // The Loop\n if ( $query->have_posts() ) { ?>\n <section class="recent-posts clear">\n <?php while ( $query->have_posts() ) : $query->the_post() ; ?>\n <article id="post-<?php the_ID(); ?>" <?php post_class( 'left' ); ?>>\n\n <? echo '<a href="' . get_permalink( $query->ID ) . '" title="' . esc_attr( $query->post_title ) . '">';\n echo get_the_post_thumbnail( $query->ID, 'large' );\n echo '</a>';\n echo '<h2><a href="' . get_permalink( $query->ID ) . '" title="' . esc_attr( $query->post_title ) . '">';\n echo get_the_title( $query->ID);\n echo '</a></h2>';\n\n ?>\n </article>\n <?php endwhile; \n wp_reset_postdata();?> \n </section> \n <?php \n $clean = ob_get_clean();\n return $clean; \n }\n}\n</code></pre>\n"
},
{
"answer_id": 369558,
"author": "mozboz",
"author_id": 176814,
"author_profile": "https://wordpress.stackexchange.com/users/176814",
"pm_score": 3,
"selected": true,
"text": "<p>So from the <a href=\"https://developer.wordpress.org/reference/classes/wp_query/\" rel=\"nofollow noreferrer\">WP_Query page</a>, I found this, which is like $args['name'] but for when you want to search for many slugs:</p>\n<blockquote>\n<p>post_name__in (array) – use post slugs. Specify posts to retrieve. (Will be available in version 4.4)</p>\n</blockquote>\n<p>I think this is maybe what you need?</p>\n<p>In that case you'd need to explode <code>$atts['post']</code> on <code>","</code> as you did, then pass that resulting array to post_name__in attribute in $attrs. You're getting that error resulting from trim because you're passing an array to the 'name' attribute in WP Query which is expecting a single slug name in a string.</p>\n<p>I'd recommend you explode on <code>","</code> first, without spaces, <em>then</em> strip off the white space from the resulting strings as that allows for much more freedom in how you (or other users) put stuff in the post attribute in the shortcode.</p>\n<p>Let me know if that is or isn't on the right track or if you want more detailed code example</p>\n"
}
] | 2020/06/22 | [
"https://wordpress.stackexchange.com/questions/369547",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/186347/"
] | I have a shortcode that works to display posts from specific categories, or a single post based on the post slug. I'm having trouble figuring out how to get it to display multiple posts based on their slugs though. I know I need to use explode, but I can't seem to get it right.
Here's the current working code:
```
add_shortcode( 'latest_post', 'latest_post_query_shortcode' );
function latest_post_query_shortcode( $atts ) {
ob_start();
$atts = shortcode_atts( array(
'posts_per_page' => '',
'category' => '',
'offset' => '',
'post' => '',
), $atts );
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page'=> $atts['posts_per_page'],
'offset' => $atts['offset'],
);
// Add category if not empty
if ( ! empty ( $atts['category'] ) ) {
$args['tax_query'] = array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => $atts['category'],
),
);
}
// Add post if not empty
if ( ! empty ( $atts['post'] ) ) {
$args['name'] = $atts['post'];
}
$string = '';
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) { ?>
<section class="recent-posts clear">
<?php while ( $query->have_posts() ) : $query->the_post() ; ?>
<article id="post-<?php the_ID(); ?>" <?php post_class( 'left' ); ?>>
<? echo '<a href="' . get_permalink( $_post->ID ) . '" title="' . esc_attr( $_post->post_title ) . '">';
echo get_the_post_thumbnail( $_post->ID, 'large' );
echo '</a>';
echo '<h2><a href="' . get_permalink( $_post->ID ) . '" title="' . esc_attr( $_post->post_title ) . '">';
echo get_the_title( $_post->ID);
echo '</a></h2>';
?>
</article>
<?php endwhile;
wp_reset_postdata();?>
</section>
<?php
$clean = ob_get_clean();
return $clean;
}
}
```
I tried adding:
```
'name' => explode( ', ', $post),
```
inside
```
$args = array(
```
but that didn't return anything when I tried specifying two slugs, for example:
[latest\_post post="almond-cake, coconut-pie"] (If I use either one of those, it works, but not both.)
Additionally once I added the explode, it game me this warning everywhere *else* the shortcode was used:
Warning: trim() expects parameter 1 to be string, array given... | So from the [WP\_Query page](https://developer.wordpress.org/reference/classes/wp_query/), I found this, which is like $args['name'] but for when you want to search for many slugs:
>
> post\_name\_\_in (array) – use post slugs. Specify posts to retrieve. (Will be available in version 4.4)
>
>
>
I think this is maybe what you need?
In that case you'd need to explode `$atts['post']` on `","` as you did, then pass that resulting array to post\_name\_\_in attribute in $attrs. You're getting that error resulting from trim because you're passing an array to the 'name' attribute in WP Query which is expecting a single slug name in a string.
I'd recommend you explode on `","` first, without spaces, *then* strip off the white space from the resulting strings as that allows for much more freedom in how you (or other users) put stuff in the post attribute in the shortcode.
Let me know if that is or isn't on the right track or if you want more detailed code example |
369,571 | <p>I don't know what's what wrong with my parent menu items. I have two that aren't working on the first click on mobile devices (I've been testing this on my android phone).</p>
<p>To make it look mobile responsive, I added some css:</p>
<pre><code>@media (max-width: 500px) {
&.main-navigation {
.menu-main-menu-container {
display: none;
position: absolute;
width: 80%;
ul#menu-main-menu {
display: block;
margin: 0;
#menu-item-6, #menu-item-7 {
ul.sub-menu {
display: none;
}
}
#menu-item-6:hover, #menu-item-7:hover {
ul.sub-menu {
display: block;
}
}
}// ul#menu-main-menu
}// .menu-main-menu-container
.menu-toggle {
margin: 0;
width: 20%;
}
.menu-toggle::before {
transform: translateX(100%);
}
}// end &.main-navigation
#header-search-toggle {
display: none;
}
}// max-width: 500px
</code></pre>
<p>It was like this from the start of my web project. I've built a handful of other wp projects the past year and this is the first time the parent menu items aren't clickable on the first click. Any ideas? Is this, perhaps, due to some sort of weird wordpress setting in the backend?</p>
| [
{
"answer_id": 369551,
"author": "Michelle",
"author_id": 16,
"author_profile": "https://wordpress.stackexchange.com/users/16",
"pm_score": 0,
"selected": false,
"text": "<p>This works for me:</p>\n<pre><code>add_shortcode( 'latest_post', 'latest_post_query_shortcode' );\nfunction latest_post_query_shortcode( $atts ) {\n ob_start();\n $atts = shortcode_atts( array(\n 'posts_per_page' => '',\n 'category' => array(), // defined as array here\n 'offset' => '',\n 'post' => '',\n ), $atts );\n\n $args = array(\n 'post_type' => 'post',\n 'post_status' => 'publish',\n 'posts_per_page'=> $atts['posts_per_page'],\n 'offset' => $atts['offset'],\n );\n\n \n // Add category if not empty\n if ( !empty( $atts['category'] ) ) {\n $terms = str_replace(' ', '', $atts['category']); // strip whitespace so admins don't have to remember whether or not to put a space after each comma\n $terms = explode(',', $atts['category']); // then get the array\n $args['tax_query'] = array( \n array(\n 'taxonomy' => 'category',\n 'field' => 'slug',\n 'terms' => $terms,\n ), \n ); \n }\n \n // Add post if not empty\n if ( ! empty ( $atts['post'] ) ) {\n $args['name'] = $atts['post'];\n }\n $string = '';\n \n // The Query\n $query = new WP_Query( $args ); \n\n // The Loop\n if ( $query->have_posts() ) { ?>\n <section class="recent-posts clear">\n <?php while ( $query->have_posts() ) : $query->the_post() ; ?>\n <article id="post-<?php the_ID(); ?>" <?php post_class( 'left' ); ?>>\n\n <? echo '<a href="' . get_permalink( $query->ID ) . '" title="' . esc_attr( $query->post_title ) . '">';\n echo get_the_post_thumbnail( $query->ID, 'large' );\n echo '</a>';\n echo '<h2><a href="' . get_permalink( $query->ID ) . '" title="' . esc_attr( $query->post_title ) . '">';\n echo get_the_title( $query->ID);\n echo '</a></h2>';\n\n ?>\n </article>\n <?php endwhile; \n wp_reset_postdata();?> \n </section> \n <?php \n $clean = ob_get_clean();\n return $clean; \n }\n}\n</code></pre>\n"
},
{
"answer_id": 369558,
"author": "mozboz",
"author_id": 176814,
"author_profile": "https://wordpress.stackexchange.com/users/176814",
"pm_score": 3,
"selected": true,
"text": "<p>So from the <a href=\"https://developer.wordpress.org/reference/classes/wp_query/\" rel=\"nofollow noreferrer\">WP_Query page</a>, I found this, which is like $args['name'] but for when you want to search for many slugs:</p>\n<blockquote>\n<p>post_name__in (array) – use post slugs. Specify posts to retrieve. (Will be available in version 4.4)</p>\n</blockquote>\n<p>I think this is maybe what you need?</p>\n<p>In that case you'd need to explode <code>$atts['post']</code> on <code>","</code> as you did, then pass that resulting array to post_name__in attribute in $attrs. You're getting that error resulting from trim because you're passing an array to the 'name' attribute in WP Query which is expecting a single slug name in a string.</p>\n<p>I'd recommend you explode on <code>","</code> first, without spaces, <em>then</em> strip off the white space from the resulting strings as that allows for much more freedom in how you (or other users) put stuff in the post attribute in the shortcode.</p>\n<p>Let me know if that is or isn't on the right track or if you want more detailed code example</p>\n"
}
] | 2020/06/23 | [
"https://wordpress.stackexchange.com/questions/369571",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/168581/"
] | I don't know what's what wrong with my parent menu items. I have two that aren't working on the first click on mobile devices (I've been testing this on my android phone).
To make it look mobile responsive, I added some css:
```
@media (max-width: 500px) {
&.main-navigation {
.menu-main-menu-container {
display: none;
position: absolute;
width: 80%;
ul#menu-main-menu {
display: block;
margin: 0;
#menu-item-6, #menu-item-7 {
ul.sub-menu {
display: none;
}
}
#menu-item-6:hover, #menu-item-7:hover {
ul.sub-menu {
display: block;
}
}
}// ul#menu-main-menu
}// .menu-main-menu-container
.menu-toggle {
margin: 0;
width: 20%;
}
.menu-toggle::before {
transform: translateX(100%);
}
}// end &.main-navigation
#header-search-toggle {
display: none;
}
}// max-width: 500px
```
It was like this from the start of my web project. I've built a handful of other wp projects the past year and this is the first time the parent menu items aren't clickable on the first click. Any ideas? Is this, perhaps, due to some sort of weird wordpress setting in the backend? | So from the [WP\_Query page](https://developer.wordpress.org/reference/classes/wp_query/), I found this, which is like $args['name'] but for when you want to search for many slugs:
>
> post\_name\_\_in (array) – use post slugs. Specify posts to retrieve. (Will be available in version 4.4)
>
>
>
I think this is maybe what you need?
In that case you'd need to explode `$atts['post']` on `","` as you did, then pass that resulting array to post\_name\_\_in attribute in $attrs. You're getting that error resulting from trim because you're passing an array to the 'name' attribute in WP Query which is expecting a single slug name in a string.
I'd recommend you explode on `","` first, without spaces, *then* strip off the white space from the resulting strings as that allows for much more freedom in how you (or other users) put stuff in the post attribute in the shortcode.
Let me know if that is or isn't on the right track or if you want more detailed code example |
369,771 | <p>I will try to summarize as simply as possible my request.</p>
<p>I have a custom post type (CPT) called “job”.
This custom post type includes 3 fields :</p>
<ul>
<li>The title (the native wordpress title field) / <em>example : Webmaster</em></li>
<li>Secondary title (ACF custom field (type = textfield) called “secondary_title”.) / <em>example : Front-end developer</em></li>
<li>Linked jobs (ACF custom field (type = Post Object) called “jobs_links”) / <em>example : Web developer – Web designer (theses examples are “job” custom post page)</em></li>
</ul>
<p><strong>I would like to create a custom wordpress search page/form who allows user to type the name of a job (including secondary title) and display the linked jobs as results.</strong></p>
<p>I tried many things with this ressource : <a href="https://www.advancedcustomfields.com/resources/query-posts-custom-fields/" rel="nofollow noreferrer">https://www.advancedcustomfields.com/resources/query-posts-custom-fields/</a></p>
<p>But i didn’t succeed to do it.</p>
<p>Any advices are welcome !</p>
<p>Thanks for reading me.</p>
| [
{
"answer_id": 370380,
"author": "joshmoto",
"author_id": 111152,
"author_profile": "https://wordpress.stackexchange.com/users/111152",
"pm_score": 1,
"selected": false,
"text": "<p>OK so I have had this problem with searching custom fields data.</p>\n<p>The thing is with the native Wordpress search, is that is really good, fast and powerful, but it's limitations is that it only searches the <code>wp_posts</code> table. It does <strong>not</strong> frickin' query the <code>wp_postmeta</code> table!</p>\n<p>So to make the most of the native Wordpress search, what you can do is tailor the exact search terms you want to be searchable by saving specific searchable custom field data to the native <code>post_content</code> as a json encoded array.</p>\n<p>If you are already using the native <code>post_content</code> field (in <code>wp_posts</code> table) for general job profile guff (in cpt <code>job</code>), then just migrate this data to a <code>ACF Wysiwyg Editor</code> field with the field name <code>job_post_content</code>. This new ACF version of <code>post_content</code> won't be searchable now. Which is probably a good thing in your situation, as you will have job profile nonsense, which you probably don't want to be picked up in the job search query anyway. If you still want this content searchable then you can still include this data in our searchable json array, if you wish (i've not shown this but it is simple to include).</p>\n<br/>\n<p>So for storing any searchable data in native <code>post_content</code>, this is where the magic happens. Follow my comments in code...</p>\n<p>Add this to your <code>functions.php</code></p>\n<pre><code>// process cpt job post when saving or updating job post\nadd_action('acf/save_post', 'acf_save_job', 20);\n\n/**\n * action to run modifications when saving or updating the job\n * @param int $post_id\n * @return void\n */\nfunction acf_save_job($post_id) {\n\n // get our current global post object\n global $post;\n\n // check we are on the cpt job else return now\n if($post->post_type <> 'job') return;\n\n // if job post status is publish or draft\n if($post->post_status == 'publish' || $post->post_status == 'draft') {\n\n // create job object from current post object\n $job = $post;\n\n // set an empty searchable data array\n $searchable_job_data = [];\n\n // we dont need to add the native post title for cpt job as this is already searchable\n\n // get our secondary title\n $secondary_title = get_field('secondary_title',$post_id);\n\n // if secondary title exists\n if($secondary_title) {\n\n // add secondary title to searchable data array\n $searchable_job_data['stitle'] = $secondary_title;\n\n }\n\n // get our job links post object field, acf must return this field as post object\n $job_links = get_field('job_links',$post_id);\n\n // I am assuming you are allowing multiple job links to be selected in job post admin...\n // so we have to loop through each array object and get the job link post title\n\n // if job links var is an array\n if(is_array($job_links)) {\n\n // foreach job link item as job object\n foreach ($job_links as $key => $job_link_object) {\n\n // if job link object has post title\n if($job_link_object->post_title) {\n\n // add job link title to our searchable data array\n $searchable_job_data['jlinks'][] = $job_link_object->post_title;\n\n }\n\n }\n\n }\n \n // add more searchable data to $searchable_job_array here if you wish\n\n // convert our searchable data array to json\n $searchable_job_json = json_encode($searchable_job_data,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);\n\n // temp remove the save job action\n remove_action('acf/save_post','acf_save_job',20);\n\n // update our native job post content with searchable data\n $job->post_content = $searchable_job_json;\n \n // update the current job with new job data\n wp_update_post($job);\n\n // re add the save job action\n add_action('acf/save_post', 'acf_save_job', 20);\n\n }\n\n}\n</code></pre>\n<br/>\n<p>So when you create or save a cpt job post, you will notice the native <code>post_content</code> now contains something like this (as an unformatted string)...</p>\n<pre><code>{\n "stitle": "Front-end developer",\n "jlinks": [\n "Web developer",\n "Web designer"\n ]\n} \n</code></pre>\n<p>Using cpt or acf you can hide the native post content visually from your admin job post page, but the search data will still exist in the database.</p>\n<br/>\n<p><strong>After looking at your custom jobs page, would it not be better to turn <code>job_links</code>, to a taxonomy, rather than a post type. So you can also filter by jobs by selecting job link/service. In my custom jobs archive page example (below) I will also demonstrate this...</strong></p>\n<br/>\n<p>Here is a search form html to search jobs only, this can go in your <code>header.php</code> or anywhere...</p>\n<pre><code><form action="/jobs" method="get">\n <input type="search" name="search" placeholder="Search jobs" />\n</form>\n</code></pre>\n<br/>\n<p>Here is some jobs query functions to add to your <code>functions.php</code>...</p>\n<pre><code>/**\n * simple method to get request parameter value\n * @param mixed $name key name to find\n * @param mixed $default default value if no value is found\n * @return mixed\n */\nfunction get_url_var($name = false, $default = false)\n{\n // if name is false\n if($name === false) {\n return $_REQUEST;\n }\n // request name var name is set\n if(isset($_REQUEST[$name])) {\n return $_REQUEST[$name];\n }\n // return default\n return $default;\n}\n\n/**\n * job custom archive page query\n * @return array\n */\nfunction job_query() {\n\n // some vars\n $jobs_per_page = 24;\n\n // check url for these filter keys and get value\n $job_search = get_url_var('search',false);\n $job_link = get_url_var('service',false);\n // add more url parameter filters here\n\n // build our jobs query\n $job_query = [\n 'post_type' => 'job',\n 'post_status' => 'publish',\n 'posts_per_page' => $jobs_per_page,\n 'orderby' => 'ASC',\n 'tax_query' => [\n 'relation' => 'AND'\n ]\n ];\n\n // filter by search query\n if($job_search) {\n // extend our jobs query with search\n $job_query['s'] = $job_search;\n }\n\n // if you convert job_links to taxonomy then...\n // filter by job link taxonomy term slug (service)\n if($job_link) {\n // extend our tax query array\n $job_query['tax_query'][] = [\n 'taxonomy' => 'job_link',\n 'field' => 'slug',\n 'terms' => [ ],\n ];\n }\n\n return $job_query;\n\n}\n</code></pre>\n<br/>\n<p>Now create a page called <strong>Jobs</strong> with page slug/name <code>jobs</code>. Then create a php page template called <code>page-jobs.php</code> in your theme root, and then add the below php to it...</p>\n<pre><code><?php\n\n// products wp query\n$jobs = new WP_Query(job_query());\n\n// get our page header\nget_header();\n\n?>\n <main>\n <?php if($jobs->have_posts()): ?>\n <?php while($jobs->have_posts()): $jobs->the_post() ?>\n <article id="job-<?=get_the_ID()?>">\n <?php the_title(); ?>\n <?php the_field('secondary_title'); ?>\n <?php the_field('jobs_links'); ?>\n </article>\n <?php endwhile; ?>\n <?php else: ?>\n No jobs found matching criteria.\n <?php endif; ?>\n </main>\n<?php\n\n// get our footer\nget_footer();\n</code></pre>\n<br/>\n<p>Now run some search tests with the url format below, or alternatively use the html search form...</p>\n<p><a href=\"https://yoursite.com/jobs?search=designer\" rel=\"nofollow noreferrer\">https://yoursite.com/jobs?search=designer</a></p>\n<p>Also if you converted your <code>job_links</code> post type to a taxonomy then you can filter cpt jobs like this... (obviously only if you set the ACF <code>job_links</code> Taxonomy field to save/load terms)</p>\n<p><a href=\"https://yoursite.com/jobs?service=web-developer\" rel=\"nofollow noreferrer\">https://yoursite.com/jobs?service=web-developer</a><br/>\n<a href=\"https://yoursite.com/jobs?service=web-designer\" rel=\"nofollow noreferrer\">https://yoursite.com/jobs?service=web-designer</a></p>\n<br/>\n<hr />\n<br/>\n<p>One other thing, i'm not sure of your level of php, but the above could be so much more if you used object oriented php classes. The above code is for your basic <code>function.php</code> user. But if you know how to use php classes then let me know and I can update code to object oriented class format.</p>\n"
},
{
"answer_id": 370583,
"author": "Chevax",
"author_id": 191221,
"author_profile": "https://wordpress.stackexchange.com/users/191221",
"pm_score": 0,
"selected": false,
"text": "<p>I wish to express my gratitude for the time spent answering my question.</p>\n<p>Your answer is very pedagogical, clear and precise.</p>\n<p>I didn't expect as much...</p>\n<p>Even if I don't have a high level in PHP, I managed to deploy your solution.</p>\n<p>Thanks again @joshmoto</p>\n"
}
] | 2020/06/25 | [
"https://wordpress.stackexchange.com/questions/369771",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/190605/"
] | I will try to summarize as simply as possible my request.
I have a custom post type (CPT) called “job”.
This custom post type includes 3 fields :
* The title (the native wordpress title field) / *example : Webmaster*
* Secondary title (ACF custom field (type = textfield) called “secondary\_title”.) / *example : Front-end developer*
* Linked jobs (ACF custom field (type = Post Object) called “jobs\_links”) / *example : Web developer – Web designer (theses examples are “job” custom post page)*
**I would like to create a custom wordpress search page/form who allows user to type the name of a job (including secondary title) and display the linked jobs as results.**
I tried many things with this ressource : <https://www.advancedcustomfields.com/resources/query-posts-custom-fields/>
But i didn’t succeed to do it.
Any advices are welcome !
Thanks for reading me. | OK so I have had this problem with searching custom fields data.
The thing is with the native Wordpress search, is that is really good, fast and powerful, but it's limitations is that it only searches the `wp_posts` table. It does **not** frickin' query the `wp_postmeta` table!
So to make the most of the native Wordpress search, what you can do is tailor the exact search terms you want to be searchable by saving specific searchable custom field data to the native `post_content` as a json encoded array.
If you are already using the native `post_content` field (in `wp_posts` table) for general job profile guff (in cpt `job`), then just migrate this data to a `ACF Wysiwyg Editor` field with the field name `job_post_content`. This new ACF version of `post_content` won't be searchable now. Which is probably a good thing in your situation, as you will have job profile nonsense, which you probably don't want to be picked up in the job search query anyway. If you still want this content searchable then you can still include this data in our searchable json array, if you wish (i've not shown this but it is simple to include).
So for storing any searchable data in native `post_content`, this is where the magic happens. Follow my comments in code...
Add this to your `functions.php`
```
// process cpt job post when saving or updating job post
add_action('acf/save_post', 'acf_save_job', 20);
/**
* action to run modifications when saving or updating the job
* @param int $post_id
* @return void
*/
function acf_save_job($post_id) {
// get our current global post object
global $post;
// check we are on the cpt job else return now
if($post->post_type <> 'job') return;
// if job post status is publish or draft
if($post->post_status == 'publish' || $post->post_status == 'draft') {
// create job object from current post object
$job = $post;
// set an empty searchable data array
$searchable_job_data = [];
// we dont need to add the native post title for cpt job as this is already searchable
// get our secondary title
$secondary_title = get_field('secondary_title',$post_id);
// if secondary title exists
if($secondary_title) {
// add secondary title to searchable data array
$searchable_job_data['stitle'] = $secondary_title;
}
// get our job links post object field, acf must return this field as post object
$job_links = get_field('job_links',$post_id);
// I am assuming you are allowing multiple job links to be selected in job post admin...
// so we have to loop through each array object and get the job link post title
// if job links var is an array
if(is_array($job_links)) {
// foreach job link item as job object
foreach ($job_links as $key => $job_link_object) {
// if job link object has post title
if($job_link_object->post_title) {
// add job link title to our searchable data array
$searchable_job_data['jlinks'][] = $job_link_object->post_title;
}
}
}
// add more searchable data to $searchable_job_array here if you wish
// convert our searchable data array to json
$searchable_job_json = json_encode($searchable_job_data,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
// temp remove the save job action
remove_action('acf/save_post','acf_save_job',20);
// update our native job post content with searchable data
$job->post_content = $searchable_job_json;
// update the current job with new job data
wp_update_post($job);
// re add the save job action
add_action('acf/save_post', 'acf_save_job', 20);
}
}
```
So when you create or save a cpt job post, you will notice the native `post_content` now contains something like this (as an unformatted string)...
```
{
"stitle": "Front-end developer",
"jlinks": [
"Web developer",
"Web designer"
]
}
```
Using cpt or acf you can hide the native post content visually from your admin job post page, but the search data will still exist in the database.
**After looking at your custom jobs page, would it not be better to turn `job_links`, to a taxonomy, rather than a post type. So you can also filter by jobs by selecting job link/service. In my custom jobs archive page example (below) I will also demonstrate this...**
Here is a search form html to search jobs only, this can go in your `header.php` or anywhere...
```
<form action="/jobs" method="get">
<input type="search" name="search" placeholder="Search jobs" />
</form>
```
Here is some jobs query functions to add to your `functions.php`...
```
/**
* simple method to get request parameter value
* @param mixed $name key name to find
* @param mixed $default default value if no value is found
* @return mixed
*/
function get_url_var($name = false, $default = false)
{
// if name is false
if($name === false) {
return $_REQUEST;
}
// request name var name is set
if(isset($_REQUEST[$name])) {
return $_REQUEST[$name];
}
// return default
return $default;
}
/**
* job custom archive page query
* @return array
*/
function job_query() {
// some vars
$jobs_per_page = 24;
// check url for these filter keys and get value
$job_search = get_url_var('search',false);
$job_link = get_url_var('service',false);
// add more url parameter filters here
// build our jobs query
$job_query = [
'post_type' => 'job',
'post_status' => 'publish',
'posts_per_page' => $jobs_per_page,
'orderby' => 'ASC',
'tax_query' => [
'relation' => 'AND'
]
];
// filter by search query
if($job_search) {
// extend our jobs query with search
$job_query['s'] = $job_search;
}
// if you convert job_links to taxonomy then...
// filter by job link taxonomy term slug (service)
if($job_link) {
// extend our tax query array
$job_query['tax_query'][] = [
'taxonomy' => 'job_link',
'field' => 'slug',
'terms' => [ ],
];
}
return $job_query;
}
```
Now create a page called **Jobs** with page slug/name `jobs`. Then create a php page template called `page-jobs.php` in your theme root, and then add the below php to it...
```
<?php
// products wp query
$jobs = new WP_Query(job_query());
// get our page header
get_header();
?>
<main>
<?php if($jobs->have_posts()): ?>
<?php while($jobs->have_posts()): $jobs->the_post() ?>
<article id="job-<?=get_the_ID()?>">
<?php the_title(); ?>
<?php the_field('secondary_title'); ?>
<?php the_field('jobs_links'); ?>
</article>
<?php endwhile; ?>
<?php else: ?>
No jobs found matching criteria.
<?php endif; ?>
</main>
<?php
// get our footer
get_footer();
```
Now run some search tests with the url format below, or alternatively use the html search form...
<https://yoursite.com/jobs?search=designer>
Also if you converted your `job_links` post type to a taxonomy then you can filter cpt jobs like this... (obviously only if you set the ACF `job_links` Taxonomy field to save/load terms)
<https://yoursite.com/jobs?service=web-developer>
<https://yoursite.com/jobs?service=web-designer>
---
One other thing, i'm not sure of your level of php, but the above could be so much more if you used object oriented php classes. The above code is for your basic `function.php` user. But if you know how to use php classes then let me know and I can update code to object oriented class format. |
369,803 | <p>How can I display only the specific category when accessing the posts related to that category? For example, I want to show only CSR Events under Categories When accessing posts related to CSR events. Here's the link to CSR post <a href="https://www.mi-eq.com/blood-donation-compaign/" rel="nofollow noreferrer">https://www.mi-eq.com/blood-donation-compaign/</a></p>
<p>Screenshot: <a href="https://i.stack.imgur.com/YoTfk.jpg" rel="nofollow noreferrer">https://i.stack.imgur.com/YoTfk.jpg</a></p>
<p>Similarly, when visiting posts related to other categories, only the specific category will be shown.</p>
| [
{
"answer_id": 370380,
"author": "joshmoto",
"author_id": 111152,
"author_profile": "https://wordpress.stackexchange.com/users/111152",
"pm_score": 1,
"selected": false,
"text": "<p>OK so I have had this problem with searching custom fields data.</p>\n<p>The thing is with the native Wordpress search, is that is really good, fast and powerful, but it's limitations is that it only searches the <code>wp_posts</code> table. It does <strong>not</strong> frickin' query the <code>wp_postmeta</code> table!</p>\n<p>So to make the most of the native Wordpress search, what you can do is tailor the exact search terms you want to be searchable by saving specific searchable custom field data to the native <code>post_content</code> as a json encoded array.</p>\n<p>If you are already using the native <code>post_content</code> field (in <code>wp_posts</code> table) for general job profile guff (in cpt <code>job</code>), then just migrate this data to a <code>ACF Wysiwyg Editor</code> field with the field name <code>job_post_content</code>. This new ACF version of <code>post_content</code> won't be searchable now. Which is probably a good thing in your situation, as you will have job profile nonsense, which you probably don't want to be picked up in the job search query anyway. If you still want this content searchable then you can still include this data in our searchable json array, if you wish (i've not shown this but it is simple to include).</p>\n<br/>\n<p>So for storing any searchable data in native <code>post_content</code>, this is where the magic happens. Follow my comments in code...</p>\n<p>Add this to your <code>functions.php</code></p>\n<pre><code>// process cpt job post when saving or updating job post\nadd_action('acf/save_post', 'acf_save_job', 20);\n\n/**\n * action to run modifications when saving or updating the job\n * @param int $post_id\n * @return void\n */\nfunction acf_save_job($post_id) {\n\n // get our current global post object\n global $post;\n\n // check we are on the cpt job else return now\n if($post->post_type <> 'job') return;\n\n // if job post status is publish or draft\n if($post->post_status == 'publish' || $post->post_status == 'draft') {\n\n // create job object from current post object\n $job = $post;\n\n // set an empty searchable data array\n $searchable_job_data = [];\n\n // we dont need to add the native post title for cpt job as this is already searchable\n\n // get our secondary title\n $secondary_title = get_field('secondary_title',$post_id);\n\n // if secondary title exists\n if($secondary_title) {\n\n // add secondary title to searchable data array\n $searchable_job_data['stitle'] = $secondary_title;\n\n }\n\n // get our job links post object field, acf must return this field as post object\n $job_links = get_field('job_links',$post_id);\n\n // I am assuming you are allowing multiple job links to be selected in job post admin...\n // so we have to loop through each array object and get the job link post title\n\n // if job links var is an array\n if(is_array($job_links)) {\n\n // foreach job link item as job object\n foreach ($job_links as $key => $job_link_object) {\n\n // if job link object has post title\n if($job_link_object->post_title) {\n\n // add job link title to our searchable data array\n $searchable_job_data['jlinks'][] = $job_link_object->post_title;\n\n }\n\n }\n\n }\n \n // add more searchable data to $searchable_job_array here if you wish\n\n // convert our searchable data array to json\n $searchable_job_json = json_encode($searchable_job_data,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);\n\n // temp remove the save job action\n remove_action('acf/save_post','acf_save_job',20);\n\n // update our native job post content with searchable data\n $job->post_content = $searchable_job_json;\n \n // update the current job with new job data\n wp_update_post($job);\n\n // re add the save job action\n add_action('acf/save_post', 'acf_save_job', 20);\n\n }\n\n}\n</code></pre>\n<br/>\n<p>So when you create or save a cpt job post, you will notice the native <code>post_content</code> now contains something like this (as an unformatted string)...</p>\n<pre><code>{\n "stitle": "Front-end developer",\n "jlinks": [\n "Web developer",\n "Web designer"\n ]\n} \n</code></pre>\n<p>Using cpt or acf you can hide the native post content visually from your admin job post page, but the search data will still exist in the database.</p>\n<br/>\n<p><strong>After looking at your custom jobs page, would it not be better to turn <code>job_links</code>, to a taxonomy, rather than a post type. So you can also filter by jobs by selecting job link/service. In my custom jobs archive page example (below) I will also demonstrate this...</strong></p>\n<br/>\n<p>Here is a search form html to search jobs only, this can go in your <code>header.php</code> or anywhere...</p>\n<pre><code><form action="/jobs" method="get">\n <input type="search" name="search" placeholder="Search jobs" />\n</form>\n</code></pre>\n<br/>\n<p>Here is some jobs query functions to add to your <code>functions.php</code>...</p>\n<pre><code>/**\n * simple method to get request parameter value\n * @param mixed $name key name to find\n * @param mixed $default default value if no value is found\n * @return mixed\n */\nfunction get_url_var($name = false, $default = false)\n{\n // if name is false\n if($name === false) {\n return $_REQUEST;\n }\n // request name var name is set\n if(isset($_REQUEST[$name])) {\n return $_REQUEST[$name];\n }\n // return default\n return $default;\n}\n\n/**\n * job custom archive page query\n * @return array\n */\nfunction job_query() {\n\n // some vars\n $jobs_per_page = 24;\n\n // check url for these filter keys and get value\n $job_search = get_url_var('search',false);\n $job_link = get_url_var('service',false);\n // add more url parameter filters here\n\n // build our jobs query\n $job_query = [\n 'post_type' => 'job',\n 'post_status' => 'publish',\n 'posts_per_page' => $jobs_per_page,\n 'orderby' => 'ASC',\n 'tax_query' => [\n 'relation' => 'AND'\n ]\n ];\n\n // filter by search query\n if($job_search) {\n // extend our jobs query with search\n $job_query['s'] = $job_search;\n }\n\n // if you convert job_links to taxonomy then...\n // filter by job link taxonomy term slug (service)\n if($job_link) {\n // extend our tax query array\n $job_query['tax_query'][] = [\n 'taxonomy' => 'job_link',\n 'field' => 'slug',\n 'terms' => [ ],\n ];\n }\n\n return $job_query;\n\n}\n</code></pre>\n<br/>\n<p>Now create a page called <strong>Jobs</strong> with page slug/name <code>jobs</code>. Then create a php page template called <code>page-jobs.php</code> in your theme root, and then add the below php to it...</p>\n<pre><code><?php\n\n// products wp query\n$jobs = new WP_Query(job_query());\n\n// get our page header\nget_header();\n\n?>\n <main>\n <?php if($jobs->have_posts()): ?>\n <?php while($jobs->have_posts()): $jobs->the_post() ?>\n <article id="job-<?=get_the_ID()?>">\n <?php the_title(); ?>\n <?php the_field('secondary_title'); ?>\n <?php the_field('jobs_links'); ?>\n </article>\n <?php endwhile; ?>\n <?php else: ?>\n No jobs found matching criteria.\n <?php endif; ?>\n </main>\n<?php\n\n// get our footer\nget_footer();\n</code></pre>\n<br/>\n<p>Now run some search tests with the url format below, or alternatively use the html search form...</p>\n<p><a href=\"https://yoursite.com/jobs?search=designer\" rel=\"nofollow noreferrer\">https://yoursite.com/jobs?search=designer</a></p>\n<p>Also if you converted your <code>job_links</code> post type to a taxonomy then you can filter cpt jobs like this... (obviously only if you set the ACF <code>job_links</code> Taxonomy field to save/load terms)</p>\n<p><a href=\"https://yoursite.com/jobs?service=web-developer\" rel=\"nofollow noreferrer\">https://yoursite.com/jobs?service=web-developer</a><br/>\n<a href=\"https://yoursite.com/jobs?service=web-designer\" rel=\"nofollow noreferrer\">https://yoursite.com/jobs?service=web-designer</a></p>\n<br/>\n<hr />\n<br/>\n<p>One other thing, i'm not sure of your level of php, but the above could be so much more if you used object oriented php classes. The above code is for your basic <code>function.php</code> user. But if you know how to use php classes then let me know and I can update code to object oriented class format.</p>\n"
},
{
"answer_id": 370583,
"author": "Chevax",
"author_id": 191221,
"author_profile": "https://wordpress.stackexchange.com/users/191221",
"pm_score": 0,
"selected": false,
"text": "<p>I wish to express my gratitude for the time spent answering my question.</p>\n<p>Your answer is very pedagogical, clear and precise.</p>\n<p>I didn't expect as much...</p>\n<p>Even if I don't have a high level in PHP, I managed to deploy your solution.</p>\n<p>Thanks again @joshmoto</p>\n"
}
] | 2020/06/26 | [
"https://wordpress.stackexchange.com/questions/369803",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/190627/"
] | How can I display only the specific category when accessing the posts related to that category? For example, I want to show only CSR Events under Categories When accessing posts related to CSR events. Here's the link to CSR post <https://www.mi-eq.com/blood-donation-compaign/>
Screenshot: <https://i.stack.imgur.com/YoTfk.jpg>
Similarly, when visiting posts related to other categories, only the specific category will be shown. | OK so I have had this problem with searching custom fields data.
The thing is with the native Wordpress search, is that is really good, fast and powerful, but it's limitations is that it only searches the `wp_posts` table. It does **not** frickin' query the `wp_postmeta` table!
So to make the most of the native Wordpress search, what you can do is tailor the exact search terms you want to be searchable by saving specific searchable custom field data to the native `post_content` as a json encoded array.
If you are already using the native `post_content` field (in `wp_posts` table) for general job profile guff (in cpt `job`), then just migrate this data to a `ACF Wysiwyg Editor` field with the field name `job_post_content`. This new ACF version of `post_content` won't be searchable now. Which is probably a good thing in your situation, as you will have job profile nonsense, which you probably don't want to be picked up in the job search query anyway. If you still want this content searchable then you can still include this data in our searchable json array, if you wish (i've not shown this but it is simple to include).
So for storing any searchable data in native `post_content`, this is where the magic happens. Follow my comments in code...
Add this to your `functions.php`
```
// process cpt job post when saving or updating job post
add_action('acf/save_post', 'acf_save_job', 20);
/**
* action to run modifications when saving or updating the job
* @param int $post_id
* @return void
*/
function acf_save_job($post_id) {
// get our current global post object
global $post;
// check we are on the cpt job else return now
if($post->post_type <> 'job') return;
// if job post status is publish or draft
if($post->post_status == 'publish' || $post->post_status == 'draft') {
// create job object from current post object
$job = $post;
// set an empty searchable data array
$searchable_job_data = [];
// we dont need to add the native post title for cpt job as this is already searchable
// get our secondary title
$secondary_title = get_field('secondary_title',$post_id);
// if secondary title exists
if($secondary_title) {
// add secondary title to searchable data array
$searchable_job_data['stitle'] = $secondary_title;
}
// get our job links post object field, acf must return this field as post object
$job_links = get_field('job_links',$post_id);
// I am assuming you are allowing multiple job links to be selected in job post admin...
// so we have to loop through each array object and get the job link post title
// if job links var is an array
if(is_array($job_links)) {
// foreach job link item as job object
foreach ($job_links as $key => $job_link_object) {
// if job link object has post title
if($job_link_object->post_title) {
// add job link title to our searchable data array
$searchable_job_data['jlinks'][] = $job_link_object->post_title;
}
}
}
// add more searchable data to $searchable_job_array here if you wish
// convert our searchable data array to json
$searchable_job_json = json_encode($searchable_job_data,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
// temp remove the save job action
remove_action('acf/save_post','acf_save_job',20);
// update our native job post content with searchable data
$job->post_content = $searchable_job_json;
// update the current job with new job data
wp_update_post($job);
// re add the save job action
add_action('acf/save_post', 'acf_save_job', 20);
}
}
```
So when you create or save a cpt job post, you will notice the native `post_content` now contains something like this (as an unformatted string)...
```
{
"stitle": "Front-end developer",
"jlinks": [
"Web developer",
"Web designer"
]
}
```
Using cpt or acf you can hide the native post content visually from your admin job post page, but the search data will still exist in the database.
**After looking at your custom jobs page, would it not be better to turn `job_links`, to a taxonomy, rather than a post type. So you can also filter by jobs by selecting job link/service. In my custom jobs archive page example (below) I will also demonstrate this...**
Here is a search form html to search jobs only, this can go in your `header.php` or anywhere...
```
<form action="/jobs" method="get">
<input type="search" name="search" placeholder="Search jobs" />
</form>
```
Here is some jobs query functions to add to your `functions.php`...
```
/**
* simple method to get request parameter value
* @param mixed $name key name to find
* @param mixed $default default value if no value is found
* @return mixed
*/
function get_url_var($name = false, $default = false)
{
// if name is false
if($name === false) {
return $_REQUEST;
}
// request name var name is set
if(isset($_REQUEST[$name])) {
return $_REQUEST[$name];
}
// return default
return $default;
}
/**
* job custom archive page query
* @return array
*/
function job_query() {
// some vars
$jobs_per_page = 24;
// check url for these filter keys and get value
$job_search = get_url_var('search',false);
$job_link = get_url_var('service',false);
// add more url parameter filters here
// build our jobs query
$job_query = [
'post_type' => 'job',
'post_status' => 'publish',
'posts_per_page' => $jobs_per_page,
'orderby' => 'ASC',
'tax_query' => [
'relation' => 'AND'
]
];
// filter by search query
if($job_search) {
// extend our jobs query with search
$job_query['s'] = $job_search;
}
// if you convert job_links to taxonomy then...
// filter by job link taxonomy term slug (service)
if($job_link) {
// extend our tax query array
$job_query['tax_query'][] = [
'taxonomy' => 'job_link',
'field' => 'slug',
'terms' => [ ],
];
}
return $job_query;
}
```
Now create a page called **Jobs** with page slug/name `jobs`. Then create a php page template called `page-jobs.php` in your theme root, and then add the below php to it...
```
<?php
// products wp query
$jobs = new WP_Query(job_query());
// get our page header
get_header();
?>
<main>
<?php if($jobs->have_posts()): ?>
<?php while($jobs->have_posts()): $jobs->the_post() ?>
<article id="job-<?=get_the_ID()?>">
<?php the_title(); ?>
<?php the_field('secondary_title'); ?>
<?php the_field('jobs_links'); ?>
</article>
<?php endwhile; ?>
<?php else: ?>
No jobs found matching criteria.
<?php endif; ?>
</main>
<?php
// get our footer
get_footer();
```
Now run some search tests with the url format below, or alternatively use the html search form...
<https://yoursite.com/jobs?search=designer>
Also if you converted your `job_links` post type to a taxonomy then you can filter cpt jobs like this... (obviously only if you set the ACF `job_links` Taxonomy field to save/load terms)
<https://yoursite.com/jobs?service=web-developer>
<https://yoursite.com/jobs?service=web-designer>
---
One other thing, i'm not sure of your level of php, but the above could be so much more if you used object oriented php classes. The above code is for your basic `function.php` user. But if you know how to use php classes then let me know and I can update code to object oriented class format. |
369,852 | <p>I am using Wordpress for my clients to log into the site, put data in a customized table and save it in a database table.
Through the code “example” that I put in funtions.php theme I can return my email at the top of the screen. Code below.</p>
<pre><code>$ current_user = wp_get_current_user ();
$ logado1 = $ current_user-> user_email;
echo $ logged1;
</code></pre>
<p>however through a new blank page I can put the HTML to make it work correctly, including with the css via plugin.
But I can't include the php on the page is to retrieve the data from the $ logado1 variable contained in theme / funtions.php.
Well, I need to retrieve the data from “$ logado1 email”, and forward it to a next php referenced in.</p>
<pre><code><form action=" http://localhost/newphp.php" method="post">.
</code></pre>
<p>do the treatment and save it in a new table in the “registration” database.</p>
<pre><code><div class = "divsearch">
<form action=" http://localhost/newphp.php" method="post">
<label class = "textout"> <b> Port 1 </b> </label>
<input type = "text" class = "box1">
<label class = "textout"> <b> Port 2 </b> </label>
<input type = "text" class = "box1">
</form>
<button type = "submit" class = "buttonacept1"> Save </button>
</div>
</code></pre>
<p>Does anyone have any solution for this problem ?.</p>
| [
{
"answer_id": 370380,
"author": "joshmoto",
"author_id": 111152,
"author_profile": "https://wordpress.stackexchange.com/users/111152",
"pm_score": 1,
"selected": false,
"text": "<p>OK so I have had this problem with searching custom fields data.</p>\n<p>The thing is with the native Wordpress search, is that is really good, fast and powerful, but it's limitations is that it only searches the <code>wp_posts</code> table. It does <strong>not</strong> frickin' query the <code>wp_postmeta</code> table!</p>\n<p>So to make the most of the native Wordpress search, what you can do is tailor the exact search terms you want to be searchable by saving specific searchable custom field data to the native <code>post_content</code> as a json encoded array.</p>\n<p>If you are already using the native <code>post_content</code> field (in <code>wp_posts</code> table) for general job profile guff (in cpt <code>job</code>), then just migrate this data to a <code>ACF Wysiwyg Editor</code> field with the field name <code>job_post_content</code>. This new ACF version of <code>post_content</code> won't be searchable now. Which is probably a good thing in your situation, as you will have job profile nonsense, which you probably don't want to be picked up in the job search query anyway. If you still want this content searchable then you can still include this data in our searchable json array, if you wish (i've not shown this but it is simple to include).</p>\n<br/>\n<p>So for storing any searchable data in native <code>post_content</code>, this is where the magic happens. Follow my comments in code...</p>\n<p>Add this to your <code>functions.php</code></p>\n<pre><code>// process cpt job post when saving or updating job post\nadd_action('acf/save_post', 'acf_save_job', 20);\n\n/**\n * action to run modifications when saving or updating the job\n * @param int $post_id\n * @return void\n */\nfunction acf_save_job($post_id) {\n\n // get our current global post object\n global $post;\n\n // check we are on the cpt job else return now\n if($post->post_type <> 'job') return;\n\n // if job post status is publish or draft\n if($post->post_status == 'publish' || $post->post_status == 'draft') {\n\n // create job object from current post object\n $job = $post;\n\n // set an empty searchable data array\n $searchable_job_data = [];\n\n // we dont need to add the native post title for cpt job as this is already searchable\n\n // get our secondary title\n $secondary_title = get_field('secondary_title',$post_id);\n\n // if secondary title exists\n if($secondary_title) {\n\n // add secondary title to searchable data array\n $searchable_job_data['stitle'] = $secondary_title;\n\n }\n\n // get our job links post object field, acf must return this field as post object\n $job_links = get_field('job_links',$post_id);\n\n // I am assuming you are allowing multiple job links to be selected in job post admin...\n // so we have to loop through each array object and get the job link post title\n\n // if job links var is an array\n if(is_array($job_links)) {\n\n // foreach job link item as job object\n foreach ($job_links as $key => $job_link_object) {\n\n // if job link object has post title\n if($job_link_object->post_title) {\n\n // add job link title to our searchable data array\n $searchable_job_data['jlinks'][] = $job_link_object->post_title;\n\n }\n\n }\n\n }\n \n // add more searchable data to $searchable_job_array here if you wish\n\n // convert our searchable data array to json\n $searchable_job_json = json_encode($searchable_job_data,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);\n\n // temp remove the save job action\n remove_action('acf/save_post','acf_save_job',20);\n\n // update our native job post content with searchable data\n $job->post_content = $searchable_job_json;\n \n // update the current job with new job data\n wp_update_post($job);\n\n // re add the save job action\n add_action('acf/save_post', 'acf_save_job', 20);\n\n }\n\n}\n</code></pre>\n<br/>\n<p>So when you create or save a cpt job post, you will notice the native <code>post_content</code> now contains something like this (as an unformatted string)...</p>\n<pre><code>{\n "stitle": "Front-end developer",\n "jlinks": [\n "Web developer",\n "Web designer"\n ]\n} \n</code></pre>\n<p>Using cpt or acf you can hide the native post content visually from your admin job post page, but the search data will still exist in the database.</p>\n<br/>\n<p><strong>After looking at your custom jobs page, would it not be better to turn <code>job_links</code>, to a taxonomy, rather than a post type. So you can also filter by jobs by selecting job link/service. In my custom jobs archive page example (below) I will also demonstrate this...</strong></p>\n<br/>\n<p>Here is a search form html to search jobs only, this can go in your <code>header.php</code> or anywhere...</p>\n<pre><code><form action="/jobs" method="get">\n <input type="search" name="search" placeholder="Search jobs" />\n</form>\n</code></pre>\n<br/>\n<p>Here is some jobs query functions to add to your <code>functions.php</code>...</p>\n<pre><code>/**\n * simple method to get request parameter value\n * @param mixed $name key name to find\n * @param mixed $default default value if no value is found\n * @return mixed\n */\nfunction get_url_var($name = false, $default = false)\n{\n // if name is false\n if($name === false) {\n return $_REQUEST;\n }\n // request name var name is set\n if(isset($_REQUEST[$name])) {\n return $_REQUEST[$name];\n }\n // return default\n return $default;\n}\n\n/**\n * job custom archive page query\n * @return array\n */\nfunction job_query() {\n\n // some vars\n $jobs_per_page = 24;\n\n // check url for these filter keys and get value\n $job_search = get_url_var('search',false);\n $job_link = get_url_var('service',false);\n // add more url parameter filters here\n\n // build our jobs query\n $job_query = [\n 'post_type' => 'job',\n 'post_status' => 'publish',\n 'posts_per_page' => $jobs_per_page,\n 'orderby' => 'ASC',\n 'tax_query' => [\n 'relation' => 'AND'\n ]\n ];\n\n // filter by search query\n if($job_search) {\n // extend our jobs query with search\n $job_query['s'] = $job_search;\n }\n\n // if you convert job_links to taxonomy then...\n // filter by job link taxonomy term slug (service)\n if($job_link) {\n // extend our tax query array\n $job_query['tax_query'][] = [\n 'taxonomy' => 'job_link',\n 'field' => 'slug',\n 'terms' => [ ],\n ];\n }\n\n return $job_query;\n\n}\n</code></pre>\n<br/>\n<p>Now create a page called <strong>Jobs</strong> with page slug/name <code>jobs</code>. Then create a php page template called <code>page-jobs.php</code> in your theme root, and then add the below php to it...</p>\n<pre><code><?php\n\n// products wp query\n$jobs = new WP_Query(job_query());\n\n// get our page header\nget_header();\n\n?>\n <main>\n <?php if($jobs->have_posts()): ?>\n <?php while($jobs->have_posts()): $jobs->the_post() ?>\n <article id="job-<?=get_the_ID()?>">\n <?php the_title(); ?>\n <?php the_field('secondary_title'); ?>\n <?php the_field('jobs_links'); ?>\n </article>\n <?php endwhile; ?>\n <?php else: ?>\n No jobs found matching criteria.\n <?php endif; ?>\n </main>\n<?php\n\n// get our footer\nget_footer();\n</code></pre>\n<br/>\n<p>Now run some search tests with the url format below, or alternatively use the html search form...</p>\n<p><a href=\"https://yoursite.com/jobs?search=designer\" rel=\"nofollow noreferrer\">https://yoursite.com/jobs?search=designer</a></p>\n<p>Also if you converted your <code>job_links</code> post type to a taxonomy then you can filter cpt jobs like this... (obviously only if you set the ACF <code>job_links</code> Taxonomy field to save/load terms)</p>\n<p><a href=\"https://yoursite.com/jobs?service=web-developer\" rel=\"nofollow noreferrer\">https://yoursite.com/jobs?service=web-developer</a><br/>\n<a href=\"https://yoursite.com/jobs?service=web-designer\" rel=\"nofollow noreferrer\">https://yoursite.com/jobs?service=web-designer</a></p>\n<br/>\n<hr />\n<br/>\n<p>One other thing, i'm not sure of your level of php, but the above could be so much more if you used object oriented php classes. The above code is for your basic <code>function.php</code> user. But if you know how to use php classes then let me know and I can update code to object oriented class format.</p>\n"
},
{
"answer_id": 370583,
"author": "Chevax",
"author_id": 191221,
"author_profile": "https://wordpress.stackexchange.com/users/191221",
"pm_score": 0,
"selected": false,
"text": "<p>I wish to express my gratitude for the time spent answering my question.</p>\n<p>Your answer is very pedagogical, clear and precise.</p>\n<p>I didn't expect as much...</p>\n<p>Even if I don't have a high level in PHP, I managed to deploy your solution.</p>\n<p>Thanks again @joshmoto</p>\n"
}
] | 2020/06/26 | [
"https://wordpress.stackexchange.com/questions/369852",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/190674/"
] | I am using Wordpress for my clients to log into the site, put data in a customized table and save it in a database table.
Through the code “example” that I put in funtions.php theme I can return my email at the top of the screen. Code below.
```
$ current_user = wp_get_current_user ();
$ logado1 = $ current_user-> user_email;
echo $ logged1;
```
however through a new blank page I can put the HTML to make it work correctly, including with the css via plugin.
But I can't include the php on the page is to retrieve the data from the $ logado1 variable contained in theme / funtions.php.
Well, I need to retrieve the data from “$ logado1 email”, and forward it to a next php referenced in.
```
<form action=" http://localhost/newphp.php" method="post">.
```
do the treatment and save it in a new table in the “registration” database.
```
<div class = "divsearch">
<form action=" http://localhost/newphp.php" method="post">
<label class = "textout"> <b> Port 1 </b> </label>
<input type = "text" class = "box1">
<label class = "textout"> <b> Port 2 </b> </label>
<input type = "text" class = "box1">
</form>
<button type = "submit" class = "buttonacept1"> Save </button>
</div>
```
Does anyone have any solution for this problem ?. | OK so I have had this problem with searching custom fields data.
The thing is with the native Wordpress search, is that is really good, fast and powerful, but it's limitations is that it only searches the `wp_posts` table. It does **not** frickin' query the `wp_postmeta` table!
So to make the most of the native Wordpress search, what you can do is tailor the exact search terms you want to be searchable by saving specific searchable custom field data to the native `post_content` as a json encoded array.
If you are already using the native `post_content` field (in `wp_posts` table) for general job profile guff (in cpt `job`), then just migrate this data to a `ACF Wysiwyg Editor` field with the field name `job_post_content`. This new ACF version of `post_content` won't be searchable now. Which is probably a good thing in your situation, as you will have job profile nonsense, which you probably don't want to be picked up in the job search query anyway. If you still want this content searchable then you can still include this data in our searchable json array, if you wish (i've not shown this but it is simple to include).
So for storing any searchable data in native `post_content`, this is where the magic happens. Follow my comments in code...
Add this to your `functions.php`
```
// process cpt job post when saving or updating job post
add_action('acf/save_post', 'acf_save_job', 20);
/**
* action to run modifications when saving or updating the job
* @param int $post_id
* @return void
*/
function acf_save_job($post_id) {
// get our current global post object
global $post;
// check we are on the cpt job else return now
if($post->post_type <> 'job') return;
// if job post status is publish or draft
if($post->post_status == 'publish' || $post->post_status == 'draft') {
// create job object from current post object
$job = $post;
// set an empty searchable data array
$searchable_job_data = [];
// we dont need to add the native post title for cpt job as this is already searchable
// get our secondary title
$secondary_title = get_field('secondary_title',$post_id);
// if secondary title exists
if($secondary_title) {
// add secondary title to searchable data array
$searchable_job_data['stitle'] = $secondary_title;
}
// get our job links post object field, acf must return this field as post object
$job_links = get_field('job_links',$post_id);
// I am assuming you are allowing multiple job links to be selected in job post admin...
// so we have to loop through each array object and get the job link post title
// if job links var is an array
if(is_array($job_links)) {
// foreach job link item as job object
foreach ($job_links as $key => $job_link_object) {
// if job link object has post title
if($job_link_object->post_title) {
// add job link title to our searchable data array
$searchable_job_data['jlinks'][] = $job_link_object->post_title;
}
}
}
// add more searchable data to $searchable_job_array here if you wish
// convert our searchable data array to json
$searchable_job_json = json_encode($searchable_job_data,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
// temp remove the save job action
remove_action('acf/save_post','acf_save_job',20);
// update our native job post content with searchable data
$job->post_content = $searchable_job_json;
// update the current job with new job data
wp_update_post($job);
// re add the save job action
add_action('acf/save_post', 'acf_save_job', 20);
}
}
```
So when you create or save a cpt job post, you will notice the native `post_content` now contains something like this (as an unformatted string)...
```
{
"stitle": "Front-end developer",
"jlinks": [
"Web developer",
"Web designer"
]
}
```
Using cpt or acf you can hide the native post content visually from your admin job post page, but the search data will still exist in the database.
**After looking at your custom jobs page, would it not be better to turn `job_links`, to a taxonomy, rather than a post type. So you can also filter by jobs by selecting job link/service. In my custom jobs archive page example (below) I will also demonstrate this...**
Here is a search form html to search jobs only, this can go in your `header.php` or anywhere...
```
<form action="/jobs" method="get">
<input type="search" name="search" placeholder="Search jobs" />
</form>
```
Here is some jobs query functions to add to your `functions.php`...
```
/**
* simple method to get request parameter value
* @param mixed $name key name to find
* @param mixed $default default value if no value is found
* @return mixed
*/
function get_url_var($name = false, $default = false)
{
// if name is false
if($name === false) {
return $_REQUEST;
}
// request name var name is set
if(isset($_REQUEST[$name])) {
return $_REQUEST[$name];
}
// return default
return $default;
}
/**
* job custom archive page query
* @return array
*/
function job_query() {
// some vars
$jobs_per_page = 24;
// check url for these filter keys and get value
$job_search = get_url_var('search',false);
$job_link = get_url_var('service',false);
// add more url parameter filters here
// build our jobs query
$job_query = [
'post_type' => 'job',
'post_status' => 'publish',
'posts_per_page' => $jobs_per_page,
'orderby' => 'ASC',
'tax_query' => [
'relation' => 'AND'
]
];
// filter by search query
if($job_search) {
// extend our jobs query with search
$job_query['s'] = $job_search;
}
// if you convert job_links to taxonomy then...
// filter by job link taxonomy term slug (service)
if($job_link) {
// extend our tax query array
$job_query['tax_query'][] = [
'taxonomy' => 'job_link',
'field' => 'slug',
'terms' => [ ],
];
}
return $job_query;
}
```
Now create a page called **Jobs** with page slug/name `jobs`. Then create a php page template called `page-jobs.php` in your theme root, and then add the below php to it...
```
<?php
// products wp query
$jobs = new WP_Query(job_query());
// get our page header
get_header();
?>
<main>
<?php if($jobs->have_posts()): ?>
<?php while($jobs->have_posts()): $jobs->the_post() ?>
<article id="job-<?=get_the_ID()?>">
<?php the_title(); ?>
<?php the_field('secondary_title'); ?>
<?php the_field('jobs_links'); ?>
</article>
<?php endwhile; ?>
<?php else: ?>
No jobs found matching criteria.
<?php endif; ?>
</main>
<?php
// get our footer
get_footer();
```
Now run some search tests with the url format below, or alternatively use the html search form...
<https://yoursite.com/jobs?search=designer>
Also if you converted your `job_links` post type to a taxonomy then you can filter cpt jobs like this... (obviously only if you set the ACF `job_links` Taxonomy field to save/load terms)
<https://yoursite.com/jobs?service=web-developer>
<https://yoursite.com/jobs?service=web-designer>
---
One other thing, i'm not sure of your level of php, but the above could be so much more if you used object oriented php classes. The above code is for your basic `function.php` user. But if you know how to use php classes then let me know and I can update code to object oriented class format. |
369,860 | <p>I am guessing this is being caused by my nginx configuration, however I can not quite figure out how to troubleshoot in order to resolve.</p>
<p>I am using Ubuntu 20.04 with a LEMP stack to host a wordpress installation. Everything works fine except this quirk, which is that if I type in the site's URL into Chrome, the site will resolve to 'https://example.com' and everything on the site loads fine.</p>
<p>However, in Firefox if I type in the site's URL it will resolve to 'https://www.example.com', which would be fine except that certain icons on the site will now not load, are not show and are replaced by a square box.</p>
<p>Below is the nginx configuration I am using:</p>
<pre><code>server {
listen 80;
server_name www.{{ domain_name }}{{ tld }} {{ domain_name }}{{ tld }};
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl;
server_name www.{{ domain_name }}{{ tld }};
ssl_certificate /etc/letsencrypt/certs/fullchain_{{ domain_name }};
ssl_certificate_key /etc/letsencrypt/keys/{{ domain_name }}.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers ECDHE-RSA-AES256-SHA384:AES256-SHA256:RC4:HIGH:!MD5:!aNULL:!EDH:!AESGCM;
# ssl_ecdh_curve secp521r1;
root /home/{{ domain_name }}/public_html;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ /index.php?q=$uri&$args;
}
# return 301 https://www.$server_name$request_uri;
location ~ \.php$ {
# Basic
try_files $uri =404;
fastcgi_index index.php;
# Create a no cache flag
set $no_cache "";
# Don't ever cache POSTs
if ($request_method = POST) {
set $no_cache 1;
}
# Admin stuff should not be cached
if ($request_uri ~* "/(wp-admin/|wp-login.php)") {
set $no_cache 1;
}
# WooCommerce stuff should not be cached
if ($request_uri ~* "/store.*|/cart.*|/my-account.*|/checkout.*|/addons.*") {
set $no_cache 1;
}
# If we are the admin, make sure nothing
# gets cached, so no weird stuff will happen
if ($http_cookie ~* "wordpress_logged_in_") {
set $no_cache 1;
}
# Cache and cache bypass handling
fastcgi_no_cache $no_cache;
fastcgi_cache_bypass $no_cache;
fastcgi_cache microcache;
fastcgi_cache_key $scheme$request_method$server_name$request_uri$args;
fastcgi_cache_valid 200 60m;
fastcgi_cache_valid 404 10m;
fastcgi_cache_use_stale updating;
# General FastCGI handling
fastcgi_pass unix:/var/run/php/{{ domain_name }}.sock;
fastcgi_pass_header Set-Cookie;
fastcgi_pass_header Cookie;
fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_param SCRIPT_FILENAME $request_filename;
fastcgi_intercept_errors on;
include fastcgi_params;
}
location ~* \.(js|css|png|jpg|jpeg|gif|ico|woff|ttf|svg|otf)$ {
expires 30d;
add_header Pragma public;
add_header Cache-Control "public";
access_log off;
}
}
</code></pre>
| [
{
"answer_id": 370380,
"author": "joshmoto",
"author_id": 111152,
"author_profile": "https://wordpress.stackexchange.com/users/111152",
"pm_score": 1,
"selected": false,
"text": "<p>OK so I have had this problem with searching custom fields data.</p>\n<p>The thing is with the native Wordpress search, is that is really good, fast and powerful, but it's limitations is that it only searches the <code>wp_posts</code> table. It does <strong>not</strong> frickin' query the <code>wp_postmeta</code> table!</p>\n<p>So to make the most of the native Wordpress search, what you can do is tailor the exact search terms you want to be searchable by saving specific searchable custom field data to the native <code>post_content</code> as a json encoded array.</p>\n<p>If you are already using the native <code>post_content</code> field (in <code>wp_posts</code> table) for general job profile guff (in cpt <code>job</code>), then just migrate this data to a <code>ACF Wysiwyg Editor</code> field with the field name <code>job_post_content</code>. This new ACF version of <code>post_content</code> won't be searchable now. Which is probably a good thing in your situation, as you will have job profile nonsense, which you probably don't want to be picked up in the job search query anyway. If you still want this content searchable then you can still include this data in our searchable json array, if you wish (i've not shown this but it is simple to include).</p>\n<br/>\n<p>So for storing any searchable data in native <code>post_content</code>, this is where the magic happens. Follow my comments in code...</p>\n<p>Add this to your <code>functions.php</code></p>\n<pre><code>// process cpt job post when saving or updating job post\nadd_action('acf/save_post', 'acf_save_job', 20);\n\n/**\n * action to run modifications when saving or updating the job\n * @param int $post_id\n * @return void\n */\nfunction acf_save_job($post_id) {\n\n // get our current global post object\n global $post;\n\n // check we are on the cpt job else return now\n if($post->post_type <> 'job') return;\n\n // if job post status is publish or draft\n if($post->post_status == 'publish' || $post->post_status == 'draft') {\n\n // create job object from current post object\n $job = $post;\n\n // set an empty searchable data array\n $searchable_job_data = [];\n\n // we dont need to add the native post title for cpt job as this is already searchable\n\n // get our secondary title\n $secondary_title = get_field('secondary_title',$post_id);\n\n // if secondary title exists\n if($secondary_title) {\n\n // add secondary title to searchable data array\n $searchable_job_data['stitle'] = $secondary_title;\n\n }\n\n // get our job links post object field, acf must return this field as post object\n $job_links = get_field('job_links',$post_id);\n\n // I am assuming you are allowing multiple job links to be selected in job post admin...\n // so we have to loop through each array object and get the job link post title\n\n // if job links var is an array\n if(is_array($job_links)) {\n\n // foreach job link item as job object\n foreach ($job_links as $key => $job_link_object) {\n\n // if job link object has post title\n if($job_link_object->post_title) {\n\n // add job link title to our searchable data array\n $searchable_job_data['jlinks'][] = $job_link_object->post_title;\n\n }\n\n }\n\n }\n \n // add more searchable data to $searchable_job_array here if you wish\n\n // convert our searchable data array to json\n $searchable_job_json = json_encode($searchable_job_data,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);\n\n // temp remove the save job action\n remove_action('acf/save_post','acf_save_job',20);\n\n // update our native job post content with searchable data\n $job->post_content = $searchable_job_json;\n \n // update the current job with new job data\n wp_update_post($job);\n\n // re add the save job action\n add_action('acf/save_post', 'acf_save_job', 20);\n\n }\n\n}\n</code></pre>\n<br/>\n<p>So when you create or save a cpt job post, you will notice the native <code>post_content</code> now contains something like this (as an unformatted string)...</p>\n<pre><code>{\n "stitle": "Front-end developer",\n "jlinks": [\n "Web developer",\n "Web designer"\n ]\n} \n</code></pre>\n<p>Using cpt or acf you can hide the native post content visually from your admin job post page, but the search data will still exist in the database.</p>\n<br/>\n<p><strong>After looking at your custom jobs page, would it not be better to turn <code>job_links</code>, to a taxonomy, rather than a post type. So you can also filter by jobs by selecting job link/service. In my custom jobs archive page example (below) I will also demonstrate this...</strong></p>\n<br/>\n<p>Here is a search form html to search jobs only, this can go in your <code>header.php</code> or anywhere...</p>\n<pre><code><form action="/jobs" method="get">\n <input type="search" name="search" placeholder="Search jobs" />\n</form>\n</code></pre>\n<br/>\n<p>Here is some jobs query functions to add to your <code>functions.php</code>...</p>\n<pre><code>/**\n * simple method to get request parameter value\n * @param mixed $name key name to find\n * @param mixed $default default value if no value is found\n * @return mixed\n */\nfunction get_url_var($name = false, $default = false)\n{\n // if name is false\n if($name === false) {\n return $_REQUEST;\n }\n // request name var name is set\n if(isset($_REQUEST[$name])) {\n return $_REQUEST[$name];\n }\n // return default\n return $default;\n}\n\n/**\n * job custom archive page query\n * @return array\n */\nfunction job_query() {\n\n // some vars\n $jobs_per_page = 24;\n\n // check url for these filter keys and get value\n $job_search = get_url_var('search',false);\n $job_link = get_url_var('service',false);\n // add more url parameter filters here\n\n // build our jobs query\n $job_query = [\n 'post_type' => 'job',\n 'post_status' => 'publish',\n 'posts_per_page' => $jobs_per_page,\n 'orderby' => 'ASC',\n 'tax_query' => [\n 'relation' => 'AND'\n ]\n ];\n\n // filter by search query\n if($job_search) {\n // extend our jobs query with search\n $job_query['s'] = $job_search;\n }\n\n // if you convert job_links to taxonomy then...\n // filter by job link taxonomy term slug (service)\n if($job_link) {\n // extend our tax query array\n $job_query['tax_query'][] = [\n 'taxonomy' => 'job_link',\n 'field' => 'slug',\n 'terms' => [ ],\n ];\n }\n\n return $job_query;\n\n}\n</code></pre>\n<br/>\n<p>Now create a page called <strong>Jobs</strong> with page slug/name <code>jobs</code>. Then create a php page template called <code>page-jobs.php</code> in your theme root, and then add the below php to it...</p>\n<pre><code><?php\n\n// products wp query\n$jobs = new WP_Query(job_query());\n\n// get our page header\nget_header();\n\n?>\n <main>\n <?php if($jobs->have_posts()): ?>\n <?php while($jobs->have_posts()): $jobs->the_post() ?>\n <article id="job-<?=get_the_ID()?>">\n <?php the_title(); ?>\n <?php the_field('secondary_title'); ?>\n <?php the_field('jobs_links'); ?>\n </article>\n <?php endwhile; ?>\n <?php else: ?>\n No jobs found matching criteria.\n <?php endif; ?>\n </main>\n<?php\n\n// get our footer\nget_footer();\n</code></pre>\n<br/>\n<p>Now run some search tests with the url format below, or alternatively use the html search form...</p>\n<p><a href=\"https://yoursite.com/jobs?search=designer\" rel=\"nofollow noreferrer\">https://yoursite.com/jobs?search=designer</a></p>\n<p>Also if you converted your <code>job_links</code> post type to a taxonomy then you can filter cpt jobs like this... (obviously only if you set the ACF <code>job_links</code> Taxonomy field to save/load terms)</p>\n<p><a href=\"https://yoursite.com/jobs?service=web-developer\" rel=\"nofollow noreferrer\">https://yoursite.com/jobs?service=web-developer</a><br/>\n<a href=\"https://yoursite.com/jobs?service=web-designer\" rel=\"nofollow noreferrer\">https://yoursite.com/jobs?service=web-designer</a></p>\n<br/>\n<hr />\n<br/>\n<p>One other thing, i'm not sure of your level of php, but the above could be so much more if you used object oriented php classes. The above code is for your basic <code>function.php</code> user. But if you know how to use php classes then let me know and I can update code to object oriented class format.</p>\n"
},
{
"answer_id": 370583,
"author": "Chevax",
"author_id": 191221,
"author_profile": "https://wordpress.stackexchange.com/users/191221",
"pm_score": 0,
"selected": false,
"text": "<p>I wish to express my gratitude for the time spent answering my question.</p>\n<p>Your answer is very pedagogical, clear and precise.</p>\n<p>I didn't expect as much...</p>\n<p>Even if I don't have a high level in PHP, I managed to deploy your solution.</p>\n<p>Thanks again @joshmoto</p>\n"
}
] | 2020/06/26 | [
"https://wordpress.stackexchange.com/questions/369860",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/190618/"
] | I am guessing this is being caused by my nginx configuration, however I can not quite figure out how to troubleshoot in order to resolve.
I am using Ubuntu 20.04 with a LEMP stack to host a wordpress installation. Everything works fine except this quirk, which is that if I type in the site's URL into Chrome, the site will resolve to 'https://example.com' and everything on the site loads fine.
However, in Firefox if I type in the site's URL it will resolve to 'https://www.example.com', which would be fine except that certain icons on the site will now not load, are not show and are replaced by a square box.
Below is the nginx configuration I am using:
```
server {
listen 80;
server_name www.{{ domain_name }}{{ tld }} {{ domain_name }}{{ tld }};
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl;
server_name www.{{ domain_name }}{{ tld }};
ssl_certificate /etc/letsencrypt/certs/fullchain_{{ domain_name }};
ssl_certificate_key /etc/letsencrypt/keys/{{ domain_name }}.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers ECDHE-RSA-AES256-SHA384:AES256-SHA256:RC4:HIGH:!MD5:!aNULL:!EDH:!AESGCM;
# ssl_ecdh_curve secp521r1;
root /home/{{ domain_name }}/public_html;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ /index.php?q=$uri&$args;
}
# return 301 https://www.$server_name$request_uri;
location ~ \.php$ {
# Basic
try_files $uri =404;
fastcgi_index index.php;
# Create a no cache flag
set $no_cache "";
# Don't ever cache POSTs
if ($request_method = POST) {
set $no_cache 1;
}
# Admin stuff should not be cached
if ($request_uri ~* "/(wp-admin/|wp-login.php)") {
set $no_cache 1;
}
# WooCommerce stuff should not be cached
if ($request_uri ~* "/store.*|/cart.*|/my-account.*|/checkout.*|/addons.*") {
set $no_cache 1;
}
# If we are the admin, make sure nothing
# gets cached, so no weird stuff will happen
if ($http_cookie ~* "wordpress_logged_in_") {
set $no_cache 1;
}
# Cache and cache bypass handling
fastcgi_no_cache $no_cache;
fastcgi_cache_bypass $no_cache;
fastcgi_cache microcache;
fastcgi_cache_key $scheme$request_method$server_name$request_uri$args;
fastcgi_cache_valid 200 60m;
fastcgi_cache_valid 404 10m;
fastcgi_cache_use_stale updating;
# General FastCGI handling
fastcgi_pass unix:/var/run/php/{{ domain_name }}.sock;
fastcgi_pass_header Set-Cookie;
fastcgi_pass_header Cookie;
fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_param SCRIPT_FILENAME $request_filename;
fastcgi_intercept_errors on;
include fastcgi_params;
}
location ~* \.(js|css|png|jpg|jpeg|gif|ico|woff|ttf|svg|otf)$ {
expires 30d;
add_header Pragma public;
add_header Cache-Control "public";
access_log off;
}
}
``` | OK so I have had this problem with searching custom fields data.
The thing is with the native Wordpress search, is that is really good, fast and powerful, but it's limitations is that it only searches the `wp_posts` table. It does **not** frickin' query the `wp_postmeta` table!
So to make the most of the native Wordpress search, what you can do is tailor the exact search terms you want to be searchable by saving specific searchable custom field data to the native `post_content` as a json encoded array.
If you are already using the native `post_content` field (in `wp_posts` table) for general job profile guff (in cpt `job`), then just migrate this data to a `ACF Wysiwyg Editor` field with the field name `job_post_content`. This new ACF version of `post_content` won't be searchable now. Which is probably a good thing in your situation, as you will have job profile nonsense, which you probably don't want to be picked up in the job search query anyway. If you still want this content searchable then you can still include this data in our searchable json array, if you wish (i've not shown this but it is simple to include).
So for storing any searchable data in native `post_content`, this is where the magic happens. Follow my comments in code...
Add this to your `functions.php`
```
// process cpt job post when saving or updating job post
add_action('acf/save_post', 'acf_save_job', 20);
/**
* action to run modifications when saving or updating the job
* @param int $post_id
* @return void
*/
function acf_save_job($post_id) {
// get our current global post object
global $post;
// check we are on the cpt job else return now
if($post->post_type <> 'job') return;
// if job post status is publish or draft
if($post->post_status == 'publish' || $post->post_status == 'draft') {
// create job object from current post object
$job = $post;
// set an empty searchable data array
$searchable_job_data = [];
// we dont need to add the native post title for cpt job as this is already searchable
// get our secondary title
$secondary_title = get_field('secondary_title',$post_id);
// if secondary title exists
if($secondary_title) {
// add secondary title to searchable data array
$searchable_job_data['stitle'] = $secondary_title;
}
// get our job links post object field, acf must return this field as post object
$job_links = get_field('job_links',$post_id);
// I am assuming you are allowing multiple job links to be selected in job post admin...
// so we have to loop through each array object and get the job link post title
// if job links var is an array
if(is_array($job_links)) {
// foreach job link item as job object
foreach ($job_links as $key => $job_link_object) {
// if job link object has post title
if($job_link_object->post_title) {
// add job link title to our searchable data array
$searchable_job_data['jlinks'][] = $job_link_object->post_title;
}
}
}
// add more searchable data to $searchable_job_array here if you wish
// convert our searchable data array to json
$searchable_job_json = json_encode($searchable_job_data,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
// temp remove the save job action
remove_action('acf/save_post','acf_save_job',20);
// update our native job post content with searchable data
$job->post_content = $searchable_job_json;
// update the current job with new job data
wp_update_post($job);
// re add the save job action
add_action('acf/save_post', 'acf_save_job', 20);
}
}
```
So when you create or save a cpt job post, you will notice the native `post_content` now contains something like this (as an unformatted string)...
```
{
"stitle": "Front-end developer",
"jlinks": [
"Web developer",
"Web designer"
]
}
```
Using cpt or acf you can hide the native post content visually from your admin job post page, but the search data will still exist in the database.
**After looking at your custom jobs page, would it not be better to turn `job_links`, to a taxonomy, rather than a post type. So you can also filter by jobs by selecting job link/service. In my custom jobs archive page example (below) I will also demonstrate this...**
Here is a search form html to search jobs only, this can go in your `header.php` or anywhere...
```
<form action="/jobs" method="get">
<input type="search" name="search" placeholder="Search jobs" />
</form>
```
Here is some jobs query functions to add to your `functions.php`...
```
/**
* simple method to get request parameter value
* @param mixed $name key name to find
* @param mixed $default default value if no value is found
* @return mixed
*/
function get_url_var($name = false, $default = false)
{
// if name is false
if($name === false) {
return $_REQUEST;
}
// request name var name is set
if(isset($_REQUEST[$name])) {
return $_REQUEST[$name];
}
// return default
return $default;
}
/**
* job custom archive page query
* @return array
*/
function job_query() {
// some vars
$jobs_per_page = 24;
// check url for these filter keys and get value
$job_search = get_url_var('search',false);
$job_link = get_url_var('service',false);
// add more url parameter filters here
// build our jobs query
$job_query = [
'post_type' => 'job',
'post_status' => 'publish',
'posts_per_page' => $jobs_per_page,
'orderby' => 'ASC',
'tax_query' => [
'relation' => 'AND'
]
];
// filter by search query
if($job_search) {
// extend our jobs query with search
$job_query['s'] = $job_search;
}
// if you convert job_links to taxonomy then...
// filter by job link taxonomy term slug (service)
if($job_link) {
// extend our tax query array
$job_query['tax_query'][] = [
'taxonomy' => 'job_link',
'field' => 'slug',
'terms' => [ ],
];
}
return $job_query;
}
```
Now create a page called **Jobs** with page slug/name `jobs`. Then create a php page template called `page-jobs.php` in your theme root, and then add the below php to it...
```
<?php
// products wp query
$jobs = new WP_Query(job_query());
// get our page header
get_header();
?>
<main>
<?php if($jobs->have_posts()): ?>
<?php while($jobs->have_posts()): $jobs->the_post() ?>
<article id="job-<?=get_the_ID()?>">
<?php the_title(); ?>
<?php the_field('secondary_title'); ?>
<?php the_field('jobs_links'); ?>
</article>
<?php endwhile; ?>
<?php else: ?>
No jobs found matching criteria.
<?php endif; ?>
</main>
<?php
// get our footer
get_footer();
```
Now run some search tests with the url format below, or alternatively use the html search form...
<https://yoursite.com/jobs?search=designer>
Also if you converted your `job_links` post type to a taxonomy then you can filter cpt jobs like this... (obviously only if you set the ACF `job_links` Taxonomy field to save/load terms)
<https://yoursite.com/jobs?service=web-developer>
<https://yoursite.com/jobs?service=web-designer>
---
One other thing, i'm not sure of your level of php, but the above could be so much more if you used object oriented php classes. The above code is for your basic `function.php` user. But if you know how to use php classes then let me know and I can update code to object oriented class format. |
369,887 | <p>I'm new to wordpress development.</p>
<p>I'm trying to develop a simple plugin for practice. It involves a form submission from the frontend. The form has an input with the following code.</p>
<pre><code><input type='hidden' name='test' value='{"id": 1}'/>
</code></pre>
<p>When I submit the form, the value of 'test' field gets altered after the "init" hook.</p>
<p>My plugin code looks like the following</p>
<pre><code>add_action('init', [$this, 'init']);
function init() {
printe_r($_POST);
}
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>Array
(
[test] => {\"id\":1}
)
</code></pre>
<p>The problem is that <strong>json_decode</strong> errors out. I have to use <strong>stripslashes</strong> like below to decode the json string.</p>
<pre><code>json_decode(stripslashes($_POST['test']));
</code></pre>
<p>Is this behavior expected in Wordpress?</p>
| [
{
"answer_id": 370380,
"author": "joshmoto",
"author_id": 111152,
"author_profile": "https://wordpress.stackexchange.com/users/111152",
"pm_score": 1,
"selected": false,
"text": "<p>OK so I have had this problem with searching custom fields data.</p>\n<p>The thing is with the native Wordpress search, is that is really good, fast and powerful, but it's limitations is that it only searches the <code>wp_posts</code> table. It does <strong>not</strong> frickin' query the <code>wp_postmeta</code> table!</p>\n<p>So to make the most of the native Wordpress search, what you can do is tailor the exact search terms you want to be searchable by saving specific searchable custom field data to the native <code>post_content</code> as a json encoded array.</p>\n<p>If you are already using the native <code>post_content</code> field (in <code>wp_posts</code> table) for general job profile guff (in cpt <code>job</code>), then just migrate this data to a <code>ACF Wysiwyg Editor</code> field with the field name <code>job_post_content</code>. This new ACF version of <code>post_content</code> won't be searchable now. Which is probably a good thing in your situation, as you will have job profile nonsense, which you probably don't want to be picked up in the job search query anyway. If you still want this content searchable then you can still include this data in our searchable json array, if you wish (i've not shown this but it is simple to include).</p>\n<br/>\n<p>So for storing any searchable data in native <code>post_content</code>, this is where the magic happens. Follow my comments in code...</p>\n<p>Add this to your <code>functions.php</code></p>\n<pre><code>// process cpt job post when saving or updating job post\nadd_action('acf/save_post', 'acf_save_job', 20);\n\n/**\n * action to run modifications when saving or updating the job\n * @param int $post_id\n * @return void\n */\nfunction acf_save_job($post_id) {\n\n // get our current global post object\n global $post;\n\n // check we are on the cpt job else return now\n if($post->post_type <> 'job') return;\n\n // if job post status is publish or draft\n if($post->post_status == 'publish' || $post->post_status == 'draft') {\n\n // create job object from current post object\n $job = $post;\n\n // set an empty searchable data array\n $searchable_job_data = [];\n\n // we dont need to add the native post title for cpt job as this is already searchable\n\n // get our secondary title\n $secondary_title = get_field('secondary_title',$post_id);\n\n // if secondary title exists\n if($secondary_title) {\n\n // add secondary title to searchable data array\n $searchable_job_data['stitle'] = $secondary_title;\n\n }\n\n // get our job links post object field, acf must return this field as post object\n $job_links = get_field('job_links',$post_id);\n\n // I am assuming you are allowing multiple job links to be selected in job post admin...\n // so we have to loop through each array object and get the job link post title\n\n // if job links var is an array\n if(is_array($job_links)) {\n\n // foreach job link item as job object\n foreach ($job_links as $key => $job_link_object) {\n\n // if job link object has post title\n if($job_link_object->post_title) {\n\n // add job link title to our searchable data array\n $searchable_job_data['jlinks'][] = $job_link_object->post_title;\n\n }\n\n }\n\n }\n \n // add more searchable data to $searchable_job_array here if you wish\n\n // convert our searchable data array to json\n $searchable_job_json = json_encode($searchable_job_data,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);\n\n // temp remove the save job action\n remove_action('acf/save_post','acf_save_job',20);\n\n // update our native job post content with searchable data\n $job->post_content = $searchable_job_json;\n \n // update the current job with new job data\n wp_update_post($job);\n\n // re add the save job action\n add_action('acf/save_post', 'acf_save_job', 20);\n\n }\n\n}\n</code></pre>\n<br/>\n<p>So when you create or save a cpt job post, you will notice the native <code>post_content</code> now contains something like this (as an unformatted string)...</p>\n<pre><code>{\n "stitle": "Front-end developer",\n "jlinks": [\n "Web developer",\n "Web designer"\n ]\n} \n</code></pre>\n<p>Using cpt or acf you can hide the native post content visually from your admin job post page, but the search data will still exist in the database.</p>\n<br/>\n<p><strong>After looking at your custom jobs page, would it not be better to turn <code>job_links</code>, to a taxonomy, rather than a post type. So you can also filter by jobs by selecting job link/service. In my custom jobs archive page example (below) I will also demonstrate this...</strong></p>\n<br/>\n<p>Here is a search form html to search jobs only, this can go in your <code>header.php</code> or anywhere...</p>\n<pre><code><form action="/jobs" method="get">\n <input type="search" name="search" placeholder="Search jobs" />\n</form>\n</code></pre>\n<br/>\n<p>Here is some jobs query functions to add to your <code>functions.php</code>...</p>\n<pre><code>/**\n * simple method to get request parameter value\n * @param mixed $name key name to find\n * @param mixed $default default value if no value is found\n * @return mixed\n */\nfunction get_url_var($name = false, $default = false)\n{\n // if name is false\n if($name === false) {\n return $_REQUEST;\n }\n // request name var name is set\n if(isset($_REQUEST[$name])) {\n return $_REQUEST[$name];\n }\n // return default\n return $default;\n}\n\n/**\n * job custom archive page query\n * @return array\n */\nfunction job_query() {\n\n // some vars\n $jobs_per_page = 24;\n\n // check url for these filter keys and get value\n $job_search = get_url_var('search',false);\n $job_link = get_url_var('service',false);\n // add more url parameter filters here\n\n // build our jobs query\n $job_query = [\n 'post_type' => 'job',\n 'post_status' => 'publish',\n 'posts_per_page' => $jobs_per_page,\n 'orderby' => 'ASC',\n 'tax_query' => [\n 'relation' => 'AND'\n ]\n ];\n\n // filter by search query\n if($job_search) {\n // extend our jobs query with search\n $job_query['s'] = $job_search;\n }\n\n // if you convert job_links to taxonomy then...\n // filter by job link taxonomy term slug (service)\n if($job_link) {\n // extend our tax query array\n $job_query['tax_query'][] = [\n 'taxonomy' => 'job_link',\n 'field' => 'slug',\n 'terms' => [ ],\n ];\n }\n\n return $job_query;\n\n}\n</code></pre>\n<br/>\n<p>Now create a page called <strong>Jobs</strong> with page slug/name <code>jobs</code>. Then create a php page template called <code>page-jobs.php</code> in your theme root, and then add the below php to it...</p>\n<pre><code><?php\n\n// products wp query\n$jobs = new WP_Query(job_query());\n\n// get our page header\nget_header();\n\n?>\n <main>\n <?php if($jobs->have_posts()): ?>\n <?php while($jobs->have_posts()): $jobs->the_post() ?>\n <article id="job-<?=get_the_ID()?>">\n <?php the_title(); ?>\n <?php the_field('secondary_title'); ?>\n <?php the_field('jobs_links'); ?>\n </article>\n <?php endwhile; ?>\n <?php else: ?>\n No jobs found matching criteria.\n <?php endif; ?>\n </main>\n<?php\n\n// get our footer\nget_footer();\n</code></pre>\n<br/>\n<p>Now run some search tests with the url format below, or alternatively use the html search form...</p>\n<p><a href=\"https://yoursite.com/jobs?search=designer\" rel=\"nofollow noreferrer\">https://yoursite.com/jobs?search=designer</a></p>\n<p>Also if you converted your <code>job_links</code> post type to a taxonomy then you can filter cpt jobs like this... (obviously only if you set the ACF <code>job_links</code> Taxonomy field to save/load terms)</p>\n<p><a href=\"https://yoursite.com/jobs?service=web-developer\" rel=\"nofollow noreferrer\">https://yoursite.com/jobs?service=web-developer</a><br/>\n<a href=\"https://yoursite.com/jobs?service=web-designer\" rel=\"nofollow noreferrer\">https://yoursite.com/jobs?service=web-designer</a></p>\n<br/>\n<hr />\n<br/>\n<p>One other thing, i'm not sure of your level of php, but the above could be so much more if you used object oriented php classes. The above code is for your basic <code>function.php</code> user. But if you know how to use php classes then let me know and I can update code to object oriented class format.</p>\n"
},
{
"answer_id": 370583,
"author": "Chevax",
"author_id": 191221,
"author_profile": "https://wordpress.stackexchange.com/users/191221",
"pm_score": 0,
"selected": false,
"text": "<p>I wish to express my gratitude for the time spent answering my question.</p>\n<p>Your answer is very pedagogical, clear and precise.</p>\n<p>I didn't expect as much...</p>\n<p>Even if I don't have a high level in PHP, I managed to deploy your solution.</p>\n<p>Thanks again @joshmoto</p>\n"
}
] | 2020/06/27 | [
"https://wordpress.stackexchange.com/questions/369887",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/190692/"
] | I'm new to wordpress development.
I'm trying to develop a simple plugin for practice. It involves a form submission from the frontend. The form has an input with the following code.
```
<input type='hidden' name='test' value='{"id": 1}'/>
```
When I submit the form, the value of 'test' field gets altered after the "init" hook.
My plugin code looks like the following
```
add_action('init', [$this, 'init']);
function init() {
printe_r($_POST);
}
```
**Output:**
```
Array
(
[test] => {\"id\":1}
)
```
The problem is that **json\_decode** errors out. I have to use **stripslashes** like below to decode the json string.
```
json_decode(stripslashes($_POST['test']));
```
Is this behavior expected in Wordpress? | OK so I have had this problem with searching custom fields data.
The thing is with the native Wordpress search, is that is really good, fast and powerful, but it's limitations is that it only searches the `wp_posts` table. It does **not** frickin' query the `wp_postmeta` table!
So to make the most of the native Wordpress search, what you can do is tailor the exact search terms you want to be searchable by saving specific searchable custom field data to the native `post_content` as a json encoded array.
If you are already using the native `post_content` field (in `wp_posts` table) for general job profile guff (in cpt `job`), then just migrate this data to a `ACF Wysiwyg Editor` field with the field name `job_post_content`. This new ACF version of `post_content` won't be searchable now. Which is probably a good thing in your situation, as you will have job profile nonsense, which you probably don't want to be picked up in the job search query anyway. If you still want this content searchable then you can still include this data in our searchable json array, if you wish (i've not shown this but it is simple to include).
So for storing any searchable data in native `post_content`, this is where the magic happens. Follow my comments in code...
Add this to your `functions.php`
```
// process cpt job post when saving or updating job post
add_action('acf/save_post', 'acf_save_job', 20);
/**
* action to run modifications when saving or updating the job
* @param int $post_id
* @return void
*/
function acf_save_job($post_id) {
// get our current global post object
global $post;
// check we are on the cpt job else return now
if($post->post_type <> 'job') return;
// if job post status is publish or draft
if($post->post_status == 'publish' || $post->post_status == 'draft') {
// create job object from current post object
$job = $post;
// set an empty searchable data array
$searchable_job_data = [];
// we dont need to add the native post title for cpt job as this is already searchable
// get our secondary title
$secondary_title = get_field('secondary_title',$post_id);
// if secondary title exists
if($secondary_title) {
// add secondary title to searchable data array
$searchable_job_data['stitle'] = $secondary_title;
}
// get our job links post object field, acf must return this field as post object
$job_links = get_field('job_links',$post_id);
// I am assuming you are allowing multiple job links to be selected in job post admin...
// so we have to loop through each array object and get the job link post title
// if job links var is an array
if(is_array($job_links)) {
// foreach job link item as job object
foreach ($job_links as $key => $job_link_object) {
// if job link object has post title
if($job_link_object->post_title) {
// add job link title to our searchable data array
$searchable_job_data['jlinks'][] = $job_link_object->post_title;
}
}
}
// add more searchable data to $searchable_job_array here if you wish
// convert our searchable data array to json
$searchable_job_json = json_encode($searchable_job_data,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
// temp remove the save job action
remove_action('acf/save_post','acf_save_job',20);
// update our native job post content with searchable data
$job->post_content = $searchable_job_json;
// update the current job with new job data
wp_update_post($job);
// re add the save job action
add_action('acf/save_post', 'acf_save_job', 20);
}
}
```
So when you create or save a cpt job post, you will notice the native `post_content` now contains something like this (as an unformatted string)...
```
{
"stitle": "Front-end developer",
"jlinks": [
"Web developer",
"Web designer"
]
}
```
Using cpt or acf you can hide the native post content visually from your admin job post page, but the search data will still exist in the database.
**After looking at your custom jobs page, would it not be better to turn `job_links`, to a taxonomy, rather than a post type. So you can also filter by jobs by selecting job link/service. In my custom jobs archive page example (below) I will also demonstrate this...**
Here is a search form html to search jobs only, this can go in your `header.php` or anywhere...
```
<form action="/jobs" method="get">
<input type="search" name="search" placeholder="Search jobs" />
</form>
```
Here is some jobs query functions to add to your `functions.php`...
```
/**
* simple method to get request parameter value
* @param mixed $name key name to find
* @param mixed $default default value if no value is found
* @return mixed
*/
function get_url_var($name = false, $default = false)
{
// if name is false
if($name === false) {
return $_REQUEST;
}
// request name var name is set
if(isset($_REQUEST[$name])) {
return $_REQUEST[$name];
}
// return default
return $default;
}
/**
* job custom archive page query
* @return array
*/
function job_query() {
// some vars
$jobs_per_page = 24;
// check url for these filter keys and get value
$job_search = get_url_var('search',false);
$job_link = get_url_var('service',false);
// add more url parameter filters here
// build our jobs query
$job_query = [
'post_type' => 'job',
'post_status' => 'publish',
'posts_per_page' => $jobs_per_page,
'orderby' => 'ASC',
'tax_query' => [
'relation' => 'AND'
]
];
// filter by search query
if($job_search) {
// extend our jobs query with search
$job_query['s'] = $job_search;
}
// if you convert job_links to taxonomy then...
// filter by job link taxonomy term slug (service)
if($job_link) {
// extend our tax query array
$job_query['tax_query'][] = [
'taxonomy' => 'job_link',
'field' => 'slug',
'terms' => [ ],
];
}
return $job_query;
}
```
Now create a page called **Jobs** with page slug/name `jobs`. Then create a php page template called `page-jobs.php` in your theme root, and then add the below php to it...
```
<?php
// products wp query
$jobs = new WP_Query(job_query());
// get our page header
get_header();
?>
<main>
<?php if($jobs->have_posts()): ?>
<?php while($jobs->have_posts()): $jobs->the_post() ?>
<article id="job-<?=get_the_ID()?>">
<?php the_title(); ?>
<?php the_field('secondary_title'); ?>
<?php the_field('jobs_links'); ?>
</article>
<?php endwhile; ?>
<?php else: ?>
No jobs found matching criteria.
<?php endif; ?>
</main>
<?php
// get our footer
get_footer();
```
Now run some search tests with the url format below, or alternatively use the html search form...
<https://yoursite.com/jobs?search=designer>
Also if you converted your `job_links` post type to a taxonomy then you can filter cpt jobs like this... (obviously only if you set the ACF `job_links` Taxonomy field to save/load terms)
<https://yoursite.com/jobs?service=web-developer>
<https://yoursite.com/jobs?service=web-designer>
---
One other thing, i'm not sure of your level of php, but the above could be so much more if you used object oriented php classes. The above code is for your basic `function.php` user. But if you know how to use php classes then let me know and I can update code to object oriented class format. |
369,902 | <p>I am creating wordpress theme on a single options page. I have customized the default do_settings_fields and do_settings_sections functions. my fields are displaying fine but when i am trying to save it, It won't save.</p>
<pre><code>function amna_theme_options_page () {
wp_enqueue_style( 'theme-options-css', get_template_directory_uri() . '/inc/admin/assets/css/theme-options-css.css' );
settings_errors();
?>
<div class="wrap flex-tab">
<form action='' method='post' class="amna-fields">
<?php
amna_do_settings_fields('amna-fields-group', 'theme_amna');
amna_do_settings_sections('theme_amna');
submit_button();
?>
</form>
</div>
<?php }
</code></pre>
<p>And these are the functions i have override to display fields</p>
<pre><code>function amna_do_settings_sections($page) {
global $wp_settings_sections, $wp_settings_fields;
if ( !isset($wp_settings_sections) || !isset($wp_settings_sections[$page]) )
return;
foreach( (array) $wp_settings_sections[$page] as $section ) {
echo "<h3>{$section['title']}</h3>\n";
call_user_func($section['callback'], $section);
if ( !isset($wp_settings_fields) ||
!isset($wp_settings_fields[$page]) ||
!isset($wp_settings_fields[$page][$section['id']]) )
continue;
echo '<div class="settings-form-wrapper">';
amna_do_settings_fields($page, $section['id']);
echo '</div>';
}
}
function amna_do_settings_fields($page, $section) {
global $wp_settings_fields;
if ( ! isset( $wp_settings_fields[ $page ][ $section ] ) ) {
return;
}
foreach ( (array) $wp_settings_fields[$page][$section] as $field ) { ?>
<div class="settings-form-row flex-tab">
<?php if ( !empty($field['args']['label_for']) )
echo '<p><label for="' . $field['args']['label_for'] . '">' .
$field['title'] . '</label><br />';
else
call_user_func($field['callback'], $field['args']);
echo '</p>';
echo '</div>';
}
}
</code></pre>
| [
{
"answer_id": 370011,
"author": "Atif Aqeel",
"author_id": 136891,
"author_profile": "https://wordpress.stackexchange.com/users/136891",
"pm_score": 0,
"selected": false,
"text": "<p>I am posting answer of my own question because of people reference and did not find solution anywhere.</p>\n<p>Basically if you are changing default do_settings_section(); and do_settings_fields(); the submit button will not find where to submit data because default function was override with new one. In Such case you will have to write you submit button function to execute the code and save the fields data into the database.</p>\n<p>So instead of submit_button(); i have write my button</p>\n<pre><code><p class="submit"><input type="submit" class="button-primary" value="<?php _e( 'Save changes', 'amna_save_settings' ); ?>" /></p>\n</code></pre>\n<p>Then on save button code</p>\n<pre><code>if(($_SERVER['REQUEST_METHOD'] == 'POST') && (isset($_POST['amna_fields']))) {\n update_site_option( 'amna_fields', $_POST['amna_fields'] );\n}\n</code></pre>\n"
},
{
"answer_id": 370053,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 3,
"selected": true,
"text": "<p>So I could understand why you "customized" (i.e. use your own version of) the <a href=\"https://developer.wordpress.org/reference/functions/do_settings_sections/\" rel=\"nofollow noreferrer\"><code>do_settings_sections()</code></a> and <a href=\"https://developer.wordpress.org/reference/functions/do_settings_fields/\" rel=\"nofollow noreferrer\"><code>do_settings_fields()</code></a> functions — because you want to use <code>div</code> and not <code>table</code>, right?</p>\n<p>But if it's just about styling, you could actually just use CSS to style the table so that it doesn't look like a table; however, you'll have to try doing that on your own. And WordPress may change the global variables (their name and/or data structure) in the future, so just keep that in mind, i.e. you'll have to make sure that your code is in sync with the original functions in the current WordPress release.</p>\n<h2>Making your form works properly (e.g. the fields are saved in the correct database option)</h2>\n<p>As I said in the comments, your form should submit to <code>options.php</code> (i.e. <code><form action="options.php" ...></code>) and call <a href=\"https://developer.wordpress.org/reference/functions/register_setting/\" rel=\"nofollow noreferrer\"><code>register_setting()</code></a> in your code to register your form or its settings group, and the <em>database</em> option (the second parameter for that function).</p>\n<p>And in the <code>amna_theme_options_page()</code>, there's no need to call the <code>amna_do_settings_fields()</code> because it's already being called in and should only be called in <code>amna_do_settings_sections()</code> which renders all the fields for your settings form, whereby each field should belong in a specific section. So instead, call <a href=\"https://developer.wordpress.org/reference/functions/settings_fields/\" rel=\"nofollow noreferrer\"><code>settings_fields()</code></a> so that WordPress knows what the options/settings page is and the database option to be updated:</p>\n<pre class=\"lang-php prettyprint-override\"><code>settings_fields( 'amna-fields-group' ); // do this\n//amna_do_settings_fields('amna-fields-group', 'theme_amna'); // not this\n</code></pre>\n<p>Another issue I noticed is that in <code>amna_do_settings_fields()</code>, if the <code>label_for</code> arg is <em>not</em> empty, then the field is not actually going to be rendered because the <code>call_user_func()</code> is only being called in the <code>else</code> part.</p>\n<p>So it should be more like so:</p>\n<pre class=\"lang-php prettyprint-override\"><code>echo '<p>';\nif ( ! empty( $field['args']['label_for'] ) ) {\n echo '<label for="' . esc_attr( $field['args']['label_for'] ) . '">' . $field['title'] . '</label>';\n} else {\n echo $field['title'];\n}\n\ncall_user_func( $field['callback'], $field['args'] );\necho '</p>';\n</code></pre>\n<p>Additionally, you should pass the slug of your settings page to <a href=\"https://developer.wordpress.org/reference/functions/settings_errors/\" rel=\"nofollow noreferrer\"><code>settings_errors()</code></a>, e.g. <code>settings_errors( 'theme_amna' );</code> if the slug is <code>theme_amna</code>. And if you don't do that, then you'd likely see the same settings errors/messages printed <em>twice</em>.</p>\n<p>Also, admin stylesheet files (<code>.css</code>) should be enqueued via the <a href=\"https://developer.wordpress.org/reference/hooks/admin_enqueue_scripts/\" rel=\"nofollow noreferrer\"><code>admin_enqueue_scripts</code> hook</a>. For example, to enqueue only on your settings page:</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'admin_enqueue_scripts', 'my_plugin_load_styles' );\nfunction my_plugin_load_styles( $hook_suffix ) {\n if ( $hook_suffix === get_plugin_page_hook( 'theme_amna', '' ) ) {\n wp_enqueue_style( 'theme-options-css',\n get_template_directory_uri() . '/inc/admin/assets/css/theme-options-css.css' );\n }\n}\n</code></pre>\n<h2>Working Example</h2>\n<p><a href=\"https://gist.github.com/5ally/776c5291b0f826ea17ef4b8467c12c48\" rel=\"nofollow noreferrer\">You can find it on GitHub</a>.</p>\n<p>It's a full working example which gives you a settings page at <em>Settings → Test</em>.</p>\n"
}
] | 2020/06/27 | [
"https://wordpress.stackexchange.com/questions/369902",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/136891/"
] | I am creating wordpress theme on a single options page. I have customized the default do\_settings\_fields and do\_settings\_sections functions. my fields are displaying fine but when i am trying to save it, It won't save.
```
function amna_theme_options_page () {
wp_enqueue_style( 'theme-options-css', get_template_directory_uri() . '/inc/admin/assets/css/theme-options-css.css' );
settings_errors();
?>
<div class="wrap flex-tab">
<form action='' method='post' class="amna-fields">
<?php
amna_do_settings_fields('amna-fields-group', 'theme_amna');
amna_do_settings_sections('theme_amna');
submit_button();
?>
</form>
</div>
<?php }
```
And these are the functions i have override to display fields
```
function amna_do_settings_sections($page) {
global $wp_settings_sections, $wp_settings_fields;
if ( !isset($wp_settings_sections) || !isset($wp_settings_sections[$page]) )
return;
foreach( (array) $wp_settings_sections[$page] as $section ) {
echo "<h3>{$section['title']}</h3>\n";
call_user_func($section['callback'], $section);
if ( !isset($wp_settings_fields) ||
!isset($wp_settings_fields[$page]) ||
!isset($wp_settings_fields[$page][$section['id']]) )
continue;
echo '<div class="settings-form-wrapper">';
amna_do_settings_fields($page, $section['id']);
echo '</div>';
}
}
function amna_do_settings_fields($page, $section) {
global $wp_settings_fields;
if ( ! isset( $wp_settings_fields[ $page ][ $section ] ) ) {
return;
}
foreach ( (array) $wp_settings_fields[$page][$section] as $field ) { ?>
<div class="settings-form-row flex-tab">
<?php if ( !empty($field['args']['label_for']) )
echo '<p><label for="' . $field['args']['label_for'] . '">' .
$field['title'] . '</label><br />';
else
call_user_func($field['callback'], $field['args']);
echo '</p>';
echo '</div>';
}
}
``` | So I could understand why you "customized" (i.e. use your own version of) the [`do_settings_sections()`](https://developer.wordpress.org/reference/functions/do_settings_sections/) and [`do_settings_fields()`](https://developer.wordpress.org/reference/functions/do_settings_fields/) functions — because you want to use `div` and not `table`, right?
But if it's just about styling, you could actually just use CSS to style the table so that it doesn't look like a table; however, you'll have to try doing that on your own. And WordPress may change the global variables (their name and/or data structure) in the future, so just keep that in mind, i.e. you'll have to make sure that your code is in sync with the original functions in the current WordPress release.
Making your form works properly (e.g. the fields are saved in the correct database option)
------------------------------------------------------------------------------------------
As I said in the comments, your form should submit to `options.php` (i.e. `<form action="options.php" ...>`) and call [`register_setting()`](https://developer.wordpress.org/reference/functions/register_setting/) in your code to register your form or its settings group, and the *database* option (the second parameter for that function).
And in the `amna_theme_options_page()`, there's no need to call the `amna_do_settings_fields()` because it's already being called in and should only be called in `amna_do_settings_sections()` which renders all the fields for your settings form, whereby each field should belong in a specific section. So instead, call [`settings_fields()`](https://developer.wordpress.org/reference/functions/settings_fields/) so that WordPress knows what the options/settings page is and the database option to be updated:
```php
settings_fields( 'amna-fields-group' ); // do this
//amna_do_settings_fields('amna-fields-group', 'theme_amna'); // not this
```
Another issue I noticed is that in `amna_do_settings_fields()`, if the `label_for` arg is *not* empty, then the field is not actually going to be rendered because the `call_user_func()` is only being called in the `else` part.
So it should be more like so:
```php
echo '<p>';
if ( ! empty( $field['args']['label_for'] ) ) {
echo '<label for="' . esc_attr( $field['args']['label_for'] ) . '">' . $field['title'] . '</label>';
} else {
echo $field['title'];
}
call_user_func( $field['callback'], $field['args'] );
echo '</p>';
```
Additionally, you should pass the slug of your settings page to [`settings_errors()`](https://developer.wordpress.org/reference/functions/settings_errors/), e.g. `settings_errors( 'theme_amna' );` if the slug is `theme_amna`. And if you don't do that, then you'd likely see the same settings errors/messages printed *twice*.
Also, admin stylesheet files (`.css`) should be enqueued via the [`admin_enqueue_scripts` hook](https://developer.wordpress.org/reference/hooks/admin_enqueue_scripts/). For example, to enqueue only on your settings page:
```php
add_action( 'admin_enqueue_scripts', 'my_plugin_load_styles' );
function my_plugin_load_styles( $hook_suffix ) {
if ( $hook_suffix === get_plugin_page_hook( 'theme_amna', '' ) ) {
wp_enqueue_style( 'theme-options-css',
get_template_directory_uri() . '/inc/admin/assets/css/theme-options-css.css' );
}
}
```
Working Example
---------------
[You can find it on GitHub](https://gist.github.com/5ally/776c5291b0f826ea17ef4b8467c12c48).
It's a full working example which gives you a settings page at *Settings → Test*. |
369,941 | <p>How can I add a Notification bubble for <strong>Pending/On Hold/Processing order</strong> on Admin Top Bar?</p>
<p><a href="https://i.stack.imgur.com/oYtZC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oYtZC.png" alt="Like This" /></a></p>
| [
{
"answer_id": 369945,
"author": "Sabbir Hasan",
"author_id": 76587,
"author_profile": "https://wordpress.stackexchange.com/users/76587",
"pm_score": 2,
"selected": true,
"text": "<p>I will get you some idea on how to do this as you didn't mention from where count data will come. Add following code to your theme/child-theme <code>functions.php</code> file</p>\n<pre><code>function custom_admin_bar_menu() {\n $pending_count = wc_orders_count('pending');\n $on_hold_count = wc_orders_count('on-hold');\n $processing_count = wc_orders_count('processing');\n\n if ( current_user_can( 'manage_options' ) ) {\n global $wp_admin_bar;\n\n //Add an icon with count\n $wp_admin_bar->add_menu( array(\n 'id' => 'custom-1', //Change this to yours\n 'title' => '<span class="ab-icon dashicons dashicons-cart"></span><span class="ab-label">'.$pending_count.'</span>',\n 'href' => get_admin_url( NULL, 'edit.php?post_status=wc-pending&post_type=shop_order' ),//Replace with your resired destination\n ) );\n\n //Add another icon with count\n $wp_admin_bar->add_menu( array(\n 'id' => 'custom-2', //Change this to yours\n 'title' => '<span class="ab-icon dashicons dashicons-chart-line"></span><span class="ab-label">'.$on_hold_count.'</span>',\n 'href' => get_admin_url( NULL, 'edit.php?post_status=wc-on-hold&post_type=shop_order' ),//Replace with your resired destination\n ) );\n\n //Add another icon with count\n $wp_admin_bar->add_menu( array(\n 'id' => 'custom-3', //Change this to yours\n 'title' => '<span class="ab-icon dashicons dashicons-carrot"></span><span class="ab-label">'.$processing_count.'</span>',\n 'href' => get_admin_url( NULL, 'edit.php?post_status=wc-processing&post_type=shop_order' ),//Replace with your resired destination\n ) );\n\n //You can add more as per your need.\n }\n}\nadd_action( 'admin_bar_menu', 'custom_admin_bar_menu' , 500 );\n</code></pre>\n<p>The <code>0</code> inside <code><span class="ab-label">0</span></code> represents the count. You can easily replace that by using a variable and some custom query.</p>\n"
},
{
"answer_id": 387100,
"author": "revive",
"author_id": 8645,
"author_profile": "https://wordpress.stackexchange.com/users/8645",
"pm_score": 0,
"selected": false,
"text": "<p>For someone looking for a working example that they can adapt based on the counts they need OR a snippet that works to SHOW UNREAD ENTRIES FROM GRAVITY FORMS ON CUSTOM MENU ITEMS... check this out.</p>\n<p>This snippet gets the count for ALL the form IDs in the array() within the count_entries() call so that the parent menu item shows the count for ALL unread entries</p>\n<p>Then as I build the menu, I change the ID in both the count_entries() call AND the URL - see comments in the snippet. This allows the SUBMENU items to each show the count for their specific unread entries</p>\n<pre><code>function register_my_custom_menu_page() {\n $search_criteria = array(\n 'status' => 'active', //Active forms \n 'field_filters' => array( //which fields to search\n array(\n 'key' => 'is_read', 'value' => false, // let's just get the count for entries that we haven't read yet.\n )\n )\n );\n\n // Add the form IDs to the array below, the parent menu will show ALL unread entries for these forms\n $notification_count = GFAPI::count_entries( array(1,4,5,6,11,13), $search_criteria );\n \n add_menu_page(\n 'Full Quote Form submissions', // Page Title\n // here we're going to use the var $notification_count to get ALL the form IDS and their counts... just for the parent menu item\n $notification_count ? sprintf( 'Quotes <span class="awaiting-mod">%d</span>', $notification_count ) : 'View Quotes',\n 'manage_options', // Capabilities \n 'admin.php?page=gf_entries&id=13', // menu slug\n '', // callback function\n 'dashicons-format-aside', // icon URL\n 6 // position\n );\n add_submenu_page( \n 'admin.php?page=gf_entries&id=13', // this needs to match menu slug of the parent\n 'View Full Quotes', // name of the page\n // The ID on the next line, 13 in this example, matches the form ID in the URL on the LAST line. Notice we're NOT using the var $notification_count from above, as that contains the entry count for ALL the forms\n GFAPI::count_entries( 13, $search_criteria ) ? sprintf( 'Full Quotes <span class="awaiting-mod">%d</span>', GFAPI::count_entries( 13, $search_criteria ) ) : 'Full Quotes',\n 'manage_options', \n // make sure to change the ID on the end of this URL to the form you want to point to, AND make sure it matches the ID two lines above in the count_entries() call\n 'admin.php?page=gf_entries&id=13'\n );\n add_submenu_page( \n 'admin.php?page=gf_entries&id=13', // this needs to match menu slug of the parent\n 'View Short Quotes', // name of the page\n // The ID on the next line, 1 in this example, matches the form ID in the URL on the LAST line. \n GFAPI::count_entries( 1, $search_criteria ) ? sprintf( 'Short Quotes <span class="awaiting-mod">%d</span>', GFAPI::count_entries( 1, $search_criteria ) ) : 'Short Quotes',\n 'manage_options', \n // make sure to change the ID on the end of this URL to the form you want to point to, AND make sure it matches the ID two lines above in the count_entries() call\n 'admin.php?page=gf_entries&id=1'\n );\n add_submenu_page( \n 'admin.php?page=gf_entries&id=13', // this needs to match menu slug of the parent\n 'Sell Your Equipment', // name of the page\n // The ID on the next line, 5 in this example, matches the form ID in the URL on the LAST line. \n GFAPI::count_entries( 5, $search_criteria ) ? sprintf( 'Selling Equip <span class="awaiting-mod">%d</span>', GFAPI::count_entries( 5, $search_criteria ) ) : 'Selling Equip',\n 'manage_options', \n // make sure to change the ID on the end of this URL to the form you want to point to, AND make sure it matches the ID two lines above in the count_entries() call\n 'admin.php?page=gf_entries&id=5'\n );\n add_submenu_page( \n 'admin.php?page=gf_entries&id=13', // this needs to match menu slug of the parent\n 'Equipment Wanted', // name of the page\n // The ID on the next line, 6 in this example, matches the form ID in the URL on the LAST line. \n GFAPI::count_entries( 6, $search_criteria ) ? sprintf( 'Equip Wanted <span class="awaiting-mod">%d</span>', GFAPI::count_entries( 6, $search_criteria ) ) : 'Equip Wanted',\n 'manage_options', \n // make sure to change the ID on the end of this URL to the form you want to point to, AND make sure it matches the ID two lines above in the count_entries() call \n 'admin.php?page=gf_entries&id=6'\n );\n add_submenu_page( \n 'admin.php?page=gf_entries&id=13', // this needs to match menu slug of the parent\n 'Appraisal Requests', // name of the page\n // The ID on the next line, 11 in this example, matches the form ID in the URL on the LAST line. \n GFAPI::count_entries( 11, $search_criteria ) ? sprintf( 'Appraisal Requests <span class="awaiting-mod">%d</span>', GFAPI::count_entries( 11, $search_criteria ) ) : 'Appraisal Requests',\n 'manage_options', \n // make sure to change the ID on the end of this URL to the form you want to point to, AND make sure it matches the ID two lines above in the count_entries() call\n 'admin.php?page=gf_entries&id=11'\n );\n add_submenu_page( \n 'admin.php?page=gf_entries&id=13', // this needs to match menu slug of the parent\n 'Contact Form', // name of the page\n // The ID on the next line, 4 in this example, matches the form ID in the URL on the LAST line. \n GFAPI::count_entries( 4, $search_criteria ) ? sprintf( 'Contact Form <span class="awaiting-mod">%d</span>', GFAPI::count_entries( 4, $search_criteria ) ) : 'Contact Form',\n 'manage_options', \n // make sure to change the ID on the end of this URL to the form you want to point to, AND make sure it matches the ID two lines above in the count_entries() call\n 'admin.php?page=gf_entries&id=4'\n );\n \n}\nadd_action( 'admin_menu', 'register_my_custom_menu_page' );\n</code></pre>\n"
}
] | 2020/06/28 | [
"https://wordpress.stackexchange.com/questions/369941",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/189220/"
] | How can I add a Notification bubble for **Pending/On Hold/Processing order** on Admin Top Bar?
[](https://i.stack.imgur.com/oYtZC.png) | I will get you some idea on how to do this as you didn't mention from where count data will come. Add following code to your theme/child-theme `functions.php` file
```
function custom_admin_bar_menu() {
$pending_count = wc_orders_count('pending');
$on_hold_count = wc_orders_count('on-hold');
$processing_count = wc_orders_count('processing');
if ( current_user_can( 'manage_options' ) ) {
global $wp_admin_bar;
//Add an icon with count
$wp_admin_bar->add_menu( array(
'id' => 'custom-1', //Change this to yours
'title' => '<span class="ab-icon dashicons dashicons-cart"></span><span class="ab-label">'.$pending_count.'</span>',
'href' => get_admin_url( NULL, 'edit.php?post_status=wc-pending&post_type=shop_order' ),//Replace with your resired destination
) );
//Add another icon with count
$wp_admin_bar->add_menu( array(
'id' => 'custom-2', //Change this to yours
'title' => '<span class="ab-icon dashicons dashicons-chart-line"></span><span class="ab-label">'.$on_hold_count.'</span>',
'href' => get_admin_url( NULL, 'edit.php?post_status=wc-on-hold&post_type=shop_order' ),//Replace with your resired destination
) );
//Add another icon with count
$wp_admin_bar->add_menu( array(
'id' => 'custom-3', //Change this to yours
'title' => '<span class="ab-icon dashicons dashicons-carrot"></span><span class="ab-label">'.$processing_count.'</span>',
'href' => get_admin_url( NULL, 'edit.php?post_status=wc-processing&post_type=shop_order' ),//Replace with your resired destination
) );
//You can add more as per your need.
}
}
add_action( 'admin_bar_menu', 'custom_admin_bar_menu' , 500 );
```
The `0` inside `<span class="ab-label">0</span>` represents the count. You can easily replace that by using a variable and some custom query. |
370,057 | <p>Currently I'm writing a WordPress plugin. I would try to re-use variables from a function on different pages. Let's say I would create a function like this:</p>
<pre><code>function test() {
global $hello;
$hello = 'hello world';
}
add_action( 'wp_head', 'test' );
</code></pre>
<p>I can do now on other pages: <code>echo $hello;</code> This is useful for me because I can get information like course settings from my plugin with <code>$course_settings</code>, without rewriting the whole code.</p>
<p>I am not sure of this is the right way to do? Because other plugins could rewrite my variables.</p>
| [
{
"answer_id": 370059,
"author": "DevelJoe",
"author_id": 188571,
"author_profile": "https://wordpress.stackexchange.com/users/188571",
"pm_score": -1,
"selected": false,
"text": "<p>Well if u already use your variable in the global scope, you should also define it in the global scope, not inside the function.</p>\n<p>You can then simply include the php file where u define ur global variable (lets call it source script) into the script u wanna use, with a simple <code>include</code> or <code>require</code> statement before using it. I precisely work like this too in my plugin. However, make sure u prefix such globally used custom variables, by defining them like so:</p>\n<p><code>$your_plugin_name_variable</code></p>\n<p>To avoid naming conflicts with other wp-globals or other globals coming from other plugins.</p>\n<p>If your global variable has a constant content, you could also define it inside a class as <code>public static</code> variable. This is especially recommended if you would like to load several global variables / functions on different pages. They would then all be safely stored under the class name, and you don't need to worry about naming collisions for all of them (just make sure ur class name is unique though). You can then simply use them in your script without the need of instantiating a class object (that's why u may define them as public static).</p>\n<p>If your global has a particular dynamic content for which the first method I explained is not suitable, consider storing it in a database in key value style. Then your source script would simply retrieve its value from the database, and you would then relate the retrieved value to your global variable's name, and include that source script wherever u use it, as in proposition 1.</p>\n<p>I recommend u to use one of these solutions, I actually use all of them with my plugins in function of the respective complexity.</p>\n"
},
{
"answer_id": 370064,
"author": "mozboz",
"author_id": 176814,
"author_profile": "https://wordpress.stackexchange.com/users/176814",
"pm_score": 1,
"selected": true,
"text": "<p>In general programming, globals are bad practice:</p>\n<ul>\n<li>You can't easily look at the use of a global in one place and see all the other uses, e.g. where it was set or will be read later.</li>\n<li>You have many places to change the use of that variable if e.g. the use or format of it changes.</li>\n<li>This makes it hard to make reliable changes to your code and to debug where/who set a global.</li>\n<li>Other code could accidentally write over your variables.</li>\n</ul>\n<p>However, Wordpress is a <em>huge</em> piece of PHP code, and if you want to write code which accesses the same information in many different places all over Wordpress, globals are a way to achieve this without writing complicated data structures, and plugins do use them to achieve this as other solutions can be much more complicated or unncessary</p>\n<p>There are a few things you can do to make your use of globals as safe and bug-free as possible, here are a few suggestions:</p>\n<ul>\n<li><p>Give your global a very unique and descriptive name. E.g. $mozboz_highscoreplugin_scores . This prevents possible conflicts where other code might accidetally overwrite your gglobal</p>\n</li>\n<li><p>Document the use of the global somewhere! E.g. at the top of your plugin describe what globals it uses and how</p>\n</li>\n<li><p>If you are a more advanced PHP programmer, you may want to try doing more clever things such as put all your variables inside a single global with an array, or even inside a class where you have much more control over the data and it may be easier to debug. For example:</p>\n<ul>\n<li><p>Instead of:</p>\n<pre><code>global $my_plugin_variable1;\nglobal $my_plugin_variable2;\n$foo = $my_plugin_variable1 + $my_plugin_variable2;\n</code></pre>\n</li>\n<li><p>Try:</p>\n<pre><code>global $my_plugin_datastore;\n$foo = $my_plugin_datastore['var1'] + my_plugin_datastore['var2']\n</code></pre>\n</li>\n</ul>\n</li>\n<li><p>Uses of classes and e.g. singletons is more advanced but may give you some benefit because it allows you wrap up and pass around all the functions as well as the variables in your plugin's program. E.g. in the example given perhaps you want to be able to call <code>test()</code> from anywhere, and in this case it might be nice to be able to do this from anywhere:</p>\n<pre><code>$myplugin_object = getPluginInstance();\n$foo = $myplugin_object->test();\n</code></pre>\n</li>\n</ul>\n"
}
] | 2020/06/30 | [
"https://wordpress.stackexchange.com/questions/370057",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/184192/"
] | Currently I'm writing a WordPress plugin. I would try to re-use variables from a function on different pages. Let's say I would create a function like this:
```
function test() {
global $hello;
$hello = 'hello world';
}
add_action( 'wp_head', 'test' );
```
I can do now on other pages: `echo $hello;` This is useful for me because I can get information like course settings from my plugin with `$course_settings`, without rewriting the whole code.
I am not sure of this is the right way to do? Because other plugins could rewrite my variables. | In general programming, globals are bad practice:
* You can't easily look at the use of a global in one place and see all the other uses, e.g. where it was set or will be read later.
* You have many places to change the use of that variable if e.g. the use or format of it changes.
* This makes it hard to make reliable changes to your code and to debug where/who set a global.
* Other code could accidentally write over your variables.
However, Wordpress is a *huge* piece of PHP code, and if you want to write code which accesses the same information in many different places all over Wordpress, globals are a way to achieve this without writing complicated data structures, and plugins do use them to achieve this as other solutions can be much more complicated or unncessary
There are a few things you can do to make your use of globals as safe and bug-free as possible, here are a few suggestions:
* Give your global a very unique and descriptive name. E.g. $mozboz\_highscoreplugin\_scores . This prevents possible conflicts where other code might accidetally overwrite your gglobal
* Document the use of the global somewhere! E.g. at the top of your plugin describe what globals it uses and how
* If you are a more advanced PHP programmer, you may want to try doing more clever things such as put all your variables inside a single global with an array, or even inside a class where you have much more control over the data and it may be easier to debug. For example:
+ Instead of:
```
global $my_plugin_variable1;
global $my_plugin_variable2;
$foo = $my_plugin_variable1 + $my_plugin_variable2;
```
+ Try:
```
global $my_plugin_datastore;
$foo = $my_plugin_datastore['var1'] + my_plugin_datastore['var2']
```
* Uses of classes and e.g. singletons is more advanced but may give you some benefit because it allows you wrap up and pass around all the functions as well as the variables in your plugin's program. E.g. in the example given perhaps you want to be able to call `test()` from anywhere, and in this case it might be nice to be able to do this from anywhere:
```
$myplugin_object = getPluginInstance();
$foo = $myplugin_object->test();
``` |
370,135 | <p>Following is my code which I am using to display comments of posts in a loop (Custom Post Types). I would like to display only latest 3 comments. Kindly help me to limit comments.</p>
<pre><code><?php foreach (get_comments() as $comment): ?>
<div><span class="author-name"><?php echo $comment->comment_author; ?> said:</span> <span class="author-cmnt">"<?php echo $comment->comment_content; ?>".</span></div>
<?php endforeach; ?>
</code></pre>
| [
{
"answer_id": 370142,
"author": "romand",
"author_id": 190900,
"author_profile": "https://wordpress.stackexchange.com/users/190900",
"pm_score": 1,
"selected": false,
"text": "<p>I don't usually work with comment so my suggestion is untested, but I see that get_comments() receives an array of args.</p>\n<p>Try this:</p>\n<p><code>$comments = get_comments(array("number" => 3))</code></p>\n<p>and instead of your foreach loop:</p>\n<p><code>foreach ($comments as $comment):</code></p>\n"
},
{
"answer_id": 370161,
"author": "Magnetize",
"author_id": 49181,
"author_profile": "https://wordpress.stackexchange.com/users/49181",
"pm_score": 0,
"selected": false,
"text": "<p>My answer to this is to use something like this:</p>\n<pre><code>$args = ['number' => 3];\n$comments = get_comments( $args );\n</code></pre>\n"
}
] | 2020/07/01 | [
"https://wordpress.stackexchange.com/questions/370135",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/190895/"
] | Following is my code which I am using to display comments of posts in a loop (Custom Post Types). I would like to display only latest 3 comments. Kindly help me to limit comments.
```
<?php foreach (get_comments() as $comment): ?>
<div><span class="author-name"><?php echo $comment->comment_author; ?> said:</span> <span class="author-cmnt">"<?php echo $comment->comment_content; ?>".</span></div>
<?php endforeach; ?>
``` | I don't usually work with comment so my suggestion is untested, but I see that get\_comments() receives an array of args.
Try this:
`$comments = get_comments(array("number" => 3))`
and instead of your foreach loop:
`foreach ($comments as $comment):` |
370,182 | <p>i am trying to make a dependend picklist set in a wordpress plugin. Within the plugin i have a javascript with the following method</p>
<pre><code> $('#am_organisation').change(function(){
var val = $(this).val();
$.ajax({
type: 'POST',
url: '/wp-content/plugins/harriecrm/admin/get-contacts.php',
data:'organisation_id='+val,
success: function(data){
$("#am_contact").html(data);
//$("#loader").hide();
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
});
</code></pre>
<p>the <strong>get-contacts.php</strong> file looks like</p>
<pre class="lang-php prettyprint-override"><code> <?php
global $wpdb;
global $xx;
if(isset($_POST['organisation_id'])){
$id = $_POST['organisation_id'];
$listitems = $wpdb->prefix . 'am_contacts';
$result = $wpdb->get_results ( "SELECT * FROM $listitems" );
//foreach ( $result as $print ) {
// echo '<option value="Maak een keuze">Maak een keuzesss-' . $id . '</option>';
//}
//if($wpdb->query($sql)){
// $resp->uf_error = $wpdb->print_error();
// alert($resp);
//};
// $result = $wpdb->get_results ($strsql);
//foreach ($result as $value) {
// echo ' <option value='.$value->id.' '.$selected.'>'.$value->am_firstname. ", ".$value->am_firstname. '</option> ';
echo '<option value="Maak een keuze">Maak een keuzesss-' . $id . '</option>';
//}
}
?>
</code></pre>
<p>i have tried a lot. I know the URL is good, and the page is being called. I have comment everything out except the echo line, i see that the pulldoen is being updated with that echo line.</p>
<p>BUt i want to use the $wpdb method to get rows from the database. But the moment i uncomment the line
$result = $wpdb->get_results ( "SELECT * FROM $listitems" );
it does not work anymore. I get an empty errormessage. the alert(xhr.responseText); is being called but is empty. If i comment the $wpdb line out, then is works again.</p>
<p>I have really no clue what i am missing. The $wpdb I use very heavily and works like a charm except in the example here.</p>
<p>Any ideas? BR Marzel</p>
| [
{
"answer_id": 370142,
"author": "romand",
"author_id": 190900,
"author_profile": "https://wordpress.stackexchange.com/users/190900",
"pm_score": 1,
"selected": false,
"text": "<p>I don't usually work with comment so my suggestion is untested, but I see that get_comments() receives an array of args.</p>\n<p>Try this:</p>\n<p><code>$comments = get_comments(array("number" => 3))</code></p>\n<p>and instead of your foreach loop:</p>\n<p><code>foreach ($comments as $comment):</code></p>\n"
},
{
"answer_id": 370161,
"author": "Magnetize",
"author_id": 49181,
"author_profile": "https://wordpress.stackexchange.com/users/49181",
"pm_score": 0,
"selected": false,
"text": "<p>My answer to this is to use something like this:</p>\n<pre><code>$args = ['number' => 3];\n$comments = get_comments( $args );\n</code></pre>\n"
}
] | 2020/07/01 | [
"https://wordpress.stackexchange.com/questions/370182",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/190935/"
] | i am trying to make a dependend picklist set in a wordpress plugin. Within the plugin i have a javascript with the following method
```
$('#am_organisation').change(function(){
var val = $(this).val();
$.ajax({
type: 'POST',
url: '/wp-content/plugins/harriecrm/admin/get-contacts.php',
data:'organisation_id='+val,
success: function(data){
$("#am_contact").html(data);
//$("#loader").hide();
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
});
```
the **get-contacts.php** file looks like
```php
<?php
global $wpdb;
global $xx;
if(isset($_POST['organisation_id'])){
$id = $_POST['organisation_id'];
$listitems = $wpdb->prefix . 'am_contacts';
$result = $wpdb->get_results ( "SELECT * FROM $listitems" );
//foreach ( $result as $print ) {
// echo '<option value="Maak een keuze">Maak een keuzesss-' . $id . '</option>';
//}
//if($wpdb->query($sql)){
// $resp->uf_error = $wpdb->print_error();
// alert($resp);
//};
// $result = $wpdb->get_results ($strsql);
//foreach ($result as $value) {
// echo ' <option value='.$value->id.' '.$selected.'>'.$value->am_firstname. ", ".$value->am_firstname. '</option> ';
echo '<option value="Maak een keuze">Maak een keuzesss-' . $id . '</option>';
//}
}
?>
```
i have tried a lot. I know the URL is good, and the page is being called. I have comment everything out except the echo line, i see that the pulldoen is being updated with that echo line.
BUt i want to use the $wpdb method to get rows from the database. But the moment i uncomment the line
$result = $wpdb->get\_results ( "SELECT \* FROM $listitems" );
it does not work anymore. I get an empty errormessage. the alert(xhr.responseText); is being called but is empty. If i comment the $wpdb line out, then is works again.
I have really no clue what i am missing. The $wpdb I use very heavily and works like a charm except in the example here.
Any ideas? BR Marzel | I don't usually work with comment so my suggestion is untested, but I see that get\_comments() receives an array of args.
Try this:
`$comments = get_comments(array("number" => 3))`
and instead of your foreach loop:
`foreach ($comments as $comment):` |
370,212 | <p>I am trying to check for an excerpt and if it doesn't exist then show the content but trimmed. Currently nothing is showing.</p>
<pre><code><?php if (has_excerpt() ): ?>
<p><?php echo get_the_excerpt(); ?></p>
<?php else: ?>
<p><?php echo wp_trim_words(get_the_content(), 25); ?></p>
<?php endif; ?>
</code></pre>
<p>However, if I simply do the below then I see content. Is there an issue with my above code? This is running inside a WP_Query loop</p>
<pre><code><p><?php echo wp_trim_words(get_the_content(), 25); ?></p>
</code></pre>
<p>The loop:</p>
<pre><code> <?php $args = array(
'post_type' => 'post',
'posts_per_page' => 8,
'category__not_in' => 4
);
$latestPosts = new WP_Query( $args );
?>
<?php if ($latestPosts->have_posts() ): ?>
<ul>
<?php while ($latestPosts->have_posts() ): $latestPosts->the_post(); ?>
<li>
//The excerpt code etc. goes here
</li>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
</ul>
<?php endif; ?>
</code></pre>
| [
{
"answer_id": 370225,
"author": "Ben",
"author_id": 190965,
"author_profile": "https://wordpress.stackexchange.com/users/190965",
"pm_score": 0,
"selected": false,
"text": "<p>Iggy!</p>\n<p>With WP functions, typically speaking the get_ before the function signifies that the call is made outside of the loop, and as such you need to declare an object ID within the brackets, like so:</p>\n<pre><code>get_the_excerpt( $post->ID )\n</code></pre>\n<p>If you're using this function within the object loop, you should just call:</p>\n<pre><code>the_excerpt()\n</code></pre>\n<p>Which doesn't require the object ID, because that is already making up the query.</p>\n"
},
{
"answer_id": 370231,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": true,
"text": "<p>So we already resolved the issue via the comments, but I thought I should explain something:</p>\n<p><a href=\"https://developer.wordpress.org/reference/functions/has_excerpt/\" rel=\"nofollow noreferrer\"><code>has_excerpt()</code></a> returns <code>! empty( $post->post_excerpt )</code> if the post has a custom/manual excerpt, so if the function is returning true when it should be false, then it's likely because the length of the excerpt in the database is > 0, e.g. when the value is a whitespace — <code>empty( ' ' )</code> = false. (But note that <code>empty( '0' )</code> or <code>empty( 0 )</code> is true)</p>\n<p>So if that's the case, then you should fix the <code>post_excerpt</code> value in the database so that the function returns the expected value.</p>\n<p>But as I said in the comment, I'm not sure why the excerpt was imported with all that whitespace, so I could only guess they were added during export or maybe the import, via a filter.</p>\n<p>Anyway, I hope this answer helps! :)</p>\n"
}
] | 2020/07/02 | [
"https://wordpress.stackexchange.com/questions/370212",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/64184/"
] | I am trying to check for an excerpt and if it doesn't exist then show the content but trimmed. Currently nothing is showing.
```
<?php if (has_excerpt() ): ?>
<p><?php echo get_the_excerpt(); ?></p>
<?php else: ?>
<p><?php echo wp_trim_words(get_the_content(), 25); ?></p>
<?php endif; ?>
```
However, if I simply do the below then I see content. Is there an issue with my above code? This is running inside a WP\_Query loop
```
<p><?php echo wp_trim_words(get_the_content(), 25); ?></p>
```
The loop:
```
<?php $args = array(
'post_type' => 'post',
'posts_per_page' => 8,
'category__not_in' => 4
);
$latestPosts = new WP_Query( $args );
?>
<?php if ($latestPosts->have_posts() ): ?>
<ul>
<?php while ($latestPosts->have_posts() ): $latestPosts->the_post(); ?>
<li>
//The excerpt code etc. goes here
</li>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
</ul>
<?php endif; ?>
``` | So we already resolved the issue via the comments, but I thought I should explain something:
[`has_excerpt()`](https://developer.wordpress.org/reference/functions/has_excerpt/) returns `! empty( $post->post_excerpt )` if the post has a custom/manual excerpt, so if the function is returning true when it should be false, then it's likely because the length of the excerpt in the database is > 0, e.g. when the value is a whitespace — `empty( ' ' )` = false. (But note that `empty( '0' )` or `empty( 0 )` is true)
So if that's the case, then you should fix the `post_excerpt` value in the database so that the function returns the expected value.
But as I said in the comment, I'm not sure why the excerpt was imported with all that whitespace, so I could only guess they were added during export or maybe the import, via a filter.
Anyway, I hope this answer helps! :) |
370,229 | <p>What is the reason that $post->ID is not working in <code>metabox_callback</code> after adding a custom query. How can I avoid this? Should I use <code>$post_id = isset( $_GET['post'] ) ? $_GET['post'] : ( isset( $_POST['post_ID'] ) ? $_POST['post_ID'] : false );</code> instead of $post->ID?</p>
<p>Similar question/same situation <a href="https://wordpress.stackexchange.com/questions/282232/post-id-incorrect-within-meta-box">here</a>.</p>
<p>What is the reason for problems like this and how can you fix it the proper way?</p>
<p><strong>EDIT:</strong></p>
<pre><code>function custom_add_meta_boxes() {
add_meta_box (
'enroll_user',
'Enroll users',
'enroll_user_callback',
'group',
'normal'
);
add_meta_box (
'module_group',
'Assign modules',
'module_group_callback',
'group',
'side'
);
}
add_action( 'add_meta_boxes', 'custom_add_meta_boxes' );
function enroll_user_callback ( $post ) {
wp_nonce_field( 'enroll_user_save', 'enroll_user_nonce' );
echo '<label for="enroll_user_field">Enroll users</label><br /><br />';
echo '<select style="width: 50%; min-width: 250px;" multiple name="enroll_user_field[]" id="enroll_user_field">';
$users = get_users( array( 'fields' => array( 'ID', 'user_email' ) ) );
foreach( $users as $user ){
$enrolledusers = get_user_meta($user->ID, '_enroll_user_value_key_' . $post->ID , false);
if( in_array($post->ID, $enrolledusers )) {
echo '<option selected value="' . $user->ID . '">' . esc_attr( $user->user_email ) . '</option>';
} else {
echo '<option value="' . $user->ID . '">' . esc_attr( $user->user_email ) . '</option>';
}
}
echo '</select>';
// This is posting a different ID after adding my query in module_group_callback
print_r($post);
}
function module_group_callback ( $post ) {
wp_nonce_field( 'module_group_save', 'module_group_nonce' );
echo '<label for="module_group_field">Assign modules</label><br /><br />';
$args = array(
'post_type' => 'module',
'orderby' => 'menu_order',
'order' => 'ASC',
'posts_per_page' => -1,
);
$query = new WP_Query( $args );
echo '<select style="width: 100%;" multiple name="module_group_field[]" id="module_group_field">';
while ( $query->have_posts() ) : $query->the_post();
$moduleid = $query->post->ID;
echo '<option value="' . $moduleid . '">' . esc_attr( get_the_title( $moduleid ) ) . '</option>';
endwhile;
echo '</select>';
}
</code></pre>
| [
{
"answer_id": 370241,
"author": "Tetragrammaton",
"author_id": 184192,
"author_profile": "https://wordpress.stackexchange.com/users/184192",
"pm_score": 0,
"selected": false,
"text": "<p>A possible solution is to save the <code>$post</code> variable before the query, like: <code>$originalpost = $post</code>. After the query you set the it back <code>$post = $originalpost</code>. I don't know of this is valid solution. But it seems to work.</p>\n<p>Thanks to @Jamie, <a href=\"https://stackoverflow.com/questions/4452599/how-can-i-reset-a-query-in-a-custom-wordpress-metabox\">here</a>.</p>\n"
},
{
"answer_id": 370245,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": true,
"text": "<p>That <code>$query->have_posts()</code> modifies the global <code>$post</code> variable which is also used on the admin side, and on the front-end/public side of the site, you would simply call <code>wp_reset_postdata()</code> to restore the global <code>$post</code> back to the post before you call the <code>$query->have_posts()</code>.</p>\n<p>But on the admin side, you need to manually restore the variable like so, after your loop ends:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function module_group_callback( $post ) {\n ...\n while ( $query->have_posts() ) : $query->the_post();\n ...\n endwhile;\n\n // Restore the global $post back to the one passed to your metabox callback.\n $GLOBALS['post'] = $post;\n}\n</code></pre>\n<p>But if you call <code>global $post</code> in your code, then yes, you can use the backup method:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function module_group_callback( $post ) {\n global $post; // this is required\n $_post = $post; // backup the current $post variable in the global scope\n\n ...\n while ( $query->have_posts() ) : $query->the_post();\n ...\n endwhile;\n\n $post = $_post; // restore\n}\n</code></pre>\n<p>Alternatively, you could just omit the <code>$query->have_posts()</code> and loop manually through <code>$query->posts</code>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function module_group_callback( $post ) {\n ...\n // Don't use $post with the 'as'. Instead, use $p, $post2 or another name.\n foreach ( $query->posts as $p ) {\n echo '<option value="' . $p->ID . '">' . esc_attr( get_the_title( $p ) ) . '</option>';\n }\n}\n</code></pre>\n<p>Either way, if your code modifies the global <code>$post</code>, then make sure to restore it later.</p>\n<p>And btw, you would want to use <code>esc_html()</code> there, because <code>esc_attr()</code> is for escaping attribute values, e.g. <code><input value="<?php echo esc_attr( 'some <b>HTML</b>' ); ?>"></code>. :-)</p>\n"
}
] | 2020/07/02 | [
"https://wordpress.stackexchange.com/questions/370229",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/184192/"
] | What is the reason that $post->ID is not working in `metabox_callback` after adding a custom query. How can I avoid this? Should I use `$post_id = isset( $_GET['post'] ) ? $_GET['post'] : ( isset( $_POST['post_ID'] ) ? $_POST['post_ID'] : false );` instead of $post->ID?
Similar question/same situation [here](https://wordpress.stackexchange.com/questions/282232/post-id-incorrect-within-meta-box).
What is the reason for problems like this and how can you fix it the proper way?
**EDIT:**
```
function custom_add_meta_boxes() {
add_meta_box (
'enroll_user',
'Enroll users',
'enroll_user_callback',
'group',
'normal'
);
add_meta_box (
'module_group',
'Assign modules',
'module_group_callback',
'group',
'side'
);
}
add_action( 'add_meta_boxes', 'custom_add_meta_boxes' );
function enroll_user_callback ( $post ) {
wp_nonce_field( 'enroll_user_save', 'enroll_user_nonce' );
echo '<label for="enroll_user_field">Enroll users</label><br /><br />';
echo '<select style="width: 50%; min-width: 250px;" multiple name="enroll_user_field[]" id="enroll_user_field">';
$users = get_users( array( 'fields' => array( 'ID', 'user_email' ) ) );
foreach( $users as $user ){
$enrolledusers = get_user_meta($user->ID, '_enroll_user_value_key_' . $post->ID , false);
if( in_array($post->ID, $enrolledusers )) {
echo '<option selected value="' . $user->ID . '">' . esc_attr( $user->user_email ) . '</option>';
} else {
echo '<option value="' . $user->ID . '">' . esc_attr( $user->user_email ) . '</option>';
}
}
echo '</select>';
// This is posting a different ID after adding my query in module_group_callback
print_r($post);
}
function module_group_callback ( $post ) {
wp_nonce_field( 'module_group_save', 'module_group_nonce' );
echo '<label for="module_group_field">Assign modules</label><br /><br />';
$args = array(
'post_type' => 'module',
'orderby' => 'menu_order',
'order' => 'ASC',
'posts_per_page' => -1,
);
$query = new WP_Query( $args );
echo '<select style="width: 100%;" multiple name="module_group_field[]" id="module_group_field">';
while ( $query->have_posts() ) : $query->the_post();
$moduleid = $query->post->ID;
echo '<option value="' . $moduleid . '">' . esc_attr( get_the_title( $moduleid ) ) . '</option>';
endwhile;
echo '</select>';
}
``` | That `$query->have_posts()` modifies the global `$post` variable which is also used on the admin side, and on the front-end/public side of the site, you would simply call `wp_reset_postdata()` to restore the global `$post` back to the post before you call the `$query->have_posts()`.
But on the admin side, you need to manually restore the variable like so, after your loop ends:
```php
function module_group_callback( $post ) {
...
while ( $query->have_posts() ) : $query->the_post();
...
endwhile;
// Restore the global $post back to the one passed to your metabox callback.
$GLOBALS['post'] = $post;
}
```
But if you call `global $post` in your code, then yes, you can use the backup method:
```php
function module_group_callback( $post ) {
global $post; // this is required
$_post = $post; // backup the current $post variable in the global scope
...
while ( $query->have_posts() ) : $query->the_post();
...
endwhile;
$post = $_post; // restore
}
```
Alternatively, you could just omit the `$query->have_posts()` and loop manually through `$query->posts`:
```php
function module_group_callback( $post ) {
...
// Don't use $post with the 'as'. Instead, use $p, $post2 or another name.
foreach ( $query->posts as $p ) {
echo '<option value="' . $p->ID . '">' . esc_attr( get_the_title( $p ) ) . '</option>';
}
}
```
Either way, if your code modifies the global `$post`, then make sure to restore it later.
And btw, you would want to use `esc_html()` there, because `esc_attr()` is for escaping attribute values, e.g. `<input value="<?php echo esc_attr( 'some <b>HTML</b>' ); ?>">`. :-) |
370,246 | <p><strong>Hi everyone,</strong></p>
<p>I am starting now to develoo my first wordpress Theme and please, I need your help with code.</p>
<p>With this code I created my post type Team, the problem is to show them, I do not know how to do it.
If it's possible, I wish to create some easy option for users in Bakery page builder to add it in a row with the option for slider. How can I do it ?</p>
<p><strong>Thanks for any information</strong></p>
<pre><code>function create_post_type() {
register_post_type( 'Team',
array(
'labels' => array(
'name' => __( 'Team' ),
'singular_name' => __( 'Team' ),
'add_new' => __( 'Add Member' ),
'add_new_item' => __( 'Add New Member' ),
'featured_image' => __( 'Add Photo' ),
'edit_item' => __( 'Edit Member' )
),
'public' => true,
'menu_icon' => 'dashicons-universal-access',
'has_archive' => true,
'rewrite' => array('slug' => 'Team'),
'supports' => array('title', 'editor','custom-fields', 'thumbnail'),
)
);
}
add_action( 'init', 'create_post_type' );
</code></pre>
| [
{
"answer_id": 370247,
"author": "Sabbir Hasan",
"author_id": 76587,
"author_profile": "https://wordpress.stackexchange.com/users/76587",
"pm_score": 0,
"selected": false,
"text": "<p>You can use <code>WP_Query</code> or <code>get_posts</code> to achieve the result. Here I'm providing you an example using <code>WP_Query</code> of how you can achieve what you need.</p>\n<pre><code>$args = array( \n 'post_type' => 'Team',\n 'post_status' => 'publish',\n 'posts_per_page' => -1, // -1 will return all entry\n 'orderby' => 'title', \n 'order' => 'ASC',\n);\n\n$loop = new WP_Query( $args ); \n\nwhile ( $loop->have_posts() ) : $loop->the_post(); \n $featured_img = wp_get_attachment_image_src( $post->ID );\n echo the_title(); // Print the title\n if ( $feature_img ) {\n //Print image if available\n echo '<img src="'.$featured_img['url'].'" width="'.$featured_img['width'].'" height="'.$featured_img['height'].'" />';\n }\n the_excerpt(); \nendwhile;\n\nwp_reset_postdata(); \n</code></pre>\n<p>You can study more about <strong>WP_Query</strong> <a href=\"https://developer.wordpress.org/reference/classes/wp_query/\" rel=\"nofollow noreferrer\">here</a>. Also read about <strong>get_posts()</strong> <a href=\"https://developer.wordpress.org/reference/functions/get_posts/\" rel=\"nofollow noreferrer\">here</a>. Have fun!</p>\n"
},
{
"answer_id": 370373,
"author": "Arpita Hunka",
"author_id": 86864,
"author_profile": "https://wordpress.stackexchange.com/users/86864",
"pm_score": 1,
"selected": false,
"text": "<p>As you said in a comment that you want to make it dynamic and wants to call anywhere of the website. Then in WP the best option is to use the shortcode. You can create a short code and call it where ever you want. One thing you can update it's design as per your need, I am sharing a way to create a short code for the CPT.</p>\n<pre><code>/**\n * Register all shortcodes\n *\n * @return null\n */\nfunction register_shortcodes() {\n add_shortcode( 'produtos', 'shortcode_mostra_produtos' );\n}\nadd_action( 'init', 'register_shortcodes' );\n/**\n * Produtos Shortcode Callback\n * \n * @param Array $atts\n *\n * @return string\n */\nfunction shortcode_mostra_produtos( $atts ) {\n global $wp_query,$post;\n $atts = shortcode_atts( array(\n 'line' => ''\n ), $atts );\n\n $loop = new WP_Query( array(\n 'posts_per_page' => 200,\n 'post_type' => 'produtos',\n 'orderby' => 'menu_order title',\n 'order' => 'ASC',\n 'tax_query' => array( array(\n 'taxonomy' => 'linhas',\n 'field' => 'slug',\n 'terms' => array( sanitize_title( $atts['line'] ) )\n ) )\n ) );\n\n if( ! $loop->have_posts() ) {\n return false;\n }\n\n while( $loop->have_posts() ) {\n $loop->the_post();\n echo the_title();\n }\n\n wp_reset_postdata();\n}\n</code></pre>\n<p>I have created a shortcode for the products to display the product list.</p>\n<p>Now you can add [produtos] on the wp backend page/post and after saving this will display the produts title (as i only echo the title) on the front end.</p>\n<p>For more reference about the shortcode API you can follow this article <a href=\"https://codex.wordpress.org/Shortcode_API\" rel=\"nofollow noreferrer\">SHORTCODE API</a></p>\n<p>Try this. I think this will help you. Let me know if you will face any issue here.</p>\n<p>Enjoy!!:)</p>\n"
}
] | 2020/07/02 | [
"https://wordpress.stackexchange.com/questions/370246",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/190941/"
] | **Hi everyone,**
I am starting now to develoo my first wordpress Theme and please, I need your help with code.
With this code I created my post type Team, the problem is to show them, I do not know how to do it.
If it's possible, I wish to create some easy option for users in Bakery page builder to add it in a row with the option for slider. How can I do it ?
**Thanks for any information**
```
function create_post_type() {
register_post_type( 'Team',
array(
'labels' => array(
'name' => __( 'Team' ),
'singular_name' => __( 'Team' ),
'add_new' => __( 'Add Member' ),
'add_new_item' => __( 'Add New Member' ),
'featured_image' => __( 'Add Photo' ),
'edit_item' => __( 'Edit Member' )
),
'public' => true,
'menu_icon' => 'dashicons-universal-access',
'has_archive' => true,
'rewrite' => array('slug' => 'Team'),
'supports' => array('title', 'editor','custom-fields', 'thumbnail'),
)
);
}
add_action( 'init', 'create_post_type' );
``` | As you said in a comment that you want to make it dynamic and wants to call anywhere of the website. Then in WP the best option is to use the shortcode. You can create a short code and call it where ever you want. One thing you can update it's design as per your need, I am sharing a way to create a short code for the CPT.
```
/**
* Register all shortcodes
*
* @return null
*/
function register_shortcodes() {
add_shortcode( 'produtos', 'shortcode_mostra_produtos' );
}
add_action( 'init', 'register_shortcodes' );
/**
* Produtos Shortcode Callback
*
* @param Array $atts
*
* @return string
*/
function shortcode_mostra_produtos( $atts ) {
global $wp_query,$post;
$atts = shortcode_atts( array(
'line' => ''
), $atts );
$loop = new WP_Query( array(
'posts_per_page' => 200,
'post_type' => 'produtos',
'orderby' => 'menu_order title',
'order' => 'ASC',
'tax_query' => array( array(
'taxonomy' => 'linhas',
'field' => 'slug',
'terms' => array( sanitize_title( $atts['line'] ) )
) )
) );
if( ! $loop->have_posts() ) {
return false;
}
while( $loop->have_posts() ) {
$loop->the_post();
echo the_title();
}
wp_reset_postdata();
}
```
I have created a shortcode for the products to display the product list.
Now you can add [produtos] on the wp backend page/post and after saving this will display the produts title (as i only echo the title) on the front end.
For more reference about the shortcode API you can follow this article [SHORTCODE API](https://codex.wordpress.org/Shortcode_API)
Try this. I think this will help you. Let me know if you will face any issue here.
Enjoy!!:) |
370,271 | <p>On functions.php I have the following which works on the homepage :</p>
<pre><code>function load_page_styles() {
if (is_front_page()) {
wp_register_style('home', get_template_directory_uri() . '/css/home.css', array(), 1, 'all');
wp_enqueue_style('home');
wp_register_style('font-awesome', get_template_directory_uri() . '/css/font-awesome.css', array(), 1, 'all');
wp_enqueue_style('font-awesome');
} else if (is_page( 'about')) {
wp_register_style('about', get_template_directory_uri() . '/css/about.css', array(), 1, 'all');
wp_enqueue_style('about');
}
}
add_action( 'wp_enqueue_scripts', 'load_page_styles' );
</code></pre>
<p>It is working fine at it showing the css file in /wp-content/themes/roots-restaurant</p>
<pre><code><link rel="stylesheet" id="home-css" href="http://localhost:8000/wp-content/themes/roots-restaurant/css/home.css?ver=1" type="text/css" media="all">
</code></pre>
<p>But on about us page it does not work. It shows the path as the following, which is wrong as it is targeting the wp-admin folder:</p>
<pre><code><link rel="stylesheet" id="about-css" href="http://localhost:8000/wp-admin/css/about.min.css?ver=5.4.2" type="text/css" media="all">
</code></pre>
<p>About Us template is in the following:</p>
<p>/wp-content/themes/roots-restaurant/template-about.php</p>
<p>Could you help me with this.</p>
<p>Ronny</p>
| [
{
"answer_id": 370247,
"author": "Sabbir Hasan",
"author_id": 76587,
"author_profile": "https://wordpress.stackexchange.com/users/76587",
"pm_score": 0,
"selected": false,
"text": "<p>You can use <code>WP_Query</code> or <code>get_posts</code> to achieve the result. Here I'm providing you an example using <code>WP_Query</code> of how you can achieve what you need.</p>\n<pre><code>$args = array( \n 'post_type' => 'Team',\n 'post_status' => 'publish',\n 'posts_per_page' => -1, // -1 will return all entry\n 'orderby' => 'title', \n 'order' => 'ASC',\n);\n\n$loop = new WP_Query( $args ); \n\nwhile ( $loop->have_posts() ) : $loop->the_post(); \n $featured_img = wp_get_attachment_image_src( $post->ID );\n echo the_title(); // Print the title\n if ( $feature_img ) {\n //Print image if available\n echo '<img src="'.$featured_img['url'].'" width="'.$featured_img['width'].'" height="'.$featured_img['height'].'" />';\n }\n the_excerpt(); \nendwhile;\n\nwp_reset_postdata(); \n</code></pre>\n<p>You can study more about <strong>WP_Query</strong> <a href=\"https://developer.wordpress.org/reference/classes/wp_query/\" rel=\"nofollow noreferrer\">here</a>. Also read about <strong>get_posts()</strong> <a href=\"https://developer.wordpress.org/reference/functions/get_posts/\" rel=\"nofollow noreferrer\">here</a>. Have fun!</p>\n"
},
{
"answer_id": 370373,
"author": "Arpita Hunka",
"author_id": 86864,
"author_profile": "https://wordpress.stackexchange.com/users/86864",
"pm_score": 1,
"selected": false,
"text": "<p>As you said in a comment that you want to make it dynamic and wants to call anywhere of the website. Then in WP the best option is to use the shortcode. You can create a short code and call it where ever you want. One thing you can update it's design as per your need, I am sharing a way to create a short code for the CPT.</p>\n<pre><code>/**\n * Register all shortcodes\n *\n * @return null\n */\nfunction register_shortcodes() {\n add_shortcode( 'produtos', 'shortcode_mostra_produtos' );\n}\nadd_action( 'init', 'register_shortcodes' );\n/**\n * Produtos Shortcode Callback\n * \n * @param Array $atts\n *\n * @return string\n */\nfunction shortcode_mostra_produtos( $atts ) {\n global $wp_query,$post;\n $atts = shortcode_atts( array(\n 'line' => ''\n ), $atts );\n\n $loop = new WP_Query( array(\n 'posts_per_page' => 200,\n 'post_type' => 'produtos',\n 'orderby' => 'menu_order title',\n 'order' => 'ASC',\n 'tax_query' => array( array(\n 'taxonomy' => 'linhas',\n 'field' => 'slug',\n 'terms' => array( sanitize_title( $atts['line'] ) )\n ) )\n ) );\n\n if( ! $loop->have_posts() ) {\n return false;\n }\n\n while( $loop->have_posts() ) {\n $loop->the_post();\n echo the_title();\n }\n\n wp_reset_postdata();\n}\n</code></pre>\n<p>I have created a shortcode for the products to display the product list.</p>\n<p>Now you can add [produtos] on the wp backend page/post and after saving this will display the produts title (as i only echo the title) on the front end.</p>\n<p>For more reference about the shortcode API you can follow this article <a href=\"https://codex.wordpress.org/Shortcode_API\" rel=\"nofollow noreferrer\">SHORTCODE API</a></p>\n<p>Try this. I think this will help you. Let me know if you will face any issue here.</p>\n<p>Enjoy!!:)</p>\n"
}
] | 2020/07/03 | [
"https://wordpress.stackexchange.com/questions/370271",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/191003/"
] | On functions.php I have the following which works on the homepage :
```
function load_page_styles() {
if (is_front_page()) {
wp_register_style('home', get_template_directory_uri() . '/css/home.css', array(), 1, 'all');
wp_enqueue_style('home');
wp_register_style('font-awesome', get_template_directory_uri() . '/css/font-awesome.css', array(), 1, 'all');
wp_enqueue_style('font-awesome');
} else if (is_page( 'about')) {
wp_register_style('about', get_template_directory_uri() . '/css/about.css', array(), 1, 'all');
wp_enqueue_style('about');
}
}
add_action( 'wp_enqueue_scripts', 'load_page_styles' );
```
It is working fine at it showing the css file in /wp-content/themes/roots-restaurant
```
<link rel="stylesheet" id="home-css" href="http://localhost:8000/wp-content/themes/roots-restaurant/css/home.css?ver=1" type="text/css" media="all">
```
But on about us page it does not work. It shows the path as the following, which is wrong as it is targeting the wp-admin folder:
```
<link rel="stylesheet" id="about-css" href="http://localhost:8000/wp-admin/css/about.min.css?ver=5.4.2" type="text/css" media="all">
```
About Us template is in the following:
/wp-content/themes/roots-restaurant/template-about.php
Could you help me with this.
Ronny | As you said in a comment that you want to make it dynamic and wants to call anywhere of the website. Then in WP the best option is to use the shortcode. You can create a short code and call it where ever you want. One thing you can update it's design as per your need, I am sharing a way to create a short code for the CPT.
```
/**
* Register all shortcodes
*
* @return null
*/
function register_shortcodes() {
add_shortcode( 'produtos', 'shortcode_mostra_produtos' );
}
add_action( 'init', 'register_shortcodes' );
/**
* Produtos Shortcode Callback
*
* @param Array $atts
*
* @return string
*/
function shortcode_mostra_produtos( $atts ) {
global $wp_query,$post;
$atts = shortcode_atts( array(
'line' => ''
), $atts );
$loop = new WP_Query( array(
'posts_per_page' => 200,
'post_type' => 'produtos',
'orderby' => 'menu_order title',
'order' => 'ASC',
'tax_query' => array( array(
'taxonomy' => 'linhas',
'field' => 'slug',
'terms' => array( sanitize_title( $atts['line'] ) )
) )
) );
if( ! $loop->have_posts() ) {
return false;
}
while( $loop->have_posts() ) {
$loop->the_post();
echo the_title();
}
wp_reset_postdata();
}
```
I have created a shortcode for the products to display the product list.
Now you can add [produtos] on the wp backend page/post and after saving this will display the produts title (as i only echo the title) on the front end.
For more reference about the shortcode API you can follow this article [SHORTCODE API](https://codex.wordpress.org/Shortcode_API)
Try this. I think this will help you. Let me know if you will face any issue here.
Enjoy!!:) |
370,304 | <p>I want to create a new user when a post is created from the back end. Is there a WP Hook that calls before a post is created. Thanks</p>
| [
{
"answer_id": 370247,
"author": "Sabbir Hasan",
"author_id": 76587,
"author_profile": "https://wordpress.stackexchange.com/users/76587",
"pm_score": 0,
"selected": false,
"text": "<p>You can use <code>WP_Query</code> or <code>get_posts</code> to achieve the result. Here I'm providing you an example using <code>WP_Query</code> of how you can achieve what you need.</p>\n<pre><code>$args = array( \n 'post_type' => 'Team',\n 'post_status' => 'publish',\n 'posts_per_page' => -1, // -1 will return all entry\n 'orderby' => 'title', \n 'order' => 'ASC',\n);\n\n$loop = new WP_Query( $args ); \n\nwhile ( $loop->have_posts() ) : $loop->the_post(); \n $featured_img = wp_get_attachment_image_src( $post->ID );\n echo the_title(); // Print the title\n if ( $feature_img ) {\n //Print image if available\n echo '<img src="'.$featured_img['url'].'" width="'.$featured_img['width'].'" height="'.$featured_img['height'].'" />';\n }\n the_excerpt(); \nendwhile;\n\nwp_reset_postdata(); \n</code></pre>\n<p>You can study more about <strong>WP_Query</strong> <a href=\"https://developer.wordpress.org/reference/classes/wp_query/\" rel=\"nofollow noreferrer\">here</a>. Also read about <strong>get_posts()</strong> <a href=\"https://developer.wordpress.org/reference/functions/get_posts/\" rel=\"nofollow noreferrer\">here</a>. Have fun!</p>\n"
},
{
"answer_id": 370373,
"author": "Arpita Hunka",
"author_id": 86864,
"author_profile": "https://wordpress.stackexchange.com/users/86864",
"pm_score": 1,
"selected": false,
"text": "<p>As you said in a comment that you want to make it dynamic and wants to call anywhere of the website. Then in WP the best option is to use the shortcode. You can create a short code and call it where ever you want. One thing you can update it's design as per your need, I am sharing a way to create a short code for the CPT.</p>\n<pre><code>/**\n * Register all shortcodes\n *\n * @return null\n */\nfunction register_shortcodes() {\n add_shortcode( 'produtos', 'shortcode_mostra_produtos' );\n}\nadd_action( 'init', 'register_shortcodes' );\n/**\n * Produtos Shortcode Callback\n * \n * @param Array $atts\n *\n * @return string\n */\nfunction shortcode_mostra_produtos( $atts ) {\n global $wp_query,$post;\n $atts = shortcode_atts( array(\n 'line' => ''\n ), $atts );\n\n $loop = new WP_Query( array(\n 'posts_per_page' => 200,\n 'post_type' => 'produtos',\n 'orderby' => 'menu_order title',\n 'order' => 'ASC',\n 'tax_query' => array( array(\n 'taxonomy' => 'linhas',\n 'field' => 'slug',\n 'terms' => array( sanitize_title( $atts['line'] ) )\n ) )\n ) );\n\n if( ! $loop->have_posts() ) {\n return false;\n }\n\n while( $loop->have_posts() ) {\n $loop->the_post();\n echo the_title();\n }\n\n wp_reset_postdata();\n}\n</code></pre>\n<p>I have created a shortcode for the products to display the product list.</p>\n<p>Now you can add [produtos] on the wp backend page/post and after saving this will display the produts title (as i only echo the title) on the front end.</p>\n<p>For more reference about the shortcode API you can follow this article <a href=\"https://codex.wordpress.org/Shortcode_API\" rel=\"nofollow noreferrer\">SHORTCODE API</a></p>\n<p>Try this. I think this will help you. Let me know if you will face any issue here.</p>\n<p>Enjoy!!:)</p>\n"
}
] | 2020/07/03 | [
"https://wordpress.stackexchange.com/questions/370304",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/191027/"
] | I want to create a new user when a post is created from the back end. Is there a WP Hook that calls before a post is created. Thanks | As you said in a comment that you want to make it dynamic and wants to call anywhere of the website. Then in WP the best option is to use the shortcode. You can create a short code and call it where ever you want. One thing you can update it's design as per your need, I am sharing a way to create a short code for the CPT.
```
/**
* Register all shortcodes
*
* @return null
*/
function register_shortcodes() {
add_shortcode( 'produtos', 'shortcode_mostra_produtos' );
}
add_action( 'init', 'register_shortcodes' );
/**
* Produtos Shortcode Callback
*
* @param Array $atts
*
* @return string
*/
function shortcode_mostra_produtos( $atts ) {
global $wp_query,$post;
$atts = shortcode_atts( array(
'line' => ''
), $atts );
$loop = new WP_Query( array(
'posts_per_page' => 200,
'post_type' => 'produtos',
'orderby' => 'menu_order title',
'order' => 'ASC',
'tax_query' => array( array(
'taxonomy' => 'linhas',
'field' => 'slug',
'terms' => array( sanitize_title( $atts['line'] ) )
) )
) );
if( ! $loop->have_posts() ) {
return false;
}
while( $loop->have_posts() ) {
$loop->the_post();
echo the_title();
}
wp_reset_postdata();
}
```
I have created a shortcode for the products to display the product list.
Now you can add [produtos] on the wp backend page/post and after saving this will display the produts title (as i only echo the title) on the front end.
For more reference about the shortcode API you can follow this article [SHORTCODE API](https://codex.wordpress.org/Shortcode_API)
Try this. I think this will help you. Let me know if you will face any issue here.
Enjoy!!:) |
370,312 | <p>I am trying to write a function that will allow me to add product meta tags as additional order notes. Unfortunately, nothing works. After a few hours I decided to bring the function to the simplest form to see what does not work.</p>
<p>Each time I place an order for two products. I check my order and see two products. My function should create a note with the text "test 2" but creates a "test 0".
And I have no idea why.</p>
<pre><code>function add_engraving_notes($order_id)
{
$order = wc_get_order($order_id);
$note = 'Test';
$items = $order->get_items();
$note .= count($items);
$order->add_order_note($note);
$order->save();
}
add_action('woocommerce_new_order', 'add_engraving_notes');
</code></pre>
| [
{
"answer_id": 370315,
"author": "mozboz",
"author_id": 176814,
"author_profile": "https://wordpress.stackexchange.com/users/176814",
"pm_score": 0,
"selected": false,
"text": "<p>I found the answer here: <a href=\"https://stackoverflow.com/questions/51014200/wc-order-items-empty\">https://stackoverflow.com/questions/51014200/wc-order-items-empty</a></p>\n<p>It seems like the get_items call is poorly named or documented as it needs extra parameters. As per the code in the linked answer, you need:</p>\n<pre><code>$items = $order->get_items( apply_filters( 'woocommerce_purchase_order_item_types', 'line_item' ) );\n</code></pre>\n"
},
{
"answer_id": 383860,
"author": "Omar Tanti",
"author_id": 70887,
"author_profile": "https://wordpress.stackexchange.com/users/70887",
"pm_score": 2,
"selected": false,
"text": "<p>The solution that was provided here did not work for me. It seems that the order items are assigned to the order after the <code>woocommerce_new_order</code> hook is triggered. I only managed to sort my issues after I changed the hook to <code>woocommerce_checkout_order_processed</code> as per below:</p>\n<pre><code>add_action( 'woocommerce_checkout_order_processed', 'get_order_items_on_checkout', 50, 3 );\nfunction get_order_items_on_checkout($order_id, $posted_data, $order){\n $items = $order->get_items();\n}\n</code></pre>\n"
}
] | 2020/07/03 | [
"https://wordpress.stackexchange.com/questions/370312",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/191029/"
] | I am trying to write a function that will allow me to add product meta tags as additional order notes. Unfortunately, nothing works. After a few hours I decided to bring the function to the simplest form to see what does not work.
Each time I place an order for two products. I check my order and see two products. My function should create a note with the text "test 2" but creates a "test 0".
And I have no idea why.
```
function add_engraving_notes($order_id)
{
$order = wc_get_order($order_id);
$note = 'Test';
$items = $order->get_items();
$note .= count($items);
$order->add_order_note($note);
$order->save();
}
add_action('woocommerce_new_order', 'add_engraving_notes');
``` | The solution that was provided here did not work for me. It seems that the order items are assigned to the order after the `woocommerce_new_order` hook is triggered. I only managed to sort my issues after I changed the hook to `woocommerce_checkout_order_processed` as per below:
```
add_action( 'woocommerce_checkout_order_processed', 'get_order_items_on_checkout', 50, 3 );
function get_order_items_on_checkout($order_id, $posted_data, $order){
$items = $order->get_items();
}
``` |
370,354 | <p>I am building the website for my startup, I have limited knowledge of WordPress but managed to build some decent websites using premade themes. I now face this problem I need to build a website that basically holds 4 WordPress websites in one and I don't know where to start with.</p>
<p>The structure would be something like</p>
<pre><code>company.com/lang1
company.com/lang2
company.com/site2/lang1
company.com/site2/lang2
</code></pre>
<p>The main site and site2 would have a different theme as site 2 is about a company branch that does something completely different than the main business. Is this workable?</p>
<p>I was planning on using Astra + elementor, is there a way to do this?</p>
<p>Side question: Do you think a landing page that links to the two websites would work better thana large side button on the main site.</p>
<p><a href="https://i.stack.imgur.com/vAtEb.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vAtEb.jpg" alt="enter image description here" /></a></p>
<p>thank you very much!</p>
| [
{
"answer_id": 370315,
"author": "mozboz",
"author_id": 176814,
"author_profile": "https://wordpress.stackexchange.com/users/176814",
"pm_score": 0,
"selected": false,
"text": "<p>I found the answer here: <a href=\"https://stackoverflow.com/questions/51014200/wc-order-items-empty\">https://stackoverflow.com/questions/51014200/wc-order-items-empty</a></p>\n<p>It seems like the get_items call is poorly named or documented as it needs extra parameters. As per the code in the linked answer, you need:</p>\n<pre><code>$items = $order->get_items( apply_filters( 'woocommerce_purchase_order_item_types', 'line_item' ) );\n</code></pre>\n"
},
{
"answer_id": 383860,
"author": "Omar Tanti",
"author_id": 70887,
"author_profile": "https://wordpress.stackexchange.com/users/70887",
"pm_score": 2,
"selected": false,
"text": "<p>The solution that was provided here did not work for me. It seems that the order items are assigned to the order after the <code>woocommerce_new_order</code> hook is triggered. I only managed to sort my issues after I changed the hook to <code>woocommerce_checkout_order_processed</code> as per below:</p>\n<pre><code>add_action( 'woocommerce_checkout_order_processed', 'get_order_items_on_checkout', 50, 3 );\nfunction get_order_items_on_checkout($order_id, $posted_data, $order){\n $items = $order->get_items();\n}\n</code></pre>\n"
}
] | 2020/07/04 | [
"https://wordpress.stackexchange.com/questions/370354",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/191066/"
] | I am building the website for my startup, I have limited knowledge of WordPress but managed to build some decent websites using premade themes. I now face this problem I need to build a website that basically holds 4 WordPress websites in one and I don't know where to start with.
The structure would be something like
```
company.com/lang1
company.com/lang2
company.com/site2/lang1
company.com/site2/lang2
```
The main site and site2 would have a different theme as site 2 is about a company branch that does something completely different than the main business. Is this workable?
I was planning on using Astra + elementor, is there a way to do this?
Side question: Do you think a landing page that links to the two websites would work better thana large side button on the main site.
[](https://i.stack.imgur.com/vAtEb.jpg)
thank you very much! | The solution that was provided here did not work for me. It seems that the order items are assigned to the order after the `woocommerce_new_order` hook is triggered. I only managed to sort my issues after I changed the hook to `woocommerce_checkout_order_processed` as per below:
```
add_action( 'woocommerce_checkout_order_processed', 'get_order_items_on_checkout', 50, 3 );
function get_order_items_on_checkout($order_id, $posted_data, $order){
$items = $order->get_items();
}
``` |
370,363 | <p>I'm searching to create a shortcode inside function.php child theme, to show last updated posts with thumbnail.
I have this code that works into page template:</p>
<pre><code> <ol class="list-numbered">
<?php
// Show recently modified posts
$recently_updated_posts = new WP_Query( array(
'post_type' => 'post',
'posts_per_page' => '13',
'orderby' => 'modified',
'no_found_rows' => 'true' // speed up query when we don't need pagination
) );
if ( $recently_updated_posts->have_posts() ) :
while( $recently_updated_posts->have_posts() ) : $recently_updated_posts->the_post(); ?>
<li><a href="<?php the_permalink(); ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?>
<?php
$size = 'thumbnail';
$attachments = get_children( array(
'post_parent' => get_the_ID(),
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => 'ASC',
'orderby' => 'menu_order ID',
'numberposts' => 1)
);
foreach ( $attachments as $thumb_id => $attachment ) {
echo wp_get_attachment_image($thumb_id, $size);
}
?>
</a></li>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php endif; ?>
</ol>
</code></pre>
<p>But I would insert into functions.php file and call the shortcode.
Do you have some ideas?
Thanks in advance.</p>
| [
{
"answer_id": 370315,
"author": "mozboz",
"author_id": 176814,
"author_profile": "https://wordpress.stackexchange.com/users/176814",
"pm_score": 0,
"selected": false,
"text": "<p>I found the answer here: <a href=\"https://stackoverflow.com/questions/51014200/wc-order-items-empty\">https://stackoverflow.com/questions/51014200/wc-order-items-empty</a></p>\n<p>It seems like the get_items call is poorly named or documented as it needs extra parameters. As per the code in the linked answer, you need:</p>\n<pre><code>$items = $order->get_items( apply_filters( 'woocommerce_purchase_order_item_types', 'line_item' ) );\n</code></pre>\n"
},
{
"answer_id": 383860,
"author": "Omar Tanti",
"author_id": 70887,
"author_profile": "https://wordpress.stackexchange.com/users/70887",
"pm_score": 2,
"selected": false,
"text": "<p>The solution that was provided here did not work for me. It seems that the order items are assigned to the order after the <code>woocommerce_new_order</code> hook is triggered. I only managed to sort my issues after I changed the hook to <code>woocommerce_checkout_order_processed</code> as per below:</p>\n<pre><code>add_action( 'woocommerce_checkout_order_processed', 'get_order_items_on_checkout', 50, 3 );\nfunction get_order_items_on_checkout($order_id, $posted_data, $order){\n $items = $order->get_items();\n}\n</code></pre>\n"
}
] | 2020/07/04 | [
"https://wordpress.stackexchange.com/questions/370363",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/191073/"
] | I'm searching to create a shortcode inside function.php child theme, to show last updated posts with thumbnail.
I have this code that works into page template:
```
<ol class="list-numbered">
<?php
// Show recently modified posts
$recently_updated_posts = new WP_Query( array(
'post_type' => 'post',
'posts_per_page' => '13',
'orderby' => 'modified',
'no_found_rows' => 'true' // speed up query when we don't need pagination
) );
if ( $recently_updated_posts->have_posts() ) :
while( $recently_updated_posts->have_posts() ) : $recently_updated_posts->the_post(); ?>
<li><a href="<?php the_permalink(); ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?>
<?php
$size = 'thumbnail';
$attachments = get_children( array(
'post_parent' => get_the_ID(),
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => 'ASC',
'orderby' => 'menu_order ID',
'numberposts' => 1)
);
foreach ( $attachments as $thumb_id => $attachment ) {
echo wp_get_attachment_image($thumb_id, $size);
}
?>
</a></li>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php endif; ?>
</ol>
```
But I would insert into functions.php file and call the shortcode.
Do you have some ideas?
Thanks in advance. | The solution that was provided here did not work for me. It seems that the order items are assigned to the order after the `woocommerce_new_order` hook is triggered. I only managed to sort my issues after I changed the hook to `woocommerce_checkout_order_processed` as per below:
```
add_action( 'woocommerce_checkout_order_processed', 'get_order_items_on_checkout', 50, 3 );
function get_order_items_on_checkout($order_id, $posted_data, $order){
$items = $order->get_items();
}
``` |
370,369 | <p>I'm using the PHP <code>file_get_contents()</code> function to retrieve and echo the contents of an SVG-file.</p>
<pre><code><?php echo file_get_contents( get_stylesheet_directory_uri() . '/assets/images/Search_Glyph.svg' ); ?>
</code></pre>
<p>I checked the theme with the <a href="https://wordpress.org/plugins/theme-check/" rel="nofollow noreferrer">Wordpress.org theme checker</a> and I am currently resolving all the issues. One of the issues is the use of <code>file_get_contents</code>.</p>
<p>It gives me the following warning:</p>
<pre><code>WARNING: file_get_contents was found in the file header.php File operations should use the WP_Filesystem methods instead of direct PHP filesystem calls.
</code></pre>
<p>I tried finding information about the <code>$wp_filesystem</code> thing, but there is very little information available and even less examples (to be honest, I'm not totally sure if that's the correct function to use).</p>
<p>How can I use a Wordpress function to retrieve a file and echo the contents of it in a PHP-file?</p>
<p>I'm really at loss what I should do with this. All help is very much appreciated!</p>
| [
{
"answer_id": 370376,
"author": "Ejaz UL Haq",
"author_id": 178714,
"author_profile": "https://wordpress.stackexchange.com/users/178714",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Solution 01</strong></p>\n<pre><code>$wp_filesystem = new WP_Filesystem_Direct(null);\n$svg= $wp_filesystem->get_contents(get_stylesheet_directory_uri() . '/assets/images/Search_Glyph.svg');\n</code></pre>\n<p><strong>Solution 02</strong></p>\n<pre><code>$remote_svg_file = wp_remote_get(get_stylesheet_directory_uri() . '/assets/images/Search_Glyph.svg');\n$svg_content = wp_remote_retrieve_body($remote_svg_file );\n</code></pre>\n"
},
{
"answer_id": 370377,
"author": "Sabbir Hasan",
"author_id": 76587,
"author_profile": "https://wordpress.stackexchange.com/users/76587",
"pm_score": 2,
"selected": true,
"text": "<p>Firstly add this two line to your functions.php file. Sorry I forgot to mention about this earlier.</p>\n<pre><code>require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php';\nrequire_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php';\n</code></pre>\n<p>now you can use <code>WP_Filesystem_Direct::get_contents($path)</code> instead of <code>file_get_contents($path)</code></p>\n"
}
] | 2020/07/04 | [
"https://wordpress.stackexchange.com/questions/370369",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/170373/"
] | I'm using the PHP `file_get_contents()` function to retrieve and echo the contents of an SVG-file.
```
<?php echo file_get_contents( get_stylesheet_directory_uri() . '/assets/images/Search_Glyph.svg' ); ?>
```
I checked the theme with the [Wordpress.org theme checker](https://wordpress.org/plugins/theme-check/) and I am currently resolving all the issues. One of the issues is the use of `file_get_contents`.
It gives me the following warning:
```
WARNING: file_get_contents was found in the file header.php File operations should use the WP_Filesystem methods instead of direct PHP filesystem calls.
```
I tried finding information about the `$wp_filesystem` thing, but there is very little information available and even less examples (to be honest, I'm not totally sure if that's the correct function to use).
How can I use a Wordpress function to retrieve a file and echo the contents of it in a PHP-file?
I'm really at loss what I should do with this. All help is very much appreciated! | Firstly add this two line to your functions.php file. Sorry I forgot to mention about this earlier.
```
require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php';
require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php';
```
now you can use `WP_Filesystem_Direct::get_contents($path)` instead of `file_get_contents($path)` |
370,391 | <p>I have been with this for several days to see if you can help me. I need to take the data of the variable $result, which is 6, from the operation function to my shortcode, how can I do this?</p>
<pre>
operation();
function operation(){
$result=5+1;
return $result;
}
function my_function($result){ //
return $all=$result+5;
}
add_shortcode( 'my-shortcode', 'my_function' );
</pre>
| [
{
"answer_id": 370392,
"author": "Will Craig",
"author_id": 16220,
"author_profile": "https://wordpress.stackexchange.com/users/16220",
"pm_score": 1,
"selected": false,
"text": "<p>Not sure what you would need this for but this is how you take the data of the variable $result from the operation function to your shortcode:</p>\n<pre><code>operation();\n\nfunction operation(){\n$result=5+1;\nreturn $result;\n}\n\nfunction my_function(){\n$result = operation();\nreturn (string)$result;\n}\nadd_shortcode( 'my-shortcode', 'my_function' );\n</code></pre>\n"
},
{
"answer_id": 370397,
"author": "Ivan Shatsky",
"author_id": 124579,
"author_profile": "https://wordpress.stackexchange.com/users/124579",
"pm_score": -1,
"selected": false,
"text": "<p>Do you mean something like this?</p>\n<pre><code>function some_function( $a ) {\n return $a * 2;\n}\nfunction my_shortcode( $atts ) {\n $params = shortcode_atts( array(\n 'value' => 0\n ), $atts );\n return (string)some_function( $params['value'] );\n}\nadd_shortcode( 'my-shortcode', 'my_shortcode' );\n</code></pre>\n<p>When you use <code>[my-shortcode value=2]</code> on your page, it would be substituted with the result of <code>some_function(2)</code> (i.e. <code>4</code>).</p>\n"
}
] | 2020/07/05 | [
"https://wordpress.stackexchange.com/questions/370391",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/189413/"
] | I have been with this for several days to see if you can help me. I need to take the data of the variable $result, which is 6, from the operation function to my shortcode, how can I do this?
```
operation();
function operation(){
$result=5+1;
return $result;
}
function my_function($result){ //
return $all=$result+5;
}
add_shortcode( 'my-shortcode', 'my_function' );
``` | Not sure what you would need this for but this is how you take the data of the variable $result from the operation function to your shortcode:
```
operation();
function operation(){
$result=5+1;
return $result;
}
function my_function(){
$result = operation();
return (string)$result;
}
add_shortcode( 'my-shortcode', 'my_function' );
``` |
370,423 | <p>I'm currently developing an updated version of a live site in a local environment. It's a very large site and the local dev site is using a entirely new theme without many of the live site's plugins or functionality. The live site uses Avada Fusion and almost all content is wrapped in shortcodes forcing me to basically re-publish each post manually using the dev site's new setup (using ACF Pro, custom fields). I've spent weeks removing the live site theme, unnecessary thumbnails, plugins, and all sorts of space hogging files. The only problem is bringing in the new posts from the live site. They are adding new posts weekly and I'm about 25 behind. :)</p>
<p>Is there a way to export/import the new posts from the live site into the local dev site that would include all the posts' featured images, galleries within the post, etc? This would only be for posts, and I would love to pull from a specific date like May 15 to Current.</p>
<p>I attempted the standard Tools > export/import and it added the posts ok but it didn't include featured images or any of the images within the posts. I'm curious about plugins like WP Migrate DB Pro and their merge feature but I don't want to overwrite or add back any of the images I've painstakingly removed or regenerated with lossless compression.</p>
| [
{
"answer_id": 370392,
"author": "Will Craig",
"author_id": 16220,
"author_profile": "https://wordpress.stackexchange.com/users/16220",
"pm_score": 1,
"selected": false,
"text": "<p>Not sure what you would need this for but this is how you take the data of the variable $result from the operation function to your shortcode:</p>\n<pre><code>operation();\n\nfunction operation(){\n$result=5+1;\nreturn $result;\n}\n\nfunction my_function(){\n$result = operation();\nreturn (string)$result;\n}\nadd_shortcode( 'my-shortcode', 'my_function' );\n</code></pre>\n"
},
{
"answer_id": 370397,
"author": "Ivan Shatsky",
"author_id": 124579,
"author_profile": "https://wordpress.stackexchange.com/users/124579",
"pm_score": -1,
"selected": false,
"text": "<p>Do you mean something like this?</p>\n<pre><code>function some_function( $a ) {\n return $a * 2;\n}\nfunction my_shortcode( $atts ) {\n $params = shortcode_atts( array(\n 'value' => 0\n ), $atts );\n return (string)some_function( $params['value'] );\n}\nadd_shortcode( 'my-shortcode', 'my_shortcode' );\n</code></pre>\n<p>When you use <code>[my-shortcode value=2]</code> on your page, it would be substituted with the result of <code>some_function(2)</code> (i.e. <code>4</code>).</p>\n"
}
] | 2020/07/05 | [
"https://wordpress.stackexchange.com/questions/370423",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/191109/"
] | I'm currently developing an updated version of a live site in a local environment. It's a very large site and the local dev site is using a entirely new theme without many of the live site's plugins or functionality. The live site uses Avada Fusion and almost all content is wrapped in shortcodes forcing me to basically re-publish each post manually using the dev site's new setup (using ACF Pro, custom fields). I've spent weeks removing the live site theme, unnecessary thumbnails, plugins, and all sorts of space hogging files. The only problem is bringing in the new posts from the live site. They are adding new posts weekly and I'm about 25 behind. :)
Is there a way to export/import the new posts from the live site into the local dev site that would include all the posts' featured images, galleries within the post, etc? This would only be for posts, and I would love to pull from a specific date like May 15 to Current.
I attempted the standard Tools > export/import and it added the posts ok but it didn't include featured images or any of the images within the posts. I'm curious about plugins like WP Migrate DB Pro and their merge feature but I don't want to overwrite or add back any of the images I've painstakingly removed or regenerated with lossless compression. | Not sure what you would need this for but this is how you take the data of the variable $result from the operation function to your shortcode:
```
operation();
function operation(){
$result=5+1;
return $result;
}
function my_function(){
$result = operation();
return (string)$result;
}
add_shortcode( 'my-shortcode', 'my_function' );
``` |
370,425 | <p><strong>UPDATE: 2020-07-12</strong> I tried installing on Windows 10 64-bit and it failed to install WordPress with the same database error as on Windows 7. That tells me that <em><strong>either there is a bug in WAMPServer 3.2.0 or there is a bug in WordPress 5.4.2.</strong></em> because the issue occurs on both operating systems.</p>
<hr />
<h2>ISSUE</h2>
<p>I'm installing WordPress on <em><strong>WAMP</strong></em> as a <em><strong>local development server</strong></em>, WordPress fails to install, so <em><strong>no config file is created</strong></em>.</p>
<blockquote>
<p>Can’t select database</p>
<p>We were able to connect to the database server (which means your username and password is okay) but not able to select the wp_ehw_20200627 database.</p>
<p>Are you sure it exists?</p>
<p>Does the user root have permission to use the wp_ehw_20200627 database?
On some systems the name of your database is prefixed with your username, so it would be like username_wp_ehw_20200627. Could that be the problem?</p>
<p>If you don’t know how to set up a database you should contact your host. If all else fails you may find help at the WordPress Support Forums.</p>
</blockquote>
<h2>MY SYSTEM DETAILS</h2>
<ul>
<li>Windows 7 Ultimate 64-bit</li>
<li>WAMPServer 3.2.0</li>
<li>WordPress 5.4.2</li>
</ul>
<h2>HERE IS WHAT I KNOW</h2>
<ul>
<li>The database exists and I can run SQL commands on it in phpMyAdmin.</li>
<li>My user is root</li>
<li>Host is localhost</li>
<li>Database is wp_ehw_20200627</li>
<li>root has all privileges to database (as verified in phpMyAdmin)</li>
</ul>
<p><em><strong>NOTE: I asked a similar question about a year ago, but this one is significantly different in that with the previous question WordPress was already installed, wheres in this scenario it is not.</strong></em></p>
<h2>THINGS I TRIED ALREADY</h2>
<p>Suspecting that there might be issues with the naming of the database, I tried creating various empty databases for the install with different names. Success here is measured by whether or not the config.php file was created. Here are some of the names and results I tried:</p>
<ul>
<li>wp_ehw_2020627 - failed</li>
<li>wpehw20200704 - failed</li>
<li>test - SUCCESS!</li>
</ul>
<p>By using the db I created named "test", for the first time I got this SUCCESS message:</p>
<blockquote>
<p>"All right, sparky! You’ve made it through this part of the
installation. WordPress can now communicate with your database. If you
are ready, time now to…</p>
<p>Run the installation"</p>
</blockquote>
<p>This result was encouraging, but that wasn't the database name I wanted. Suspect the issue was the length of the database name (in characters), I continued testing with differnt names, getting smaller in size each time.</p>
<ul>
<li>ehw200704 - failed</li>
<li>200704 - failed</li>
</ul>
<p>Finally, since "test" was the only name that worked so far, I picked another easy four-letter word to test if four was the magic number.</p>
<ul>
<li>john - failed</li>
</ul>
<p>WEIRD ....</p>
<p>I also cleared Chrome cache in between each install attempt. I deleted the config file after success.</p>
<h3>RESULTS</h3>
<p>Only "test" created the config file.</p>
<p>I am very confused by these results.</p>
<p>Any help is appreciated.</p>
| [
{
"answer_id": 370392,
"author": "Will Craig",
"author_id": 16220,
"author_profile": "https://wordpress.stackexchange.com/users/16220",
"pm_score": 1,
"selected": false,
"text": "<p>Not sure what you would need this for but this is how you take the data of the variable $result from the operation function to your shortcode:</p>\n<pre><code>operation();\n\nfunction operation(){\n$result=5+1;\nreturn $result;\n}\n\nfunction my_function(){\n$result = operation();\nreturn (string)$result;\n}\nadd_shortcode( 'my-shortcode', 'my_function' );\n</code></pre>\n"
},
{
"answer_id": 370397,
"author": "Ivan Shatsky",
"author_id": 124579,
"author_profile": "https://wordpress.stackexchange.com/users/124579",
"pm_score": -1,
"selected": false,
"text": "<p>Do you mean something like this?</p>\n<pre><code>function some_function( $a ) {\n return $a * 2;\n}\nfunction my_shortcode( $atts ) {\n $params = shortcode_atts( array(\n 'value' => 0\n ), $atts );\n return (string)some_function( $params['value'] );\n}\nadd_shortcode( 'my-shortcode', 'my_shortcode' );\n</code></pre>\n<p>When you use <code>[my-shortcode value=2]</code> on your page, it would be substituted with the result of <code>some_function(2)</code> (i.e. <code>4</code>).</p>\n"
}
] | 2020/07/05 | [
"https://wordpress.stackexchange.com/questions/370425",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/49697/"
] | **UPDATE: 2020-07-12** I tried installing on Windows 10 64-bit and it failed to install WordPress with the same database error as on Windows 7. That tells me that ***either there is a bug in WAMPServer 3.2.0 or there is a bug in WordPress 5.4.2.*** because the issue occurs on both operating systems.
---
ISSUE
-----
I'm installing WordPress on ***WAMP*** as a ***local development server***, WordPress fails to install, so ***no config file is created***.
>
> Can’t select database
>
>
> We were able to connect to the database server (which means your username and password is okay) but not able to select the wp\_ehw\_20200627 database.
>
>
> Are you sure it exists?
>
>
> Does the user root have permission to use the wp\_ehw\_20200627 database?
> On some systems the name of your database is prefixed with your username, so it would be like username\_wp\_ehw\_20200627. Could that be the problem?
>
>
> If you don’t know how to set up a database you should contact your host. If all else fails you may find help at the WordPress Support Forums.
>
>
>
MY SYSTEM DETAILS
-----------------
* Windows 7 Ultimate 64-bit
* WAMPServer 3.2.0
* WordPress 5.4.2
HERE IS WHAT I KNOW
-------------------
* The database exists and I can run SQL commands on it in phpMyAdmin.
* My user is root
* Host is localhost
* Database is wp\_ehw\_20200627
* root has all privileges to database (as verified in phpMyAdmin)
***NOTE: I asked a similar question about a year ago, but this one is significantly different in that with the previous question WordPress was already installed, wheres in this scenario it is not.***
THINGS I TRIED ALREADY
----------------------
Suspecting that there might be issues with the naming of the database, I tried creating various empty databases for the install with different names. Success here is measured by whether or not the config.php file was created. Here are some of the names and results I tried:
* wp\_ehw\_2020627 - failed
* wpehw20200704 - failed
* test - SUCCESS!
By using the db I created named "test", for the first time I got this SUCCESS message:
>
> "All right, sparky! You’ve made it through this part of the
> installation. WordPress can now communicate with your database. If you
> are ready, time now to…
>
>
> Run the installation"
>
>
>
This result was encouraging, but that wasn't the database name I wanted. Suspect the issue was the length of the database name (in characters), I continued testing with differnt names, getting smaller in size each time.
* ehw200704 - failed
* 200704 - failed
Finally, since "test" was the only name that worked so far, I picked another easy four-letter word to test if four was the magic number.
* john - failed
WEIRD ....
I also cleared Chrome cache in between each install attempt. I deleted the config file after success.
### RESULTS
Only "test" created the config file.
I am very confused by these results.
Any help is appreciated. | Not sure what you would need this for but this is how you take the data of the variable $result from the operation function to your shortcode:
```
operation();
function operation(){
$result=5+1;
return $result;
}
function my_function(){
$result = operation();
return (string)$result;
}
add_shortcode( 'my-shortcode', 'my_function' );
``` |
370,452 | <p>I am having trouble getting pagination working for custom taxonomy archive with the custom query. The pagination on the taxonomy archive ends up with a 404 page.</p>
<p>I have to run a query multiple times on many areas, so I have created a method for that.</p>
<h1>Query Method</h1>
<pre><code>/**
* @param bool $post_type
* @param bool $posts_per_page
* @param bool $paged
* @param array $extra_args
*
* @return \WP_Query
*/
public function module_query( $post_type = FALSE, $posts_per_page = FALSE, $paged = FALSE, array $extra_args = [] ) {
// basic arguments
$args = [
'post_type' => $post_type ? $post_type : self::get_module_cpt(),
'posts_per_page' => $posts_per_page ? $posts_per_page : - 1,
'orderby' => 'title',
'order' => 'ASC',
];
// set paged
if ( $paged ) {
$args[ 'paged' ] = $paged;
}
$args = wp_parse_args( $extra_args, $args );
// init meta query var
$meta_query = [];
$meta_query[] = [
'relation' => 'AND',
[
'key' => 'permit_roles',
'compare' => 'NOT EXISTS',
],
[
'key' => 'permit_users',
'compare' => 'NOT EXISTS',
],
];
$meta_query[] = [
'relation' => 'AND',
[
'key' => 'permit_roles',
'value' => '',
'compare' => '=',
],
[
'key' => 'permit_users',
'value' => '',
'compare' => '=',
],
];
// init permit roles var
$permit_roles = [];
$r = 0;
// loop through each roles and prepare array for meta query
foreach ( $this->get_current_user_roles() as $current_user_role ) {
$permit_roles[ $r ][ 'key' ] = 'permit_roles';
$permit_roles[ $r ][ 'value' ] = sprintf( ':"%s";', $current_user_role );
$permit_roles[ $r ][ 'compare' ] = 'LIKE';
$r ++;
}
$meta_query[] = [
'relation' => 'OR',
$permit_roles,
[
'key' => 'permit_users',
'value' => sprintf( ':"%s";', get_current_user_id() ),
'compare' => 'LIKE',
],
];
// add meta query relation if more than one query
if ( count( $meta_query ) > 1 ) {
$meta_query[ 'relation' ] = 'OR';
}
// add meta query only for non admin users
if ( ! current_user_can( 'administrator' ) ) {
$args[ 'meta_query' ] = $meta_query;
}
// return the query object
return new WP_Query( $args );
}
</code></pre>
<h1>taxonomy.php Query</h1>
<pre><code>$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$the_query = $cp->module_query(
$cp::get_resource_cpt(), cp_get_addons_per_page(), $paged,
[
'orderby' => 'publish_date',
'tax_query' => [
'taxonomy' => $term->taxonomy,
'field' => 'slug',
'terms' => [ $term->slug ],
'operator' => 'IN',
],
]
);
...
// while loop
...
// pagination
$cp->bootstrap_pagination( $the_query );
// reset query
wp_reset_postdata();
</code></pre>
<h1>Pagination function</h1>
<blockquote>
<p>The pagination is working fine on the Custom Post time page with a
custom loop.</p>
</blockquote>
<pre><code>function bootstrap_pagination( \WP_Query $wp_query = NULL, $echo = TRUE ) {
if ( NULL === $wp_query ) {
global $wp_query;
}
$pages = paginate_links( [
'base' => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var( 'paged' ) ),
'total' => $wp_query->max_num_pages,
'type' => 'array',
'show_all' => FALSE,
'end_size' => 3,
'mid_size' => 1,
'prev_next' => TRUE,
'prev_text' => __( '« Prev' ),
'next_text' => __( 'Next »' ),
'add_args' => FALSE,
'add_fragment' => '',
]
);
if ( is_array( $pages ) ) {
$pagination = '<div class="row"><div class="col mt-5"><div class="pagination d-flex justify-content-center"><ul class="pagination pagination-sm">';
foreach ( $pages as $page ) {
$pagination .= '<li class="page-item' . ( strpos( $page, 'current' ) !== FALSE ? ' active' : '' ) . '"> ' . str_replace( 'page-numbers', 'page-link', $page ) . '</li>';
}
$pagination .= '</ul></div></div></div><!-- end pagination -->';
if ( $echo ) {
echo $pagination;
} else {
return $pagination;
}
}
return NULL;
}
</code></pre>
| [
{
"answer_id": 370462,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 3,
"selected": true,
"text": "<p><em>In short, your code is fine, but the custom query's pagination and the one for the main query, they can't be using the same <code>paged</code> URL query string</em> (which WordPress reads the value from for the <code>paged</code> query arg used in a <code>WP_Query</code> request).</p>\n<h2>Why the error 404?</h2>\n<p>So for examples, paginated/paged category requests can have one of these URLs:</p>\n<ul>\n<li><p>Full pretty URL:<br>\n<code>https://example.com/category/uncategorized/page/2/</code></p>\n</li>\n<li><p>Semi-pretty URL which redirects to the above URL:<br>\n<code>https://example.com/category/uncategorized/?paged=2</code></p>\n</li>\n<li><p>"Ugly URL" (e.g. when permalinks are not enabled)<br>\n<code>https://example.com/?cat=1&paged=2</code></p>\n</li>\n</ul>\n<p>And as you can see, the URLs are using the query string <code>paged</code> which you can get the value using <code>get_query_var( 'paged' )</code>. (Note that in the first URL, the <code>page/2</code> is equivalent to <code>paged=2</code>)</p>\n<p>And because a category/taxonomy archive is a <strong>non</strong>-singular request (just like search results pages), the <code>paged</code> value will be used in the main query's request, i.e. the SQL command for querying the requested archive, unless of course if pagination is <em>not</em> enabled for the main query.</p>\n<p>Therefore, the <code>paged</code> value needs to be valid, i.e. it must not exceed the <em>max number of</em> pages for that specific request (the main query). And if the max is exceeded, then you'd get a <code>404</code> error because there were no more posts found via the main query. Just like a book with 10 pages (including covers); there's logically no page #11, right?</p>\n<p>So because your custom query is being paginated using the <code>paged</code> query string, then if you get the error 404, it's likely because the custom query had more pages than the main query.</p>\n<p>Sample scenario demonstrating the above:</p>\n<ul>\n<li><p>On a category archive page (e.g. at <code>example.com/category/uncategorized</code>), there were 3 pages shown in the pagination. And that's for the main query which WordPress runs first on page load.</p>\n</li>\n<li><p>Then in the category template, you run a custom query for, maybe a custom post type.</p>\n</li>\n<li><p>Then you added a pagination for the custom query and there were 5 pages shown in that pagination.</p>\n</li>\n<li><p>So if both the paginations are using the same <code>paged</code> query string, then for example, going to page #4 will cause a <code>404</code> error because the main query (for the category) had only at most 3 pages of results.</p>\n</li>\n</ul>\n<h2>How to fix the error</h2>\n<p>(<strong>Note:</strong> These are listed in <em>no specific order</em>.)</p>\n<ul>\n<li><p>As I said in the comments, you can use a custom URL query string like <code>page_num</code>, <code>pg</code>, etc. along with <code>paged</code>.</p>\n<p>So the <code>paged</code> will always be just for the main query, while <code>page_num</code> or <code>pg</code> will be used with your custom query.</p>\n</li>\n<li><p>Use AJAX instead to paginate the custom query, but AJAX is not in scope of this answer. (Or that it's up to you to look for a solution and implement it.)</p>\n</li>\n<li><p>Use a static Page (post of the <code>page</code> type), e.g. at <code>example.com/my-tax-archive</code>, and run your custom queries in the Page Template.</p>\n<p>For singular requests, WordPress doesn't use the <code>paged</code> in the request SQL, so the <code>paged</code> value can be any number (2, 20, 200, 2000, etc.).</p>\n</li>\n</ul>\n<h2>But there's a trick to make <code>paged</code> works for both the main query and custom queries.. on archive pages.</h2>\n<ol>\n<li><p>Add this to your theme's <code>functions.php</code> file:</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'pre_get_posts', function ( $query ) {\n if ( is_admin() || ! $query->is_main_query() ||\n ! is_tax( 'your_tax' ) ) {\n return;\n }\n\n if ( ! empty( $_GET['pgs'] ) &&\n ( $paged = max( 1, $query->get( 'paged' ) ) ) &&\n // Runs only if the current page number exceeds the main query's max pages.\n $paged > $_GET['pgs']\n ) {\n $query->set( 'pg', $paged ); // for the custom query's pagination\n $query->set( 'paged', $_GET['pgs'] ); // for the main query's pagination\n\n // Prevent WordPress from redirecting to page/<max pages>.\n remove_action( 'template_redirect', 'redirect_canonical' );\n } else {\n $query->set( 'pg', $query->get( 'paged' ) );\n }\n} );\n</code></pre>\n</li>\n<li><p>Then in the <code>bootstrap_pagination()</code> function, apply the four (<code>[1]</code> to <code>[4]</code>) changes below:</p>\n<pre class=\"lang-php prettyprint-override\"><code>// [1] Add the $use_alt\nfunction bootstrap_pagination( \\WP_Query $wp_query = NULL, $echo = TRUE, $use_alt = null ) {\n\n ...\n\n // [2] Add these:\n $add_args = [];\n if ( $use_alt ) {\n $add_args['pgs'] = $GLOBALS['wp_query']->max_num_pages;\n }\n\n $pages = paginate_links( [\n ...\n // [3] Use this instead.\n 'current' => max( 1, get_query_var( $use_alt ? 'pg' : 'paged' ) ),\n ...\n // [4] Use the $add_args\n 'add_args' => $add_args,\n ...\n ]\n );\n\n ...\n}\n</code></pre>\n</li>\n<li><p>Then in the archive/<code>taxonomy.php</code> template:</p>\n<pre class=\"lang-php prettyprint-override\"><code>// Define the $paged like so:\n$paged = max( 1, get_query_var( 'pg' ) );\n\n// ... your code here.\n\n// Then call bootstrap_pagination() like so:\nbootstrap_pagination( $the_query, true, true );\n</code></pre>\n</li>\n</ol>\n<p>Tried & tested working, but obviously as you can see above, once the max num pages for the main query has been reached, the next pages will set the <code>paged</code> to that max num pages value. So it's up to you how to not make that "look bad/weird/whatever" and to handle things like performance (if your custom query had 20 extra pages than the main query, then one would see the main query's last page 20 times.. if they viewed them all).</p>\n"
},
{
"answer_id": 395399,
"author": "Divyesh Sapariya",
"author_id": 212264,
"author_profile": "https://wordpress.stackexchange.com/users/212264",
"pm_score": 0,
"selected": false,
"text": "<p>If you facing the same issue so please go to the reading option page in settings and check how many numbers were set in the "Blog pages show at most" field value. if "Blog pages show at most" values are set greater than compared to your custom archive page or default page query string per page post parameter so you need to change the backend "Blog pages show at most" field value to match custom query per page post value.</p>\n<p>For example :<br />\n"Blog pages show at most" field value is 12 and my custom query is</p>\n<pre class=\"lang-php prettyprint-override\"><code>$args = array(\n 'post_type' => 'post',\n 'posts_per_page' => 10,\n 'tax_query' => array(\n 'relation' => 'OR',\n array(\n 'taxonomy' => 'category',\n 'field' => 'id',\n 'include_children' => true,\n 'terms' => array(get_queried_object_id())\n )\n ),\n 'paged' => $paged\n);\n$wp_query = new WP_Query($args);\n</code></pre>\n<p>As an above query, you see posts_per_page parameter value is 10 but still, we have set 12 in backend so it will cause an issue in pagination page because it will consider per page 12 posts so please change 12 to 10 and pagination will work properly, In my case, it works.</p>\n"
}
] | 2020/07/06 | [
"https://wordpress.stackexchange.com/questions/370452",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/9821/"
] | I am having trouble getting pagination working for custom taxonomy archive with the custom query. The pagination on the taxonomy archive ends up with a 404 page.
I have to run a query multiple times on many areas, so I have created a method for that.
Query Method
============
```
/**
* @param bool $post_type
* @param bool $posts_per_page
* @param bool $paged
* @param array $extra_args
*
* @return \WP_Query
*/
public function module_query( $post_type = FALSE, $posts_per_page = FALSE, $paged = FALSE, array $extra_args = [] ) {
// basic arguments
$args = [
'post_type' => $post_type ? $post_type : self::get_module_cpt(),
'posts_per_page' => $posts_per_page ? $posts_per_page : - 1,
'orderby' => 'title',
'order' => 'ASC',
];
// set paged
if ( $paged ) {
$args[ 'paged' ] = $paged;
}
$args = wp_parse_args( $extra_args, $args );
// init meta query var
$meta_query = [];
$meta_query[] = [
'relation' => 'AND',
[
'key' => 'permit_roles',
'compare' => 'NOT EXISTS',
],
[
'key' => 'permit_users',
'compare' => 'NOT EXISTS',
],
];
$meta_query[] = [
'relation' => 'AND',
[
'key' => 'permit_roles',
'value' => '',
'compare' => '=',
],
[
'key' => 'permit_users',
'value' => '',
'compare' => '=',
],
];
// init permit roles var
$permit_roles = [];
$r = 0;
// loop through each roles and prepare array for meta query
foreach ( $this->get_current_user_roles() as $current_user_role ) {
$permit_roles[ $r ][ 'key' ] = 'permit_roles';
$permit_roles[ $r ][ 'value' ] = sprintf( ':"%s";', $current_user_role );
$permit_roles[ $r ][ 'compare' ] = 'LIKE';
$r ++;
}
$meta_query[] = [
'relation' => 'OR',
$permit_roles,
[
'key' => 'permit_users',
'value' => sprintf( ':"%s";', get_current_user_id() ),
'compare' => 'LIKE',
],
];
// add meta query relation if more than one query
if ( count( $meta_query ) > 1 ) {
$meta_query[ 'relation' ] = 'OR';
}
// add meta query only for non admin users
if ( ! current_user_can( 'administrator' ) ) {
$args[ 'meta_query' ] = $meta_query;
}
// return the query object
return new WP_Query( $args );
}
```
taxonomy.php Query
==================
```
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$the_query = $cp->module_query(
$cp::get_resource_cpt(), cp_get_addons_per_page(), $paged,
[
'orderby' => 'publish_date',
'tax_query' => [
'taxonomy' => $term->taxonomy,
'field' => 'slug',
'terms' => [ $term->slug ],
'operator' => 'IN',
],
]
);
...
// while loop
...
// pagination
$cp->bootstrap_pagination( $the_query );
// reset query
wp_reset_postdata();
```
Pagination function
===================
>
> The pagination is working fine on the Custom Post time page with a
> custom loop.
>
>
>
```
function bootstrap_pagination( \WP_Query $wp_query = NULL, $echo = TRUE ) {
if ( NULL === $wp_query ) {
global $wp_query;
}
$pages = paginate_links( [
'base' => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var( 'paged' ) ),
'total' => $wp_query->max_num_pages,
'type' => 'array',
'show_all' => FALSE,
'end_size' => 3,
'mid_size' => 1,
'prev_next' => TRUE,
'prev_text' => __( '« Prev' ),
'next_text' => __( 'Next »' ),
'add_args' => FALSE,
'add_fragment' => '',
]
);
if ( is_array( $pages ) ) {
$pagination = '<div class="row"><div class="col mt-5"><div class="pagination d-flex justify-content-center"><ul class="pagination pagination-sm">';
foreach ( $pages as $page ) {
$pagination .= '<li class="page-item' . ( strpos( $page, 'current' ) !== FALSE ? ' active' : '' ) . '"> ' . str_replace( 'page-numbers', 'page-link', $page ) . '</li>';
}
$pagination .= '</ul></div></div></div><!-- end pagination -->';
if ( $echo ) {
echo $pagination;
} else {
return $pagination;
}
}
return NULL;
}
``` | *In short, your code is fine, but the custom query's pagination and the one for the main query, they can't be using the same `paged` URL query string* (which WordPress reads the value from for the `paged` query arg used in a `WP_Query` request).
Why the error 404?
------------------
So for examples, paginated/paged category requests can have one of these URLs:
* Full pretty URL:
`https://example.com/category/uncategorized/page/2/`
* Semi-pretty URL which redirects to the above URL:
`https://example.com/category/uncategorized/?paged=2`
* "Ugly URL" (e.g. when permalinks are not enabled)
`https://example.com/?cat=1&paged=2`
And as you can see, the URLs are using the query string `paged` which you can get the value using `get_query_var( 'paged' )`. (Note that in the first URL, the `page/2` is equivalent to `paged=2`)
And because a category/taxonomy archive is a **non**-singular request (just like search results pages), the `paged` value will be used in the main query's request, i.e. the SQL command for querying the requested archive, unless of course if pagination is *not* enabled for the main query.
Therefore, the `paged` value needs to be valid, i.e. it must not exceed the *max number of* pages for that specific request (the main query). And if the max is exceeded, then you'd get a `404` error because there were no more posts found via the main query. Just like a book with 10 pages (including covers); there's logically no page #11, right?
So because your custom query is being paginated using the `paged` query string, then if you get the error 404, it's likely because the custom query had more pages than the main query.
Sample scenario demonstrating the above:
* On a category archive page (e.g. at `example.com/category/uncategorized`), there were 3 pages shown in the pagination. And that's for the main query which WordPress runs first on page load.
* Then in the category template, you run a custom query for, maybe a custom post type.
* Then you added a pagination for the custom query and there were 5 pages shown in that pagination.
* So if both the paginations are using the same `paged` query string, then for example, going to page #4 will cause a `404` error because the main query (for the category) had only at most 3 pages of results.
How to fix the error
--------------------
(**Note:** These are listed in *no specific order*.)
* As I said in the comments, you can use a custom URL query string like `page_num`, `pg`, etc. along with `paged`.
So the `paged` will always be just for the main query, while `page_num` or `pg` will be used with your custom query.
* Use AJAX instead to paginate the custom query, but AJAX is not in scope of this answer. (Or that it's up to you to look for a solution and implement it.)
* Use a static Page (post of the `page` type), e.g. at `example.com/my-tax-archive`, and run your custom queries in the Page Template.
For singular requests, WordPress doesn't use the `paged` in the request SQL, so the `paged` value can be any number (2, 20, 200, 2000, etc.).
But there's a trick to make `paged` works for both the main query and custom queries.. on archive pages.
--------------------------------------------------------------------------------------------------------
1. Add this to your theme's `functions.php` file:
```php
add_action( 'pre_get_posts', function ( $query ) {
if ( is_admin() || ! $query->is_main_query() ||
! is_tax( 'your_tax' ) ) {
return;
}
if ( ! empty( $_GET['pgs'] ) &&
( $paged = max( 1, $query->get( 'paged' ) ) ) &&
// Runs only if the current page number exceeds the main query's max pages.
$paged > $_GET['pgs']
) {
$query->set( 'pg', $paged ); // for the custom query's pagination
$query->set( 'paged', $_GET['pgs'] ); // for the main query's pagination
// Prevent WordPress from redirecting to page/<max pages>.
remove_action( 'template_redirect', 'redirect_canonical' );
} else {
$query->set( 'pg', $query->get( 'paged' ) );
}
} );
```
2. Then in the `bootstrap_pagination()` function, apply the four (`[1]` to `[4]`) changes below:
```php
// [1] Add the $use_alt
function bootstrap_pagination( \WP_Query $wp_query = NULL, $echo = TRUE, $use_alt = null ) {
...
// [2] Add these:
$add_args = [];
if ( $use_alt ) {
$add_args['pgs'] = $GLOBALS['wp_query']->max_num_pages;
}
$pages = paginate_links( [
...
// [3] Use this instead.
'current' => max( 1, get_query_var( $use_alt ? 'pg' : 'paged' ) ),
...
// [4] Use the $add_args
'add_args' => $add_args,
...
]
);
...
}
```
3. Then in the archive/`taxonomy.php` template:
```php
// Define the $paged like so:
$paged = max( 1, get_query_var( 'pg' ) );
// ... your code here.
// Then call bootstrap_pagination() like so:
bootstrap_pagination( $the_query, true, true );
```
Tried & tested working, but obviously as you can see above, once the max num pages for the main query has been reached, the next pages will set the `paged` to that max num pages value. So it's up to you how to not make that "look bad/weird/whatever" and to handle things like performance (if your custom query had 20 extra pages than the main query, then one would see the main query's last page 20 times.. if they viewed them all). |
370,494 | <p>I'm trying to create shortcodes that will display both avatar and logged in user first name in a text widget. I have managed to create something that displays the avatar, but not the username.</p>
<p>My code is as follows:</p>
<pre><code> <?php
// show user avatar if logged in
function colaborator_avatar($atts)
{
if (is_user_logged_in() && !is_feed()) {
return get_avatar(get_the_author_meta( 'user_email' ));
}
}
add_shortcode('colaborator_avatar', 'colaborator_avatar');
// show user avatar if logged in
/**/
function colaborator_nome($atts)
{
if (is_user_logged_in() && !is_feed()) {
return get_user_meta( $new_user->ID, 'first_name', true );
}
}
add_shortcode('colaborator_nome', 'colaborator_nome');
?>
</code></pre>
<p>Have in mind that this is not for an specific ID, this to show on screen which user is logged in.</p>
<p>By the way, is it possible to define the avatar's size?</p>
<p>EDITED: Corrected a typo error in the code.</p>
| [
{
"answer_id": 370496,
"author": "mozboz",
"author_id": 176814,
"author_profile": "https://wordpress.stackexchange.com/users/176814",
"pm_score": 0,
"selected": false,
"text": "<p>I searched for 'wordpress get name of logged in user' and the first result gave <a href=\"https://developer.wordpress.org/reference/functions/wp_get_current_user/\" rel=\"nofollow noreferrer\">wp_get_current_user</a>, which will show logged in user first name. Examples of how to use from that page:</p>\n<pre><code>$current_user = wp_get_current_user();\n \n/*\n * @example Safe usage: $current_user = wp_get_current_user();\n * if ( ! ( $current_user instanceof WP_User ) ) {\n * return;\n * }\n */\nprintf( __( 'Username: %s', 'textdomain' ), esc_html( $current_user->user_login ) ) . '<br />';\nprintf( __( 'User email: %s', 'textdomain' ), esc_html( $current_user->user_email ) ) . '<br />';\nprintf( __( 'User first name: %s', 'textdomain' ), esc_html( $current_user->user_firstname ) ) . '<br />';\nprintf( __( 'User last name: %s', 'textdomain' ), esc_html( $current_user->user_lastname ) ) . '<br />';\nprintf( __( 'User display name: %s', 'textdomain' ), esc_html( $current_user->display_name ) ) . '<br />';\nprintf( __( 'User ID: %s', 'textdomain' ), esc_html( $current_user->ID ) );\n</code></pre>\n"
},
{
"answer_id": 370517,
"author": "Fredrik",
"author_id": 184451,
"author_profile": "https://wordpress.stackexchange.com/users/184451",
"pm_score": 2,
"selected": true,
"text": "<p>The issue here is that both the functions have the same name - colaborator_avatar().</p>\n<p>Make sure that $new_user contains the current user. Else use get_current_user_id() like this:</p>\n<pre><code>get_user_meta( get_current_user_id(), 'first_name', true );\n</code></pre>\n<p>Show avatar and first name:</p>\n<pre><code>// show user avatar if logged in\nfunction colaborator_avatar($atts)\n{\n if (is_user_logged_in() && !is_feed()) {\n return get_avatar(get_the_author_meta( 'user_email' ));\n }\n}\nadd_shortcode('colaborator_avatar', 'colaborator_avatar');\n\n// show username if logged in\nfunction colaborator_nome($atts)\n{\n if (is_user_logged_in() && !is_feed()) {\n return get_user_meta( $new_user->ID, 'first_name', true );\n\n }\n}\nadd_shortcode('colaborator_nome', 'colaborator_nome');\n</code></pre>\n<p>Or show Username:</p>\n<pre><code>function colaborator_nome($atts) { \n if (is_user_logged_in() && !is_feed()) { \n $current_user = wp_get_current_user();\n echo $current_user->user_login;\n } \n} \n\nadd_shortcode('colaborator_nome', 'colaborator_nome'); \n</code></pre>\n"
}
] | 2020/07/06 | [
"https://wordpress.stackexchange.com/questions/370494",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/59090/"
] | I'm trying to create shortcodes that will display both avatar and logged in user first name in a text widget. I have managed to create something that displays the avatar, but not the username.
My code is as follows:
```
<?php
// show user avatar if logged in
function colaborator_avatar($atts)
{
if (is_user_logged_in() && !is_feed()) {
return get_avatar(get_the_author_meta( 'user_email' ));
}
}
add_shortcode('colaborator_avatar', 'colaborator_avatar');
// show user avatar if logged in
/**/
function colaborator_nome($atts)
{
if (is_user_logged_in() && !is_feed()) {
return get_user_meta( $new_user->ID, 'first_name', true );
}
}
add_shortcode('colaborator_nome', 'colaborator_nome');
?>
```
Have in mind that this is not for an specific ID, this to show on screen which user is logged in.
By the way, is it possible to define the avatar's size?
EDITED: Corrected a typo error in the code. | The issue here is that both the functions have the same name - colaborator\_avatar().
Make sure that $new\_user contains the current user. Else use get\_current\_user\_id() like this:
```
get_user_meta( get_current_user_id(), 'first_name', true );
```
Show avatar and first name:
```
// show user avatar if logged in
function colaborator_avatar($atts)
{
if (is_user_logged_in() && !is_feed()) {
return get_avatar(get_the_author_meta( 'user_email' ));
}
}
add_shortcode('colaborator_avatar', 'colaborator_avatar');
// show username if logged in
function colaborator_nome($atts)
{
if (is_user_logged_in() && !is_feed()) {
return get_user_meta( $new_user->ID, 'first_name', true );
}
}
add_shortcode('colaborator_nome', 'colaborator_nome');
```
Or show Username:
```
function colaborator_nome($atts) {
if (is_user_logged_in() && !is_feed()) {
$current_user = wp_get_current_user();
echo $current_user->user_login;
}
}
add_shortcode('colaborator_nome', 'colaborator_nome');
``` |
370,564 | <p>Contact form 7 is loading reCaptcha v3 scripts on all the pages of the sites which is making the website slow.<br />
So I was using the script below which was working fine before two weeks from now, but now it stopped working and it's now loading even more scripts. Why could it be?</p>
<p>I don't want to use extra plugins.</p>
<pre><code>function contactform_dequeue_scripts() {
$load_scripts = false;
if( is_singular() ) {
$post = get_post();
if( has_shortcode($post->post_content, 'contact-form-7') ) {
$load_scripts = true;
}
}
if( ! $load_scripts ) {
wp_dequeue_script( 'contact-form-7' );
wp_dequeue_script('google-recaptcha');
wp_dequeue_style( 'contact-form-7' );
}
}
add_action( 'wp_enqueue_scripts', 'contactform_dequeue_scripts', 99 );
</code></pre>
| [
{
"answer_id": 370591,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 2,
"selected": false,
"text": "<p>I'd put the dequeue statements inside the 'if', replacing the $loadscripts line. No need to set the flag and then check the flag to dequeue. That might simplify the code for further debugging.</p>\n<p>Edited: suggested code corrections:</p>\n<pre><code>function contactform_dequeue_scripts() {\n if (is_singular()) {\n $post = get_post();\n if (has_shortcode($post->post_content, 'contact-form-7')) {\n wp_dequeue_script('contact-form-7');\n wp_dequeue_script('google-recaptcha');\n wp_dequeue_style('contact-form-7');\n }\n }\n}\nadd_action('wp_enqueue_scripts', 'contactform_dequeue_scripts', 99);\n</code></pre>\n<p>This only dequeue's scripts if there is a shortcode for CF7, and if it is a singular page. Otherwise, things are done normally. Easier to read the code and figure out what is happening.</p>\n"
},
{
"answer_id": 384498,
"author": "Krzysztof",
"author_id": 202848,
"author_profile": "https://wordpress.stackexchange.com/users/202848",
"pm_score": 1,
"selected": false,
"text": "<p>This works for me.</p>\n<pre><code>function contactform_dequeue_scripts() {\n\n $load_scripts = false;\n\n if( is_singular() ) {\n $post = get_post();\n\n if( has_shortcode($post->post_content, 'contact-form-7') ) {\n $load_scripts = true;\n \n }\n\n }\n\n if( ! $load_scripts ) {\n wp_dequeue_script( 'contact-form-7' );\n wp_dequeue_script( 'google-recaptcha' );\n wp_dequeue_script( 'wpcf7-recaptcha' ); \n wp_dequeue_style( 'wpcf7-recaptcha' );\n wp_dequeue_style( 'contact-form-7' );\n \n }\n\n}\nadd_action( 'wp_enqueue_scripts', 'contactform_dequeue_scripts', 99 );\n</code></pre>\n"
},
{
"answer_id": 387065,
"author": "user6786748",
"author_id": 205290,
"author_profile": "https://wordpress.stackexchange.com/users/205290",
"pm_score": 1,
"selected": false,
"text": "<p>A neater version:</p>\n<pre><code>function wpcf7_dequeue_redundant_scripts() {\n $post = get_post();\n if ( is_singular() && !has_shortcode( $post->post_content, 'contact-form-7' ) ) {\n wp_dequeue_script( 'contact-form-7' );\n wp_dequeue_style( 'contact-form-7' );\n wp_dequeue_script( 'wpcf7-recaptcha' ); \n wp_dequeue_style( 'wpcf7-recaptcha' );\n wp_dequeue_script( 'google-recaptcha' );\n }\n}\nadd_action( 'wp_enqueue_scripts', 'wpcf7_dequeue_redundant_scripts', 99 );\n</code></pre>\n"
},
{
"answer_id": 405033,
"author": "Lovor",
"author_id": 135704,
"author_profile": "https://wordpress.stackexchange.com/users/135704",
"pm_score": 0,
"selected": false,
"text": "<p>I use Block editor and Contact form 7 block, and this is a very elegant solution for this requirement:</p>\n<pre class=\"lang-php prettyprint-override\"><code>/**\n * Remove Contact form 7 recaptcha from each page, load only when block exists - works on version 5.5.6\n */\n\nadd_action( 'wp_enqueue_scripts', function() {\n if ( ! has_block( 'contact-form-7/contact-form-selector' ) ) {\n wp_dequeue_script( 'contact-form-7' );\n wp_dequeue_script( 'google-recaptcha' );\n wp_dequeue_script( 'wpcf7-recaptcha' );\n wp_dequeue_style( 'contact-form-7' );\n }\n}, 101 );\n</code></pre>\n<p>Please do note that author claims <a href=\"https://contactform7.com/faq-about-recaptcha-v3/#stop-script-loading\" rel=\"nofollow noreferrer\">this is not a good idea</a>.</p>\n"
}
] | 2020/07/07 | [
"https://wordpress.stackexchange.com/questions/370564",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/187916/"
] | Contact form 7 is loading reCaptcha v3 scripts on all the pages of the sites which is making the website slow.
So I was using the script below which was working fine before two weeks from now, but now it stopped working and it's now loading even more scripts. Why could it be?
I don't want to use extra plugins.
```
function contactform_dequeue_scripts() {
$load_scripts = false;
if( is_singular() ) {
$post = get_post();
if( has_shortcode($post->post_content, 'contact-form-7') ) {
$load_scripts = true;
}
}
if( ! $load_scripts ) {
wp_dequeue_script( 'contact-form-7' );
wp_dequeue_script('google-recaptcha');
wp_dequeue_style( 'contact-form-7' );
}
}
add_action( 'wp_enqueue_scripts', 'contactform_dequeue_scripts', 99 );
``` | I'd put the dequeue statements inside the 'if', replacing the $loadscripts line. No need to set the flag and then check the flag to dequeue. That might simplify the code for further debugging.
Edited: suggested code corrections:
```
function contactform_dequeue_scripts() {
if (is_singular()) {
$post = get_post();
if (has_shortcode($post->post_content, 'contact-form-7')) {
wp_dequeue_script('contact-form-7');
wp_dequeue_script('google-recaptcha');
wp_dequeue_style('contact-form-7');
}
}
}
add_action('wp_enqueue_scripts', 'contactform_dequeue_scripts', 99);
```
This only dequeue's scripts if there is a shortcode for CF7, and if it is a singular page. Otherwise, things are done normally. Easier to read the code and figure out what is happening. |
370,569 | <p>Been trying to re-map the following</p>
<pre class="lang-none prettyprint-override"><code>/test-sale-yacht/comfortably-numb-262749/
/test-sale-yacht/?yacht_name_id=comfortably-numb-262749
</code></pre>
<p>After some testing in a regular expression tester I've put the following command in the init routine of the new plugin</p>
<pre class="lang-php prettyprint-override"><code>add_rewrite_rule('test-sale-yacht/([^/]*)?', 'index.php?name=test-sale-yacht&yacht_name_id=$1', 'top');
</code></pre>
<p>This looks similar to others so i figure it should work</p>
<p>I reset the permalinks several times by going to settings > permalinks and hitting save still does not work.</p>
<p>Tried putting it in <code>functions.php</code> in the theme, still no soap.</p>
<p>According to a debug plugin there are no rules getting hits on the page.</p>
<p>tried <code>/test-sale-yacht/?yacht_name_id=comfortably-numb-262749</code>, that works<br />
tried <code>/?name=test-sale-yacht&yacht_name_id=comfortably-numb-262749</code>, that works<br />
but <code>/test-sale-yacht/comfortably-numb-262749/</code>, nothing.</p>
<p>Totally foxed on this.</p>
<p>Jules</p>
| [
{
"answer_id": 370572,
"author": "mozboz",
"author_id": 176814,
"author_profile": "https://wordpress.stackexchange.com/users/176814",
"pm_score": 1,
"selected": false,
"text": "<p>You're missing the WP <code>$matches[1]</code> syntax for the regex that gets matched.</p>\n<p>I think you want <code>/?</code> on the end too.</p>\n<p>Easiest way I found to test was to temporarily put <code>flush_rewrite_rules()</code> in whilst testing, then you don't have to do anything else. I have a similar regex which sends <code>/foo/catname/</code> to <code>index.php?taxonomy=category&term=catname</code>, here's what I used to develop on a clean test WP install - this is working fine for me.</p>\n<pre><code>function foobar() {\n add_rewrite_rule('^foo/([^/]+)/?', 'index.php?taxonomy=category&term=$matches[1]', 'top');\n flush_rewrite_rules();\n}\nadd_action('init', 'foobar', 10, 0);\n</code></pre>\n<p>So you might want to try:</p>\n<pre><code>add_rewrite_rule('test-sale-yacht/([^/]+)/?', 'index.php?name=test-sale-yacht&yacht_name_id=$matches[1]', 'top');\n</code></pre>\n<p>Edit: As per comment by @Tom J Nowell, flush_rewrite_rules is an expensive call - my suggestion to do this only on a dev or very low traffic site.</p>\n"
},
{
"answer_id": 370627,
"author": "Jules",
"author_id": 191212,
"author_profile": "https://wordpress.stackexchange.com/users/191212",
"pm_score": 0,
"selected": false,
"text": "<p>This worked in the end, not sure why I was not getting anything showing up in the re-write rules initially but this worked.</p>\n<pre><code>add_rewrite_rule( 'test-sale-yacht/([^/]*)?', \n 'index.php?pagename=test-sale-yacht&yacht_name_id=$matches[1]', 'top');\n</code></pre>\n<p>with <code>yacht_name_id</code> added in as a filter</p>\n<p>Jules</p>\n"
}
] | 2020/07/07 | [
"https://wordpress.stackexchange.com/questions/370569",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/191212/"
] | Been trying to re-map the following
```none
/test-sale-yacht/comfortably-numb-262749/
/test-sale-yacht/?yacht_name_id=comfortably-numb-262749
```
After some testing in a regular expression tester I've put the following command in the init routine of the new plugin
```php
add_rewrite_rule('test-sale-yacht/([^/]*)?', 'index.php?name=test-sale-yacht&yacht_name_id=$1', 'top');
```
This looks similar to others so i figure it should work
I reset the permalinks several times by going to settings > permalinks and hitting save still does not work.
Tried putting it in `functions.php` in the theme, still no soap.
According to a debug plugin there are no rules getting hits on the page.
tried `/test-sale-yacht/?yacht_name_id=comfortably-numb-262749`, that works
tried `/?name=test-sale-yacht&yacht_name_id=comfortably-numb-262749`, that works
but `/test-sale-yacht/comfortably-numb-262749/`, nothing.
Totally foxed on this.
Jules | You're missing the WP `$matches[1]` syntax for the regex that gets matched.
I think you want `/?` on the end too.
Easiest way I found to test was to temporarily put `flush_rewrite_rules()` in whilst testing, then you don't have to do anything else. I have a similar regex which sends `/foo/catname/` to `index.php?taxonomy=category&term=catname`, here's what I used to develop on a clean test WP install - this is working fine for me.
```
function foobar() {
add_rewrite_rule('^foo/([^/]+)/?', 'index.php?taxonomy=category&term=$matches[1]', 'top');
flush_rewrite_rules();
}
add_action('init', 'foobar', 10, 0);
```
So you might want to try:
```
add_rewrite_rule('test-sale-yacht/([^/]+)/?', 'index.php?name=test-sale-yacht&yacht_name_id=$matches[1]', 'top');
```
Edit: As per comment by @Tom J Nowell, flush\_rewrite\_rules is an expensive call - my suggestion to do this only on a dev or very low traffic site. |
370,571 | <p>My basic titles are something like</p>
<p>Part One: Part Two</p>
<p>And I'm trying to end up with something like this using the colon as what I find in the regex:</p>
<pre><code><span class="one-class">Part One:</span><br><span class="two-class">Part Two</span>
</code></pre>
<p>This is the original in <code>entry-header.php</code> and I want to continue to have that html:</p>
<pre><code>if ( is_singular() ) {
the_title( '<h1 class="entry-title">', '</h1>' );
}
</code></pre>
<p>The following works as long as there is a colon in the title. If there is no colon, then none of the html gets added.</p>
<pre><code>if ( is_singular() ) {
$string = get_the_title();
$pattern = '~(.+): (.+)~i';
$replacement = '<h1 class="entry-title"><span class="title-cite-pali">$1:</span><br><span class="title-english">$2</span></h1>';
echo preg_replace($pattern, $replacement, $string);
}
</code></pre>
<p>But I think what I really want is the following, <em><strong>but it doesn't work</strong></em>. The output is as if my added code is not there.</p>
<pre><code>if ( is_singular() ) {
$string = the_title( '<h1 class="entry-title test">', '</h1>' );
$pattern = '~(.+): (.+)~i';
$replacement = '<span class="title-cite-pali">$1:</span><br><span class="title-english">$2</span>';
echo preg_replace($pattern, $replacement, $string);
}
</code></pre>
<p>I think if I could get the above code working, it is preferable since if there was no colon at least the <code>h1</code> tags would be added.</p>
| [
{
"answer_id": 370572,
"author": "mozboz",
"author_id": 176814,
"author_profile": "https://wordpress.stackexchange.com/users/176814",
"pm_score": 1,
"selected": false,
"text": "<p>You're missing the WP <code>$matches[1]</code> syntax for the regex that gets matched.</p>\n<p>I think you want <code>/?</code> on the end too.</p>\n<p>Easiest way I found to test was to temporarily put <code>flush_rewrite_rules()</code> in whilst testing, then you don't have to do anything else. I have a similar regex which sends <code>/foo/catname/</code> to <code>index.php?taxonomy=category&term=catname</code>, here's what I used to develop on a clean test WP install - this is working fine for me.</p>\n<pre><code>function foobar() {\n add_rewrite_rule('^foo/([^/]+)/?', 'index.php?taxonomy=category&term=$matches[1]', 'top');\n flush_rewrite_rules();\n}\nadd_action('init', 'foobar', 10, 0);\n</code></pre>\n<p>So you might want to try:</p>\n<pre><code>add_rewrite_rule('test-sale-yacht/([^/]+)/?', 'index.php?name=test-sale-yacht&yacht_name_id=$matches[1]', 'top');\n</code></pre>\n<p>Edit: As per comment by @Tom J Nowell, flush_rewrite_rules is an expensive call - my suggestion to do this only on a dev or very low traffic site.</p>\n"
},
{
"answer_id": 370627,
"author": "Jules",
"author_id": 191212,
"author_profile": "https://wordpress.stackexchange.com/users/191212",
"pm_score": 0,
"selected": false,
"text": "<p>This worked in the end, not sure why I was not getting anything showing up in the re-write rules initially but this worked.</p>\n<pre><code>add_rewrite_rule( 'test-sale-yacht/([^/]*)?', \n 'index.php?pagename=test-sale-yacht&yacht_name_id=$matches[1]', 'top');\n</code></pre>\n<p>with <code>yacht_name_id</code> added in as a filter</p>\n<p>Jules</p>\n"
}
] | 2020/07/07 | [
"https://wordpress.stackexchange.com/questions/370571",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/184735/"
] | My basic titles are something like
Part One: Part Two
And I'm trying to end up with something like this using the colon as what I find in the regex:
```
<span class="one-class">Part One:</span><br><span class="two-class">Part Two</span>
```
This is the original in `entry-header.php` and I want to continue to have that html:
```
if ( is_singular() ) {
the_title( '<h1 class="entry-title">', '</h1>' );
}
```
The following works as long as there is a colon in the title. If there is no colon, then none of the html gets added.
```
if ( is_singular() ) {
$string = get_the_title();
$pattern = '~(.+): (.+)~i';
$replacement = '<h1 class="entry-title"><span class="title-cite-pali">$1:</span><br><span class="title-english">$2</span></h1>';
echo preg_replace($pattern, $replacement, $string);
}
```
But I think what I really want is the following, ***but it doesn't work***. The output is as if my added code is not there.
```
if ( is_singular() ) {
$string = the_title( '<h1 class="entry-title test">', '</h1>' );
$pattern = '~(.+): (.+)~i';
$replacement = '<span class="title-cite-pali">$1:</span><br><span class="title-english">$2</span>';
echo preg_replace($pattern, $replacement, $string);
}
```
I think if I could get the above code working, it is preferable since if there was no colon at least the `h1` tags would be added. | You're missing the WP `$matches[1]` syntax for the regex that gets matched.
I think you want `/?` on the end too.
Easiest way I found to test was to temporarily put `flush_rewrite_rules()` in whilst testing, then you don't have to do anything else. I have a similar regex which sends `/foo/catname/` to `index.php?taxonomy=category&term=catname`, here's what I used to develop on a clean test WP install - this is working fine for me.
```
function foobar() {
add_rewrite_rule('^foo/([^/]+)/?', 'index.php?taxonomy=category&term=$matches[1]', 'top');
flush_rewrite_rules();
}
add_action('init', 'foobar', 10, 0);
```
So you might want to try:
```
add_rewrite_rule('test-sale-yacht/([^/]+)/?', 'index.php?name=test-sale-yacht&yacht_name_id=$matches[1]', 'top');
```
Edit: As per comment by @Tom J Nowell, flush\_rewrite\_rules is an expensive call - my suggestion to do this only on a dev or very low traffic site. |
370,621 | <p>When you use the default WordPress search functionality you can only search on Title, so if you type in the title than the posts you search for will appear in the results. I would like to expand this by also being able to search on date, category and author.</p>
<p>I tried to look it up but what I mostly find is to search between dateranges or build a custom searchpage. This is however not what I am trying to accomplish. I just want the normal searchbar that puts the ?s=mysearch in the url to be able to also search on this three things.</p>
<p>Is this possible to extend somehow or do I really need to build a custom searchpage for this?</p>
<p>Thanks!</p>
| [
{
"answer_id": 370631,
"author": "Az Rieil",
"author_id": 154993,
"author_profile": "https://wordpress.stackexchange.com/users/154993",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n<p>When you use the default WordPress search functionality you can only\nsearch on Title</p>\n</blockquote>\n<p>No.</p>\n<p>WP_Query support search by multiply parameters. Include author, dates, categories.\nYou can check how it working in <code>WP_Query->parse_query</code> and <code>WP_Query->get_posts</code> and build your requests like</p>\n<pre><code>/?s=some&author=1&year=2020&monthnum=10\n</code></pre>\n"
},
{
"answer_id": 370641,
"author": "Ben",
"author_id": 190965,
"author_profile": "https://wordpress.stackexchange.com/users/190965",
"pm_score": 1,
"selected": false,
"text": "<p>By default, the WordPress search gives an omni-like search facility to WP Posts and Pages that should search any built-in WP content. This can be further extended through a plugin such as Relevanssi.</p>\n<p>You can though, if I'm understanding you correctly, create a custom search form where you can dictate the fields available to search on.</p>\n<p>You would do this first of all by creating a new file in your theme's root titled something like <code>mysearch-searchform.php</code>. This is just a HTML form, so whatever you put in will work in theory. The one must that I'm aware of is a hidden field to tell WP what post type you want to search within. So you'd use something like:</p>\n<p><code><input type="hidden" name="search" value="mycpt"></code></p>\n<p>To search for news posts only. So, you now have your custom search form, which you can call in your theme by using:</p>\n<p><code><?php get_template_part( 'mycpt', 'searchform' ); ?></code></p>\n<p>So, you have your custom form, and it's outputting onto your page. Now you need to deal with the results. For that you will look to your <code>functions.php</code> where I use the below function to tell WP what results file to load depending on the search form used:</p>\n<pre><code>function load_search_template_results(){\n if(isset($_GET['search'])) {\n if( $_GET['search'] == 'mycpt' ) {\n load_template( locate_template( 'mycpt-search-result.php' ));\n } else {\n load_template( locate_template( 'search.php' ));\n }\n }\n}\nadd_action('init','load_search_template_results');\n</code></pre>\n<p>The page <code>mycpt-search-result.php</code> is just a wp_query loop, looping through post data as required to tailor to your design.</p>\n<p>Hope that puts you on the right track.</p>\n"
}
] | 2020/07/08 | [
"https://wordpress.stackexchange.com/questions/370621",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/34616/"
] | When you use the default WordPress search functionality you can only search on Title, so if you type in the title than the posts you search for will appear in the results. I would like to expand this by also being able to search on date, category and author.
I tried to look it up but what I mostly find is to search between dateranges or build a custom searchpage. This is however not what I am trying to accomplish. I just want the normal searchbar that puts the ?s=mysearch in the url to be able to also search on this three things.
Is this possible to extend somehow or do I really need to build a custom searchpage for this?
Thanks! | By default, the WordPress search gives an omni-like search facility to WP Posts and Pages that should search any built-in WP content. This can be further extended through a plugin such as Relevanssi.
You can though, if I'm understanding you correctly, create a custom search form where you can dictate the fields available to search on.
You would do this first of all by creating a new file in your theme's root titled something like `mysearch-searchform.php`. This is just a HTML form, so whatever you put in will work in theory. The one must that I'm aware of is a hidden field to tell WP what post type you want to search within. So you'd use something like:
`<input type="hidden" name="search" value="mycpt">`
To search for news posts only. So, you now have your custom search form, which you can call in your theme by using:
`<?php get_template_part( 'mycpt', 'searchform' ); ?>`
So, you have your custom form, and it's outputting onto your page. Now you need to deal with the results. For that you will look to your `functions.php` where I use the below function to tell WP what results file to load depending on the search form used:
```
function load_search_template_results(){
if(isset($_GET['search'])) {
if( $_GET['search'] == 'mycpt' ) {
load_template( locate_template( 'mycpt-search-result.php' ));
} else {
load_template( locate_template( 'search.php' ));
}
}
}
add_action('init','load_search_template_results');
```
The page `mycpt-search-result.php` is just a wp\_query loop, looping through post data as required to tailor to your design.
Hope that puts you on the right track. |
370,625 | <p>Is possible to assign a default class to the images that are part of a post content? I have a problem with teh layout, this because the attached images insetred inside a post will break my bootstrap layout. I want to assign a default class so the user when add an image into the content will have the class assigned and the layout will not break.</p>
| [
{
"answer_id": 370630,
"author": "Az Rieil",
"author_id": 154993,
"author_profile": "https://wordpress.stackexchange.com/users/154993",
"pm_score": -1,
"selected": false,
"text": "<p>I guess you seeking of <a href=\"https://developer.wordpress.org/reference/hooks/get_image_tag_class/\" rel=\"nofollow noreferrer\">get_image_tag_class</a> filter.</p>\n"
},
{
"answer_id": 370633,
"author": "Sabbir Hasan",
"author_id": 76587,
"author_profile": "https://wordpress.stackexchange.com/users/76587",
"pm_score": 1,
"selected": true,
"text": "<p>As you are using bootstrap you can add <code>img-fluid</code> helper class to images like this.</p>\n<pre><code>function example_add_img_class( $class ) {\n \n return $class . ' img-fluid';\n \n}\n \nadd_filter( 'get_image_tag_class', 'example_add_img_class' );\n</code></pre>\n<p><code>get_image_tag_class</code> filter allows to add custom css class along side WordPress default classes. Read more about the filter <a href=\"https://developer.wordpress.org/reference/hooks/get_image_tag_class/\" rel=\"nofollow noreferrer\">here</a></p>\n"
}
] | 2020/07/08 | [
"https://wordpress.stackexchange.com/questions/370625",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/191201/"
] | Is possible to assign a default class to the images that are part of a post content? I have a problem with teh layout, this because the attached images insetred inside a post will break my bootstrap layout. I want to assign a default class so the user when add an image into the content will have the class assigned and the layout will not break. | As you are using bootstrap you can add `img-fluid` helper class to images like this.
```
function example_add_img_class( $class ) {
return $class . ' img-fluid';
}
add_filter( 'get_image_tag_class', 'example_add_img_class' );
```
`get_image_tag_class` filter allows to add custom css class along side WordPress default classes. Read more about the filter [here](https://developer.wordpress.org/reference/hooks/get_image_tag_class/) |
370,665 | <p>I currently have a block that passes some of its <code>attributes</code> down to the nested <code>InnerBlocks</code> using React's Context API (the version of WordPress that I'm on does not yet have the <a href="https://developer.wordpress.org/block-editor/developers/block-api/block-context/" rel="nofollow noreferrer">Block Context</a> feature. This allows me to successfully access the parent block's <code>attributes</code> in the nested blocks' <code>edit</code> function.</p>
<pre><code>registerBlockType("myblock", {
title: "My Block",
attributes: {
someValue: {
type: 'string',
default: '',
},
},
edit(props) {
const { someValue } = props.attributes;
// ...other code...
return (
<MyContext.Provider value={someValue}>
<InnerBlocks />
</MyContext.Provider>
);
},
save(props) {
const { someValue } = props.attributes;
return (
<InnerBlocks.Content />
);
}
});
</code></pre>
<p>However, I also want to access the parent block's attributes in the <code>save</code> function of the nested blocks. I have not been able to get React's Context API to work. Is there a method for doing this in WordPress's Block API?</p>
| [
{
"answer_id": 384997,
"author": "PattyOK",
"author_id": 107904,
"author_profile": "https://wordpress.stackexchange.com/users/107904",
"pm_score": 2,
"selected": false,
"text": "<p>You can pass data to a child via the select and dispatch hooks. So you would set up your child block with the inherited attribute and update that when the setting on the parent block changes.</p>\n<p><strong>Parent Block</strong></p>\n<p>Import dependencies</p>\n<pre><code>import { dispatch, select } from "@wordpress/data";\n</code></pre>\n<p>Your edit function might look something like this:</p>\n<pre><code>edit({ attributes, className, setAttributes, clientId }) {\n const { headerStyle } = attributes;\n\n const updateHeaderStyle = function( value ) {\n setAttributes({ headerStyle: value });\n\n // Update the child block's attributes\n var children = select('core/block-editor').getBlocksByClientId(clientId)[0].innerBlocks;\n children.forEach(function(child){\n dispatch('core/block-editor').updateBlockAttributes(child.clientId, {inheritedHeaderStyle: value})\n });\n }\n \n\n return (\n <>\n <InspectorControls>\n <PanelBody>\n \n\n <RadioControl\n label="Section Header Style"\n selected = {headerStyle}\n options = { [\n { label: 'h2', value: 'h2' },\n { label: 'h3', value: 'h3' },\n { label: 'h4', value: 'h4' },\n { label: 'h5', value: 'h5' },\n { label: 'h6', value: 'h6' },\n ]}\n onChange= {updateHeaderStyle}\n />\n </PanelBody>\n </InspectorControls>\n <InnerBlocks\n ...\n />\n <>\n );\n }\n</code></pre>\n<p><strong>Child Block</strong></p>\n<p>The above function will update on change, but within the edit function of the child block you can grab the parent attribute and set it if undefined...</p>\n<pre><code>if (!inheritedHeaderStyle) {\n var parent = select('core/block-editor').getBlockParents(clientId);\n const parentAtts = select('core/block-editor').getBlockAttributes(parent);\n setAttributes( { inheritedHeaderStyle: parentAtts.headerStyle } )\n}\n</code></pre>\n"
},
{
"answer_id": 402005,
"author": "Miroslav Peterka",
"author_id": 218565,
"author_profile": "https://wordpress.stackexchange.com/users/218565",
"pm_score": 1,
"selected": false,
"text": "<p>To achieve this you can use build in feature <code>Context</code>.</p>\n<p><strong>Parent Block</strong></p>\n<pre><code>registerBlockType( 'my-plugin/parent', {\n \n attributes: {\n switch: {\n type: 'boolean',\n default:false\n },\n },\n \n providesContext: {\n 'my-plugin/switch': 'switch',\n },\n\n edit: Edit,\n\n save,\n} );\n</code></pre>\n<p><strong>Child Block</strong></p>\n<pre><code>registerBlockType( 'my-plugin/child', {\n attributes: {\n switch: {\n type: 'boolean',\n default:false\n },\n },\n\n usesContext: [ 'my-plugin/switch' ],\n \n edit({ attributes, setAttributes, context }) {\n\n // copy value from parent context into child attribute\n setAttributes({\n switch: context["my-plugin/switch"],\n });\n },\n \n save({ attributes }) {\n\n // use this attribute\n \n },\n} );\n</code></pre>\n<p>API Reference: <a href=\"https://developer.wordpress.org/block-editor/reference-guides/block-api/block-context/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/block-editor/reference-guides/block-api/block-context/</a></p>\n"
}
] | 2020/07/09 | [
"https://wordpress.stackexchange.com/questions/370665",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/191311/"
] | I currently have a block that passes some of its `attributes` down to the nested `InnerBlocks` using React's Context API (the version of WordPress that I'm on does not yet have the [Block Context](https://developer.wordpress.org/block-editor/developers/block-api/block-context/) feature. This allows me to successfully access the parent block's `attributes` in the nested blocks' `edit` function.
```
registerBlockType("myblock", {
title: "My Block",
attributes: {
someValue: {
type: 'string',
default: '',
},
},
edit(props) {
const { someValue } = props.attributes;
// ...other code...
return (
<MyContext.Provider value={someValue}>
<InnerBlocks />
</MyContext.Provider>
);
},
save(props) {
const { someValue } = props.attributes;
return (
<InnerBlocks.Content />
);
}
});
```
However, I also want to access the parent block's attributes in the `save` function of the nested blocks. I have not been able to get React's Context API to work. Is there a method for doing this in WordPress's Block API? | You can pass data to a child via the select and dispatch hooks. So you would set up your child block with the inherited attribute and update that when the setting on the parent block changes.
**Parent Block**
Import dependencies
```
import { dispatch, select } from "@wordpress/data";
```
Your edit function might look something like this:
```
edit({ attributes, className, setAttributes, clientId }) {
const { headerStyle } = attributes;
const updateHeaderStyle = function( value ) {
setAttributes({ headerStyle: value });
// Update the child block's attributes
var children = select('core/block-editor').getBlocksByClientId(clientId)[0].innerBlocks;
children.forEach(function(child){
dispatch('core/block-editor').updateBlockAttributes(child.clientId, {inheritedHeaderStyle: value})
});
}
return (
<>
<InspectorControls>
<PanelBody>
<RadioControl
label="Section Header Style"
selected = {headerStyle}
options = { [
{ label: 'h2', value: 'h2' },
{ label: 'h3', value: 'h3' },
{ label: 'h4', value: 'h4' },
{ label: 'h5', value: 'h5' },
{ label: 'h6', value: 'h6' },
]}
onChange= {updateHeaderStyle}
/>
</PanelBody>
</InspectorControls>
<InnerBlocks
...
/>
<>
);
}
```
**Child Block**
The above function will update on change, but within the edit function of the child block you can grab the parent attribute and set it if undefined...
```
if (!inheritedHeaderStyle) {
var parent = select('core/block-editor').getBlockParents(clientId);
const parentAtts = select('core/block-editor').getBlockAttributes(parent);
setAttributes( { inheritedHeaderStyle: parentAtts.headerStyle } )
}
``` |
370,781 | <p>I have a custom post type called products, which I have attached a custom taxonomy called Product Categories.</p>
<p>On each of the Product Categories, I have used Advanced Custom Fields to add fields such as product category colour, logo etc.</p>
<p>Initially, I'm trying to display the Product Category colour as a background colour for all of the products that fall inside that specific Product Category.</p>
<p>I've tried using the same method as I used to display the colour on the actual Product Category page (taxonomy-product_category.php), by adding this to the top of the page:</p>
<pre><code>// get the current taxonomy term
$term = get_queried_object();
// vars
$category_colour_primary = get_field('category_colour_primary', $term);
</code></pre>
<p>and then referencing it later on like this:</p>
<pre><code><div class="container-flex" style="background-color:<?php echo $category_colour_secondary; ?>;">
</div>
</code></pre>
<p>This works great on each of the Product Category pages, but doesn't seem to work on the single page template (single-products.php).</p>
<p>I feel I need to get the name (or terms?!) of the current product's taxonomy and then display them as usual...</p>
<p>I've come to a bit of a dead end and I'm unsure what I need to try next...</p>
<p>Can anyone point me in the right direction? I feel I've tried a million things, but can't quite get my head around it. Thanks for looking!</p>
| [
{
"answer_id": 370786,
"author": "Daniel Morell",
"author_id": 142138,
"author_profile": "https://wordpress.stackexchange.com/users/142138",
"pm_score": 2,
"selected": false,
"text": "<p>I would try something like this...</p>\n<pre class=\"lang-php prettyprint-override\"><code>// Assume there is only one category.\n$product_category = get_the_terms($post, 'product-category')[0];\n\n$cat_fields = get_fields("term_$product_category");\n\n$color = $cat_fields['category_colour_primary'];\n</code></pre>\n<p>You could also do this...</p>\n<pre class=\"lang-php prettyprint-override\"><code>// Assume there is only one category.\n$product_category = get_the_terms($post, 'product-category')[0];\n\n$color = get_field('category_colour_primary', "term_$product_category");\n</code></pre>\n"
},
{
"answer_id": 370811,
"author": "Shaun Taylor",
"author_id": 112099,
"author_profile": "https://wordpress.stackexchange.com/users/112099",
"pm_score": 1,
"selected": false,
"text": "<p>Managed to get it working with the following code:</p>\n<pre><code><?php\n$terms = wp_get_object_terms($post->ID, 'product_category');\nif(!empty($terms)){\n foreach($terms as $term){\n $exampleName = $term->name;\n $exampleSlugs[] = $term->slug;\n\n $category_colour_primary = get_field('category_colour_primary', $term);\n $category_colour_secondary = get_field('category_colour_secondary', $term);\n\n }\n}\n?>\n</code></pre>\n"
}
] | 2020/07/10 | [
"https://wordpress.stackexchange.com/questions/370781",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112099/"
] | I have a custom post type called products, which I have attached a custom taxonomy called Product Categories.
On each of the Product Categories, I have used Advanced Custom Fields to add fields such as product category colour, logo etc.
Initially, I'm trying to display the Product Category colour as a background colour for all of the products that fall inside that specific Product Category.
I've tried using the same method as I used to display the colour on the actual Product Category page (taxonomy-product\_category.php), by adding this to the top of the page:
```
// get the current taxonomy term
$term = get_queried_object();
// vars
$category_colour_primary = get_field('category_colour_primary', $term);
```
and then referencing it later on like this:
```
<div class="container-flex" style="background-color:<?php echo $category_colour_secondary; ?>;">
</div>
```
This works great on each of the Product Category pages, but doesn't seem to work on the single page template (single-products.php).
I feel I need to get the name (or terms?!) of the current product's taxonomy and then display them as usual...
I've come to a bit of a dead end and I'm unsure what I need to try next...
Can anyone point me in the right direction? I feel I've tried a million things, but can't quite get my head around it. Thanks for looking! | I would try something like this...
```php
// Assume there is only one category.
$product_category = get_the_terms($post, 'product-category')[0];
$cat_fields = get_fields("term_$product_category");
$color = $cat_fields['category_colour_primary'];
```
You could also do this...
```php
// Assume there is only one category.
$product_category = get_the_terms($post, 'product-category')[0];
$color = get_field('category_colour_primary', "term_$product_category");
``` |
370,794 | <p>I'm building theme and using this link in navigation bar to <code>about.php</code> page.</p>
<pre><code><li><a href="<?php echo get_template_directory_uri(); ?>/about.php">אודות</a></li>
</code></pre>
<p>Now I can't understand why but when I enter <code>about.php</code> I get the following error:</p>
<blockquote>
<p>Fatal error: Uncaught Error: Call to undefined function get_header()
in D:\XAMPP\htdocs\wordpress\wp-content\themes\photography\about.php:2
Stack trace: #0 {main} thrown in
D:\XAMPP\htdocs\wordpress\wp-content\themes\photography\about.php on
line 2</p>
</blockquote>
<p>About.php page</p>
<pre><code><?php get_header(); ?>
<?php get_footer(); ?>
</code></pre>
<p>I'm not sure if I need to define something in my functions.php file.</p>
<p>How can I load properly <code>get_header();</code> function in about.php?</p>
| [
{
"answer_id": 370795,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 2,
"selected": true,
"text": "<p>Look into <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">the theme template hierarchy</a>. There is no "about.php" file and you should not link to any of the theme (PHP) files directly. Instead, you would create a theme file such as "page-about.php" and create its content in wp-admin as a Page with the slug "about," and WordPress will process that Editor content within the PHP file to create the final visible page. If you have pretty permalinks enabled you will want to link to "/about/" instead of the theme file, but because you have named the PHP file "page-about," WP will apply it to a Page with the slug "about."</p>\n"
},
{
"answer_id": 370798,
"author": "Az Rieil",
"author_id": 154993,
"author_profile": "https://wordpress.stackexchange.com/users/154993",
"pm_score": -1,
"selected": false,
"text": "<p><code>get_header()</code> is part of wordpress core.</p>\n<p>Seems your wordpress files damaged or installed incorrect. Try to reinstall it.\nProbably you should move <code>D:\\XAMPP\\htdocs\\wordpress</code> into <code>D:\\XAMPP\\htdocs\\</code></p>\n"
}
] | 2020/07/10 | [
"https://wordpress.stackexchange.com/questions/370794",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/191084/"
] | I'm building theme and using this link in navigation bar to `about.php` page.
```
<li><a href="<?php echo get_template_directory_uri(); ?>/about.php">אודות</a></li>
```
Now I can't understand why but when I enter `about.php` I get the following error:
>
> Fatal error: Uncaught Error: Call to undefined function get\_header()
> in D:\XAMPP\htdocs\wordpress\wp-content\themes\photography\about.php:2
> Stack trace: #0 {main} thrown in
> D:\XAMPP\htdocs\wordpress\wp-content\themes\photography\about.php on
> line 2
>
>
>
About.php page
```
<?php get_header(); ?>
<?php get_footer(); ?>
```
I'm not sure if I need to define something in my functions.php file.
How can I load properly `get_header();` function in about.php? | Look into [the theme template hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/). There is no "about.php" file and you should not link to any of the theme (PHP) files directly. Instead, you would create a theme file such as "page-about.php" and create its content in wp-admin as a Page with the slug "about," and WordPress will process that Editor content within the PHP file to create the final visible page. If you have pretty permalinks enabled you will want to link to "/about/" instead of the theme file, but because you have named the PHP file "page-about," WP will apply it to a Page with the slug "about." |
370,809 | <p>I have a custom WordPress theme I've developed and have included the following lines in my wp-config.php in hopes to automate plugin and core updates:</p>
<pre><code>define( 'WP_AUTO_UPDATE_CORE', true );
add_filter( 'auto_update_plugin', '__return_true' );
add_filter( 'auto_update_theme', '__return_true' );
</code></pre>
<p>I've let it process for about a week now but the plugins that have available updates aren't updating. Do I need to include anything additional in my theme's functions.php to initiate these automatic updates?</p>
<p>Additionally, does anyone know how quickly these updates take place when a new plugin or core update is released? Or is it essentially instantaneous?</p>
<p>Thanks for your help!</p>
| [
{
"answer_id": 370795,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 2,
"selected": true,
"text": "<p>Look into <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">the theme template hierarchy</a>. There is no "about.php" file and you should not link to any of the theme (PHP) files directly. Instead, you would create a theme file such as "page-about.php" and create its content in wp-admin as a Page with the slug "about," and WordPress will process that Editor content within the PHP file to create the final visible page. If you have pretty permalinks enabled you will want to link to "/about/" instead of the theme file, but because you have named the PHP file "page-about," WP will apply it to a Page with the slug "about."</p>\n"
},
{
"answer_id": 370798,
"author": "Az Rieil",
"author_id": 154993,
"author_profile": "https://wordpress.stackexchange.com/users/154993",
"pm_score": -1,
"selected": false,
"text": "<p><code>get_header()</code> is part of wordpress core.</p>\n<p>Seems your wordpress files damaged or installed incorrect. Try to reinstall it.\nProbably you should move <code>D:\\XAMPP\\htdocs\\wordpress</code> into <code>D:\\XAMPP\\htdocs\\</code></p>\n"
}
] | 2020/07/10 | [
"https://wordpress.stackexchange.com/questions/370809",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/191409/"
] | I have a custom WordPress theme I've developed and have included the following lines in my wp-config.php in hopes to automate plugin and core updates:
```
define( 'WP_AUTO_UPDATE_CORE', true );
add_filter( 'auto_update_plugin', '__return_true' );
add_filter( 'auto_update_theme', '__return_true' );
```
I've let it process for about a week now but the plugins that have available updates aren't updating. Do I need to include anything additional in my theme's functions.php to initiate these automatic updates?
Additionally, does anyone know how quickly these updates take place when a new plugin or core update is released? Or is it essentially instantaneous?
Thanks for your help! | Look into [the theme template hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/). There is no "about.php" file and you should not link to any of the theme (PHP) files directly. Instead, you would create a theme file such as "page-about.php" and create its content in wp-admin as a Page with the slug "about," and WordPress will process that Editor content within the PHP file to create the final visible page. If you have pretty permalinks enabled you will want to link to "/about/" instead of the theme file, but because you have named the PHP file "page-about," WP will apply it to a Page with the slug "about." |
370,828 | <p>I basically want to loop through each post I have and get the taxonomy/category id. After that I want to output those id's into a single string (not as a numeric value), separated by a space.</p>
<p>I get this error when I try to echo the string: <strong>"Object of class WP_Term could not be converted to string"</strong></p>
<p>Here is what i have so far:</p>
<pre><code> <?php
$taxonomy = wp_get_object_terms($post->ID, 'categories');
$ids = "";
foreach ($taxonomy as $cat) {
$ids .= $cat;
?>
</code></pre>
| [
{
"answer_id": 370829,
"author": "shanebp",
"author_id": 16575,
"author_profile": "https://wordpress.stackexchange.com/users/16575",
"pm_score": 0,
"selected": false,
"text": "<p><code>$cat</code> is an object, not a string. You are also missing a closing bracket.</p>\n<p>Try: <code>$ids .= $cat->id . ' ';</code></p>\n<p>It is often helpful to take a look at the returned structure and data:</p>\n<pre><code>foreach ($taxonomy as $cat) {\n \n echo '<pre>'; var_dump( $cat ); echo '</pre>';\n\n}\n</code></pre>\n"
},
{
"answer_id": 370839,
"author": "mozboz",
"author_id": 176814,
"author_profile": "https://wordpress.stackexchange.com/users/176814",
"pm_score": 2,
"selected": false,
"text": "<p>According to <a href=\"https://developer.wordpress.org/reference/classes/wp_term/\" rel=\"nofollow noreferrer\">the docs for the Term object</a> the ID is in the property <code>term_id</code> So you need:</p>\n<pre><code> $ids = array();\n\n foreach ($taxonomy as $tax) {\n $ids[] = $tax->term_id;\n }\n\n $joinedIds = implode(" ", $ids);\n\n // do something with $joinedIds;\n</code></pre>\n"
}
] | 2020/07/10 | [
"https://wordpress.stackexchange.com/questions/370828",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180361/"
] | I basically want to loop through each post I have and get the taxonomy/category id. After that I want to output those id's into a single string (not as a numeric value), separated by a space.
I get this error when I try to echo the string: **"Object of class WP\_Term could not be converted to string"**
Here is what i have so far:
```
<?php
$taxonomy = wp_get_object_terms($post->ID, 'categories');
$ids = "";
foreach ($taxonomy as $cat) {
$ids .= $cat;
?>
``` | According to [the docs for the Term object](https://developer.wordpress.org/reference/classes/wp_term/) the ID is in the property `term_id` So you need:
```
$ids = array();
foreach ($taxonomy as $tax) {
$ids[] = $tax->term_id;
}
$joinedIds = implode(" ", $ids);
// do something with $joinedIds;
``` |
370,836 | <p>So I have a function which counts the amount of customer orders.</p>
<p>I want to show a congratulations modal that appears when a customer hits a specific amount of orders.</p>
<p>All of my code is working fine, except when I add this part to the IF statement:</p>
<p><code>|| in_array($count, $the_digits) && isset( $_COOKIE['tier_advance'] ) && $_COOKIE['tier_advance'] !== $count )</code></p>
<p>The cookie is being saved properly, and when saved the number is saved as the current value of <code>count</code>. The idea is that the modal will only show if:</p>
<p>A) their current count is in <code>$the_digits</code> array & the cookie is not set.
B) their current count is in <code>$the_digits</code> array & the cookie IS set, however the cookies value does not equal their current order <code>$count</code> amount.</p>
<p>This is to prevent the modal showing after the initial display, but still allow it to show again if they hit the next <code>$count</code> amount to move to the next tier.</p>
<p>Can't figure out what is wrong. Or perhaps there is a better way to do this. All help appreciated.</p>
<pre><code> $the_digits = ['3','5','15','30','50'];
if ( in_array($count, $the_digits) && !isset( $_COOKIE[ 'tier_advance' ] ) || in_array($count, $the_digits) && isset( $_COOKIE['tier_advance'] ) && $_COOKIE['tier_advance'] !== $count ) {
echo'
<script>
jQuery(window).on("load",function(){
jQuery("#tier_advance").modal("show");
});
jQuery(document).on("click", "#tier_confirm", function(){
// Set a cookie
Cookies.set("tier_advance", "' . $count . '", { expires: 356 });
});
</script>
<!-- BEGIN Share Modal -->
<div class="modal fade" id="tier_advance" tabindex="-1" role="dialog">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header text-center">
<h5>CONGRATULATIONS!</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body text-center">
<p>You are now a <strong class="all-caps"> ' . $tier_name . ' </strong>tier customer!</p>
<p>Expect some dope rewards to start coming your way!</p>
</div>
<div class="modal-footer modal-footer-centered">
<button id="tier_confirm" type="button" class="btn btn-secondary" data-dismiss="modal">Awesome, thanks!</button>
</div>
</div>
</div>
</div>
<!-- END Share Modal -->';
}
</code></pre>
| [
{
"answer_id": 370829,
"author": "shanebp",
"author_id": 16575,
"author_profile": "https://wordpress.stackexchange.com/users/16575",
"pm_score": 0,
"selected": false,
"text": "<p><code>$cat</code> is an object, not a string. You are also missing a closing bracket.</p>\n<p>Try: <code>$ids .= $cat->id . ' ';</code></p>\n<p>It is often helpful to take a look at the returned structure and data:</p>\n<pre><code>foreach ($taxonomy as $cat) {\n \n echo '<pre>'; var_dump( $cat ); echo '</pre>';\n\n}\n</code></pre>\n"
},
{
"answer_id": 370839,
"author": "mozboz",
"author_id": 176814,
"author_profile": "https://wordpress.stackexchange.com/users/176814",
"pm_score": 2,
"selected": false,
"text": "<p>According to <a href=\"https://developer.wordpress.org/reference/classes/wp_term/\" rel=\"nofollow noreferrer\">the docs for the Term object</a> the ID is in the property <code>term_id</code> So you need:</p>\n<pre><code> $ids = array();\n\n foreach ($taxonomy as $tax) {\n $ids[] = $tax->term_id;\n }\n\n $joinedIds = implode(" ", $ids);\n\n // do something with $joinedIds;\n</code></pre>\n"
}
] | 2020/07/11 | [
"https://wordpress.stackexchange.com/questions/370836",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/191188/"
] | So I have a function which counts the amount of customer orders.
I want to show a congratulations modal that appears when a customer hits a specific amount of orders.
All of my code is working fine, except when I add this part to the IF statement:
`|| in_array($count, $the_digits) && isset( $_COOKIE['tier_advance'] ) && $_COOKIE['tier_advance'] !== $count )`
The cookie is being saved properly, and when saved the number is saved as the current value of `count`. The idea is that the modal will only show if:
A) their current count is in `$the_digits` array & the cookie is not set.
B) their current count is in `$the_digits` array & the cookie IS set, however the cookies value does not equal their current order `$count` amount.
This is to prevent the modal showing after the initial display, but still allow it to show again if they hit the next `$count` amount to move to the next tier.
Can't figure out what is wrong. Or perhaps there is a better way to do this. All help appreciated.
```
$the_digits = ['3','5','15','30','50'];
if ( in_array($count, $the_digits) && !isset( $_COOKIE[ 'tier_advance' ] ) || in_array($count, $the_digits) && isset( $_COOKIE['tier_advance'] ) && $_COOKIE['tier_advance'] !== $count ) {
echo'
<script>
jQuery(window).on("load",function(){
jQuery("#tier_advance").modal("show");
});
jQuery(document).on("click", "#tier_confirm", function(){
// Set a cookie
Cookies.set("tier_advance", "' . $count . '", { expires: 356 });
});
</script>
<!-- BEGIN Share Modal -->
<div class="modal fade" id="tier_advance" tabindex="-1" role="dialog">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header text-center">
<h5>CONGRATULATIONS!</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body text-center">
<p>You are now a <strong class="all-caps"> ' . $tier_name . ' </strong>tier customer!</p>
<p>Expect some dope rewards to start coming your way!</p>
</div>
<div class="modal-footer modal-footer-centered">
<button id="tier_confirm" type="button" class="btn btn-secondary" data-dismiss="modal">Awesome, thanks!</button>
</div>
</div>
</div>
</div>
<!-- END Share Modal -->';
}
``` | According to [the docs for the Term object](https://developer.wordpress.org/reference/classes/wp_term/) the ID is in the property `term_id` So you need:
```
$ids = array();
foreach ($taxonomy as $tax) {
$ids[] = $tax->term_id;
}
$joinedIds = implode(" ", $ids);
// do something with $joinedIds;
``` |
370,853 | <p>I use TinyMCE advanced on my Wordpress website. My logged-in users have the ability to fill forms with WYSIWYG fields. I don't understand why some styles are not applied on those fields while it applied well on the admin area. Fields are set in up with ACF or formidable forms. In both case I have the same issue.</p>
<p>On the admin:
<a href="https://i.stack.imgur.com/gr97a.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gr97a.jpg" alt="enter image description here" /></a></p>
<p>On the frontend:
<a href="https://i.stack.imgur.com/VHmJY.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VHmJY.jpg" alt="enter image description here" /></a></p>
<p>There are many discussion about TinyMCE style and I did a lot of reseach, but I still don't understand why this happen.</p>
<p>Thanks in advance for your answers.</p>
<p>EDIT:
Seems like editor.css is not loaded in the frontend, I forced the loading of this css using this piece of code</p>
<pre><code>function wpb_adding_styles() {
wp_register_style('my_stylesheet','https://www.example.com/wp-includes/css/editor.min.css?ver=5.4.2');
wp_enqueue_style('my_stylesheet');
}
add_action( 'wp_enqueue_scripts', 'wpb_adding_styles' );
</code></pre>
<p>The result is better but nor perfect. Also for non admin user the icons disappears, here the result:
<a href="https://i.stack.imgur.com/3W4t9.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3W4t9.jpg" alt="enter image description here" /></a></p>
<p>Thanks for your help !</p>
| [
{
"answer_id": 370829,
"author": "shanebp",
"author_id": 16575,
"author_profile": "https://wordpress.stackexchange.com/users/16575",
"pm_score": 0,
"selected": false,
"text": "<p><code>$cat</code> is an object, not a string. You are also missing a closing bracket.</p>\n<p>Try: <code>$ids .= $cat->id . ' ';</code></p>\n<p>It is often helpful to take a look at the returned structure and data:</p>\n<pre><code>foreach ($taxonomy as $cat) {\n \n echo '<pre>'; var_dump( $cat ); echo '</pre>';\n\n}\n</code></pre>\n"
},
{
"answer_id": 370839,
"author": "mozboz",
"author_id": 176814,
"author_profile": "https://wordpress.stackexchange.com/users/176814",
"pm_score": 2,
"selected": false,
"text": "<p>According to <a href=\"https://developer.wordpress.org/reference/classes/wp_term/\" rel=\"nofollow noreferrer\">the docs for the Term object</a> the ID is in the property <code>term_id</code> So you need:</p>\n<pre><code> $ids = array();\n\n foreach ($taxonomy as $tax) {\n $ids[] = $tax->term_id;\n }\n\n $joinedIds = implode(" ", $ids);\n\n // do something with $joinedIds;\n</code></pre>\n"
}
] | 2020/07/11 | [
"https://wordpress.stackexchange.com/questions/370853",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/191437/"
] | I use TinyMCE advanced on my Wordpress website. My logged-in users have the ability to fill forms with WYSIWYG fields. I don't understand why some styles are not applied on those fields while it applied well on the admin area. Fields are set in up with ACF or formidable forms. In both case I have the same issue.
On the admin:
[](https://i.stack.imgur.com/gr97a.jpg)
On the frontend:
[](https://i.stack.imgur.com/VHmJY.jpg)
There are many discussion about TinyMCE style and I did a lot of reseach, but I still don't understand why this happen.
Thanks in advance for your answers.
EDIT:
Seems like editor.css is not loaded in the frontend, I forced the loading of this css using this piece of code
```
function wpb_adding_styles() {
wp_register_style('my_stylesheet','https://www.example.com/wp-includes/css/editor.min.css?ver=5.4.2');
wp_enqueue_style('my_stylesheet');
}
add_action( 'wp_enqueue_scripts', 'wpb_adding_styles' );
```
The result is better but nor perfect. Also for non admin user the icons disappears, here the result:
[](https://i.stack.imgur.com/3W4t9.jpg)
Thanks for your help ! | According to [the docs for the Term object](https://developer.wordpress.org/reference/classes/wp_term/) the ID is in the property `term_id` So you need:
```
$ids = array();
foreach ($taxonomy as $tax) {
$ids[] = $tax->term_id;
}
$joinedIds = implode(" ", $ids);
// do something with $joinedIds;
``` |
370,859 | <p>In my Wordpress website main directory, I created a folder <code>servers</code>, which contains two files <code>.htaccess</code> & <code>index.php</code>.</p>
<p>In the <code>.htaccess</code> file, I add those lines to redirect all requests to that folder to the <code>index.php</code> file.</p>
<pre><code># Enable rewriting.
RewriteEngine on
# Optional: do not allow perusal of directories.
Options -Indexes
# Optional: explicitly enable per-directory rewrites in the .htaccess context.
Options +FollowSymLinks
# Required when not in the webroot. Always use a trailing slash.
RewriteBase /
# To be able to access existing directories and files (standalone scripts).
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
# Redirect everything else to index.php.
# Add QSA to ensure that querystring variables are registered as such.
RewriteRule . index.php [L,QSA]
# php -- BEGIN cPanel-generated handler, do not edit
# Set the “ea-php72” package as the default “PHP” programming language.
<IfModule mime_module>
AddHandler application/x-httpd-ea-php72 .php .php7 .phtml
</IfModule>
# php -- END cPanel-generated handler, do not edit
</code></pre>
<p>So whenever a user requests a link like <code>example.com</code>, <code>example.com/foo</code> or <code>example.com/foo/bar</code>, the default Wordpress website should load. and when I request any url that starts with the <code>servers</code> folder: <code>example.com/servers</code>, <code>example.com/servers/foo</code>, <code>example.com/servers/foo/bar</code>, I want the <code>example/com/servers/index.php</code> file to be executed.</p>
<p>The current <code>example.com/servers/.htaccess</code> file only executes this url <code>example.com/servers</code> with the <code>example.com/servers/index.php</code> file but it's not executing other urls that start with the <code>servers</code> folder(<code>example.com/servers/foo</code>, <code>example.com/servers/foo/bar</code>) by the <code>example.com/servers/index.php</code> file.</p>
<p>How can edit the htaccess file so that all request to <code>example.com/servers/*</code> are executed by the <code>example.com/servers/index.php</code> file</p>
| [
{
"answer_id": 370829,
"author": "shanebp",
"author_id": 16575,
"author_profile": "https://wordpress.stackexchange.com/users/16575",
"pm_score": 0,
"selected": false,
"text": "<p><code>$cat</code> is an object, not a string. You are also missing a closing bracket.</p>\n<p>Try: <code>$ids .= $cat->id . ' ';</code></p>\n<p>It is often helpful to take a look at the returned structure and data:</p>\n<pre><code>foreach ($taxonomy as $cat) {\n \n echo '<pre>'; var_dump( $cat ); echo '</pre>';\n\n}\n</code></pre>\n"
},
{
"answer_id": 370839,
"author": "mozboz",
"author_id": 176814,
"author_profile": "https://wordpress.stackexchange.com/users/176814",
"pm_score": 2,
"selected": false,
"text": "<p>According to <a href=\"https://developer.wordpress.org/reference/classes/wp_term/\" rel=\"nofollow noreferrer\">the docs for the Term object</a> the ID is in the property <code>term_id</code> So you need:</p>\n<pre><code> $ids = array();\n\n foreach ($taxonomy as $tax) {\n $ids[] = $tax->term_id;\n }\n\n $joinedIds = implode(" ", $ids);\n\n // do something with $joinedIds;\n</code></pre>\n"
}
] | 2020/07/11 | [
"https://wordpress.stackexchange.com/questions/370859",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86145/"
] | In my Wordpress website main directory, I created a folder `servers`, which contains two files `.htaccess` & `index.php`.
In the `.htaccess` file, I add those lines to redirect all requests to that folder to the `index.php` file.
```
# Enable rewriting.
RewriteEngine on
# Optional: do not allow perusal of directories.
Options -Indexes
# Optional: explicitly enable per-directory rewrites in the .htaccess context.
Options +FollowSymLinks
# Required when not in the webroot. Always use a trailing slash.
RewriteBase /
# To be able to access existing directories and files (standalone scripts).
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
# Redirect everything else to index.php.
# Add QSA to ensure that querystring variables are registered as such.
RewriteRule . index.php [L,QSA]
# php -- BEGIN cPanel-generated handler, do not edit
# Set the “ea-php72” package as the default “PHP” programming language.
<IfModule mime_module>
AddHandler application/x-httpd-ea-php72 .php .php7 .phtml
</IfModule>
# php -- END cPanel-generated handler, do not edit
```
So whenever a user requests a link like `example.com`, `example.com/foo` or `example.com/foo/bar`, the default Wordpress website should load. and when I request any url that starts with the `servers` folder: `example.com/servers`, `example.com/servers/foo`, `example.com/servers/foo/bar`, I want the `example/com/servers/index.php` file to be executed.
The current `example.com/servers/.htaccess` file only executes this url `example.com/servers` with the `example.com/servers/index.php` file but it's not executing other urls that start with the `servers` folder(`example.com/servers/foo`, `example.com/servers/foo/bar`) by the `example.com/servers/index.php` file.
How can edit the htaccess file so that all request to `example.com/servers/*` are executed by the `example.com/servers/index.php` file | According to [the docs for the Term object](https://developer.wordpress.org/reference/classes/wp_term/) the ID is in the property `term_id` So you need:
```
$ids = array();
foreach ($taxonomy as $tax) {
$ids[] = $tax->term_id;
}
$joinedIds = implode(" ", $ids);
// do something with $joinedIds;
``` |
370,902 | <p>I'm using WordPress to host a few sites. Lately it includes this feature called Site Health Status. This information has in part been valuable, but it also itches me the wrong way somehow that I can't get it to show "green" due to something I'd consider non-issues </p>
<p>Here is how the "critical issue" looks.</p>
<p><a href="https://i.stack.imgur.com/mRXmw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mRXmw.png" alt="Relevant snippet from Site Health Status" /></a></p>
<p>Here's the relevant text excerpt, because search engines aren't all too good with indexing text from screenshots:</p>
<blockquote>
<h3>1 critical issue</h3>
<p><strong>Background updates are not working as expected</strong> [Security]</p>
<p>Background updates ensure that WordPress can auto-update if a security
update is released for the version you are currently using.</p>
<ul>
<li>Warning The folder <code>/vhosts/sitename</code> was detected as being under
version control (<code>.hg</code>).</li>
<li>Error Your installation of WordPress prompts
for FTP credentials to perform updates. (Your site is performing
updates over FTP due to file ownership. Talk to your hosting company.)</li>
</ul>
</blockquote>
<p>The folder <code>/vhosts/sitename</code> is indeed under version control and the actual <em>blog</em> is under <code>/vhosts/sitename/blog</code> and that's what the web server serves as webroot. However, <code>/vhosts/sitename/wp-config.php</code> contains the blog configuration. <a href="https://wordpress.stackexchange.com/q/58391/27498">As WordPress allows it to live outside of the webroot, that's what I opted for <em>out of security reasons</em>.</a> Anyway, the conclusion from this first (yellow) point should be that there's no way anyone could glean the contents of the version control system, since it lives entirely outside the webroot.</p>
<p>The second (and red) point is about FTP credentials. This one I find particularly unnerving. I have scripts in place, I have 2FA, and the servers in question are only accessible via SSH (and by extension SFTP). WordPress doesn't support SFTP nor would I want to enable this <em>at all</em>. In fact the files inside the webroot have tight file modes so that even in case a breach occurred very little could be done. In other words, I am updating WordPress in a semi-automated fashion triggered <em>manually</em>. Unlike some setups of WordPress I have seen or administrated in the past with FTP enabled, I haven't had a breach, going by all the indicators I have available. So to me this is the desired setting. But someone decided to categorize this as a critical issue.</p>
<p>So my questions (two actually):</p>
<ul>
<li>Is there a way to dismiss and ignore <em>these</em> exact two items in the future?</li>
<li>Should I trust some WordPress dev who doesn't know my exact setup more for security advice than myself or should I spend (mental) energy on actively ignoring the issue (under the assumption that it can't be dismissed and ignored for the future)?</li>
</ul>
<p>NB: I am <em>not</em> interested in having <a href="https://wordpress.stackexchange.com/q/363042/27498">the overall feature (or the visible widget) removed</a>. I simply want this feature to be valuable and that means not raising the alarm when nothing is wrong, as far as I'm concerned.</p>
<hr />
<p>After setting <code>define('FS_METHOD','direct');</code> in <code>wp-config.php</code> - as per recommendation from the one answer at this point - the message changed, but still shows as critical issue </p>
<p><a href="https://i.stack.imgur.com/v0KWx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/v0KWx.png" alt="After setting FS_METHOD=direct" /></a></p>
| [
{
"answer_id": 370906,
"author": "mozboz",
"author_id": 176814,
"author_profile": "https://wordpress.stackexchange.com/users/176814",
"pm_score": 2,
"selected": false,
"text": "<p>I have not tested this, but <a href=\"https://support.cloudways.com/how-to-resolve-wordpress-asking-for-ftp-credentials-error/\" rel=\"nofollow noreferrer\">this post</a> suggests that not having a FS_METHOD setting in wp-config.php is leading to the second warning. To fix it add this line to <code>wp-config.php</code>:</p>\n<pre><code>define('FS_METHOD','direct');\n</code></pre>\n<p>For the version control message, a bit of exploration found that this problem is actually poorly described as the actual result is that Wordpress will not apply updates automatically to files that it thinks are under version control. See <a href=\"https://github.com/WordPress/health-check/issues/323\" rel=\"nofollow noreferrer\">https://github.com/WordPress/health-check/issues/323</a> .</p>\n<p>There is a plugin that enables you to turn off specific Site Health Monitor alerts without disabling it, but it doesn't appear to support the version control message yet.</p>\n<p><a href=\"https://wordpress.org/plugins/site-health-tool-manager/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/site-health-tool-manager/</a></p>\n"
},
{
"answer_id": 390553,
"author": "paul b.",
"author_id": 67870,
"author_profile": "https://wordpress.stackexchange.com/users/67870",
"pm_score": 3,
"selected": true,
"text": "<p>You should be able to filter out some tests by using the filter <code>site_status_tests</code></p>\n<p>Quoting the <a href=\"https://developer.wordpress.org/reference/hooks/site_status_tests/\" rel=\"nofollow noreferrer\">WordPress documentation</a>:</p>\n<p>Usage:</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_filter('site_status_tests', function (array $test_type) {\n unset($test_type['direct']['theme_version']); // remove warning about Twenty* themes\n unset($test_type['async']['background_updates']); // remove warning about Automatic background updates\n \n return $test_type;\n}, 10, 1);\n</code></pre>\n<p>You can get the list of tests from the <code>WP_Site_Health->get_tests()</code> method in <code>class-wp-site-health.php</code> file.</p>\n"
}
] | 2020/07/12 | [
"https://wordpress.stackexchange.com/questions/370902",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/27498/"
] | I'm using WordPress to host a few sites. Lately it includes this feature called Site Health Status. This information has in part been valuable, but it also itches me the wrong way somehow that I can't get it to show "green" due to something I'd consider non-issues
Here is how the "critical issue" looks.
[](https://i.stack.imgur.com/mRXmw.png)
Here's the relevant text excerpt, because search engines aren't all too good with indexing text from screenshots:
>
> ### 1 critical issue
>
>
> **Background updates are not working as expected** [Security]
>
>
> Background updates ensure that WordPress can auto-update if a security
> update is released for the version you are currently using.
>
>
> * Warning The folder `/vhosts/sitename` was detected as being under
> version control (`.hg`).
> * Error Your installation of WordPress prompts
> for FTP credentials to perform updates. (Your site is performing
> updates over FTP due to file ownership. Talk to your hosting company.)
>
>
>
The folder `/vhosts/sitename` is indeed under version control and the actual *blog* is under `/vhosts/sitename/blog` and that's what the web server serves as webroot. However, `/vhosts/sitename/wp-config.php` contains the blog configuration. [As WordPress allows it to live outside of the webroot, that's what I opted for *out of security reasons*.](https://wordpress.stackexchange.com/q/58391/27498) Anyway, the conclusion from this first (yellow) point should be that there's no way anyone could glean the contents of the version control system, since it lives entirely outside the webroot.
The second (and red) point is about FTP credentials. This one I find particularly unnerving. I have scripts in place, I have 2FA, and the servers in question are only accessible via SSH (and by extension SFTP). WordPress doesn't support SFTP nor would I want to enable this *at all*. In fact the files inside the webroot have tight file modes so that even in case a breach occurred very little could be done. In other words, I am updating WordPress in a semi-automated fashion triggered *manually*. Unlike some setups of WordPress I have seen or administrated in the past with FTP enabled, I haven't had a breach, going by all the indicators I have available. So to me this is the desired setting. But someone decided to categorize this as a critical issue.
So my questions (two actually):
* Is there a way to dismiss and ignore *these* exact two items in the future?
* Should I trust some WordPress dev who doesn't know my exact setup more for security advice than myself or should I spend (mental) energy on actively ignoring the issue (under the assumption that it can't be dismissed and ignored for the future)?
NB: I am *not* interested in having [the overall feature (or the visible widget) removed](https://wordpress.stackexchange.com/q/363042/27498). I simply want this feature to be valuable and that means not raising the alarm when nothing is wrong, as far as I'm concerned.
---
After setting `define('FS_METHOD','direct');` in `wp-config.php` - as per recommendation from the one answer at this point - the message changed, but still shows as critical issue
[](https://i.stack.imgur.com/v0KWx.png) | You should be able to filter out some tests by using the filter `site_status_tests`
Quoting the [WordPress documentation](https://developer.wordpress.org/reference/hooks/site_status_tests/):
Usage:
```php
add_filter('site_status_tests', function (array $test_type) {
unset($test_type['direct']['theme_version']); // remove warning about Twenty* themes
unset($test_type['async']['background_updates']); // remove warning about Automatic background updates
return $test_type;
}, 10, 1);
```
You can get the list of tests from the `WP_Site_Health->get_tests()` method in `class-wp-site-health.php` file. |
370,916 | <p>I'm using the following PHP code to echo post thumbnails.</p>
<pre><code> <?php
$args = array(
'post_type' => 'post' ,
'orderby' => 'date' ,
'order' => 'DESC' ,
'posts_per_page' => 1,
'category' => '2',
'paged' => get_query_var('paged'),
'post_parent' => $parent
);
// The Query
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '' . the_post_thumbnail() . '';
}
} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
?>
</code></pre>
<p>But I'm having issue, since this wont work, but when I try to echo <code>get_post_title()</code> it works perfectly fine.
I can't figure out where do I got this wrong.</p>
<p>How can I display/echo post thumbnails?</p>
| [
{
"answer_id": 370919,
"author": "shanebp",
"author_id": 16575,
"author_profile": "https://wordpress.stackexchange.com/users/16575",
"pm_score": 0,
"selected": false,
"text": "<pre><code>'posts_per_page' => 1,\n</code></pre>\n<p>Do you really only want a single post to be returned?\nAnd what is the <code>$parent</code> value?</p>\n<p>Since you don't want anything but the post thumbnail, specify that you only need the post id(s).\nTry:</p>\n<pre><code> $args = array(\n 'post_type' => 'post' ,\n 'orderby' => 'date' ,\n 'order' => 'DESC' ,\n 'posts_per_page' => 1,\n 'category' => '2',\n 'paged' => get_query_var('paged'),\n 'post_parent' => $parent,\n 'fields' => 'ids'\n );\n // The Query\n $the_query = new WP_Query( $args );\n\n if ( ! empty ( $query->posts ) ) {\n\n $post_ids = $query->posts; // just the post IDs\n\n foreach ( $post_ids as $post_id )\n echo get_the_post_thumbnail( $post_id, 'post-thumbnail' );\n\n } else {\n echo 'No posts were found';\n }\n /* Restore original Post Data */\n wp_reset_postdata();\n</code></pre>\n<p>A good and relevant read <a href=\"https://wordpress.stackexchange.com/questions/112184/how-to-create-a-flexible-abstraction-for-wp-query/112196#112196\">here</a>.</p>\n"
},
{
"answer_id": 370931,
"author": "Steve Johnson",
"author_id": 191486,
"author_profile": "https://wordpress.stackexchange.com/users/191486",
"pm_score": 2,
"selected": false,
"text": "<p>Not sure what you're trying to do, but the problem you're having with this specific bit of code is that you're using the wrong function. You want <strong>get_the_post_thumbnail()</strong> instead. The function the_post_thumbnail() echoes the result of get_the_post_thumbnail().</p>\n<pre><code>$args = array(\n 'post_type' => 'post',\n 'orderby' => 'date',\n 'order' => 'DESC',\n 'posts_per_page' => 1,\n 'category' => '2',\n 'paged' => get_query_var('paged'),\n 'post_parent' => $parent\n);\n// The Query\n$the_query = new WP_Query($args);\n\n// The Loop\nif ( $the_query->have_posts() ) {\n while ( $the_query->have_posts() ) {\n $the_query->the_post();\n echo get_the_post_thumbnail();\n }\n} else {\n// no posts found\n}\n/* Restore original Post Data */\nwp_reset_postdata();\n</code></pre>\n"
}
] | 2020/07/12 | [
"https://wordpress.stackexchange.com/questions/370916",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/191084/"
] | I'm using the following PHP code to echo post thumbnails.
```
<?php
$args = array(
'post_type' => 'post' ,
'orderby' => 'date' ,
'order' => 'DESC' ,
'posts_per_page' => 1,
'category' => '2',
'paged' => get_query_var('paged'),
'post_parent' => $parent
);
// The Query
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '' . the_post_thumbnail() . '';
}
} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
?>
```
But I'm having issue, since this wont work, but when I try to echo `get_post_title()` it works perfectly fine.
I can't figure out where do I got this wrong.
How can I display/echo post thumbnails? | Not sure what you're trying to do, but the problem you're having with this specific bit of code is that you're using the wrong function. You want **get\_the\_post\_thumbnail()** instead. The function the\_post\_thumbnail() echoes the result of get\_the\_post\_thumbnail().
```
$args = array(
'post_type' => 'post',
'orderby' => 'date',
'order' => 'DESC',
'posts_per_page' => 1,
'category' => '2',
'paged' => get_query_var('paged'),
'post_parent' => $parent
);
// The Query
$the_query = new WP_Query($args);
// The Loop
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo get_the_post_thumbnail();
}
} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
``` |
370,986 | <p>I've created a custom post type "testimonials" -- works fine, except I want the url to be "domain.com/results/testimonials" instead of "domain.com/testimonials"</p>
<p>Do I just need to change something in the function that creates the custom post type? Or is there something else I need to do?</p>
<p>Thanks,
Scott</p>
| [
{
"answer_id": 370919,
"author": "shanebp",
"author_id": 16575,
"author_profile": "https://wordpress.stackexchange.com/users/16575",
"pm_score": 0,
"selected": false,
"text": "<pre><code>'posts_per_page' => 1,\n</code></pre>\n<p>Do you really only want a single post to be returned?\nAnd what is the <code>$parent</code> value?</p>\n<p>Since you don't want anything but the post thumbnail, specify that you only need the post id(s).\nTry:</p>\n<pre><code> $args = array(\n 'post_type' => 'post' ,\n 'orderby' => 'date' ,\n 'order' => 'DESC' ,\n 'posts_per_page' => 1,\n 'category' => '2',\n 'paged' => get_query_var('paged'),\n 'post_parent' => $parent,\n 'fields' => 'ids'\n );\n // The Query\n $the_query = new WP_Query( $args );\n\n if ( ! empty ( $query->posts ) ) {\n\n $post_ids = $query->posts; // just the post IDs\n\n foreach ( $post_ids as $post_id )\n echo get_the_post_thumbnail( $post_id, 'post-thumbnail' );\n\n } else {\n echo 'No posts were found';\n }\n /* Restore original Post Data */\n wp_reset_postdata();\n</code></pre>\n<p>A good and relevant read <a href=\"https://wordpress.stackexchange.com/questions/112184/how-to-create-a-flexible-abstraction-for-wp-query/112196#112196\">here</a>.</p>\n"
},
{
"answer_id": 370931,
"author": "Steve Johnson",
"author_id": 191486,
"author_profile": "https://wordpress.stackexchange.com/users/191486",
"pm_score": 2,
"selected": false,
"text": "<p>Not sure what you're trying to do, but the problem you're having with this specific bit of code is that you're using the wrong function. You want <strong>get_the_post_thumbnail()</strong> instead. The function the_post_thumbnail() echoes the result of get_the_post_thumbnail().</p>\n<pre><code>$args = array(\n 'post_type' => 'post',\n 'orderby' => 'date',\n 'order' => 'DESC',\n 'posts_per_page' => 1,\n 'category' => '2',\n 'paged' => get_query_var('paged'),\n 'post_parent' => $parent\n);\n// The Query\n$the_query = new WP_Query($args);\n\n// The Loop\nif ( $the_query->have_posts() ) {\n while ( $the_query->have_posts() ) {\n $the_query->the_post();\n echo get_the_post_thumbnail();\n }\n} else {\n// no posts found\n}\n/* Restore original Post Data */\nwp_reset_postdata();\n</code></pre>\n"
}
] | 2020/07/13 | [
"https://wordpress.stackexchange.com/questions/370986",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/57399/"
] | I've created a custom post type "testimonials" -- works fine, except I want the url to be "domain.com/results/testimonials" instead of "domain.com/testimonials"
Do I just need to change something in the function that creates the custom post type? Or is there something else I need to do?
Thanks,
Scott | Not sure what you're trying to do, but the problem you're having with this specific bit of code is that you're using the wrong function. You want **get\_the\_post\_thumbnail()** instead. The function the\_post\_thumbnail() echoes the result of get\_the\_post\_thumbnail().
```
$args = array(
'post_type' => 'post',
'orderby' => 'date',
'order' => 'DESC',
'posts_per_page' => 1,
'category' => '2',
'paged' => get_query_var('paged'),
'post_parent' => $parent
);
// The Query
$the_query = new WP_Query($args);
// The Loop
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo get_the_post_thumbnail();
}
} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
``` |
370,990 | <p>I have the link of WordPress doc about this function, but there is nothing explaining how to use this. I have a Ajax function, PHP and a HTML input. In this HTML I set the title and content, and I'd like to set the thumbnail too. Maybe I can do that with this function? Is there some example?</p>
<p><a href="https://developer.wordpress.org/reference/functions/wp_ajax_set_post_thumbnail/" rel="nofollow noreferrer">https://developer.wordpress.org/reference/functions/wp_ajax_set_post_thumbnail/</a></p>
<p><strong>[EDIT]</strong></p>
<p>I have an html input</p>
<pre><code><input type="file">
</code></pre>
<p>I have an AJAX Call</p>
<pre><code>$.ajax({
url: Ajax.ajax_url,
type: 'POST',
data: {
action: 'make_the_post_activity',
security: Ajax.nonce,
dataType: 'json'
},
success: function( response ){
}
});
</code></pre>
<p>And a PHP function</p>
<pre><code>add_action('wp_ajax_make_the_post_activity', 'make_the_post_activity');
add_action('wp_ajax_nopriv_make_the_post_activity', 'make_the_post_activity');
function make_the_post_activity(){
if( check_ajax_referer('namorada-security-ajax', 'security', false) ){
// Here inside I add the the new post calling by ajax the fields as title and content from the HTML file.
}
}
</code></pre>
<p>Then here I get the ID of the New Post. But I don't know how to update this new post id with the image from the input (file). I know that the Ajax can't upload the image with XMLHttpRequest, but I'm sure there is another possibility that I still don't know.</p>
<p>I understand the function that the friend added bellow, but in this condition, I need already pass maybe sending a JSON to the Ajax function, the ID of the image I've uploaded in the wordpress library, but I don't know how to upload it and get the ID to send to Ajax and then publish it via REST API.</p>
<p><strong>[EDIT 2]</strong>
I'll put here the complete functions I use to upload the photo with Ajax and PHP, and the fiels I need to use to make the new post, maybe it will be a big amount of code.</p>
<p>HTML</p>
<pre><code><div class="modal-dialog vertical-align-center" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel"><?php echo __('Escreva seu post', 'namorada-general'); ?></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<form action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<textarea class="form-control input_activity_content" id="post_activity_form_emoji" data-emoji-placeholder=":smiley:"></textarea>
</div>
<div style="width:100%;float:left;">
<i class="fa fa-image p-1 upload_photo_activity" style="float:right;font-size:20px;cursor:pointer;"></i>
<i class="fa fa-video-camera p-1 youtube_video_activity" style="float:right;font-size:20px;cursor:pointer;"></i>
</div>
<div style="width:100%;float:left;display:none;" id="youtube_video_activity">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-default">YouTube</span>
</div>
<input type="text" class="form-control input_youtube_video_activity" aria-label="Default" aria-describedby="inputGroup-sizing-default">
</div>
</div>
<div style="width:100%;float:left;display:none;" id="upload_photo_activity">
<div class="custom-file">
<input type="file" class="custom-file-input input_upload_photo_activity" id="packagephoto" name="packagephoto">
<label class="custom-file-label choose_photo_activity" for="validatedCustomFile" accept="image/x-png,image/gif,image/jpeg">Escolha sua foto</label>
<div class="invalid-feedback">Example invalid custom file feedback</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal"><?php echo __('Cancelar', 'namorada-general'); ?></button>
<input id="addimage" name="addimage" class="btn btn-primary make_the_post_activity" value="<?php echo __('Publicar', 'namorada-general'); ?>">
</div>
</div>
</div>
</code></pre>
<p><strong>The AJAX Functions</strong> (I have one function I use to insert the POST (the first) and another that I use to insert the image in my own database (the second), and I don't know how to connect this image with the featured image of this new post.</p>
<p>[first AJAX function]</p>
<pre><code>$('.make_the_post_activity').live('click', function(){
var post_activity_video_url = $('.input_youtube_video_activity').val();
var post_activity_image_url = $('.input_upload_photo_activity').val();
var post_activity_content = $('.input_activity_content').val();
$.ajax({
url: Ajax.ajax_url,
type: 'POST',
data: {
action: 'make_the_post_activity',
security: Ajax.nonce,
dataType: 'json',
user_id: user_id,
girl_page_author: girl_page_author,
post_activity_video_url: post_activity_video_url,
post_activity_image_url: post_activity_image_url,
post_activity_content: post_activity_content
},
success: function( response ){
if( response.hasOwnProperty('status') ){
alert( response.message );
}
},
error: function( error ){
},
complete: function(){
}
});
});
</code></pre>
<p>And this this AJAX Function, I have the Action with this First PHP Function</p>
<p><strong>[PHP Function for the Previous AJAX Function]</strong></p>
<pre><code>add_action('wp_ajax_make_the_post_activity', 'make_the_post_activity');
add_action('wp_ajax_nopriv_make_the_post_activity', 'make_the_post_activity');
function make_the_post_activity(){
if( check_ajax_referer('namorada-security-ajax', 'security', false) ){
$user_id = $_REQUEST['user_id'];
$garota_id = $_REQUEST['garota_id'];
$girl_page_author = $_REQUEST['girl_page_author'];
$post_activity_video_url = $_REQUEST['post_activity_video_url'];
$post_activity_image_url = $_REQUEST['post_activity_image_url'];
$post_activity_content = $_REQUEST['post_activity_content'];
if( is_user_logged_in() && current_user_can('publish_posts') && $user_id == $girl_page_author ){
$args = array(
'post_author' => $user_id,
'post_content' => $post_activity_content,
'post_title' => __('Nova postagem de', 'namorada-general'),
'post_type' => 'post-activity',
'post_status' => 'publish'
);
$new_post = wp_insert_post( $args );
if( isset($new_post) ){
// Save the YouTube URL when it exists
if( isset($post_activity_video_url) && $post_activity_video_url != '' ){
$field_key_video_url_youtube_post_activity = 'field_5f08ca584384d';
update_field( $field_key_video_url_youtube_post_activity, $post_activity_video_url, $new_post );
}
// Save the Featured Image of the Post when it exists
$field_key_image_url_post_activity = 'field_5f08ca6d4384e';
update_field( $field_key_image_url_post_activity, $post_activity_image_url, $new_post );
$response = array(
'status' => 'success',
'message' => 'Your post was published'
);
}
} else {
$response = array(
'status' => 'fail',
'message' => 'you are not the author'
);
}
} else {
$response = array(
'status' => 'fail',
'message' => 'it is not passing by the ajax referer'
);
}
wp_send_json( $response );
}
</code></pre>
<p>AND THEN, I have the SECOND AJAX FUNCTION - To add the Image (from the HTML Input with the others fields).</p>
<p><strong>[SECOND AJAX FUNCTION]</strong></p>
<pre><code>$('#addimage').click(function(e) {
var packagename = $('#packagename').val();
var packagephoto_data = $('#packagephoto').prop('files')[0];
var form_data = new FormData();
form_data.append('packagephoto_name', packagephoto_data);
form_data.append('packagename', packagename);
form_data.append('action', 'ng_add_image_ajax');
$.ajax({
url: Ajax.ajax_url,
type: 'post',
contentType: false,
processData: false,
data: form_data,
success: function(data){
}
});
});
</code></pre>
<p>And this function, has this next PHP Function as the ACTION</p>
<p><strong>[PHP FUNCTION FOR THE PREVIOUS AJAX CALL]</strong></p>
<pre><code>function ng_add_image_ajax() {
add_filter( 'upload_dir', 'ng_upload_dir' );
global $wpdb;
$tablename = $wpdb->prefix . 'imagepackages';
$uploadedfile = $_FILES['packagephoto_name'];
$packagephoto_name = $_FILES["packagephoto_name"]["name"];
$upload_overrides = array(
'test_form' => false, /* this was in your existing override array */
'unique_filename_callback' => 'ng_packagephoto_filename' // Function for image rename
);
$movefile = wp_handle_upload($uploadedfile, $upload_overrides);
if ($movefile && !isset($movefile['error'])) {
$data = array(
'packagename' => $_POST['packagename'],
'packagephoto' => ng_packagephoto_filename('', $packagephoto_name, ''),
'status' => 0 );
// FOR database SQL injection security, set up the formats
$formats = array(
'%s', // packagename should be an string
'%s', // packagephoto should be a integer
'%d' // status should be an integer
);
// Actually attempt to insert the data
$insert = $wpdb->insert($tablename, $data, $formats);
if($insert){
echo "<span class='text-success'>The image has been added succefully</span>";
}else{
echo "<span class='text-danger'>The image not added succefully</span>";
}
}else{
echo "<span class='text-danger'>Image Not Upload</span>";
}
remove_filter( 'upload_dir', 'ng_upload_dir' );
}
add_action( 'wp_ajax_ng_add_image_ajax', 'ng_add_image_ajax' ); // If called from admin panel
add_action( 'wp_ajax_nopriv_ng_add_image_ajax', 'ng_add_image_ajax' );
function ng_packagephoto_filename($dir, $filename, $ext){
$newfilename = time() . '1_'. $filename;
return $newfilename;
}
function ng_upload_dir( $dirs ) {
$user = wp_get_current_user();
$dirs['subdir'] = '';
$dirs['path'] = $dirs['basedir'].'';
$dirs['url'] = $dirs['baseurl'].'';
return $dirs;
}
</code></pre>
<p>Saying again, this second AJAX function, add upload the image using the FormData(). Then there is a way to connect this formData with the Media Library and then make this photo as the Featured Image of the Post.</p>
<p>Sorry, I know it is big and unpleasant to read like that.</p>
| [
{
"answer_id": 370919,
"author": "shanebp",
"author_id": 16575,
"author_profile": "https://wordpress.stackexchange.com/users/16575",
"pm_score": 0,
"selected": false,
"text": "<pre><code>'posts_per_page' => 1,\n</code></pre>\n<p>Do you really only want a single post to be returned?\nAnd what is the <code>$parent</code> value?</p>\n<p>Since you don't want anything but the post thumbnail, specify that you only need the post id(s).\nTry:</p>\n<pre><code> $args = array(\n 'post_type' => 'post' ,\n 'orderby' => 'date' ,\n 'order' => 'DESC' ,\n 'posts_per_page' => 1,\n 'category' => '2',\n 'paged' => get_query_var('paged'),\n 'post_parent' => $parent,\n 'fields' => 'ids'\n );\n // The Query\n $the_query = new WP_Query( $args );\n\n if ( ! empty ( $query->posts ) ) {\n\n $post_ids = $query->posts; // just the post IDs\n\n foreach ( $post_ids as $post_id )\n echo get_the_post_thumbnail( $post_id, 'post-thumbnail' );\n\n } else {\n echo 'No posts were found';\n }\n /* Restore original Post Data */\n wp_reset_postdata();\n</code></pre>\n<p>A good and relevant read <a href=\"https://wordpress.stackexchange.com/questions/112184/how-to-create-a-flexible-abstraction-for-wp-query/112196#112196\">here</a>.</p>\n"
},
{
"answer_id": 370931,
"author": "Steve Johnson",
"author_id": 191486,
"author_profile": "https://wordpress.stackexchange.com/users/191486",
"pm_score": 2,
"selected": false,
"text": "<p>Not sure what you're trying to do, but the problem you're having with this specific bit of code is that you're using the wrong function. You want <strong>get_the_post_thumbnail()</strong> instead. The function the_post_thumbnail() echoes the result of get_the_post_thumbnail().</p>\n<pre><code>$args = array(\n 'post_type' => 'post',\n 'orderby' => 'date',\n 'order' => 'DESC',\n 'posts_per_page' => 1,\n 'category' => '2',\n 'paged' => get_query_var('paged'),\n 'post_parent' => $parent\n);\n// The Query\n$the_query = new WP_Query($args);\n\n// The Loop\nif ( $the_query->have_posts() ) {\n while ( $the_query->have_posts() ) {\n $the_query->the_post();\n echo get_the_post_thumbnail();\n }\n} else {\n// no posts found\n}\n/* Restore original Post Data */\nwp_reset_postdata();\n</code></pre>\n"
}
] | 2020/07/13 | [
"https://wordpress.stackexchange.com/questions/370990",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/186694/"
] | I have the link of WordPress doc about this function, but there is nothing explaining how to use this. I have a Ajax function, PHP and a HTML input. In this HTML I set the title and content, and I'd like to set the thumbnail too. Maybe I can do that with this function? Is there some example?
<https://developer.wordpress.org/reference/functions/wp_ajax_set_post_thumbnail/>
**[EDIT]**
I have an html input
```
<input type="file">
```
I have an AJAX Call
```
$.ajax({
url: Ajax.ajax_url,
type: 'POST',
data: {
action: 'make_the_post_activity',
security: Ajax.nonce,
dataType: 'json'
},
success: function( response ){
}
});
```
And a PHP function
```
add_action('wp_ajax_make_the_post_activity', 'make_the_post_activity');
add_action('wp_ajax_nopriv_make_the_post_activity', 'make_the_post_activity');
function make_the_post_activity(){
if( check_ajax_referer('namorada-security-ajax', 'security', false) ){
// Here inside I add the the new post calling by ajax the fields as title and content from the HTML file.
}
}
```
Then here I get the ID of the New Post. But I don't know how to update this new post id with the image from the input (file). I know that the Ajax can't upload the image with XMLHttpRequest, but I'm sure there is another possibility that I still don't know.
I understand the function that the friend added bellow, but in this condition, I need already pass maybe sending a JSON to the Ajax function, the ID of the image I've uploaded in the wordpress library, but I don't know how to upload it and get the ID to send to Ajax and then publish it via REST API.
**[EDIT 2]**
I'll put here the complete functions I use to upload the photo with Ajax and PHP, and the fiels I need to use to make the new post, maybe it will be a big amount of code.
HTML
```
<div class="modal-dialog vertical-align-center" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel"><?php echo __('Escreva seu post', 'namorada-general'); ?></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<textarea class="form-control input_activity_content" id="post_activity_form_emoji" data-emoji-placeholder=":smiley:"></textarea>
</div>
<div style="width:100%;float:left;">
<i class="fa fa-image p-1 upload_photo_activity" style="float:right;font-size:20px;cursor:pointer;"></i>
<i class="fa fa-video-camera p-1 youtube_video_activity" style="float:right;font-size:20px;cursor:pointer;"></i>
</div>
<div style="width:100%;float:left;display:none;" id="youtube_video_activity">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-default">YouTube</span>
</div>
<input type="text" class="form-control input_youtube_video_activity" aria-label="Default" aria-describedby="inputGroup-sizing-default">
</div>
</div>
<div style="width:100%;float:left;display:none;" id="upload_photo_activity">
<div class="custom-file">
<input type="file" class="custom-file-input input_upload_photo_activity" id="packagephoto" name="packagephoto">
<label class="custom-file-label choose_photo_activity" for="validatedCustomFile" accept="image/x-png,image/gif,image/jpeg">Escolha sua foto</label>
<div class="invalid-feedback">Example invalid custom file feedback</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal"><?php echo __('Cancelar', 'namorada-general'); ?></button>
<input id="addimage" name="addimage" class="btn btn-primary make_the_post_activity" value="<?php echo __('Publicar', 'namorada-general'); ?>">
</div>
</div>
</div>
```
**The AJAX Functions** (I have one function I use to insert the POST (the first) and another that I use to insert the image in my own database (the second), and I don't know how to connect this image with the featured image of this new post.
[first AJAX function]
```
$('.make_the_post_activity').live('click', function(){
var post_activity_video_url = $('.input_youtube_video_activity').val();
var post_activity_image_url = $('.input_upload_photo_activity').val();
var post_activity_content = $('.input_activity_content').val();
$.ajax({
url: Ajax.ajax_url,
type: 'POST',
data: {
action: 'make_the_post_activity',
security: Ajax.nonce,
dataType: 'json',
user_id: user_id,
girl_page_author: girl_page_author,
post_activity_video_url: post_activity_video_url,
post_activity_image_url: post_activity_image_url,
post_activity_content: post_activity_content
},
success: function( response ){
if( response.hasOwnProperty('status') ){
alert( response.message );
}
},
error: function( error ){
},
complete: function(){
}
});
});
```
And this this AJAX Function, I have the Action with this First PHP Function
**[PHP Function for the Previous AJAX Function]**
```
add_action('wp_ajax_make_the_post_activity', 'make_the_post_activity');
add_action('wp_ajax_nopriv_make_the_post_activity', 'make_the_post_activity');
function make_the_post_activity(){
if( check_ajax_referer('namorada-security-ajax', 'security', false) ){
$user_id = $_REQUEST['user_id'];
$garota_id = $_REQUEST['garota_id'];
$girl_page_author = $_REQUEST['girl_page_author'];
$post_activity_video_url = $_REQUEST['post_activity_video_url'];
$post_activity_image_url = $_REQUEST['post_activity_image_url'];
$post_activity_content = $_REQUEST['post_activity_content'];
if( is_user_logged_in() && current_user_can('publish_posts') && $user_id == $girl_page_author ){
$args = array(
'post_author' => $user_id,
'post_content' => $post_activity_content,
'post_title' => __('Nova postagem de', 'namorada-general'),
'post_type' => 'post-activity',
'post_status' => 'publish'
);
$new_post = wp_insert_post( $args );
if( isset($new_post) ){
// Save the YouTube URL when it exists
if( isset($post_activity_video_url) && $post_activity_video_url != '' ){
$field_key_video_url_youtube_post_activity = 'field_5f08ca584384d';
update_field( $field_key_video_url_youtube_post_activity, $post_activity_video_url, $new_post );
}
// Save the Featured Image of the Post when it exists
$field_key_image_url_post_activity = 'field_5f08ca6d4384e';
update_field( $field_key_image_url_post_activity, $post_activity_image_url, $new_post );
$response = array(
'status' => 'success',
'message' => 'Your post was published'
);
}
} else {
$response = array(
'status' => 'fail',
'message' => 'you are not the author'
);
}
} else {
$response = array(
'status' => 'fail',
'message' => 'it is not passing by the ajax referer'
);
}
wp_send_json( $response );
}
```
AND THEN, I have the SECOND AJAX FUNCTION - To add the Image (from the HTML Input with the others fields).
**[SECOND AJAX FUNCTION]**
```
$('#addimage').click(function(e) {
var packagename = $('#packagename').val();
var packagephoto_data = $('#packagephoto').prop('files')[0];
var form_data = new FormData();
form_data.append('packagephoto_name', packagephoto_data);
form_data.append('packagename', packagename);
form_data.append('action', 'ng_add_image_ajax');
$.ajax({
url: Ajax.ajax_url,
type: 'post',
contentType: false,
processData: false,
data: form_data,
success: function(data){
}
});
});
```
And this function, has this next PHP Function as the ACTION
**[PHP FUNCTION FOR THE PREVIOUS AJAX CALL]**
```
function ng_add_image_ajax() {
add_filter( 'upload_dir', 'ng_upload_dir' );
global $wpdb;
$tablename = $wpdb->prefix . 'imagepackages';
$uploadedfile = $_FILES['packagephoto_name'];
$packagephoto_name = $_FILES["packagephoto_name"]["name"];
$upload_overrides = array(
'test_form' => false, /* this was in your existing override array */
'unique_filename_callback' => 'ng_packagephoto_filename' // Function for image rename
);
$movefile = wp_handle_upload($uploadedfile, $upload_overrides);
if ($movefile && !isset($movefile['error'])) {
$data = array(
'packagename' => $_POST['packagename'],
'packagephoto' => ng_packagephoto_filename('', $packagephoto_name, ''),
'status' => 0 );
// FOR database SQL injection security, set up the formats
$formats = array(
'%s', // packagename should be an string
'%s', // packagephoto should be a integer
'%d' // status should be an integer
);
// Actually attempt to insert the data
$insert = $wpdb->insert($tablename, $data, $formats);
if($insert){
echo "<span class='text-success'>The image has been added succefully</span>";
}else{
echo "<span class='text-danger'>The image not added succefully</span>";
}
}else{
echo "<span class='text-danger'>Image Not Upload</span>";
}
remove_filter( 'upload_dir', 'ng_upload_dir' );
}
add_action( 'wp_ajax_ng_add_image_ajax', 'ng_add_image_ajax' ); // If called from admin panel
add_action( 'wp_ajax_nopriv_ng_add_image_ajax', 'ng_add_image_ajax' );
function ng_packagephoto_filename($dir, $filename, $ext){
$newfilename = time() . '1_'. $filename;
return $newfilename;
}
function ng_upload_dir( $dirs ) {
$user = wp_get_current_user();
$dirs['subdir'] = '';
$dirs['path'] = $dirs['basedir'].'';
$dirs['url'] = $dirs['baseurl'].'';
return $dirs;
}
```
Saying again, this second AJAX function, add upload the image using the FormData(). Then there is a way to connect this formData with the Media Library and then make this photo as the Featured Image of the Post.
Sorry, I know it is big and unpleasant to read like that. | Not sure what you're trying to do, but the problem you're having with this specific bit of code is that you're using the wrong function. You want **get\_the\_post\_thumbnail()** instead. The function the\_post\_thumbnail() echoes the result of get\_the\_post\_thumbnail().
```
$args = array(
'post_type' => 'post',
'orderby' => 'date',
'order' => 'DESC',
'posts_per_page' => 1,
'category' => '2',
'paged' => get_query_var('paged'),
'post_parent' => $parent
);
// The Query
$the_query = new WP_Query($args);
// The Loop
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo get_the_post_thumbnail();
}
} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
``` |
371,064 | <p><a href="https://wordpress.stackexchange.com/questions/218824/parent-comments-author-name">Parent comment's author name</a></p>
<p>I found this code and would like to modify it as follows: if someone changes the display_name, the name in the comments should also change.
I was able to achieve this with the following code in the comments:</p>
<pre><code>$usermeta = get_userdata($comment->user_id);
<?php echo $usermeta->display_name?>
</code></pre>
<p>However, I don't know how to change the code below to show display_name here as well.</p>
<pre><code>if( $comment->comment_parent )
comment_author( $comment->comment_parent );
</code></pre>
<p>I appreciate any help.</p>
| [
{
"answer_id": 370919,
"author": "shanebp",
"author_id": 16575,
"author_profile": "https://wordpress.stackexchange.com/users/16575",
"pm_score": 0,
"selected": false,
"text": "<pre><code>'posts_per_page' => 1,\n</code></pre>\n<p>Do you really only want a single post to be returned?\nAnd what is the <code>$parent</code> value?</p>\n<p>Since you don't want anything but the post thumbnail, specify that you only need the post id(s).\nTry:</p>\n<pre><code> $args = array(\n 'post_type' => 'post' ,\n 'orderby' => 'date' ,\n 'order' => 'DESC' ,\n 'posts_per_page' => 1,\n 'category' => '2',\n 'paged' => get_query_var('paged'),\n 'post_parent' => $parent,\n 'fields' => 'ids'\n );\n // The Query\n $the_query = new WP_Query( $args );\n\n if ( ! empty ( $query->posts ) ) {\n\n $post_ids = $query->posts; // just the post IDs\n\n foreach ( $post_ids as $post_id )\n echo get_the_post_thumbnail( $post_id, 'post-thumbnail' );\n\n } else {\n echo 'No posts were found';\n }\n /* Restore original Post Data */\n wp_reset_postdata();\n</code></pre>\n<p>A good and relevant read <a href=\"https://wordpress.stackexchange.com/questions/112184/how-to-create-a-flexible-abstraction-for-wp-query/112196#112196\">here</a>.</p>\n"
},
{
"answer_id": 370931,
"author": "Steve Johnson",
"author_id": 191486,
"author_profile": "https://wordpress.stackexchange.com/users/191486",
"pm_score": 2,
"selected": false,
"text": "<p>Not sure what you're trying to do, but the problem you're having with this specific bit of code is that you're using the wrong function. You want <strong>get_the_post_thumbnail()</strong> instead. The function the_post_thumbnail() echoes the result of get_the_post_thumbnail().</p>\n<pre><code>$args = array(\n 'post_type' => 'post',\n 'orderby' => 'date',\n 'order' => 'DESC',\n 'posts_per_page' => 1,\n 'category' => '2',\n 'paged' => get_query_var('paged'),\n 'post_parent' => $parent\n);\n// The Query\n$the_query = new WP_Query($args);\n\n// The Loop\nif ( $the_query->have_posts() ) {\n while ( $the_query->have_posts() ) {\n $the_query->the_post();\n echo get_the_post_thumbnail();\n }\n} else {\n// no posts found\n}\n/* Restore original Post Data */\nwp_reset_postdata();\n</code></pre>\n"
}
] | 2020/07/14 | [
"https://wordpress.stackexchange.com/questions/371064",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/187945/"
] | [Parent comment's author name](https://wordpress.stackexchange.com/questions/218824/parent-comments-author-name)
I found this code and would like to modify it as follows: if someone changes the display\_name, the name in the comments should also change.
I was able to achieve this with the following code in the comments:
```
$usermeta = get_userdata($comment->user_id);
<?php echo $usermeta->display_name?>
```
However, I don't know how to change the code below to show display\_name here as well.
```
if( $comment->comment_parent )
comment_author( $comment->comment_parent );
```
I appreciate any help. | Not sure what you're trying to do, but the problem you're having with this specific bit of code is that you're using the wrong function. You want **get\_the\_post\_thumbnail()** instead. The function the\_post\_thumbnail() echoes the result of get\_the\_post\_thumbnail().
```
$args = array(
'post_type' => 'post',
'orderby' => 'date',
'order' => 'DESC',
'posts_per_page' => 1,
'category' => '2',
'paged' => get_query_var('paged'),
'post_parent' => $parent
);
// The Query
$the_query = new WP_Query($args);
// The Loop
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo get_the_post_thumbnail();
}
} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
``` |
371,065 | <p>I uploaded my first wordpress website on the server, but trying to add new media files, i have got the message "Missing a temporary folder", I tried the solutions on the forum:</p>
<pre><code>define('WP_TEMP_DIR',dirname(__FILE__).'/wp-content/temp/');
</code></pre>
<p>and created a 'temp' folder on 'wp-content', but the problem still happened ..
how to fix that please ??</p>
<p>I tried by doing this : creating the folder on localhost with writable property then upload it to the server, but it still doesn't work</p>
<p><a href="https://i.stack.imgur.com/WR2Po.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WR2Po.jpg" alt="enter image description here" /></a></p>
| [
{
"answer_id": 370919,
"author": "shanebp",
"author_id": 16575,
"author_profile": "https://wordpress.stackexchange.com/users/16575",
"pm_score": 0,
"selected": false,
"text": "<pre><code>'posts_per_page' => 1,\n</code></pre>\n<p>Do you really only want a single post to be returned?\nAnd what is the <code>$parent</code> value?</p>\n<p>Since you don't want anything but the post thumbnail, specify that you only need the post id(s).\nTry:</p>\n<pre><code> $args = array(\n 'post_type' => 'post' ,\n 'orderby' => 'date' ,\n 'order' => 'DESC' ,\n 'posts_per_page' => 1,\n 'category' => '2',\n 'paged' => get_query_var('paged'),\n 'post_parent' => $parent,\n 'fields' => 'ids'\n );\n // The Query\n $the_query = new WP_Query( $args );\n\n if ( ! empty ( $query->posts ) ) {\n\n $post_ids = $query->posts; // just the post IDs\n\n foreach ( $post_ids as $post_id )\n echo get_the_post_thumbnail( $post_id, 'post-thumbnail' );\n\n } else {\n echo 'No posts were found';\n }\n /* Restore original Post Data */\n wp_reset_postdata();\n</code></pre>\n<p>A good and relevant read <a href=\"https://wordpress.stackexchange.com/questions/112184/how-to-create-a-flexible-abstraction-for-wp-query/112196#112196\">here</a>.</p>\n"
},
{
"answer_id": 370931,
"author": "Steve Johnson",
"author_id": 191486,
"author_profile": "https://wordpress.stackexchange.com/users/191486",
"pm_score": 2,
"selected": false,
"text": "<p>Not sure what you're trying to do, but the problem you're having with this specific bit of code is that you're using the wrong function. You want <strong>get_the_post_thumbnail()</strong> instead. The function the_post_thumbnail() echoes the result of get_the_post_thumbnail().</p>\n<pre><code>$args = array(\n 'post_type' => 'post',\n 'orderby' => 'date',\n 'order' => 'DESC',\n 'posts_per_page' => 1,\n 'category' => '2',\n 'paged' => get_query_var('paged'),\n 'post_parent' => $parent\n);\n// The Query\n$the_query = new WP_Query($args);\n\n// The Loop\nif ( $the_query->have_posts() ) {\n while ( $the_query->have_posts() ) {\n $the_query->the_post();\n echo get_the_post_thumbnail();\n }\n} else {\n// no posts found\n}\n/* Restore original Post Data */\nwp_reset_postdata();\n</code></pre>\n"
}
] | 2020/07/14 | [
"https://wordpress.stackexchange.com/questions/371065",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/184325/"
] | I uploaded my first wordpress website on the server, but trying to add new media files, i have got the message "Missing a temporary folder", I tried the solutions on the forum:
```
define('WP_TEMP_DIR',dirname(__FILE__).'/wp-content/temp/');
```
and created a 'temp' folder on 'wp-content', but the problem still happened ..
how to fix that please ??
I tried by doing this : creating the folder on localhost with writable property then upload it to the server, but it still doesn't work
[](https://i.stack.imgur.com/WR2Po.jpg) | Not sure what you're trying to do, but the problem you're having with this specific bit of code is that you're using the wrong function. You want **get\_the\_post\_thumbnail()** instead. The function the\_post\_thumbnail() echoes the result of get\_the\_post\_thumbnail().
```
$args = array(
'post_type' => 'post',
'orderby' => 'date',
'order' => 'DESC',
'posts_per_page' => 1,
'category' => '2',
'paged' => get_query_var('paged'),
'post_parent' => $parent
);
// The Query
$the_query = new WP_Query($args);
// The Loop
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo get_the_post_thumbnail();
}
} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
``` |
371,091 | <p>I'm using a function that changes the front-end and back-end post title for a custom post type according to what you put in certain custom fields.</p>
<pre><code> //Save ACF fields as post_content for back-end
add_action('save_post', 'change_title_cars');
function change_title_cars($post_id) {
global $_POST;
if('cars'== get_post_type()){
$car_name = get_post_meta($post_id,'car_name',true);
$first_car_model = ????????????;
$last_car_model = ????????????;
$my_post = array();
$my_post['ID'] = $post_id;
$my_post['post_title'] = $car_name . ' - ' . $first_car_model . ' ~ ' . $last_car_model;
remove_action('save_post', 'change_title_cars');
wp_update_post( $my_post );
add_action('save_post', 'change_title_cars');
}
}
//Save ACF fields as post_content for front-end
add_action('acf/save_post', 'change_title_frontend_cars');
function change_title_frontend_cars($post_id) {
global $_POST;
if('cars'== get_post_type()){
$car_name = get_post_meta($post_id,'car_name',true);
$first_car_model = ????????????;
$last_car_model = ????????????;
$my_post = array();
$my_post['ID'] = $post_id;
$my_post['post_title'] = $car_name . ' - ' . $first_car_model . ' ~ ' . $last_car_model;
remove_action('acf/save_post', 'change_title_frontend_cars');
wp_update_post( $my_post );
add_action('acf/save_post', 'change_title_frontend_cars');
}
}
</code></pre>
<p>I'm using a repeater which has a sub-field named "car_model". I'm trying to have the title changed into something like this:</p>
<p><em>(car_name) - (first "car_model" in the repeater) ~ (last "car_model" in the repeater)</em></p>
<p>but I couldn't get values of the repeater sub-fields inside the function.</p>
<p>Note: the repeater has random number of rows.</p>
| [
{
"answer_id": 370919,
"author": "shanebp",
"author_id": 16575,
"author_profile": "https://wordpress.stackexchange.com/users/16575",
"pm_score": 0,
"selected": false,
"text": "<pre><code>'posts_per_page' => 1,\n</code></pre>\n<p>Do you really only want a single post to be returned?\nAnd what is the <code>$parent</code> value?</p>\n<p>Since you don't want anything but the post thumbnail, specify that you only need the post id(s).\nTry:</p>\n<pre><code> $args = array(\n 'post_type' => 'post' ,\n 'orderby' => 'date' ,\n 'order' => 'DESC' ,\n 'posts_per_page' => 1,\n 'category' => '2',\n 'paged' => get_query_var('paged'),\n 'post_parent' => $parent,\n 'fields' => 'ids'\n );\n // The Query\n $the_query = new WP_Query( $args );\n\n if ( ! empty ( $query->posts ) ) {\n\n $post_ids = $query->posts; // just the post IDs\n\n foreach ( $post_ids as $post_id )\n echo get_the_post_thumbnail( $post_id, 'post-thumbnail' );\n\n } else {\n echo 'No posts were found';\n }\n /* Restore original Post Data */\n wp_reset_postdata();\n</code></pre>\n<p>A good and relevant read <a href=\"https://wordpress.stackexchange.com/questions/112184/how-to-create-a-flexible-abstraction-for-wp-query/112196#112196\">here</a>.</p>\n"
},
{
"answer_id": 370931,
"author": "Steve Johnson",
"author_id": 191486,
"author_profile": "https://wordpress.stackexchange.com/users/191486",
"pm_score": 2,
"selected": false,
"text": "<p>Not sure what you're trying to do, but the problem you're having with this specific bit of code is that you're using the wrong function. You want <strong>get_the_post_thumbnail()</strong> instead. The function the_post_thumbnail() echoes the result of get_the_post_thumbnail().</p>\n<pre><code>$args = array(\n 'post_type' => 'post',\n 'orderby' => 'date',\n 'order' => 'DESC',\n 'posts_per_page' => 1,\n 'category' => '2',\n 'paged' => get_query_var('paged'),\n 'post_parent' => $parent\n);\n// The Query\n$the_query = new WP_Query($args);\n\n// The Loop\nif ( $the_query->have_posts() ) {\n while ( $the_query->have_posts() ) {\n $the_query->the_post();\n echo get_the_post_thumbnail();\n }\n} else {\n// no posts found\n}\n/* Restore original Post Data */\nwp_reset_postdata();\n</code></pre>\n"
}
] | 2020/07/15 | [
"https://wordpress.stackexchange.com/questions/371091",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/191421/"
] | I'm using a function that changes the front-end and back-end post title for a custom post type according to what you put in certain custom fields.
```
//Save ACF fields as post_content for back-end
add_action('save_post', 'change_title_cars');
function change_title_cars($post_id) {
global $_POST;
if('cars'== get_post_type()){
$car_name = get_post_meta($post_id,'car_name',true);
$first_car_model = ????????????;
$last_car_model = ????????????;
$my_post = array();
$my_post['ID'] = $post_id;
$my_post['post_title'] = $car_name . ' - ' . $first_car_model . ' ~ ' . $last_car_model;
remove_action('save_post', 'change_title_cars');
wp_update_post( $my_post );
add_action('save_post', 'change_title_cars');
}
}
//Save ACF fields as post_content for front-end
add_action('acf/save_post', 'change_title_frontend_cars');
function change_title_frontend_cars($post_id) {
global $_POST;
if('cars'== get_post_type()){
$car_name = get_post_meta($post_id,'car_name',true);
$first_car_model = ????????????;
$last_car_model = ????????????;
$my_post = array();
$my_post['ID'] = $post_id;
$my_post['post_title'] = $car_name . ' - ' . $first_car_model . ' ~ ' . $last_car_model;
remove_action('acf/save_post', 'change_title_frontend_cars');
wp_update_post( $my_post );
add_action('acf/save_post', 'change_title_frontend_cars');
}
}
```
I'm using a repeater which has a sub-field named "car\_model". I'm trying to have the title changed into something like this:
*(car\_name) - (first "car\_model" in the repeater) ~ (last "car\_model" in the repeater)*
but I couldn't get values of the repeater sub-fields inside the function.
Note: the repeater has random number of rows. | Not sure what you're trying to do, but the problem you're having with this specific bit of code is that you're using the wrong function. You want **get\_the\_post\_thumbnail()** instead. The function the\_post\_thumbnail() echoes the result of get\_the\_post\_thumbnail().
```
$args = array(
'post_type' => 'post',
'orderby' => 'date',
'order' => 'DESC',
'posts_per_page' => 1,
'category' => '2',
'paged' => get_query_var('paged'),
'post_parent' => $parent
);
// The Query
$the_query = new WP_Query($args);
// The Loop
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo get_the_post_thumbnail();
}
} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
``` |
371,136 | <p>I'm looking to force a 403 access denied response for an xml file in a directory outside of the default Wordpress install.</p>
<p>The url I'm trying to force the 403 response on looks like this mydomain.com/autodiscover/autodiscover.xml</p>
<p>I've tried modifying the default Wordpress htaccess file by adding a line to ignore the custom directory but it doesn't seem to work. When visiting the url I get a 404. I did create the directory and xml file and pushed them to our server.</p>
<pre><code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^(autodiscover)($|/) – [L]
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
<Files ~ "\.(xml)$">
deny from all
</Files>
</code></pre>
<p>Wondering if anyone has every run into this before and if they found a solution. My end goal would be to just force the 403 on the one file so my xml sitemaps don't get blocked as well.</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 370919,
"author": "shanebp",
"author_id": 16575,
"author_profile": "https://wordpress.stackexchange.com/users/16575",
"pm_score": 0,
"selected": false,
"text": "<pre><code>'posts_per_page' => 1,\n</code></pre>\n<p>Do you really only want a single post to be returned?\nAnd what is the <code>$parent</code> value?</p>\n<p>Since you don't want anything but the post thumbnail, specify that you only need the post id(s).\nTry:</p>\n<pre><code> $args = array(\n 'post_type' => 'post' ,\n 'orderby' => 'date' ,\n 'order' => 'DESC' ,\n 'posts_per_page' => 1,\n 'category' => '2',\n 'paged' => get_query_var('paged'),\n 'post_parent' => $parent,\n 'fields' => 'ids'\n );\n // The Query\n $the_query = new WP_Query( $args );\n\n if ( ! empty ( $query->posts ) ) {\n\n $post_ids = $query->posts; // just the post IDs\n\n foreach ( $post_ids as $post_id )\n echo get_the_post_thumbnail( $post_id, 'post-thumbnail' );\n\n } else {\n echo 'No posts were found';\n }\n /* Restore original Post Data */\n wp_reset_postdata();\n</code></pre>\n<p>A good and relevant read <a href=\"https://wordpress.stackexchange.com/questions/112184/how-to-create-a-flexible-abstraction-for-wp-query/112196#112196\">here</a>.</p>\n"
},
{
"answer_id": 370931,
"author": "Steve Johnson",
"author_id": 191486,
"author_profile": "https://wordpress.stackexchange.com/users/191486",
"pm_score": 2,
"selected": false,
"text": "<p>Not sure what you're trying to do, but the problem you're having with this specific bit of code is that you're using the wrong function. You want <strong>get_the_post_thumbnail()</strong> instead. The function the_post_thumbnail() echoes the result of get_the_post_thumbnail().</p>\n<pre><code>$args = array(\n 'post_type' => 'post',\n 'orderby' => 'date',\n 'order' => 'DESC',\n 'posts_per_page' => 1,\n 'category' => '2',\n 'paged' => get_query_var('paged'),\n 'post_parent' => $parent\n);\n// The Query\n$the_query = new WP_Query($args);\n\n// The Loop\nif ( $the_query->have_posts() ) {\n while ( $the_query->have_posts() ) {\n $the_query->the_post();\n echo get_the_post_thumbnail();\n }\n} else {\n// no posts found\n}\n/* Restore original Post Data */\nwp_reset_postdata();\n</code></pre>\n"
}
] | 2020/07/15 | [
"https://wordpress.stackexchange.com/questions/371136",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/64789/"
] | I'm looking to force a 403 access denied response for an xml file in a directory outside of the default Wordpress install.
The url I'm trying to force the 403 response on looks like this mydomain.com/autodiscover/autodiscover.xml
I've tried modifying the default Wordpress htaccess file by adding a line to ignore the custom directory but it doesn't seem to work. When visiting the url I get a 404. I did create the directory and xml file and pushed them to our server.
```
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^(autodiscover)($|/) – [L]
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
<Files ~ "\.(xml)$">
deny from all
</Files>
```
Wondering if anyone has every run into this before and if they found a solution. My end goal would be to just force the 403 on the one file so my xml sitemaps don't get blocked as well.
Thanks in advance. | Not sure what you're trying to do, but the problem you're having with this specific bit of code is that you're using the wrong function. You want **get\_the\_post\_thumbnail()** instead. The function the\_post\_thumbnail() echoes the result of get\_the\_post\_thumbnail().
```
$args = array(
'post_type' => 'post',
'orderby' => 'date',
'order' => 'DESC',
'posts_per_page' => 1,
'category' => '2',
'paged' => get_query_var('paged'),
'post_parent' => $parent
);
// The Query
$the_query = new WP_Query($args);
// The Loop
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo get_the_post_thumbnail();
}
} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
``` |
371,157 | <p>I inherited a website that had a significant number of customized PHP files. I have removed many since, however, this is one of the few that still seemed relevant. The code below displays 1 image at random from a particular post type (gallery) in the website footer.</p>
<p>There was only one post type category prior to me working on the website. Now I have added more gallery categories, but the footer is displaying images from all categories. How can I modify this to show a particular category from the gallery post type?</p>
<pre><code><?php query_posts('orderby=rand&showposts=1&post_type=gallery');
while ( have_posts() ) : the_post();?>
<script>
jQuery(document).ready(function(){
$voice = '<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), "medium" ); echo $image[0]; ?>';
jQuery('.footer-voice').attr('src', $voice);
});
</script>
<?php endwhile; ?>
</code></pre>
| [
{
"answer_id": 381456,
"author": "per.eight",
"author_id": 200313,
"author_profile": "https://wordpress.stackexchange.com/users/200313",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the nl2br PHP function.\nIt means insert line breaks where newlines (\\n) occur in the string.\n<a href=\"https://www.w3schools.com/php/func_string_nl2br.asp\" rel=\"nofollow noreferrer\">https://www.w3schools.com/php/func_string_nl2br.asp</a></p>\n<p>example:</p>\n<pre><code>echo nl2br($userbio);\n</code></pre>\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 381467,
"author": "Jasper B",
"author_id": 194933,
"author_profile": "https://wordpress.stackexchange.com/users/194933",
"pm_score": 1,
"selected": false,
"text": "<p>You could use "white-space: pre;" in CSS to display newlines as they are</p>\n"
}
] | 2020/07/15 | [
"https://wordpress.stackexchange.com/questions/371157",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/191689/"
] | I inherited a website that had a significant number of customized PHP files. I have removed many since, however, this is one of the few that still seemed relevant. The code below displays 1 image at random from a particular post type (gallery) in the website footer.
There was only one post type category prior to me working on the website. Now I have added more gallery categories, but the footer is displaying images from all categories. How can I modify this to show a particular category from the gallery post type?
```
<?php query_posts('orderby=rand&showposts=1&post_type=gallery');
while ( have_posts() ) : the_post();?>
<script>
jQuery(document).ready(function(){
$voice = '<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), "medium" ); echo $image[0]; ?>';
jQuery('.footer-voice').attr('src', $voice);
});
</script>
<?php endwhile; ?>
``` | You could use "white-space: pre;" in CSS to display newlines as they are |
371,187 | <p>I need help how to translate the custom post type and taxonomy when using multisite and multi-language.
I am using subdirectory a /en /sv etc.</p>
<p>Are using the plugin (Multisite Language Switcher), but can not change the rewrite settings there. So I am guesing I have to change some rewrite?
Or should I translate the post type with translations file, .mo .po?</p>
<p>This is how the post type set up are in functions.php.
Should I do something with the rewrite?</p>
<pre><code>function create_posttype_product() {
register_post_type( 'product',
array(
'labels' => array(
'name' => __('Products'),
'singular_name' => __('product'),
'add_new' => __('Add new product'),
'add_new_item' => __('New product'),
'edit_item' => __('Edit product')
),
'public' => true,
'rewrite' => array( 'slug' => 'product', 'with_front' => false ),
'has_archive' => 'product',
'menu_icon' => 'dashicons-editor-help',
'supports' => array('title', 'editor', 'thumbnail')
)
);
}
add_action( 'init', 'create_posttype_product' );
</code></pre>
<p>So for example on english webpage url would be: <br>
<strong><a href="http://www.mypage.com/en/products" rel="nofollow noreferrer">www.mypage.com/en/products</a></strong></p>
<p>But for the swedish I want <br>
<strong><a href="http://www.mypage.com/sv/produkter" rel="nofollow noreferrer">www.mypage.com/sv/produkter</a></strong></p>
<p>And other language : <br>
<strong><a href="http://www.mypage.com/xx/product-name-in-this-language" rel="nofollow noreferrer">www.mypage.com/xx/product-name-in-this-language</a></strong></p>
<p>How can I manage to get this result? I have searched and search and can not find the right answer.</p>
| [
{
"answer_id": 381456,
"author": "per.eight",
"author_id": 200313,
"author_profile": "https://wordpress.stackexchange.com/users/200313",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the nl2br PHP function.\nIt means insert line breaks where newlines (\\n) occur in the string.\n<a href=\"https://www.w3schools.com/php/func_string_nl2br.asp\" rel=\"nofollow noreferrer\">https://www.w3schools.com/php/func_string_nl2br.asp</a></p>\n<p>example:</p>\n<pre><code>echo nl2br($userbio);\n</code></pre>\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 381467,
"author": "Jasper B",
"author_id": 194933,
"author_profile": "https://wordpress.stackexchange.com/users/194933",
"pm_score": 1,
"selected": false,
"text": "<p>You could use "white-space: pre;" in CSS to display newlines as they are</p>\n"
}
] | 2020/07/16 | [
"https://wordpress.stackexchange.com/questions/371187",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/185742/"
] | I need help how to translate the custom post type and taxonomy when using multisite and multi-language.
I am using subdirectory a /en /sv etc.
Are using the plugin (Multisite Language Switcher), but can not change the rewrite settings there. So I am guesing I have to change some rewrite?
Or should I translate the post type with translations file, .mo .po?
This is how the post type set up are in functions.php.
Should I do something with the rewrite?
```
function create_posttype_product() {
register_post_type( 'product',
array(
'labels' => array(
'name' => __('Products'),
'singular_name' => __('product'),
'add_new' => __('Add new product'),
'add_new_item' => __('New product'),
'edit_item' => __('Edit product')
),
'public' => true,
'rewrite' => array( 'slug' => 'product', 'with_front' => false ),
'has_archive' => 'product',
'menu_icon' => 'dashicons-editor-help',
'supports' => array('title', 'editor', 'thumbnail')
)
);
}
add_action( 'init', 'create_posttype_product' );
```
So for example on english webpage url would be:
**[www.mypage.com/en/products](http://www.mypage.com/en/products)**
But for the swedish I want
**[www.mypage.com/sv/produkter](http://www.mypage.com/sv/produkter)**
And other language :
**[www.mypage.com/xx/product-name-in-this-language](http://www.mypage.com/xx/product-name-in-this-language)**
How can I manage to get this result? I have searched and search and can not find the right answer. | You could use "white-space: pre;" in CSS to display newlines as they are |
371,189 | <p>I have function which gets menu next and previous item url. I want to get also title for them. How can I do this? This is what i have :</p>
<pre><code> <?php
$menu_name = 'main-menu';
$locations = get_nav_menu_locations();
$menu = wp_get_nav_menu_object( $locations[ $menu_name ] );
$menuitems = wp_get_nav_menu_items( $menu->term_id, array( 'order' => 'DESC' ) );
$i=-1;
foreach ( $menuitems as $item ):
$i++;
$id = get_post_meta( $item->ID, '_menu_item_object_id', true );
$page = get_page( $id );
$link = get_page_link( $id );
$linkarray.=$id.",";
$urlarray.=$link.",";
if ($id==$post->ID){
$previd=$i-1;
$nextid=$i+1;
}
endforeach;
$linkarray=explode(',',$linkarray);
$urlarray=explode(',',$urlarray);
$nextid=$urlarray[$nextid];
if (empty($nextid)){
$nextid=$urlarray[0];
}
$previd=$urlarray[$previd];
if (empty($previd)){
$previd=$urlarray[$i];
}
?>
<a href="<?php echo $nextid; ?>">Next Item</a>
<a href="<?php echo $previd; ?>">Previous Item</a>
</code></pre>
<p>Destination point is to replace 'next item' and 'previous item' with wp_nav_menu's next and prev item titles. Is that possible with this function? Any answer will be helpful!</p>
| [
{
"answer_id": 381456,
"author": "per.eight",
"author_id": 200313,
"author_profile": "https://wordpress.stackexchange.com/users/200313",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the nl2br PHP function.\nIt means insert line breaks where newlines (\\n) occur in the string.\n<a href=\"https://www.w3schools.com/php/func_string_nl2br.asp\" rel=\"nofollow noreferrer\">https://www.w3schools.com/php/func_string_nl2br.asp</a></p>\n<p>example:</p>\n<pre><code>echo nl2br($userbio);\n</code></pre>\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 381467,
"author": "Jasper B",
"author_id": 194933,
"author_profile": "https://wordpress.stackexchange.com/users/194933",
"pm_score": 1,
"selected": false,
"text": "<p>You could use "white-space: pre;" in CSS to display newlines as they are</p>\n"
}
] | 2020/07/16 | [
"https://wordpress.stackexchange.com/questions/371189",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/191729/"
] | I have function which gets menu next and previous item url. I want to get also title for them. How can I do this? This is what i have :
```
<?php
$menu_name = 'main-menu';
$locations = get_nav_menu_locations();
$menu = wp_get_nav_menu_object( $locations[ $menu_name ] );
$menuitems = wp_get_nav_menu_items( $menu->term_id, array( 'order' => 'DESC' ) );
$i=-1;
foreach ( $menuitems as $item ):
$i++;
$id = get_post_meta( $item->ID, '_menu_item_object_id', true );
$page = get_page( $id );
$link = get_page_link( $id );
$linkarray.=$id.",";
$urlarray.=$link.",";
if ($id==$post->ID){
$previd=$i-1;
$nextid=$i+1;
}
endforeach;
$linkarray=explode(',',$linkarray);
$urlarray=explode(',',$urlarray);
$nextid=$urlarray[$nextid];
if (empty($nextid)){
$nextid=$urlarray[0];
}
$previd=$urlarray[$previd];
if (empty($previd)){
$previd=$urlarray[$i];
}
?>
<a href="<?php echo $nextid; ?>">Next Item</a>
<a href="<?php echo $previd; ?>">Previous Item</a>
```
Destination point is to replace 'next item' and 'previous item' with wp\_nav\_menu's next and prev item titles. Is that possible with this function? Any answer will be helpful! | You could use "white-space: pre;" in CSS to display newlines as they are |
371,213 | <p>I have a <code>search form</code> with<code>wp_query</code>argument
There are many <code>checkbox</code> in this form</p>
<p>The problem start here, it takes a long time to load when you <code>select all</code> the options,
this query takes almost a minute to complete. Has anyone had this issue before?</p>
<p>I used these codes
in HTML</p>
<pre><code><form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
<label> <input type="checkbox" name="real_time_antivirus" /> Real-time Antivirus </label></br>
.
.
.
<label> <input type="checkbox" name="adware_prevention" /> adware_prevention </label></br>
<button>Apply filter</button>
<input type="hidden" name="action" value="myfilter">
</code></pre>
<p>in functions.php</p>
<pre><code>add_action('wp_ajax_myfilter', 'misha_filter_function'); // wp_ajax_{ACTION HERE}
add_action('wp_ajax_nopriv_myfilter', 'misha_filter_function');
function misha_filter_function(){
$args = array(
'posts_per_page' =>-1,
);
$args['meta_query'] = array( 'relation'=>'AND' );
// Antivirus_featured_scaning
if( isset( $_POST['real_time_antivirus'] ) && $_POST['real_time_antivirus'] == 'on' )
$args['meta_query'][] = array(
'key' => 'antivirus_antivirus_featured_scaning',
'value' => 'real_time_antivirus',
'compare' => 'LIKE'
);
if( isset( $_POST['manual_virus_scanning'] ) && $_POST['manual_virus_scanning'] == 'on' )
$args['meta_query'][] = array(
'key' => 'antivirus_antivirus_featured_scaning',
'value' => 'manual_virus_scanning',
'compare' => 'LIKE'
);
if( isset( $_POST['usb_virus_scan'] ) && $_POST['usb_virus_scan'] == 'on' )
$args['meta_query'][] = array(
'key' => 'antivirus_antivirus_featured_scaning',
'value' => 'usb_virus_scan',
'compare' => 'LIKE'
);
if( isset( $_POST['registry_startup_scan'] ) && $_POST['registry_startup_scan'] == 'on' )
$args['meta_query'][] = array(
'key' => 'antivirus_antivirus_featured_scaning',
'value' => 'registry_startup_scan',
'compare' => 'LIKE'
);
if( isset( $_POST['auto_virus_scanning'] ) && $_POST['auto_virus_scanning'] == 'on' )
$args['meta_query'][] = array(
'key' => 'antivirus_antivirus_featured_scaning',
'value' => 'auto_virus_scanning',
'compare' => 'LIKE'
);
if( isset( $_POST['scheduled_scan'] ) && $_POST['scheduled_scan'] == 'on' )
$args['meta_query'][] = array(
'key' => 'antivirus_antivirus_featured_scaning',
'value' => 'scheduled_scan',
'compare' => 'LIKE'
);
// antivirus_featured_threat
if( isset( $_POST['anti_spyware'] ) && $_POST['anti_spyware'] == 'on' )
$args['meta_query'][] = array(
'key' => 'antivirus_antivirus_featured_threat',
'value' => 'anti_spyware',
'compare' => 'LIKE'
);
if( isset( $_POST['anti_worm'] ) && $_POST['anti_worm'] == 'on' )
$args['meta_query'][] = array(
'key' => 'antivirus_antivirus_featured_threat',
'value' => 'anti_worm',
'compare' => 'LIKE'
);
if( isset( $_POST['anti_trojan'] ) && $_POST['anti_trojan'] == 'on' )
$args['meta_query'][] = array(
'key' => 'antivirus_antivirus_featured_threat',
'value' => 'anti_trojan',
'compare' => 'LIKE'
);
if( isset( $_POST['anti_rootkit'] ) && $_POST['anti_rootkit'] == 'on' )
$args['meta_query'][] = array(
'key' => 'antivirus_antivirus_featured_threat',
'value' => 'anti_rootkit',
'compare' => 'LIKE'
);
if( isset( $_POST['anti_phishing'] ) && $_POST['anti_phishing'] == 'on' )
$args['meta_query'][] = array(
'key' => 'antivirus_antivirus_featured_threat',
'value' => 'anti_phishing',
'compare' => 'LIKE'
);
if( isset( $_POST['anti_spam'] ) && $_POST['anti_spam'] == 'on' )
$args['meta_query'][] = array(
'key' => 'antivirus_antivirus_featured_threat',
'value' => 'anti_spam',
'compare' => 'LIKE'
);
if( isset( $_POST['email_protection'] ) && $_POST['email_protection'] == 'on' )
$args['meta_query'][] = array(
'key' => 'antivirus_antivirus_featured_threat',
'value' => 'email_protection',
'compare' => 'LIKE'
);
if( isset( $_POST['chat_im_protection'] ) && $_POST['chat_im_protection'] == 'on' )
$args['meta_query'][] = array(
'key' => 'antivirus_antivirus_featured_threat',
'value' => 'chat_im_protection',
'compare' => 'LIKE'
);
if( isset( $_POST['adware_prevention'] ) && $_POST['adware_prevention'] == 'on' )
$args['meta_query'][] = array(
'key' => 'antivirus_antivirus_featured_threat',
'value' => 'adware_prevention',
'compare' => 'LIKE'
);
$query = new WP_Query( $args );
</code></pre>
<p>Thanks for any help.</p>
| [
{
"answer_id": 371212,
"author": "mozboz",
"author_id": 176814,
"author_profile": "https://wordpress.stackexchange.com/users/176814",
"pm_score": 2,
"selected": false,
"text": "<p>This is a partially subjective question, so it may get closed on that basis. Answer given here may be somewhat subjective but tries to cover the main considerations.</p>\n<h2>Short Answer</h2>\n<p>The short answer is you'll definitely have a much easier life running Wordpress on Linux. This is simply due to many more people hosting Wordpress on Linux and the resulting huge amount of documentation, support and development effort that is purposely or just coincidentally specific to Linux. Linux will be much easier unless you have a <strong>lot</strong> more Windows server administration experience than Linux experience, or some other compelling reason such as you need to host a huge website and have free Windows hosting for some reason.</p>\n<h2>Long Anwer</h2>\n<p>This quesition is not inherent to Linux vs Windows, it's specific to where Wordpress and PHP are today and there are a few factors about why it's like this:</p>\n<ol>\n<li>Server software implemtations of PHP and MySQL are basically equal.</li>\n<li>Linux being free and dominance of Unix on the internet lead to there being more Linux hosting, which leads to more web apps being written which may purposely or accidentally favour Linux</li>\n<li>Available documentation, resources for support and problem solving reflect disproportionate use of Linux</li>\n</ol>\n<h3>Server Software</h3>\n<p>Without considering the application you're running, or if we considered a 'perfectly written' PHP and MySQL application, there should be little or no difference between Windows and Linux. PHP and MySQL are available for Windows and run PHP code and SQL databases exactly the same as on Linux, <strong>but</strong> the differences start when PHP or MySQL need to talk to the operating system. When it gets to this point the developer needs to make sure his code runs does the right thing in both cases.</p>\n<h3>Linux is free and open source software</h3>\n<p>Linux is FOSS and therefore web hosting companies have favoured it for providing web hosting. Linux (and Unix in general) took 'market share' as the server operating system for the Internet from the beginning, which means that applications of all types, including web applications written in PHP, get more exposure to that operating system.</p>\n<p>A developer who has 90% of their users using PHP on Linux and 10% of their users using PHP on Windows may quite easily fail to check that operating-system calls in their code work as they expect on Windows. The less users some software has, and the less frequent specific OS users are, the less likely it is the developer will put effort into dealing with these less-common cases.</p>\n<p>For Wordpress, this means Wordpress itself probably supports Windows well, but if you need a use a small or poorly written plugin you're at much greater risk of it failing on Windows because the developer is much more likely to have developed it on Linux.</p>\n<h3>Documentation, Support</h3>\n<p>This big difference in server marketshare and therefore use of operating systems on the web means that there's a similar distribution in the documentation and support. You'll find many more people dealing with Linux hosting issues than Windows, and therefore much more content, questions and answers, and documentation.</p>\n<p>Again, this will be skewed according to the size of the project: bigger projects will have time and resource to support Windows, smaller projects quite probably won't.</p>\n"
},
{
"answer_id": 371226,
"author": "breadwild",
"author_id": 153797,
"author_profile": "https://wordpress.stackexchange.com/users/153797",
"pm_score": 0,
"selected": false,
"text": "<p>I will only say that operating from the Linux, Apache, and MySQL command lines is a joy. I host about 50 websites, 12 of which areWordPress, and I can't imagine doing it without that level of access, especially when setting up GIT and LetsEncrypt.</p>\n"
}
] | 2020/07/16 | [
"https://wordpress.stackexchange.com/questions/371213",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/187881/"
] | I have a `search form` with`wp_query`argument
There are many `checkbox` in this form
The problem start here, it takes a long time to load when you `select all` the options,
this query takes almost a minute to complete. Has anyone had this issue before?
I used these codes
in HTML
```
<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
<label> <input type="checkbox" name="real_time_antivirus" /> Real-time Antivirus </label></br>
.
.
.
<label> <input type="checkbox" name="adware_prevention" /> adware_prevention </label></br>
<button>Apply filter</button>
<input type="hidden" name="action" value="myfilter">
```
in functions.php
```
add_action('wp_ajax_myfilter', 'misha_filter_function'); // wp_ajax_{ACTION HERE}
add_action('wp_ajax_nopriv_myfilter', 'misha_filter_function');
function misha_filter_function(){
$args = array(
'posts_per_page' =>-1,
);
$args['meta_query'] = array( 'relation'=>'AND' );
// Antivirus_featured_scaning
if( isset( $_POST['real_time_antivirus'] ) && $_POST['real_time_antivirus'] == 'on' )
$args['meta_query'][] = array(
'key' => 'antivirus_antivirus_featured_scaning',
'value' => 'real_time_antivirus',
'compare' => 'LIKE'
);
if( isset( $_POST['manual_virus_scanning'] ) && $_POST['manual_virus_scanning'] == 'on' )
$args['meta_query'][] = array(
'key' => 'antivirus_antivirus_featured_scaning',
'value' => 'manual_virus_scanning',
'compare' => 'LIKE'
);
if( isset( $_POST['usb_virus_scan'] ) && $_POST['usb_virus_scan'] == 'on' )
$args['meta_query'][] = array(
'key' => 'antivirus_antivirus_featured_scaning',
'value' => 'usb_virus_scan',
'compare' => 'LIKE'
);
if( isset( $_POST['registry_startup_scan'] ) && $_POST['registry_startup_scan'] == 'on' )
$args['meta_query'][] = array(
'key' => 'antivirus_antivirus_featured_scaning',
'value' => 'registry_startup_scan',
'compare' => 'LIKE'
);
if( isset( $_POST['auto_virus_scanning'] ) && $_POST['auto_virus_scanning'] == 'on' )
$args['meta_query'][] = array(
'key' => 'antivirus_antivirus_featured_scaning',
'value' => 'auto_virus_scanning',
'compare' => 'LIKE'
);
if( isset( $_POST['scheduled_scan'] ) && $_POST['scheduled_scan'] == 'on' )
$args['meta_query'][] = array(
'key' => 'antivirus_antivirus_featured_scaning',
'value' => 'scheduled_scan',
'compare' => 'LIKE'
);
// antivirus_featured_threat
if( isset( $_POST['anti_spyware'] ) && $_POST['anti_spyware'] == 'on' )
$args['meta_query'][] = array(
'key' => 'antivirus_antivirus_featured_threat',
'value' => 'anti_spyware',
'compare' => 'LIKE'
);
if( isset( $_POST['anti_worm'] ) && $_POST['anti_worm'] == 'on' )
$args['meta_query'][] = array(
'key' => 'antivirus_antivirus_featured_threat',
'value' => 'anti_worm',
'compare' => 'LIKE'
);
if( isset( $_POST['anti_trojan'] ) && $_POST['anti_trojan'] == 'on' )
$args['meta_query'][] = array(
'key' => 'antivirus_antivirus_featured_threat',
'value' => 'anti_trojan',
'compare' => 'LIKE'
);
if( isset( $_POST['anti_rootkit'] ) && $_POST['anti_rootkit'] == 'on' )
$args['meta_query'][] = array(
'key' => 'antivirus_antivirus_featured_threat',
'value' => 'anti_rootkit',
'compare' => 'LIKE'
);
if( isset( $_POST['anti_phishing'] ) && $_POST['anti_phishing'] == 'on' )
$args['meta_query'][] = array(
'key' => 'antivirus_antivirus_featured_threat',
'value' => 'anti_phishing',
'compare' => 'LIKE'
);
if( isset( $_POST['anti_spam'] ) && $_POST['anti_spam'] == 'on' )
$args['meta_query'][] = array(
'key' => 'antivirus_antivirus_featured_threat',
'value' => 'anti_spam',
'compare' => 'LIKE'
);
if( isset( $_POST['email_protection'] ) && $_POST['email_protection'] == 'on' )
$args['meta_query'][] = array(
'key' => 'antivirus_antivirus_featured_threat',
'value' => 'email_protection',
'compare' => 'LIKE'
);
if( isset( $_POST['chat_im_protection'] ) && $_POST['chat_im_protection'] == 'on' )
$args['meta_query'][] = array(
'key' => 'antivirus_antivirus_featured_threat',
'value' => 'chat_im_protection',
'compare' => 'LIKE'
);
if( isset( $_POST['adware_prevention'] ) && $_POST['adware_prevention'] == 'on' )
$args['meta_query'][] = array(
'key' => 'antivirus_antivirus_featured_threat',
'value' => 'adware_prevention',
'compare' => 'LIKE'
);
$query = new WP_Query( $args );
```
Thanks for any help. | This is a partially subjective question, so it may get closed on that basis. Answer given here may be somewhat subjective but tries to cover the main considerations.
Short Answer
------------
The short answer is you'll definitely have a much easier life running Wordpress on Linux. This is simply due to many more people hosting Wordpress on Linux and the resulting huge amount of documentation, support and development effort that is purposely or just coincidentally specific to Linux. Linux will be much easier unless you have a **lot** more Windows server administration experience than Linux experience, or some other compelling reason such as you need to host a huge website and have free Windows hosting for some reason.
Long Anwer
----------
This quesition is not inherent to Linux vs Windows, it's specific to where Wordpress and PHP are today and there are a few factors about why it's like this:
1. Server software implemtations of PHP and MySQL are basically equal.
2. Linux being free and dominance of Unix on the internet lead to there being more Linux hosting, which leads to more web apps being written which may purposely or accidentally favour Linux
3. Available documentation, resources for support and problem solving reflect disproportionate use of Linux
### Server Software
Without considering the application you're running, or if we considered a 'perfectly written' PHP and MySQL application, there should be little or no difference between Windows and Linux. PHP and MySQL are available for Windows and run PHP code and SQL databases exactly the same as on Linux, **but** the differences start when PHP or MySQL need to talk to the operating system. When it gets to this point the developer needs to make sure his code runs does the right thing in both cases.
### Linux is free and open source software
Linux is FOSS and therefore web hosting companies have favoured it for providing web hosting. Linux (and Unix in general) took 'market share' as the server operating system for the Internet from the beginning, which means that applications of all types, including web applications written in PHP, get more exposure to that operating system.
A developer who has 90% of their users using PHP on Linux and 10% of their users using PHP on Windows may quite easily fail to check that operating-system calls in their code work as they expect on Windows. The less users some software has, and the less frequent specific OS users are, the less likely it is the developer will put effort into dealing with these less-common cases.
For Wordpress, this means Wordpress itself probably supports Windows well, but if you need a use a small or poorly written plugin you're at much greater risk of it failing on Windows because the developer is much more likely to have developed it on Linux.
### Documentation, Support
This big difference in server marketshare and therefore use of operating systems on the web means that there's a similar distribution in the documentation and support. You'll find many more people dealing with Linux hosting issues than Windows, and therefore much more content, questions and answers, and documentation.
Again, this will be skewed according to the size of the project: bigger projects will have time and resource to support Windows, smaller projects quite probably won't. |
371,219 | <p>As the title states <a href="https://developer.wordpress.org/block-editor/data/data-core/#getEntityRecords" rel="nofollow noreferrer">https://developer.wordpress.org/block-editor/data/data-core/#getEntityRecords</a> doesn't allow an array of post types or any sort of delimited types. WP_Query normally accepts 'any' but that doesn't work any suggestion for a JSX novice please. Ive checked my local endpoint REST endpoint <code>/wp/v2/types</code> for any clues and this just shows me all my existing post types i can filter by but no indication how to filter by multiple post types. I currently have this.</p>
<pre><code>const { getEntityRecords } = select( 'core' );
return {
suggestions: getEntityRecords( 'posts', '', { per_page: -1, search: ownProps.value } ),
onChange: ownProps.onChange,
value: ownProps.value
}
</code></pre>
| [
{
"answer_id": 391102,
"author": "bosco",
"author_id": 25324,
"author_profile": "https://wordpress.stackexchange.com/users/25324",
"pm_score": 1,
"selected": false,
"text": "<p>It is not possible to query multiple post types simultaneously using the <code>getEntityRecords()</code> selector. This is because the WordPress REST API is not built around the same ideology as the core WordPress back-end.</p>\n<p>All data-types being "posts" in the traditional PHP APIs is the product of the somewhat controversial underlying database implementation, while the REST API was built to be insulated from the database implementation, and treats each post type as it's own "resource" in isolation for the most part.</p>\n<p>In your case, searching the relevant record-types individually is probably the best solution. If you really do wish to search <em>all</em> post types which are exposed over the REST API, you can use the <code>getPostTypes()</code> selector from the <code>core</code> data store in order to retrieve a list of types.</p>\n<p>Alternatively, the REST API does expose a <a href=\"https://developer.wordpress.org/rest-api/reference/search-results/\" rel=\"nofollow noreferrer\"><code>search</code> endpoint</a>. While not presently very clearly documented in the REST API Handbook, this endpoint's <code>subtype</code> parameter does accept an array of post types. This could be queried using <a href=\"https://github.com/WordPress/gutenberg/tree/trunk/packages/api-fetch\" rel=\"nofollow noreferrer\">the <code>@wordpress/api-fetch</code> package</a>, but it's worth noting that the functionality and caching would not automatically leverage Gutenberg's data stores - it may be necessary to implement a custom data-store to most efficiently implement your search functionality (prevent identical repeated requests to the REST API per render, automatically trigger re-renders for selected data, etc.).</p>\n"
},
{
"answer_id": 411379,
"author": "tiadotdev",
"author_id": 83771,
"author_profile": "https://wordpress.stackexchange.com/users/83771",
"pm_score": 0,
"selected": false,
"text": "<p>I found a workaround for this by</p>\n<ol>\n<li>creating a function to query all post types in PHP</li>\n<li>passing this data as a var via a localized script into the block editor</li>\n<li>mapping this var and calling the getEntityRecords for each one</li>\n<li>pushing that into an array to use as needed</li>\n</ol>\n<p>Code snippets below.</p>\n<p><strong>PHP</strong></p>\n<pre><code>function get_all_post_types() {\n\n $post_types_arr[];\n $post_types = get_post_types(array(\n 'public' => true,\n ), 'objects');\n\n // sort post types by name\n uasort($post_types, function($a, $b) {\n return strcmp($a->labels->name, $b->labels->name);\n });\n\n foreach ($post_types as $post_type) {\n array_push($post_types_arr, $post_type);\n }\n\n return $post_types_arr;\n}\n\nadd_action( 'init', 'include_posttype_array_in_blocks_on_init' );\nfunction include_posttype_array_in_blocks_on_init() {\n\n $asset_file = include( __DIR__ . 'build/index.asset.php' );\n\n wp_register_script(\n 'posttypes-for-blocks',\n __DIR__ . '/build/index.js',\n $asset_file['dependencies'],\n $asset_file['version']\n );\n\n wp_localize_script(\n 'posttypes-for-blocks',\n 'postTypeVars',\n array(\n 'postTypes' => get_all_post_types()\n )\n ); \n}\n</code></pre>\n<p><strong>In the block edit.js file</strong></p>\n<pre><code>let data = [];\nconst postTypes = postTypeVars.postTypes;\nconst posts = postTypes.map( ( postType ) => {\n const post = useSelect( ( select ) => {\n return select( 'core' ).getEntityRecords( 'postType', postType, args );\n });\n data.push( post );\n } );\n\n// flatten the array into one array\ndata = data.flat();\n</code></pre>\n<p>Now you can do whatever you want with the post data.</p>\n"
}
] | 2020/07/16 | [
"https://wordpress.stackexchange.com/questions/371219",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/190706/"
] | As the title states <https://developer.wordpress.org/block-editor/data/data-core/#getEntityRecords> doesn't allow an array of post types or any sort of delimited types. WP\_Query normally accepts 'any' but that doesn't work any suggestion for a JSX novice please. Ive checked my local endpoint REST endpoint `/wp/v2/types` for any clues and this just shows me all my existing post types i can filter by but no indication how to filter by multiple post types. I currently have this.
```
const { getEntityRecords } = select( 'core' );
return {
suggestions: getEntityRecords( 'posts', '', { per_page: -1, search: ownProps.value } ),
onChange: ownProps.onChange,
value: ownProps.value
}
``` | It is not possible to query multiple post types simultaneously using the `getEntityRecords()` selector. This is because the WordPress REST API is not built around the same ideology as the core WordPress back-end.
All data-types being "posts" in the traditional PHP APIs is the product of the somewhat controversial underlying database implementation, while the REST API was built to be insulated from the database implementation, and treats each post type as it's own "resource" in isolation for the most part.
In your case, searching the relevant record-types individually is probably the best solution. If you really do wish to search *all* post types which are exposed over the REST API, you can use the `getPostTypes()` selector from the `core` data store in order to retrieve a list of types.
Alternatively, the REST API does expose a [`search` endpoint](https://developer.wordpress.org/rest-api/reference/search-results/). While not presently very clearly documented in the REST API Handbook, this endpoint's `subtype` parameter does accept an array of post types. This could be queried using [the `@wordpress/api-fetch` package](https://github.com/WordPress/gutenberg/tree/trunk/packages/api-fetch), but it's worth noting that the functionality and caching would not automatically leverage Gutenberg's data stores - it may be necessary to implement a custom data-store to most efficiently implement your search functionality (prevent identical repeated requests to the REST API per render, automatically trigger re-renders for selected data, etc.). |
371,224 | <p>I am trying to develop a hook when save_post to get the categories but for new posts I don't get any categories and for updated posts I get the categories "before" updating the post. This should be super simple but I can't figure it out. I have been hours trying to find a solution.</p>
<p>This is the minimal code that I am trying to run:</p>
<pre><code>add_action('save_post', 'test' , 10, 3 );
function test($post_id, $post, $update){
$categories=get_the_category($post_id);
var_dump($categories);
}
</code></pre>
<p>I am also trying to get things from $_REQUEST but its only content is this:</p>
<pre><code>Array
(
[_locale] => user
)
</code></pre>
<p>What am I doing wrong here?</p>
| [
{
"answer_id": 371288,
"author": "malago",
"author_id": 191766,
"author_profile": "https://wordpress.stackexchange.com/users/191766",
"pm_score": 1,
"selected": false,
"text": "<p>After doing much more search... it looks like the save_post hook does not run after the post categories are updated so it will only show the categories that the post had before the update (or no categories for new posts).</p>\n<p>I found that I need to use this hook and then everything inside my function is updated:</p>\n<pre><code>add_action('rest_after_insert_post', 'test' , 10, 2 );\n</code></pre>\n<p>I had no idea that was the hook I needed to use. I hope this helps someone!</p>\n"
},
{
"answer_id": 410369,
"author": "omukiguy",
"author_id": 102683,
"author_profile": "https://wordpress.stackexchange.com/users/102683",
"pm_score": 0,
"selected": false,
"text": "<p>It is best to use the <code>wp_after_insert_post</code> hook which fires once a post, its terms and meta data has been saved.</p>\n<p>See: <a href=\"https://developer.wordpress.org/reference/hooks/wp_after_insert_post/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/wp_after_insert_post/</a></p>\n<pre><code>add_action('wp_after_insert_post', 'test' , 10, 2 );\n\nfunction test( $post_id, $post ){\n $categories = get_the_terms( $post_id, 'category' );\n error_log( print_r( $categories, true ) );\n}\n</code></pre>\n<p>use the <code>get_the_terms</code> function to get all the categories but make sure to add the right category term name. For Posts, WordPress comes with the category as the default for all posts.</p>\n<p>You need to <code>error_log</code> the values since this hook will not be seen on the front-end but rather you can use the <code>debug.log</code> file to see all the results.</p>\n<p>See: <a href=\"https://wordpress.org/support/article/debugging-in-wordpress/\" rel=\"nofollow noreferrer\">https://wordpress.org/support/article/debugging-in-wordpress/</a></p>\n"
}
] | 2020/07/17 | [
"https://wordpress.stackexchange.com/questions/371224",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/191766/"
] | I am trying to develop a hook when save\_post to get the categories but for new posts I don't get any categories and for updated posts I get the categories "before" updating the post. This should be super simple but I can't figure it out. I have been hours trying to find a solution.
This is the minimal code that I am trying to run:
```
add_action('save_post', 'test' , 10, 3 );
function test($post_id, $post, $update){
$categories=get_the_category($post_id);
var_dump($categories);
}
```
I am also trying to get things from $\_REQUEST but its only content is this:
```
Array
(
[_locale] => user
)
```
What am I doing wrong here? | After doing much more search... it looks like the save\_post hook does not run after the post categories are updated so it will only show the categories that the post had before the update (or no categories for new posts).
I found that I need to use this hook and then everything inside my function is updated:
```
add_action('rest_after_insert_post', 'test' , 10, 2 );
```
I had no idea that was the hook I needed to use. I hope this helps someone! |
371,238 | <p>Let's say my custom post type is 'story'.
I've got 20 stories published on my site.
So each post becomes: 'story 1', 'story 2', ... 'story 20'.
Thus, first post is 'story 1', and last post is 'story 20'.
Now when I open one of these custom posts, I want to see the number. Example, if I open the ninth (published) post I want to see it mentions 'story 9'.
I don't want to hardcode it which I can do using ACF plugin. I want that data to be generated dynamically, just like how wordpress dynamically generates post id or slug.</p>
| [
{
"answer_id": 371288,
"author": "malago",
"author_id": 191766,
"author_profile": "https://wordpress.stackexchange.com/users/191766",
"pm_score": 1,
"selected": false,
"text": "<p>After doing much more search... it looks like the save_post hook does not run after the post categories are updated so it will only show the categories that the post had before the update (or no categories for new posts).</p>\n<p>I found that I need to use this hook and then everything inside my function is updated:</p>\n<pre><code>add_action('rest_after_insert_post', 'test' , 10, 2 );\n</code></pre>\n<p>I had no idea that was the hook I needed to use. I hope this helps someone!</p>\n"
},
{
"answer_id": 410369,
"author": "omukiguy",
"author_id": 102683,
"author_profile": "https://wordpress.stackexchange.com/users/102683",
"pm_score": 0,
"selected": false,
"text": "<p>It is best to use the <code>wp_after_insert_post</code> hook which fires once a post, its terms and meta data has been saved.</p>\n<p>See: <a href=\"https://developer.wordpress.org/reference/hooks/wp_after_insert_post/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/wp_after_insert_post/</a></p>\n<pre><code>add_action('wp_after_insert_post', 'test' , 10, 2 );\n\nfunction test( $post_id, $post ){\n $categories = get_the_terms( $post_id, 'category' );\n error_log( print_r( $categories, true ) );\n}\n</code></pre>\n<p>use the <code>get_the_terms</code> function to get all the categories but make sure to add the right category term name. For Posts, WordPress comes with the category as the default for all posts.</p>\n<p>You need to <code>error_log</code> the values since this hook will not be seen on the front-end but rather you can use the <code>debug.log</code> file to see all the results.</p>\n<p>See: <a href=\"https://wordpress.org/support/article/debugging-in-wordpress/\" rel=\"nofollow noreferrer\">https://wordpress.org/support/article/debugging-in-wordpress/</a></p>\n"
}
] | 2020/07/17 | [
"https://wordpress.stackexchange.com/questions/371238",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/120120/"
] | Let's say my custom post type is 'story'.
I've got 20 stories published on my site.
So each post becomes: 'story 1', 'story 2', ... 'story 20'.
Thus, first post is 'story 1', and last post is 'story 20'.
Now when I open one of these custom posts, I want to see the number. Example, if I open the ninth (published) post I want to see it mentions 'story 9'.
I don't want to hardcode it which I can do using ACF plugin. I want that data to be generated dynamically, just like how wordpress dynamically generates post id or slug. | After doing much more search... it looks like the save\_post hook does not run after the post categories are updated so it will only show the categories that the post had before the update (or no categories for new posts).
I found that I need to use this hook and then everything inside my function is updated:
```
add_action('rest_after_insert_post', 'test' , 10, 2 );
```
I had no idea that was the hook I needed to use. I hope this helps someone! |
371,244 | <p>I’m using Easy Digital Downloads for my Wordpress webshop. After someone buy a item it needs to add data to the SQL database. I got this working by adding PHP code to shortcode-receipt.php. This is working correct but when I reload the receipt via browser or mail the PHP code will fire again.</p>
<p>I figured out that there was a hook in EDD, but i'm not sure how to use them. I figured out that the function needs to be added to functions.php.</p>
<p>file: /wp-content/themes/twentytwenty/functions.php</p>
<pre><code>function pw_edd_on_complete_purchase( $payment_id ) {
## write data to the database ##
}
add_action( 'edd_complete_purchase', 'pw_edd_on_complete_purchase' );
</code></pre>
<p>But in what file do i place</p>
<p><code>do_action( 'edd_complete_purchase', $payment_id );</code> ?</p>
| [
{
"answer_id": 371288,
"author": "malago",
"author_id": 191766,
"author_profile": "https://wordpress.stackexchange.com/users/191766",
"pm_score": 1,
"selected": false,
"text": "<p>After doing much more search... it looks like the save_post hook does not run after the post categories are updated so it will only show the categories that the post had before the update (or no categories for new posts).</p>\n<p>I found that I need to use this hook and then everything inside my function is updated:</p>\n<pre><code>add_action('rest_after_insert_post', 'test' , 10, 2 );\n</code></pre>\n<p>I had no idea that was the hook I needed to use. I hope this helps someone!</p>\n"
},
{
"answer_id": 410369,
"author": "omukiguy",
"author_id": 102683,
"author_profile": "https://wordpress.stackexchange.com/users/102683",
"pm_score": 0,
"selected": false,
"text": "<p>It is best to use the <code>wp_after_insert_post</code> hook which fires once a post, its terms and meta data has been saved.</p>\n<p>See: <a href=\"https://developer.wordpress.org/reference/hooks/wp_after_insert_post/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/wp_after_insert_post/</a></p>\n<pre><code>add_action('wp_after_insert_post', 'test' , 10, 2 );\n\nfunction test( $post_id, $post ){\n $categories = get_the_terms( $post_id, 'category' );\n error_log( print_r( $categories, true ) );\n}\n</code></pre>\n<p>use the <code>get_the_terms</code> function to get all the categories but make sure to add the right category term name. For Posts, WordPress comes with the category as the default for all posts.</p>\n<p>You need to <code>error_log</code> the values since this hook will not be seen on the front-end but rather you can use the <code>debug.log</code> file to see all the results.</p>\n<p>See: <a href=\"https://wordpress.org/support/article/debugging-in-wordpress/\" rel=\"nofollow noreferrer\">https://wordpress.org/support/article/debugging-in-wordpress/</a></p>\n"
}
] | 2020/07/17 | [
"https://wordpress.stackexchange.com/questions/371244",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/177769/"
] | I’m using Easy Digital Downloads for my Wordpress webshop. After someone buy a item it needs to add data to the SQL database. I got this working by adding PHP code to shortcode-receipt.php. This is working correct but when I reload the receipt via browser or mail the PHP code will fire again.
I figured out that there was a hook in EDD, but i'm not sure how to use them. I figured out that the function needs to be added to functions.php.
file: /wp-content/themes/twentytwenty/functions.php
```
function pw_edd_on_complete_purchase( $payment_id ) {
## write data to the database ##
}
add_action( 'edd_complete_purchase', 'pw_edd_on_complete_purchase' );
```
But in what file do i place
`do_action( 'edd_complete_purchase', $payment_id );` ? | After doing much more search... it looks like the save\_post hook does not run after the post categories are updated so it will only show the categories that the post had before the update (or no categories for new posts).
I found that I need to use this hook and then everything inside my function is updated:
```
add_action('rest_after_insert_post', 'test' , 10, 2 );
```
I had no idea that was the hook I needed to use. I hope this helps someone! |
Subsets and Splits