qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
309,219 | <p>new here and to wordpress plugins development, go easy on me :D</p>
<p>Anyway, I am trying to create a new plugin and I am getting a 500 error.
I changed <code>WP_DEBUG</code> in config.php to true in order to see what is causing the 500 error and got this message:</p>
<p><code>Fatal error: Uncaught Error: Call to undefined function is_woocommerce() in...</code></p>
<p>This is my code currently:</p>
<pre><code><?php
/**
* Plugin Name:
* Plugin URI:
* Description:
* Author:
* Author URI:
* Version: 1.0
* Text Domain:
*
* Copyright: (c) 2018
*
* License:
* License URI:
*
* @author
* @copyright Copyright (c) 2018
* @license
*
*/
//
defined( 'ABSPATH' ) or exit;
if (function_exists(is_woocommerce())) {
echo "test: ".is_woocommerce();
} else {
echo "test: Function does not exists!";
}
</code></pre>
<p>If you need any more information, tell me and I'll edit the question.
Help will be appreciated, thanks!</p>
| [
{
"answer_id": 309239,
"author": "Futuritous",
"author_id": 122392,
"author_profile": "https://wordpress.stackexchange.com/users/122392",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to check one Plugin's Function / Class etc. from another Plugin, then it's best to use a hook like <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/plugins_loaded\" rel=\"nofollow noreferrer\"><code>plugins_loaded</code></a>.</p>\n\n<p>Based on this, your Plugin CODE will look like:</p>\n\n<pre><code><?php\n/*\nPlugin Name: YOUR PLUGIN NAME\n*/\n\ndefined( 'ABSPATH' ) or exit;\n\nadd_action( 'plugins_loaded', 'plugin_prefix_woocommerce_check' );\n function plugin_prefix_woocommerce_check() {\n if( function_exists( 'is_woocommerce' ) ) { \n add_action( \"wp_footer\", \"wpse_woocommerce_exists\" );\n } \n else {\n add_action( \"wp_footer\", \"wpse_woocommerce_doesnt_exist\" );\n } \n} \n\nfunction wpse_woocommerce_exists() {\n echo \"<h1>WooCommerce Exists!</h1>\";\n} \n\nfunction wpse_woocommerce_doesnt_exist() {\n echo \"<h1>WooCommerce Doesn't Exists!</h1>\";\n}\n</code></pre>\n\n<p>Directly checking other plugin functions will often lead to error, since WordPress may not be done loading other plugins by the time your CODE executes. However, when WordPress is done, it'll fire the <code>plugins_loaded</code> hook.</p>\n\n<p>Check <a href=\"https://developer.wordpress.org/plugins/\" rel=\"nofollow noreferrer\">Plugin Development Guide</a> for more information on how to develop a WordPress Plugin.</p>\n"
},
{
"answer_id": 365409,
"author": "Michael Ecklund",
"author_id": 9579,
"author_profile": "https://wordpress.stackexchange.com/users/9579",
"pm_score": 1,
"selected": false,
"text": "<p>This may or may not be a relevant answer.</p>\n\n<p>However, I was receiving a very similar error after updating the Divi theme.</p>\n\n<pre><code>Uncaught Error: Call to undefined function et_is_woocommerce_plugin_active()\n</code></pre>\n\n<p>I deleted the old Divi directory in the theme directory and replaced with the new Divi directory.</p>\n\n<p>I tend to also delete the directory <code>/wp-content/et-cache</code> as well, when updating Divi.</p>\n\n<p>Anyways, long story short, I ran this WP CLI command after updating the Divi theme.</p>\n\n<pre><code>wp transient delete --all --skip-packages --skip-themes --skip-plugins\n</code></pre>\n\n<p>The error was immediately resolved, and the updated Divi theme was functioning as expected once again. </p>\n"
}
]
| 2018/07/22 | [
"https://wordpress.stackexchange.com/questions/309219",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147331/"
]
| new here and to wordpress plugins development, go easy on me :D
Anyway, I am trying to create a new plugin and I am getting a 500 error.
I changed `WP_DEBUG` in config.php to true in order to see what is causing the 500 error and got this message:
`Fatal error: Uncaught Error: Call to undefined function is_woocommerce() in...`
This is my code currently:
```
<?php
/**
* Plugin Name:
* Plugin URI:
* Description:
* Author:
* Author URI:
* Version: 1.0
* Text Domain:
*
* Copyright: (c) 2018
*
* License:
* License URI:
*
* @author
* @copyright Copyright (c) 2018
* @license
*
*/
//
defined( 'ABSPATH' ) or exit;
if (function_exists(is_woocommerce())) {
echo "test: ".is_woocommerce();
} else {
echo "test: Function does not exists!";
}
```
If you need any more information, tell me and I'll edit the question.
Help will be appreciated, thanks! | If you want to check one Plugin's Function / Class etc. from another Plugin, then it's best to use a hook like [`plugins_loaded`](https://codex.wordpress.org/Plugin_API/Action_Reference/plugins_loaded).
Based on this, your Plugin CODE will look like:
```
<?php
/*
Plugin Name: YOUR PLUGIN NAME
*/
defined( 'ABSPATH' ) or exit;
add_action( 'plugins_loaded', 'plugin_prefix_woocommerce_check' );
function plugin_prefix_woocommerce_check() {
if( function_exists( 'is_woocommerce' ) ) {
add_action( "wp_footer", "wpse_woocommerce_exists" );
}
else {
add_action( "wp_footer", "wpse_woocommerce_doesnt_exist" );
}
}
function wpse_woocommerce_exists() {
echo "<h1>WooCommerce Exists!</h1>";
}
function wpse_woocommerce_doesnt_exist() {
echo "<h1>WooCommerce Doesn't Exists!</h1>";
}
```
Directly checking other plugin functions will often lead to error, since WordPress may not be done loading other plugins by the time your CODE executes. However, when WordPress is done, it'll fire the `plugins_loaded` hook.
Check [Plugin Development Guide](https://developer.wordpress.org/plugins/) for more information on how to develop a WordPress Plugin. |
309,222 | <p>My website is a product review website. I'm using woocomerce in order to store all products and let user be able to search them by category and attributes.</p>
<p>Due this, I would like to remove some unnecessary options from my wordpress admin like inventory and shipping.</p>
<p>.<a href="https://i.stack.imgur.com/woW1A.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/woW1A.png" alt="enter image description here"></a></p>
<p>How can I disable those functions from my wordpress??</p>
| [
{
"answer_id": 309281,
"author": "Sitezilla",
"author_id": 143362,
"author_profile": "https://wordpress.stackexchange.com/users/143362",
"pm_score": 0,
"selected": false,
"text": "<p>Do you give users access to the backpanel? Shipping and inventory are not attributes that really distract users on a frontend I guess. A quick solution would be hiding individual meta data with CSS. </p>\n\n<pre><code>.sku_wrapper{display: none;}\n</code></pre>\n\n<p>You could also use this to hide parts in your admin panel (example the product data top table row with product type, virtual and downloadable)</p>\n\n<pre><code>add_action('admin_head', 'my_custom_admin_styles');\nfunction my_custom_admin_styles() {\n// just add the css selectors below to hide each field as required\necho '<style>\n#woocommerce-product-data .hndle {\ndisplay: none; }\n</style>';\n}\n</code></pre>\n"
},
{
"answer_id": 309301,
"author": "Harsh",
"author_id": 131853,
"author_profile": "https://wordpress.stackexchange.com/users/131853",
"pm_score": 2,
"selected": true,
"text": "<p>Just add below function in your function file</p>\n\n<pre><code>/*For remove tab from product tab*/\nfunction remove_linked_products($tabs){\n unset($tabs['inventory']);\n unset($tabs['shipping']);\n return($tabs);\n}\nadd_filter('woocommerce_product_data_tabs', 'remove_linked_products', 10, 1);\n\n/*Remove Virtual and Downloadeble checkbox*/\nfunction remove_product_type_options( $options ) {\n unset( $options['virtual'] );\n unset( $options['downloadable'] );\n return $options;\n}\nadd_filter( 'product_type_options', 'remove_product_type_options' );\n</code></pre>\n"
}
]
| 2018/07/22 | [
"https://wordpress.stackexchange.com/questions/309222",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97543/"
]
| My website is a product review website. I'm using woocomerce in order to store all products and let user be able to search them by category and attributes.
Due this, I would like to remove some unnecessary options from my wordpress admin like inventory and shipping.
.[](https://i.stack.imgur.com/woW1A.png)
How can I disable those functions from my wordpress?? | Just add below function in your function file
```
/*For remove tab from product tab*/
function remove_linked_products($tabs){
unset($tabs['inventory']);
unset($tabs['shipping']);
return($tabs);
}
add_filter('woocommerce_product_data_tabs', 'remove_linked_products', 10, 1);
/*Remove Virtual and Downloadeble checkbox*/
function remove_product_type_options( $options ) {
unset( $options['virtual'] );
unset( $options['downloadable'] );
return $options;
}
add_filter( 'product_type_options', 'remove_product_type_options' );
``` |
309,223 | <p>I have created a code through which the current user can add other users to his project. These users are only shown on the project page. They will not have any right to modify the project.</p>
<p>Once these users are inserted to database it sends an email to them. I want to restrict sending mail to the current user. How can I do that?</p>
<pre><code>$member_details->user_email = array_map( 'sanitize_text_field', $_POST['user_email'] );
$member_details->user_role = array_map( 'sanitize_text_field', $_POST['user_role'] );
$member_details->status = array_map( 'sanitize_text_field', $_POST['status'] );
$member_details_encode = wp_json_encode( $member_details );
global $wpdb;
$member_result = $wpdb->insert( 'wpxa_project_members',
array(
'project_id' => $_SESSION['project_id'],
'author_id' => $post_author,
'member_details' => $member_details_encode
),
array(
'%d',
'%d',
'%s'
)
);
$user_email = $member_details->user_email;
$subject = "Congrats! You are added to the Project - " . "'" . $project_title . "'";
$message = 'If you are not the member of project plz contact us to remove at [email protected]';
wp_mail( $user_email, $subject, $message );
</code></pre>
| [
{
"answer_id": 309306,
"author": "Andrea Somovigo",
"author_id": 64435,
"author_profile": "https://wordpress.stackexchange.com/users/64435",
"pm_score": 1,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>//after $wpdb->insert function\n\n$current_user = wp_get_current_user();\n$current_mail = $current_user->user_email;\n//$user_email = $member_details->user_email;\nif($current_mail !== $_POST['user_email'] ){ // send mail only if different from the current_user email\n $subject = \"Congrats! You are added to the Project - \" . \"'\" . \n $project_title . \"'\";\n $message = 'If you are not the member of project plz contact us to remove at [email protected]';\n wp_mail( $user_email, $subject, $message );\n}\n</code></pre>\n"
},
{
"answer_id": 309366,
"author": "Minesh",
"author_id": 124069,
"author_profile": "https://wordpress.stackexchange.com/users/124069",
"pm_score": 1,
"selected": true,
"text": "<p>I have found the answer. Here it is:</p>\n\n<pre><code>if ( ! empty( $member_result ) ) {\n\n$user_emails = $member_details->user_email;\n\nfor ($i=1; $i < count($user_emails); $i++) { \n $user_email[] = $user_emails[$i];\n}\n\n$to = $user_email;\n$subject = \"Congrats! You are added to the Project - \" . \"'\" . $project_title . \"'\";\n$message = 'If you are not the member of project plz contact us to remove at [email protected]';\n\nwp_mail( $to, $subject, $message );\n\n}\n</code></pre>\n"
}
]
| 2018/07/22 | [
"https://wordpress.stackexchange.com/questions/309223",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/124069/"
]
| I have created a code through which the current user can add other users to his project. These users are only shown on the project page. They will not have any right to modify the project.
Once these users are inserted to database it sends an email to them. I want to restrict sending mail to the current user. How can I do that?
```
$member_details->user_email = array_map( 'sanitize_text_field', $_POST['user_email'] );
$member_details->user_role = array_map( 'sanitize_text_field', $_POST['user_role'] );
$member_details->status = array_map( 'sanitize_text_field', $_POST['status'] );
$member_details_encode = wp_json_encode( $member_details );
global $wpdb;
$member_result = $wpdb->insert( 'wpxa_project_members',
array(
'project_id' => $_SESSION['project_id'],
'author_id' => $post_author,
'member_details' => $member_details_encode
),
array(
'%d',
'%d',
'%s'
)
);
$user_email = $member_details->user_email;
$subject = "Congrats! You are added to the Project - " . "'" . $project_title . "'";
$message = 'If you are not the member of project plz contact us to remove at [email protected]';
wp_mail( $user_email, $subject, $message );
``` | I have found the answer. Here it is:
```
if ( ! empty( $member_result ) ) {
$user_emails = $member_details->user_email;
for ($i=1; $i < count($user_emails); $i++) {
$user_email[] = $user_emails[$i];
}
$to = $user_email;
$subject = "Congrats! You are added to the Project - " . "'" . $project_title . "'";
$message = 'If you are not the member of project plz contact us to remove at [email protected]';
wp_mail( $to, $subject, $message );
}
``` |
309,240 | <p>I've cloned the production site at example.com to my own dev server, calling it example.mydomain.com. It displays OK, as long as I use port 8080 (bypassing my varnish server).</p>
<p>I can successfully log in to the <code>wp-admin</code> page at <strong>example.com</strong>, but I can't reach the page at <strong>example.mydomain.com/wp-admin</strong> - it redirects to the homepage of <strong>example.com</strong>. </p>
<p>Suspecting my varnish set up might be at fault, I visited <strong>example.mydomain.com:8080/wp-admin</strong> and was presented with a login form.</p>
<p>However, entering the credentials there logs me into and redirects me to, <strong>example.com/wp-admin/</strong> - the production site.
I've even looked at the query string that appears thus: <strong><a href="http://example.myserver.com:8080/wp-login.php?redirect_to=http%3A%2F%2Fexample.myserver.com%3A8080%2Fwp-admin%2F&reauth=1" rel="nofollow noreferrer">http://example.myserver.com:8080/wp-login.php?redirect_to=http%3A%2F%2Fexample.myserver.com%3A8080%2Fwp-admin%2F&reauth=1</a></strong> - which looks like it'll do the right thing, but no joy.</p>
<p>I've done a full text search of the codebase, looking for places where the server name might be hard coded, and found nothing obvious (except some image links in the CSS).</p>
<p>So I'm thinking maybe there's some config settings stored in the database. But I have no idea where to look.</p>
| [
{
"answer_id": 309241,
"author": "Castiblanco",
"author_id": 44370,
"author_profile": "https://wordpress.stackexchange.com/users/44370",
"pm_score": 2,
"selected": true,
"text": "<p>Check for <code>wp-config.php</code> file.</p>\n\n<p>Find these two lines to your <code>wp-config.php</code>, and make sure \"example.com\" is the correct location of your site.</p>\n\n<pre><code>define('WP_HOME','http://example.com');\ndefine('WP_SITEURL','http://example.com');\n</code></pre>\n\n<p>Also on the database, check for table <code>wp_options</code>, check these two <strong>option_name</strong>; <code>siteurl</code> and <code>home</code>.</p>\n"
},
{
"answer_id": 412656,
"author": "MPN",
"author_id": 228899,
"author_profile": "https://wordpress.stackexchange.com/users/228899",
"pm_score": 0,
"selected": false,
"text": "<p>Try this to change the url under wp_options on the database: <a href=\"https://www.hostinger.co.uk/tutorials/wordpress/how-to-change-wordpress-urls-in-mysql-database-using-phpmyadmin\" rel=\"nofollow noreferrer\">https://www.hostinger.co.uk/tutorials/wordpress/how-to-change-wordpress-urls-in-mysql-database-using-phpmyadmin</a></p>\n"
}
]
| 2018/07/22 | [
"https://wordpress.stackexchange.com/questions/309240",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147347/"
]
| I've cloned the production site at example.com to my own dev server, calling it example.mydomain.com. It displays OK, as long as I use port 8080 (bypassing my varnish server).
I can successfully log in to the `wp-admin` page at **example.com**, but I can't reach the page at **example.mydomain.com/wp-admin** - it redirects to the homepage of **example.com**.
Suspecting my varnish set up might be at fault, I visited **example.mydomain.com:8080/wp-admin** and was presented with a login form.
However, entering the credentials there logs me into and redirects me to, **example.com/wp-admin/** - the production site.
I've even looked at the query string that appears thus: **<http://example.myserver.com:8080/wp-login.php?redirect_to=http%3A%2F%2Fexample.myserver.com%3A8080%2Fwp-admin%2F&reauth=1>** - which looks like it'll do the right thing, but no joy.
I've done a full text search of the codebase, looking for places where the server name might be hard coded, and found nothing obvious (except some image links in the CSS).
So I'm thinking maybe there's some config settings stored in the database. But I have no idea where to look. | Check for `wp-config.php` file.
Find these two lines to your `wp-config.php`, and make sure "example.com" is the correct location of your site.
```
define('WP_HOME','http://example.com');
define('WP_SITEURL','http://example.com');
```
Also on the database, check for table `wp_options`, check these two **option\_name**; `siteurl` and `home`. |
309,310 | <p>used this code and that did not worked for me.</p>
<pre><code>echo str_replace( "<br>", "", wp_list_categories(array('title_li' => false, 'style' => false)));
</code></pre>
<p>what did I missed?</p>
| [
{
"answer_id": 309312,
"author": "Trilok",
"author_id": 145962,
"author_profile": "https://wordpress.stackexchange.com/users/145962",
"pm_score": 1,
"selected": false,
"text": "<pre><code>Please use below code it will help you\n $args = [\n 'style' => 'none',\n 'separator' => '', // <-- Removes the default one\n];\n\nwp_list_categories( $args );\n</code></pre>\n"
},
{
"answer_id": 309313,
"author": "Bhupen",
"author_id": 128529,
"author_profile": "https://wordpress.stackexchange.com/users/128529",
"pm_score": 1,
"selected": true,
"text": "<p>You can replace '<br>' with '' by setting <strong>separator</strong> value</p>\n\n<pre><code>echo wp_list_categories(array('title_li' => false, 'style' => false, 'separator' => ''));\n</code></pre>\n"
}
]
| 2018/07/23 | [
"https://wordpress.stackexchange.com/questions/309310",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147385/"
]
| used this code and that did not worked for me.
```
echo str_replace( "<br>", "", wp_list_categories(array('title_li' => false, 'style' => false)));
```
what did I missed? | You can replace '<br>' with '' by setting **separator** value
```
echo wp_list_categories(array('title_li' => false, 'style' => false, 'separator' => ''));
``` |
309,331 | <p>I create a table in the footer.</p>
<p>I would like to show some statistics, like total posts, weekly posts, total posts of the specific category.</p>
<p>I just echo total posts with <code>wp_count_posts()->publish;</code></p>
<p>What can I do for the other one?</p>
| [
{
"answer_id": 309333,
"author": "idpokute",
"author_id": 87895,
"author_profile": "https://wordpress.stackexchange.com/users/87895",
"pm_score": 1,
"selected": false,
"text": "<p>Wordpress query supports <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters\" rel=\"nofollow noreferrer\">Date Query</a>.\nTo get the specific category, you will need to add category parameter as well.</p>\n"
},
{
"answer_id": 309334,
"author": "Castiblanco",
"author_id": 44370,
"author_profile": "https://wordpress.stackexchange.com/users/44370",
"pm_score": 3,
"selected": true,
"text": "<p>You already have the total post, so in order to get the total post within the last week, it's better if you do this on your <code>functions.php</code> file:</p>\n\n<pre><code>function get_posts_count_from_last_week($post_type ='post') {\n global $wpdb;\n\n $numposts = $wpdb->get_var(\n $wpdb->prepare(\n \"SELECT COUNT(ID) \".\n \"FROM {$wpdb->posts} \".\n \"WHERE \".\n \"post_status='publish' \".\n \"AND post_type= %s \".\n \"AND post_date> %s\",\n $post_type, date('Y-m-d H:i:s', strtotime('-168 hours'))\n )\n );\n return $numposts;\n}\n</code></pre>\n\n<p>And then use it in the footer.</p>\n\n<pre><code><?php echo get_posts_count_from_last_week(); ?>\n</code></pre>\n\n<p>To work with categories we could use <a href=\"http://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\">WP_Query</a>:</p>\n\n<pre><code>$args = array(\n 'cat' => 4,\n 'post_type' => 'videos'\n);\n$the_query = new WP_Query( $args );\necho $the_query->found_posts;\n</code></pre>\n"
}
]
| 2018/07/23 | [
"https://wordpress.stackexchange.com/questions/309331",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/141105/"
]
| I create a table in the footer.
I would like to show some statistics, like total posts, weekly posts, total posts of the specific category.
I just echo total posts with `wp_count_posts()->publish;`
What can I do for the other one? | You already have the total post, so in order to get the total post within the last week, it's better if you do this on your `functions.php` file:
```
function get_posts_count_from_last_week($post_type ='post') {
global $wpdb;
$numposts = $wpdb->get_var(
$wpdb->prepare(
"SELECT COUNT(ID) ".
"FROM {$wpdb->posts} ".
"WHERE ".
"post_status='publish' ".
"AND post_type= %s ".
"AND post_date> %s",
$post_type, date('Y-m-d H:i:s', strtotime('-168 hours'))
)
);
return $numposts;
}
```
And then use it in the footer.
```
<?php echo get_posts_count_from_last_week(); ?>
```
To work with categories we could use [WP\_Query](http://codex.wordpress.org/Class_Reference/WP_Query):
```
$args = array(
'cat' => 4,
'post_type' => 'videos'
);
$the_query = new WP_Query( $args );
echo $the_query->found_posts;
``` |
309,395 | <p>Is it possible to add custom meta boxes to the default blocks in Gutenberg? I would need to add a user-defined data-attribute to each block. This data-attribute then would be printed on the frontend to the wrapper element. I havent been able to find any documentation on how to do this.</p>
<p>An image to illustrate what I mean.
<a href="https://i.stack.imgur.com/jevKz.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/jevKz.jpg" alt="enter image description here"></a></p>
| [
{
"answer_id": 309401,
"author": "Harsh",
"author_id": 131853,
"author_profile": "https://wordpress.stackexchange.com/users/131853",
"pm_score": -1,
"selected": false,
"text": "<p>For custom meta boxes usees in Gutenberg, please check the following link.\n<a href=\"https://wordpress.org/gutenberg/handbook/extensibility/meta-box/\" rel=\"nofollow noreferrer\">https://wordpress.org/gutenberg/handbook/extensibility/meta-box/</a></p>\n"
},
{
"answer_id": 323834,
"author": "Alvaro",
"author_id": 16533,
"author_profile": "https://wordpress.stackexchange.com/users/16533",
"pm_score": 3,
"selected": false,
"text": "<p>Using <a href=\"https://wordpress.org/gutenberg/handbook/designers-developers/developers/filters/block-filters/\" rel=\"noreferrer\">filters</a> we can modify the props and attributes of blocks.\nFirst we extend the attributes to include the new attribute:</p>\n\n<pre><code>const { addFilter } = wp.hooks;\n\n// Register/add the new attribute.\nconst addExtraAttribute = props => {\n const attributes = {\n ...props.attributes,\n extra_attribute: {\n type: \"string\",\n default: \"default_value\"\n }\n };\n\n return { ...props, attributes };\n};\n\naddFilter(\n \"blocks.registerBlockType\",\n \"my-plugin/extra-attribute\",\n addExtraAttribute\n);\n</code></pre>\n\n<p>Then we extend the edit function of the block to include a control to modify the attribute:</p>\n\n<pre><code>const { addFilter } = wp.hooks;\nconst { createHigherOrderComponent } = wp.compose;\nconst { Fragment } = wp.element;\nconst { InspectorControls } = wp.editor;\nconst { PanelBody, TextControl } = wp.components;\n\nconst addTextControl = createHigherOrderComponent(BlockEdit => {\n return props => {\n const { attributes, setAttributes } = props;\n return (\n <Fragment>\n <BlockEdit {...props} />\n <InspectorControls>\n <PanelBody>\n <TextControl\n value={attributes.extra_attribute}\n onChange={value => {\n setAttributes({ extra_attribute: value });\n }}\n />\n </PanelBody>\n </InspectorControls>\n </Fragment>\n );\n };\n}, \"withInspectorControl\");\n\naddFilter(\"editor.BlockEdit\", \"my-plugin/extra-attribute\", addTextControl);\n</code></pre>\n\n<p>Finally we extend the props assigned to the save function and include the <a href=\"https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes\" rel=\"noreferrer\">data attribute</a> with the added attribute value:</p>\n\n<pre><code>const { addFilter } = wp.hooks;\n\n// Add extra props. Here we assign an html\n// data-attribute with the extra_attribute value.\nconst addExtraData = (props, block_type, attributes) => {\n return {\n ...props,\n \"data-extra\": attributes.extra_attribute\n }\n};\n\naddFilter(\n \"blocks.getSaveContent.extraProps\",\n \"my-plugin/extra-attribute\",\n addExtraData\n);\n</code></pre>\n"
}
]
| 2018/07/24 | [
"https://wordpress.stackexchange.com/questions/309395",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97361/"
]
| Is it possible to add custom meta boxes to the default blocks in Gutenberg? I would need to add a user-defined data-attribute to each block. This data-attribute then would be printed on the frontend to the wrapper element. I havent been able to find any documentation on how to do this.
An image to illustrate what I mean.
[](https://i.stack.imgur.com/jevKz.jpg) | Using [filters](https://wordpress.org/gutenberg/handbook/designers-developers/developers/filters/block-filters/) we can modify the props and attributes of blocks.
First we extend the attributes to include the new attribute:
```
const { addFilter } = wp.hooks;
// Register/add the new attribute.
const addExtraAttribute = props => {
const attributes = {
...props.attributes,
extra_attribute: {
type: "string",
default: "default_value"
}
};
return { ...props, attributes };
};
addFilter(
"blocks.registerBlockType",
"my-plugin/extra-attribute",
addExtraAttribute
);
```
Then we extend the edit function of the block to include a control to modify the attribute:
```
const { addFilter } = wp.hooks;
const { createHigherOrderComponent } = wp.compose;
const { Fragment } = wp.element;
const { InspectorControls } = wp.editor;
const { PanelBody, TextControl } = wp.components;
const addTextControl = createHigherOrderComponent(BlockEdit => {
return props => {
const { attributes, setAttributes } = props;
return (
<Fragment>
<BlockEdit {...props} />
<InspectorControls>
<PanelBody>
<TextControl
value={attributes.extra_attribute}
onChange={value => {
setAttributes({ extra_attribute: value });
}}
/>
</PanelBody>
</InspectorControls>
</Fragment>
);
};
}, "withInspectorControl");
addFilter("editor.BlockEdit", "my-plugin/extra-attribute", addTextControl);
```
Finally we extend the props assigned to the save function and include the [data attribute](https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes) with the added attribute value:
```
const { addFilter } = wp.hooks;
// Add extra props. Here we assign an html
// data-attribute with the extra_attribute value.
const addExtraData = (props, block_type, attributes) => {
return {
...props,
"data-extra": attributes.extra_attribute
}
};
addFilter(
"blocks.getSaveContent.extraProps",
"my-plugin/extra-attribute",
addExtraData
);
``` |
309,403 | <p>I have created an Add / Remove Dynamic input fields. I am using <code>wp_mail();</code> to send mails. I have restricted the first user from receiving mail. I want to send mail to other users. Everything is working properly. The only problem is that every user is getting double emails. <code>wp_mail();</code> creates it twice at same time.</p>
<p>Means when I submits the form each user receives same email twice. I want each user should receive one email only. Following is my code :</p>
<pre><code><?php get_header(); ?>
<?php
$member_details->user_email = array_map( 'sanitize_text_field', $_POST['user_email'] );
$member_details->user_role = array_map( 'sanitize_text_field', $_POST['user_role'] );
$member_details->status = array_map( 'sanitize_text_field', $_POST['status'] );
if ( isset( $_POST['project_prev'] ) ) {
$user_emails = $member_details->user_email;
$user_statuses = $member_details->status;
for ($i=1; $i < count($user_emails); $i++) {
$user_email1[] = $user_emails[$i];
}
for ($a=1; $a < count($user_statuses); $a++) {
$user_status = $user_statuses[$a];
if ( $user_status == 'Unverified' ) {
$to = $user_email1;
$subject = "Congrats! You are added to the Project - " . "'" . $project_title . "'";
$message = 'If you are not the member of project plz contact us to remove at [email protected]';
wp_mail( $to, $subject, $message );
}
}
}
?>
<form method="POST">
<div class="panel panel-default">
<div class="panel-heading"><center><b>Team Members</b></center></div>
<div class="panel-body">
<div class="row">
<div class="col-md-5"><label>Member's Registered Email</label></div>
<div class="col-md-5"><label>Role in Project</label></div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-5">
<div class="form-group">
<input type="text" class="form-control" name="user_email[]" value="<?php $current_user = wp_get_current_user(); if ( !($current_user instanceof WP_User) ) return; echo $current_user->user_email; ?>" placeholder="" readonly="readonly">
</div>
</div>
<div class="col-md-5">
<div class="form-group">
<input type="text" class="form-control" name="user_role[]" placeholder="">
<input type="hidden" class="form-control" name="status[]" value="Verified" placeholder="">
</div>
</div>
<div class="col-md-2">
<button type="button" class="btn btn-success" id="add-member-fields"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span> Add</button>
</div>
</div>
<div id="member-fields">
</div>
<p class="help-block"><i>To add member please register new User, if already not registered.</i></p>
</div>
</div>
<input class="btn btn-info btn-block" type="submit" name="project_prev" value="Preview" style="border-radius: 0px;">
</form>
<?php
$user = wp_get_current_user();
$args = array(
'role' => 'backer',
'exclude' => array( $user->ID ),
);
$users = get_users( $args );
$get_user_emails = wp_list_pluck( $users, 'user_email' );
?>
<script type='text/javascript'>
jQuery(document).ready(function($) {
var wrapper = $("#member-fields");
var add_button = $("#add-member-fields");
var x = 1;
var availableAttributes = <?php echo json_encode($get_user_emails); ?>;
var previousValue="";
add_button.click(function(e) {
e.preventDefault();
x++;
var element = $('<div id="user-fields"><div class="row"><div class="col-md-5"><div class="form-group"><input type="text" class="form-control" id="user_email" name="user_email[]" placeholder=""></div></div><div class="col-md-5"><div class="form-group"><input type="text" class="form-control" name="user_role[]" placeholder=""><input type="hidden" class="form-control" name="status[]" value="Unverified" placeholder=""></div></div><div class="col-md-2"><button type="button" class="btn btn-danger" id="remove_member_field"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span> Remove</button></div></div><div class="clear"></div></div>');
element.fadeIn("slow").find("input[name^='user_email']").autocomplete({
autoFocus: true,
source: availableAttributes,
});
wrapper.append(element);
});
wrapper.on("keyup","#user_email",function() {
var isValid = false;
for (i in availableAttributes) {
if (availableAttributes[i].toLowerCase().match(this.value.toLowerCase())) {
isValid = true;
}
}
if (!isValid) {
this.value = previousValue
} else {
previousValue = this.value;
}
});
wrapper.on("click", "#remove_member_field", function(e) {
e.preventDefault();
$(this).parent().fadeOut(300, function() {
$(this).closest('#user-fields').remove();
x--;
});
});
});
</script>
<?php get_footer(); ?>
</code></pre>
| [
{
"answer_id": 309406,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 0,
"selected": false,
"text": "<p>The problem here is, you first create an array of all the email addresses, and then in your second \"for\" loop for user statuses, if the current user's status in the loop is unverified, you send an email to the entire array <code>$user_email1</code>. If it's safe to assume that <code>$i</code> refers to the same user in both the <code>$user_email1</code> array and the <code>$user_statuses</code> array, you can just change</p>\n\n<p><code>$to = $user_email1;</code></p>\n\n<p>to</p>\n\n<p><code>$to = $user_email1[$i];</code></p>\n\n<p>and that way you're only sending the email to the current user in your for loop.</p>\n"
},
{
"answer_id": 309468,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": true,
"text": "<p>These <code>POST</code> variables: <code>$_POST['user_email']</code>, <code>$_POST['user_role']</code>, and <code>$_POST['status']</code> (which each is an <code>array</code>) are connected to each other by their index, hence you can loop through just one of them and use the <em>same index</em> (or iterator) to access the items in the <em>other</em> arrays.</p>\n\n<p>This should help you understand it:</p>\n\n<pre><code>for ( $i = 0; $i < count( $member_details->user_email ); $i++ ) {\n $user_email = $member_details->user_email[ $i ];\n $user_role = $member_details->user_role[ $i ];\n $status = $member_details->status[ $i ];\n ...\n}\n</code></pre>\n\n<p>So this part/code:</p>\n\n<pre><code>if ( isset( $_POST['project_prev'] ) ) {\n\n$user_emails = $member_details->user_email;\n$user_statuses = $member_details->status;\n\n...\n\n}\n</code></pre>\n\n<p>I coded it like this:</p>\n\n<p>(<em>Note that I re-indented it for clarity.</em>)</p>\n\n<pre><code>if ( isset( $_POST['project_prev'] ) ) {\n\n // Starts with the first user (index 1).\n for ( $i = 1; $i < count( $member_details->user_email ); $i++ ) {\n $user_status = $member_details->status[ $i ];\n\n if ( $user_status === 'Unverified' ) {\n\n $to = $member_details->user_email[ $i ];\n $project_title = '??'; // This wasn't defined anywhere in the file/code.\n $subject = \"Congrats! You are added to the Project - \" . \"'\" . $project_title . \"'\";\n $message = 'If you are not the member of project plz contact us to remove at [email protected]';\n\n wp_mail( $to, $subject, $message );\n\n }\n\n }\n\n}\n</code></pre>\n"
}
]
| 2018/07/24 | [
"https://wordpress.stackexchange.com/questions/309403",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/124069/"
]
| I have created an Add / Remove Dynamic input fields. I am using `wp_mail();` to send mails. I have restricted the first user from receiving mail. I want to send mail to other users. Everything is working properly. The only problem is that every user is getting double emails. `wp_mail();` creates it twice at same time.
Means when I submits the form each user receives same email twice. I want each user should receive one email only. Following is my code :
```
<?php get_header(); ?>
<?php
$member_details->user_email = array_map( 'sanitize_text_field', $_POST['user_email'] );
$member_details->user_role = array_map( 'sanitize_text_field', $_POST['user_role'] );
$member_details->status = array_map( 'sanitize_text_field', $_POST['status'] );
if ( isset( $_POST['project_prev'] ) ) {
$user_emails = $member_details->user_email;
$user_statuses = $member_details->status;
for ($i=1; $i < count($user_emails); $i++) {
$user_email1[] = $user_emails[$i];
}
for ($a=1; $a < count($user_statuses); $a++) {
$user_status = $user_statuses[$a];
if ( $user_status == 'Unverified' ) {
$to = $user_email1;
$subject = "Congrats! You are added to the Project - " . "'" . $project_title . "'";
$message = 'If you are not the member of project plz contact us to remove at [email protected]';
wp_mail( $to, $subject, $message );
}
}
}
?>
<form method="POST">
<div class="panel panel-default">
<div class="panel-heading"><center><b>Team Members</b></center></div>
<div class="panel-body">
<div class="row">
<div class="col-md-5"><label>Member's Registered Email</label></div>
<div class="col-md-5"><label>Role in Project</label></div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-5">
<div class="form-group">
<input type="text" class="form-control" name="user_email[]" value="<?php $current_user = wp_get_current_user(); if ( !($current_user instanceof WP_User) ) return; echo $current_user->user_email; ?>" placeholder="" readonly="readonly">
</div>
</div>
<div class="col-md-5">
<div class="form-group">
<input type="text" class="form-control" name="user_role[]" placeholder="">
<input type="hidden" class="form-control" name="status[]" value="Verified" placeholder="">
</div>
</div>
<div class="col-md-2">
<button type="button" class="btn btn-success" id="add-member-fields"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span> Add</button>
</div>
</div>
<div id="member-fields">
</div>
<p class="help-block"><i>To add member please register new User, if already not registered.</i></p>
</div>
</div>
<input class="btn btn-info btn-block" type="submit" name="project_prev" value="Preview" style="border-radius: 0px;">
</form>
<?php
$user = wp_get_current_user();
$args = array(
'role' => 'backer',
'exclude' => array( $user->ID ),
);
$users = get_users( $args );
$get_user_emails = wp_list_pluck( $users, 'user_email' );
?>
<script type='text/javascript'>
jQuery(document).ready(function($) {
var wrapper = $("#member-fields");
var add_button = $("#add-member-fields");
var x = 1;
var availableAttributes = <?php echo json_encode($get_user_emails); ?>;
var previousValue="";
add_button.click(function(e) {
e.preventDefault();
x++;
var element = $('<div id="user-fields"><div class="row"><div class="col-md-5"><div class="form-group"><input type="text" class="form-control" id="user_email" name="user_email[]" placeholder=""></div></div><div class="col-md-5"><div class="form-group"><input type="text" class="form-control" name="user_role[]" placeholder=""><input type="hidden" class="form-control" name="status[]" value="Unverified" placeholder=""></div></div><div class="col-md-2"><button type="button" class="btn btn-danger" id="remove_member_field"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span> Remove</button></div></div><div class="clear"></div></div>');
element.fadeIn("slow").find("input[name^='user_email']").autocomplete({
autoFocus: true,
source: availableAttributes,
});
wrapper.append(element);
});
wrapper.on("keyup","#user_email",function() {
var isValid = false;
for (i in availableAttributes) {
if (availableAttributes[i].toLowerCase().match(this.value.toLowerCase())) {
isValid = true;
}
}
if (!isValid) {
this.value = previousValue
} else {
previousValue = this.value;
}
});
wrapper.on("click", "#remove_member_field", function(e) {
e.preventDefault();
$(this).parent().fadeOut(300, function() {
$(this).closest('#user-fields').remove();
x--;
});
});
});
</script>
<?php get_footer(); ?>
``` | These `POST` variables: `$_POST['user_email']`, `$_POST['user_role']`, and `$_POST['status']` (which each is an `array`) are connected to each other by their index, hence you can loop through just one of them and use the *same index* (or iterator) to access the items in the *other* arrays.
This should help you understand it:
```
for ( $i = 0; $i < count( $member_details->user_email ); $i++ ) {
$user_email = $member_details->user_email[ $i ];
$user_role = $member_details->user_role[ $i ];
$status = $member_details->status[ $i ];
...
}
```
So this part/code:
```
if ( isset( $_POST['project_prev'] ) ) {
$user_emails = $member_details->user_email;
$user_statuses = $member_details->status;
...
}
```
I coded it like this:
(*Note that I re-indented it for clarity.*)
```
if ( isset( $_POST['project_prev'] ) ) {
// Starts with the first user (index 1).
for ( $i = 1; $i < count( $member_details->user_email ); $i++ ) {
$user_status = $member_details->status[ $i ];
if ( $user_status === 'Unverified' ) {
$to = $member_details->user_email[ $i ];
$project_title = '??'; // This wasn't defined anywhere in the file/code.
$subject = "Congrats! You are added to the Project - " . "'" . $project_title . "'";
$message = 'If you are not the member of project plz contact us to remove at [email protected]';
wp_mail( $to, $subject, $message );
}
}
}
``` |
309,430 | <p>Could someone please help me to add category id with in this query so this will return posts from a certain category? Thanks in advance.</p>
<pre><code><?php foreach(_get($wp_query->posts? : array()) as $n => $post){ setup_postdata($post); ?>
// HTML and post Tags
<?php } ?>
</code></pre>
| [
{
"answer_id": 309481,
"author": "Suraj Rathod",
"author_id": 141555,
"author_profile": "https://wordpress.stackexchange.com/users/141555",
"pm_score": 1,
"selected": true,
"text": "<p>Please follow proper wordpress method not follow someone's code or copy paste code.</p>\n\n<pre><code> /*\n * CODEX: http://codex.wordpress.org/Class_Reference/WP_Query#Parameters\n * Source: https://core.trac.wordpress.org/browser/tags/3.9/src/wp- \n includes/query.php\n */\n$args = array(\n\n//////Category Parameters - Show posts associated with certain categories.\n//http://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters\n //all categories parameter \n\n'cat' => 5,//(int) - use category id.\n'category_name' => 'staff, news', //(string) - Display posts that \n have these categories, using category slug.\n'category_name' => 'staff+news', //(string) - Display posts that \n have \"all\" of these categories, using category slug.\n'category__and' => array( 2, 6 ), //(array) - use category id.\n'category__in' => array( 2, 6 ), //(array) - use category id.\n'category__not_in' => array( 2, 6 ), //(array) - use category id.\n'post_type' => 'post', //post or you can use your custom post type \n'post_status' => 'publish',\n'order' => 'DESC',\n'orderby' => 'date');\n\n$the_query = new WP_Query( $args );\nif ( $the_query->have_posts() ) {\nwhile ( $the_query->have_posts() ) {\n $the_query->the_post();\n // Do Stuff\n } // end while\n} // endif\n// Reset Post Data\nwp_reset_postdata();\n</code></pre>\n"
},
{
"answer_id": 309489,
"author": "Mahmud Farooque",
"author_id": 147385,
"author_profile": "https://wordpress.stackexchange.com/users/147385",
"pm_score": 1,
"selected": false,
"text": "<p>Solved it this way. Thanks everyone.</p>\n\n<pre><code><?php\n$q = new WP_Query(array(\n 'post_type' => 'post',\n 'posts_per_page' => '1',\n 'fields' => 'ids',\n 'cat' => '8'\n));\nforeach(_get($q->posts? : array()) as $post){\n setup_postdata($post);?>\n\n // HTML and post Tags\n\n<?php } ?>\n</code></pre>\n"
}
]
| 2018/07/24 | [
"https://wordpress.stackexchange.com/questions/309430",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147385/"
]
| Could someone please help me to add category id with in this query so this will return posts from a certain category? Thanks in advance.
```
<?php foreach(_get($wp_query->posts? : array()) as $n => $post){ setup_postdata($post); ?>
// HTML and post Tags
<?php } ?>
``` | Please follow proper wordpress method not follow someone's code or copy paste code.
```
/*
* CODEX: http://codex.wordpress.org/Class_Reference/WP_Query#Parameters
* Source: https://core.trac.wordpress.org/browser/tags/3.9/src/wp-
includes/query.php
*/
$args = array(
//////Category Parameters - Show posts associated with certain categories.
//http://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters
//all categories parameter
'cat' => 5,//(int) - use category id.
'category_name' => 'staff, news', //(string) - Display posts that
have these categories, using category slug.
'category_name' => 'staff+news', //(string) - Display posts that
have "all" of these categories, using category slug.
'category__and' => array( 2, 6 ), //(array) - use category id.
'category__in' => array( 2, 6 ), //(array) - use category id.
'category__not_in' => array( 2, 6 ), //(array) - use category id.
'post_type' => 'post', //post or you can use your custom post type
'post_status' => 'publish',
'order' => 'DESC',
'orderby' => 'date');
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
// Do Stuff
} // end while
} // endif
// Reset Post Data
wp_reset_postdata();
``` |
309,462 | <p>I migrated my site from localhost (LAMP) to Namecheap and it is broken in that the images it is supposed to load from <code>/wp-content</code> return a 404 error. </p>
<p>I can login to wp-admin and I can see the pages which load menus and text correctly. But I can't seem to get the images to load, I have tried:</p>
<ul>
<li>flushing permalinks</li>
<li>some <code>.htaccess</code> and wp-config changes</li>
</ul>
<p>For example: The logo does not load when you're on the <code>/about</code> page:</p>
<pre><code>https://example.com/site_dir/about
</code></pre>
<p>If you go to the wp-content folder the image is there but the site is not looking for it in the right directory (wp-content is in a subdirectory):</p>
<pre><code>https://example.com/site_dir/wp-content/uploads/2018/05/site_dir_logo_light_textfull.png
</code></pre>
<p>Any help is very much appreciated!</p>
| [
{
"answer_id": 309465,
"author": "juggler",
"author_id": 147502,
"author_profile": "https://wordpress.stackexchange.com/users/147502",
"pm_score": 1,
"selected": false,
"text": "<p>It looks like your localhost site had WordPress installed in the root directory but your production site is in a sub-directory.</p>\n\n<p>You should review the instructions in the the WordPress Codex for <a href=\"https://codex.wordpress.org/Moving_WordPress\" rel=\"nofollow noreferrer\" title=\"Moving WordPress\">Moving WordPress</a> to see if you missed any steps. It describes both moving a WordPress installation from one server to another, and moving it from one directory to another. It seems like you did both, so all those instructions would apply.</p>\n"
},
{
"answer_id": 310679,
"author": "wiredthorax",
"author_id": 118088,
"author_profile": "https://wordpress.stackexchange.com/users/118088",
"pm_score": 0,
"selected": false,
"text": "<p>So @juggler and @mrwhite were both correct. </p>\n\n<p>Following the instructions to move wordpress into a subfolder would have worked. The problem had to do with the fact that I set up virtual hosts on my localhost machine, because I had multiple wordpress installs in the /var/www/html directory. </p>\n\n<p>So I installed the migrated site in the root folder and it now works. I also had to enable mod_c rewrite rules for apache so that it would show write correctly to my .htaccess file. And I had to edit the site sitename and URL in the database wp-options table.</p>\n"
}
]
| 2018/07/25 | [
"https://wordpress.stackexchange.com/questions/309462",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118088/"
]
| I migrated my site from localhost (LAMP) to Namecheap and it is broken in that the images it is supposed to load from `/wp-content` return a 404 error.
I can login to wp-admin and I can see the pages which load menus and text correctly. But I can't seem to get the images to load, I have tried:
* flushing permalinks
* some `.htaccess` and wp-config changes
For example: The logo does not load when you're on the `/about` page:
```
https://example.com/site_dir/about
```
If you go to the wp-content folder the image is there but the site is not looking for it in the right directory (wp-content is in a subdirectory):
```
https://example.com/site_dir/wp-content/uploads/2018/05/site_dir_logo_light_textfull.png
```
Any help is very much appreciated! | It looks like your localhost site had WordPress installed in the root directory but your production site is in a sub-directory.
You should review the instructions in the the WordPress Codex for [Moving WordPress](https://codex.wordpress.org/Moving_WordPress "Moving WordPress") to see if you missed any steps. It describes both moving a WordPress installation from one server to another, and moving it from one directory to another. It seems like you did both, so all those instructions would apply. |
309,535 | <pre><code><?php
$args = array(
'post_type'=>'weather_today',
'orderby'=>'ID',
'order'=>'ASC',
'posts_per_page'=>1
);
$query = new WP_Query($args);
if ($query->have_posts()) {
while ( have_posts() ) : the_post();
the_content();
endwhile;
}
wp_reset_postdata();
?>
</code></pre>
<p>Outputs a post content (<code>the_content()</code>) that is not of a <code>weather_today</code> type. Why is this? I checked my SQL, in <code>wp_posts</code> I only have <em>one</em> post of <code>post_type = "weather_today"</code> and it's not the one being outputted. This query is up in my header... and I believe above any other custom queries. Furthermore, it seems the other params are respected, the post I am getting is only <code>1</code> and is that last <em>regular post</em> by <code>ID</code>. </p>
<p>So why is the <code>post_type</code>, the most important param in this query, being ignored?</p>
| [
{
"answer_id": 309538,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<p>Try this </p>\n\n<pre><code><?php\n $args = array(\n 'post_type'=>'weather_today',\n 'orderby'=>'ID',\n 'order'=>'ASC',\n 'posts_per_page'=>1\n );\n $query = new WP_Query( $args );\n while ( $query->have_posts() ) : $query->the_post();\n\n //loop \n\n endwhile;\n wp_reset_postdata();\n?>\n</code></pre>\n"
},
{
"answer_id": 309555,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>The problem with your code is pretty simple... You use your custom <code>$query</code> in if statement, but then you use global <code>$wp_query</code> in while loop...</p>\n\n<pre><code><?php\n $args = array(\n 'post_type'=>'weather_today',\n 'orderby'=>'ID',\n 'order'=>'ASC',\n 'posts_per_page'=>1\n );\n $query = new WP_Query($args); // <- here you create custom $query\n if ($query->have_posts()) { // <- here you check if it has any posts\n while ( have_posts() ) : the_post(); // <- here you don't use it\n // it should be: while ( $query->have_posts() ) : $query->the_post();\n the_content();\n endwhile;\n }\n wp_reset_postdata();\n?>\n</code></pre>\n\n<p>PS. Another suggestion - don't use <code>{</code> and <code>:</code> notation in same context - it's bad for readability ;)</p>\n"
}
]
| 2018/07/25 | [
"https://wordpress.stackexchange.com/questions/309535",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77764/"
]
| ```
<?php
$args = array(
'post_type'=>'weather_today',
'orderby'=>'ID',
'order'=>'ASC',
'posts_per_page'=>1
);
$query = new WP_Query($args);
if ($query->have_posts()) {
while ( have_posts() ) : the_post();
the_content();
endwhile;
}
wp_reset_postdata();
?>
```
Outputs a post content (`the_content()`) that is not of a `weather_today` type. Why is this? I checked my SQL, in `wp_posts` I only have *one* post of `post_type = "weather_today"` and it's not the one being outputted. This query is up in my header... and I believe above any other custom queries. Furthermore, it seems the other params are respected, the post I am getting is only `1` and is that last *regular post* by `ID`.
So why is the `post_type`, the most important param in this query, being ignored? | Try this
```
<?php
$args = array(
'post_type'=>'weather_today',
'orderby'=>'ID',
'order'=>'ASC',
'posts_per_page'=>1
);
$query = new WP_Query( $args );
while ( $query->have_posts() ) : $query->the_post();
//loop
endwhile;
wp_reset_postdata();
?>
``` |
309,548 | <p>I am using wordpress 4.9.7 and would like to add a custom taxonomy to my post-type.</p>
<p>I have packed my code in a <code>mu-plugins</code> folder so that it is required by wordpress. Find below my code:</p>
<pre><code><?php
function computerBoxBuilder_post_types()
{
// Computer Hardware Post Type
register_post_type('Computer-Hardware', array(
'supports' => array('title', 'editor', 'thumbnail', 'custom-fields'),
'public' => true,
// 'exclude_from_search' => true,
'publicly_queryable' => true,
'show_ui' => true,
'labels' => array(
'name' => 'Computer-Hardware',
'add_new_item' => 'Add New Computer-Hardware',
'edit_item' => 'Edit Computer-Hardware',
'all_items' => 'All Computer-Hardware',
'singular_name' => 'Computer-Hardware',
),
'menu_icon' => 'dashicons-dashboard',
'taxonomies' => array( 'category' ),
));
}
// Register Custom Taxonomy
function custom_taxonomy() {
$labels = array(
'name' => _x( 'Hardware-Creators', 'Taxonomy General Name', 'text_domain' ),
'singular_name' => _x( 'Hardware-Creator', 'Taxonomy Singular Name', 'text_domain' ),
'menu_name' => __( 'Taxonomy', 'text_domain' ),
'all_items' => __( 'All Items', 'text_domain' ),
'parent_item' => __( 'Parent Item', 'text_domain' ),
'parent_item_colon' => __( 'Parent Item:', 'text_domain' ),
'new_item_name' => __( 'New Item Name', 'text_domain' ),
'add_new_item' => __( 'Add New Item', 'text_domain' ),
'edit_item' => __( 'Edit Item', 'text_domain' ),
'update_item' => __( 'Update Item', 'text_domain' ),
'view_item' => __( 'View Item', 'text_domain' ),
'separate_items_with_commas' => __( 'Separate items with commas', 'text_domain' ),
'add_or_remove_items' => __( 'Add or remove items', 'text_domain' ),
'choose_from_most_used' => __( 'Choose from the most used', 'text_domain' ),
'popular_items' => __( 'Popular Items', 'text_domain' ),
'search_items' => __( 'Search Items', 'text_domain' ),
'not_found' => __( 'Not Found', 'text_domain' ),
'no_terms' => __( 'No items', 'text_domain' ),
'items_list' => __( 'Items list', 'text_domain' ),
'items_list_navigation' => __( 'Items list navigation', 'text_domain' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_nav_menus' => true,
'show_tagcloud' => true,
);
register_taxonomy( 'Hardware-Creator', array( 'Computer-Hardware' ), $args );
}
add_action('init', 'computerBoxBuilder_post_types');
add_action( 'init', 'custom_taxonomy', 2 );
</code></pre>
<p>As you can see the taxonomy is not shown:</p>
<p><a href="https://i.stack.imgur.com/KUQ0Y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KUQ0Y.png" alt="enter image description here" /></a></p>
<p>Any suggestion what I am doing wrong?</p>
<p>Appreciate your reply!</p>
| [
{
"answer_id": 309554,
"author": "nmr",
"author_id": 147428,
"author_profile": "https://wordpress.stackexchange.com/users/147428",
"pm_score": 1,
"selected": false,
"text": "<p>Try to change order of <code>add_action</code>:</p>\n\n<p><code>add_action( 'init', 'computerBoxBuilder_post_types');\n add_action( 'init', 'custom_taxonomy' );</code></p>\n\n<p>In your code, function <code>custom_taxonomy</code> is executed before <code>computerBoxBuilder_post_types</code> and tries to use custom post type <code>Computer-Hardware</code> before it is created.</p>\n"
},
{
"answer_id": 309573,
"author": "Techno Deviser",
"author_id": 146401,
"author_profile": "https://wordpress.stackexchange.com/users/146401",
"pm_score": 3,
"selected": true,
"text": "<p>Just change this line, it will display in admin</p>\n\n<pre><code>register_taxonomy( 'Hardware-Creator', array( 'Computer-Hardware' ), $args );\n</code></pre>\n\n<p>to</p>\n\n<pre><code>register_taxonomy( 'Hardware-Creator', array( 'computer-hardware' ), $args );\n</code></pre>\n"
}
]
| 2018/07/25 | [
"https://wordpress.stackexchange.com/questions/309548",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48703/"
]
| I am using wordpress 4.9.7 and would like to add a custom taxonomy to my post-type.
I have packed my code in a `mu-plugins` folder so that it is required by wordpress. Find below my code:
```
<?php
function computerBoxBuilder_post_types()
{
// Computer Hardware Post Type
register_post_type('Computer-Hardware', array(
'supports' => array('title', 'editor', 'thumbnail', 'custom-fields'),
'public' => true,
// 'exclude_from_search' => true,
'publicly_queryable' => true,
'show_ui' => true,
'labels' => array(
'name' => 'Computer-Hardware',
'add_new_item' => 'Add New Computer-Hardware',
'edit_item' => 'Edit Computer-Hardware',
'all_items' => 'All Computer-Hardware',
'singular_name' => 'Computer-Hardware',
),
'menu_icon' => 'dashicons-dashboard',
'taxonomies' => array( 'category' ),
));
}
// Register Custom Taxonomy
function custom_taxonomy() {
$labels = array(
'name' => _x( 'Hardware-Creators', 'Taxonomy General Name', 'text_domain' ),
'singular_name' => _x( 'Hardware-Creator', 'Taxonomy Singular Name', 'text_domain' ),
'menu_name' => __( 'Taxonomy', 'text_domain' ),
'all_items' => __( 'All Items', 'text_domain' ),
'parent_item' => __( 'Parent Item', 'text_domain' ),
'parent_item_colon' => __( 'Parent Item:', 'text_domain' ),
'new_item_name' => __( 'New Item Name', 'text_domain' ),
'add_new_item' => __( 'Add New Item', 'text_domain' ),
'edit_item' => __( 'Edit Item', 'text_domain' ),
'update_item' => __( 'Update Item', 'text_domain' ),
'view_item' => __( 'View Item', 'text_domain' ),
'separate_items_with_commas' => __( 'Separate items with commas', 'text_domain' ),
'add_or_remove_items' => __( 'Add or remove items', 'text_domain' ),
'choose_from_most_used' => __( 'Choose from the most used', 'text_domain' ),
'popular_items' => __( 'Popular Items', 'text_domain' ),
'search_items' => __( 'Search Items', 'text_domain' ),
'not_found' => __( 'Not Found', 'text_domain' ),
'no_terms' => __( 'No items', 'text_domain' ),
'items_list' => __( 'Items list', 'text_domain' ),
'items_list_navigation' => __( 'Items list navigation', 'text_domain' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_nav_menus' => true,
'show_tagcloud' => true,
);
register_taxonomy( 'Hardware-Creator', array( 'Computer-Hardware' ), $args );
}
add_action('init', 'computerBoxBuilder_post_types');
add_action( 'init', 'custom_taxonomy', 2 );
```
As you can see the taxonomy is not shown:
[](https://i.stack.imgur.com/KUQ0Y.png)
Any suggestion what I am doing wrong?
Appreciate your reply! | Just change this line, it will display in admin
```
register_taxonomy( 'Hardware-Creator', array( 'Computer-Hardware' ), $args );
```
to
```
register_taxonomy( 'Hardware-Creator', array( 'computer-hardware' ), $args );
``` |
309,550 | <p>I tried to make mysite.com/category page where I want to see list of categories.
How to show list of categories I know.
I can not make a link 'category'.
I have tried to call this file 'archive-category.php', but site response 404.
If I tried to call this file 'category.php' , then site route url mysite.com/category/info through template category.php, but url /category return me again 404.
Please help me.</p>
| [
{
"answer_id": 309554,
"author": "nmr",
"author_id": 147428,
"author_profile": "https://wordpress.stackexchange.com/users/147428",
"pm_score": 1,
"selected": false,
"text": "<p>Try to change order of <code>add_action</code>:</p>\n\n<p><code>add_action( 'init', 'computerBoxBuilder_post_types');\n add_action( 'init', 'custom_taxonomy' );</code></p>\n\n<p>In your code, function <code>custom_taxonomy</code> is executed before <code>computerBoxBuilder_post_types</code> and tries to use custom post type <code>Computer-Hardware</code> before it is created.</p>\n"
},
{
"answer_id": 309573,
"author": "Techno Deviser",
"author_id": 146401,
"author_profile": "https://wordpress.stackexchange.com/users/146401",
"pm_score": 3,
"selected": true,
"text": "<p>Just change this line, it will display in admin</p>\n\n<pre><code>register_taxonomy( 'Hardware-Creator', array( 'Computer-Hardware' ), $args );\n</code></pre>\n\n<p>to</p>\n\n<pre><code>register_taxonomy( 'Hardware-Creator', array( 'computer-hardware' ), $args );\n</code></pre>\n"
}
]
| 2018/07/25 | [
"https://wordpress.stackexchange.com/questions/309550",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147561/"
]
| I tried to make mysite.com/category page where I want to see list of categories.
How to show list of categories I know.
I can not make a link 'category'.
I have tried to call this file 'archive-category.php', but site response 404.
If I tried to call this file 'category.php' , then site route url mysite.com/category/info through template category.php, but url /category return me again 404.
Please help me. | Just change this line, it will display in admin
```
register_taxonomy( 'Hardware-Creator', array( 'Computer-Hardware' ), $args );
```
to
```
register_taxonomy( 'Hardware-Creator', array( 'computer-hardware' ), $args );
``` |
309,564 | <p>I appreciate all help in advance. I am building a fairly customised website using Avada theme and BNE Flyouts.</p>
<p>I need to be able to enable the Avada's Fusion Builder when editing flyouts, so it can be edited in drag and drop mode.</p>
<p>I have tried enabling both for custom post types, but still when I go to edit the flyout, none of the wysiwyg editors show: <a href="https://www.screencast.com/t/5dQ5hdDew3a" rel="nofollow noreferrer">https://www.screencast.com/t/5dQ5hdDew3a</a></p>
<p>I checked in the database and I am certain that flyouts are actually stored as posts: <a href="https://www.screencast.com/t/OMDsavM5o" rel="nofollow noreferrer">https://www.screencast.com/t/OMDsavM5o</a></p>
<p>Question:
- Is there a way to enable fusion builder on every editor window that I open, whatever is the post type
- Can I force particular post type to open fusion builder on certain post type? How do I determine the post type name for functions.php?</p>
| [
{
"answer_id": 309554,
"author": "nmr",
"author_id": 147428,
"author_profile": "https://wordpress.stackexchange.com/users/147428",
"pm_score": 1,
"selected": false,
"text": "<p>Try to change order of <code>add_action</code>:</p>\n\n<p><code>add_action( 'init', 'computerBoxBuilder_post_types');\n add_action( 'init', 'custom_taxonomy' );</code></p>\n\n<p>In your code, function <code>custom_taxonomy</code> is executed before <code>computerBoxBuilder_post_types</code> and tries to use custom post type <code>Computer-Hardware</code> before it is created.</p>\n"
},
{
"answer_id": 309573,
"author": "Techno Deviser",
"author_id": 146401,
"author_profile": "https://wordpress.stackexchange.com/users/146401",
"pm_score": 3,
"selected": true,
"text": "<p>Just change this line, it will display in admin</p>\n\n<pre><code>register_taxonomy( 'Hardware-Creator', array( 'Computer-Hardware' ), $args );\n</code></pre>\n\n<p>to</p>\n\n<pre><code>register_taxonomy( 'Hardware-Creator', array( 'computer-hardware' ), $args );\n</code></pre>\n"
}
]
| 2018/07/26 | [
"https://wordpress.stackexchange.com/questions/309564",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143166/"
]
| I appreciate all help in advance. I am building a fairly customised website using Avada theme and BNE Flyouts.
I need to be able to enable the Avada's Fusion Builder when editing flyouts, so it can be edited in drag and drop mode.
I have tried enabling both for custom post types, but still when I go to edit the flyout, none of the wysiwyg editors show: <https://www.screencast.com/t/5dQ5hdDew3a>
I checked in the database and I am certain that flyouts are actually stored as posts: <https://www.screencast.com/t/OMDsavM5o>
Question:
- Is there a way to enable fusion builder on every editor window that I open, whatever is the post type
- Can I force particular post type to open fusion builder on certain post type? How do I determine the post type name for functions.php? | Just change this line, it will display in admin
```
register_taxonomy( 'Hardware-Creator', array( 'Computer-Hardware' ), $args );
```
to
```
register_taxonomy( 'Hardware-Creator', array( 'computer-hardware' ), $args );
``` |
309,610 | <p>I created a custom template. It contains 3 columns, and the middle column should only display the post thumbnail. But no matter what size attribute I'm setting, it's not changing the size the way I want. I'd like the image to take over most of the space from that column.</p>
<pre><code> <div class="col-lg-4">
.. first column with some content
</div><!-- col-lg-4 -->
<div class="col-lg-4">
<?php
//post_thumbnail
if (!empty(get_the_post_thumbnail())) : ?>
<?php the_post_thumbnail(array(360,466), array( 'class' => 'aligncenter'));
endif; ?>
</div><!-- col-lg-4 -->
<div class="col-lg-4">
third column with some content..
</div><!-- col-lg-4 -->
</code></pre>
<p>No matter what I put as a size (i also tried 'medium', 'full' etc.) it's remaining the same size as in the picture below:
<a href="https://i.stack.imgur.com/4QDEU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4QDEU.png" alt="enter image description here"></a></p>
<p>any ideas where my problem is?</p>
<p><strong>EDIT</strong></p>
<p>the same thing happens when I simply add </p>
<pre><code>if (!empty(get_the_post_thumbnail())) : ?>
<?php the_post_thumbnail();
endif; ?>
</code></pre>
<p>or add any size (thumbnail, middle, large). It doesn't change anything..</p>
| [
{
"answer_id": 309554,
"author": "nmr",
"author_id": 147428,
"author_profile": "https://wordpress.stackexchange.com/users/147428",
"pm_score": 1,
"selected": false,
"text": "<p>Try to change order of <code>add_action</code>:</p>\n\n<p><code>add_action( 'init', 'computerBoxBuilder_post_types');\n add_action( 'init', 'custom_taxonomy' );</code></p>\n\n<p>In your code, function <code>custom_taxonomy</code> is executed before <code>computerBoxBuilder_post_types</code> and tries to use custom post type <code>Computer-Hardware</code> before it is created.</p>\n"
},
{
"answer_id": 309573,
"author": "Techno Deviser",
"author_id": 146401,
"author_profile": "https://wordpress.stackexchange.com/users/146401",
"pm_score": 3,
"selected": true,
"text": "<p>Just change this line, it will display in admin</p>\n\n<pre><code>register_taxonomy( 'Hardware-Creator', array( 'Computer-Hardware' ), $args );\n</code></pre>\n\n<p>to</p>\n\n<pre><code>register_taxonomy( 'Hardware-Creator', array( 'computer-hardware' ), $args );\n</code></pre>\n"
}
]
| 2018/07/26 | [
"https://wordpress.stackexchange.com/questions/309610",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/137532/"
]
| I created a custom template. It contains 3 columns, and the middle column should only display the post thumbnail. But no matter what size attribute I'm setting, it's not changing the size the way I want. I'd like the image to take over most of the space from that column.
```
<div class="col-lg-4">
.. first column with some content
</div><!-- col-lg-4 -->
<div class="col-lg-4">
<?php
//post_thumbnail
if (!empty(get_the_post_thumbnail())) : ?>
<?php the_post_thumbnail(array(360,466), array( 'class' => 'aligncenter'));
endif; ?>
</div><!-- col-lg-4 -->
<div class="col-lg-4">
third column with some content..
</div><!-- col-lg-4 -->
```
No matter what I put as a size (i also tried 'medium', 'full' etc.) it's remaining the same size as in the picture below:
[](https://i.stack.imgur.com/4QDEU.png)
any ideas where my problem is?
**EDIT**
the same thing happens when I simply add
```
if (!empty(get_the_post_thumbnail())) : ?>
<?php the_post_thumbnail();
endif; ?>
```
or add any size (thumbnail, middle, large). It doesn't change anything.. | Just change this line, it will display in admin
```
register_taxonomy( 'Hardware-Creator', array( 'Computer-Hardware' ), $args );
```
to
```
register_taxonomy( 'Hardware-Creator', array( 'computer-hardware' ), $args );
``` |
309,647 | <p>I want to add a filter to a form submission
<a href="https://gravitywp.com/capitalize-fields-in-gravity-forms/" rel="nofollow noreferrer">like it is done here</a>.</p>
<pre><code>add_action('gform_pre_submission_6', 'capitalize_fields_6');
function capitalize_fields_6($form){
// Code here
}
</code></pre>
<p>My question is, how do you get the form ID on the WP admin side? Where is the number 6 coming from to access the form in the action? </p>
| [
{
"answer_id": 309648,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>If you look at the list of Forms (Forms > Forms) in the back end there's a column that tells you the ID. You can also get it from the top of the screen when editing a form. Next to the form's Title there's an orange box that says \"ID: 6\".</p>\n"
},
{
"answer_id": 309672,
"author": "Tony Logarta",
"author_id": 106116,
"author_profile": "https://wordpress.stackexchange.com/users/106116",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://i.stack.imgur.com/cLzyc.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/cLzyc.jpg\" alt=\"3 ways you get view gravity form ID\"></a></p>\n\n<p>There are 3 ways you can view the gravity form ID</p>\n\n<ol>\n<li><p>Via inspect element - when you are viewing the page were the gravity form is embedded. Right click on the form and choose Inspect element.</p></li>\n<li><p>When you are editing a specific form. It's on top highlighted with color orange.</p></li>\n<li><p>When you are viewing all the forms. A columns names such as ID, ENTRIES, VIEWS.</p></li>\n</ol>\n"
}
]
| 2018/07/26 | [
"https://wordpress.stackexchange.com/questions/309647",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145214/"
]
| I want to add a filter to a form submission
[like it is done here](https://gravitywp.com/capitalize-fields-in-gravity-forms/).
```
add_action('gform_pre_submission_6', 'capitalize_fields_6');
function capitalize_fields_6($form){
// Code here
}
```
My question is, how do you get the form ID on the WP admin side? Where is the number 6 coming from to access the form in the action? | If you look at the list of Forms (Forms > Forms) in the back end there's a column that tells you the ID. You can also get it from the top of the screen when editing a form. Next to the form's Title there's an orange box that says "ID: 6". |
309,652 | <p>I'm trying to cutomise the TinyMce editor within WordPress and I took this code from an older WP site I did, but the buttons I have set don't seem to be working, for example, this is what I have:</p>
<pre><code>add_filter( 'tiny_mce_before_init', 'blm_format_tiny_mce' );
function blm_format_tiny_mce( $in ) {
$in['remove_linebreaks'] = true;
$in['convert_newlines_to_brs'] = false;
$in['keep_styles'] = true;
$in['tabfocus_elements'] = 'major-publishing-actions';
$in['paste_remove_styles'] = false;
$in['paste_remove_spans'] = true;
$in['paste_strip_class_attributes'] = 'mso';
$in['paste_text_linebreaktype'] = 'combined';
$in['plugins'] = 'tabfocus,paste,media,fullscreen,wordpress,wpeditimage,wpgallery,wplink,wpdialogs';
$in['theme_advanced_buttons1'] = 'formatselect,forecolor,|,bold,italic,underline,|,bullist,numlist,blockquote,|,justifyleft,justifycenter,justifyright,justifyfull,|,link,unlink,|,wp_adv';
$in['theme_advanced_buttons2'] = 'pastetext,pasteword,selectall,removeformat,|,charmap,|,outdent,indent,|,undo,redo';
$in['theme_advanced_buttons3'] = '';
$in['theme_advanced_buttons4'] = '';
//$in['valid_children'] = '+div[p]';
return $in;
}
</code></pre>
<p>Now, even though I have <code>bullist,numlist</code> listed, I don't see them on the editor; however I see <code>strikethrough</code> even though it's not listed.</p>
<p>The only two other ones missing are <code>horizontal line</code> and <code>special character</code>; on top of that they don't show up in the order I put them, the order seems somewhat random.</p>
<p>I'm happy to just not set the buttons, as with this site it's ok if everything is available, but I thought I needed to use it to insert the plugin buttons such as <code>pastetext,pasteword,selectall</code>?</p>
<p>What am I doing wrong here?</p>
| [
{
"answer_id": 309648,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>If you look at the list of Forms (Forms > Forms) in the back end there's a column that tells you the ID. You can also get it from the top of the screen when editing a form. Next to the form's Title there's an orange box that says \"ID: 6\".</p>\n"
},
{
"answer_id": 309672,
"author": "Tony Logarta",
"author_id": 106116,
"author_profile": "https://wordpress.stackexchange.com/users/106116",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://i.stack.imgur.com/cLzyc.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/cLzyc.jpg\" alt=\"3 ways you get view gravity form ID\"></a></p>\n\n<p>There are 3 ways you can view the gravity form ID</p>\n\n<ol>\n<li><p>Via inspect element - when you are viewing the page were the gravity form is embedded. Right click on the form and choose Inspect element.</p></li>\n<li><p>When you are editing a specific form. It's on top highlighted with color orange.</p></li>\n<li><p>When you are viewing all the forms. A columns names such as ID, ENTRIES, VIEWS.</p></li>\n</ol>\n"
}
]
| 2018/07/26 | [
"https://wordpress.stackexchange.com/questions/309652",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1839/"
]
| I'm trying to cutomise the TinyMce editor within WordPress and I took this code from an older WP site I did, but the buttons I have set don't seem to be working, for example, this is what I have:
```
add_filter( 'tiny_mce_before_init', 'blm_format_tiny_mce' );
function blm_format_tiny_mce( $in ) {
$in['remove_linebreaks'] = true;
$in['convert_newlines_to_brs'] = false;
$in['keep_styles'] = true;
$in['tabfocus_elements'] = 'major-publishing-actions';
$in['paste_remove_styles'] = false;
$in['paste_remove_spans'] = true;
$in['paste_strip_class_attributes'] = 'mso';
$in['paste_text_linebreaktype'] = 'combined';
$in['plugins'] = 'tabfocus,paste,media,fullscreen,wordpress,wpeditimage,wpgallery,wplink,wpdialogs';
$in['theme_advanced_buttons1'] = 'formatselect,forecolor,|,bold,italic,underline,|,bullist,numlist,blockquote,|,justifyleft,justifycenter,justifyright,justifyfull,|,link,unlink,|,wp_adv';
$in['theme_advanced_buttons2'] = 'pastetext,pasteword,selectall,removeformat,|,charmap,|,outdent,indent,|,undo,redo';
$in['theme_advanced_buttons3'] = '';
$in['theme_advanced_buttons4'] = '';
//$in['valid_children'] = '+div[p]';
return $in;
}
```
Now, even though I have `bullist,numlist` listed, I don't see them on the editor; however I see `strikethrough` even though it's not listed.
The only two other ones missing are `horizontal line` and `special character`; on top of that they don't show up in the order I put them, the order seems somewhat random.
I'm happy to just not set the buttons, as with this site it's ok if everything is available, but I thought I needed to use it to insert the plugin buttons such as `pastetext,pasteword,selectall`?
What am I doing wrong here? | If you look at the list of Forms (Forms > Forms) in the back end there's a column that tells you the ID. You can also get it from the top of the screen when editing a form. Next to the form's Title there's an orange box that says "ID: 6". |
309,670 | <p>When I add a new WP_Query, everything works, but if I add a 'tax_query' with a taxonomy, it doesn't pull the posts. post_count would always be 0.</p>
<pre><code> $products = new WP_Query([
'post_type' => 'post',
'tax_query' => [
[
'taxonomy' => 'show_product_on_only_premium',
'field' => 'slug',
'terms' => 'yes',
'operator' => 'AND',
]
]
]);
echo var_dump($products);
</code></pre>
<p>I've played with the tax_query with different values and I've had no luck.
This works on production but not locally and I can't figure out why.
edit> my database has the taxonomy </p>
<p>Please help! Thank you in advance!</p>
| [
{
"answer_id": 309669,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<p>Such a link does exist and is already in the admin menu:</p>\n\n<p><a href=\"https://i.stack.imgur.com/lSXwd.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lSXwd.png\" alt=\"enter image description here\"></a></p>\n\n<p>And again, in the admin toolbar:</p>\n\n<p><a href=\"https://i.stack.imgur.com/o1WKe.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/o1WKe.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 309679,
"author": "Quang Hoang",
"author_id": 134874,
"author_profile": "https://wordpress.stackexchange.com/users/134874",
"pm_score": 2,
"selected": false,
"text": "<p>You can use this function <code><?php get_edit_user_link( $user_id ) ?></code> </p>\n\n<p>Read more: <a href=\"https://codex.wordpress.org/Function_Reference/get_edit_user_link\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/get_edit_user_link</a></p>\n\n<p>Best regards,</p>\n"
}
]
| 2018/07/26 | [
"https://wordpress.stackexchange.com/questions/309670",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147639/"
]
| When I add a new WP\_Query, everything works, but if I add a 'tax\_query' with a taxonomy, it doesn't pull the posts. post\_count would always be 0.
```
$products = new WP_Query([
'post_type' => 'post',
'tax_query' => [
[
'taxonomy' => 'show_product_on_only_premium',
'field' => 'slug',
'terms' => 'yes',
'operator' => 'AND',
]
]
]);
echo var_dump($products);
```
I've played with the tax\_query with different values and I've had no luck.
This works on production but not locally and I can't figure out why.
edit> my database has the taxonomy
Please help! Thank you in advance! | You can use this function `<?php get_edit_user_link( $user_id ) ?>`
Read more: <https://codex.wordpress.org/Function_Reference/get_edit_user_link>
Best regards, |
309,697 | <p>I've created a custom post type & taxonomy, however when I go to my taxonomy page it throws a 404 error and I can't understand why.</p>
<pre><code>// Register Custom Post Type
function portfolio_post_type() {
register_taxonomy_for_object_type('category','portfolio');
register_post_type( 'portfolio',
array(
'labels' => array(
'name' => __('Portfolio'),
'singular_name' => __('Portfolio'),
'add_new' => __('Add new item'),
'add_new_item' => __('Add new item'),
'edit' => __('Edit'),
'edit_item' => __('Edit item'),
'new_item' => __('New item'),
'view' => __('View item'),
'view_item' => __('View item'),
'search_items' => __('Search portfolio'),
'not_found' => __('No portfolio items found'),
'not_found_in_trash' => __('No portfolio items found in trash'),
),
'public' => true,
'rewrite' => array('slug' => 'portfolio'),
'publicly_queryable' => true,
'hierarchical' => false,
'has_archive' => true,
'menu_icon' => 'dashicons-art',
'supports' => array('title', 'editor', 'excerpt', 'thumbnail', 'revisions','author'),
'can_export' => true,
'taxonomies' => array('portfolio-category'),
)
);
}
add_action( 'init', 'portfolio_post_type', 0 );
function portfolio_create_taxonomy() {
register_taxonomy(
'portfolio-category',
'portfolio',
array(
'label' => __( 'Category' ),
'rewrite' => array( 'slug' => 'category' ),
'hierarchical' => true,
)
);
}
add_action( 'init', 'portfolio_create_taxonomy' );
</code></pre>
<p>When I click to view a taxonomy it takes me to <code>http://domain.local/category/all/</code></p>
<p>However it throws the 404 page template.</p>
| [
{
"answer_id": 309669,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<p>Such a link does exist and is already in the admin menu:</p>\n\n<p><a href=\"https://i.stack.imgur.com/lSXwd.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lSXwd.png\" alt=\"enter image description here\"></a></p>\n\n<p>And again, in the admin toolbar:</p>\n\n<p><a href=\"https://i.stack.imgur.com/o1WKe.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/o1WKe.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 309679,
"author": "Quang Hoang",
"author_id": 134874,
"author_profile": "https://wordpress.stackexchange.com/users/134874",
"pm_score": 2,
"selected": false,
"text": "<p>You can use this function <code><?php get_edit_user_link( $user_id ) ?></code> </p>\n\n<p>Read more: <a href=\"https://codex.wordpress.org/Function_Reference/get_edit_user_link\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/get_edit_user_link</a></p>\n\n<p>Best regards,</p>\n"
}
]
| 2018/07/27 | [
"https://wordpress.stackexchange.com/questions/309697",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115473/"
]
| I've created a custom post type & taxonomy, however when I go to my taxonomy page it throws a 404 error and I can't understand why.
```
// Register Custom Post Type
function portfolio_post_type() {
register_taxonomy_for_object_type('category','portfolio');
register_post_type( 'portfolio',
array(
'labels' => array(
'name' => __('Portfolio'),
'singular_name' => __('Portfolio'),
'add_new' => __('Add new item'),
'add_new_item' => __('Add new item'),
'edit' => __('Edit'),
'edit_item' => __('Edit item'),
'new_item' => __('New item'),
'view' => __('View item'),
'view_item' => __('View item'),
'search_items' => __('Search portfolio'),
'not_found' => __('No portfolio items found'),
'not_found_in_trash' => __('No portfolio items found in trash'),
),
'public' => true,
'rewrite' => array('slug' => 'portfolio'),
'publicly_queryable' => true,
'hierarchical' => false,
'has_archive' => true,
'menu_icon' => 'dashicons-art',
'supports' => array('title', 'editor', 'excerpt', 'thumbnail', 'revisions','author'),
'can_export' => true,
'taxonomies' => array('portfolio-category'),
)
);
}
add_action( 'init', 'portfolio_post_type', 0 );
function portfolio_create_taxonomy() {
register_taxonomy(
'portfolio-category',
'portfolio',
array(
'label' => __( 'Category' ),
'rewrite' => array( 'slug' => 'category' ),
'hierarchical' => true,
)
);
}
add_action( 'init', 'portfolio_create_taxonomy' );
```
When I click to view a taxonomy it takes me to `http://domain.local/category/all/`
However it throws the 404 page template. | You can use this function `<?php get_edit_user_link( $user_id ) ?>`
Read more: <https://codex.wordpress.org/Function_Reference/get_edit_user_link>
Best regards, |
309,700 | <p>Each field of the default Woocommerce form checkout has this markup: </p>
<pre><code><p class="form-row form-row-first validate-required" id="billing_first_name_field" data-priority="10">
<label for="billing_first_name" class="">Name&nbsp;
<abbr class="required" title="required">*</abbr>
</label>
<span class="woocommerce-input-wrapper">
<input type="text" class="input-text " name="billing_first_name" id="billing_first_name" placeholder="" value="" autocomplete="given-name">
</span>
</p>
</code></pre>
<p>Now, I want:</p>
<ol>
<li>Wrap each field in a wrapper like <code><div class="single-field-wrapper"><p [...] </div></code></li>
<li>Wrap the first two fields, 'billing_first_name' and 'billing_last_name' in a wrapper like <code><div class="first-and-second-field-wrapper"> [...] </div></code></li>
</ol>
<p>To achieve this, I've tried to use the filter hooks made available by <code>function woocommerce_form_field( $key, $args, $value = null )</code> called in <code>form-billing.php</code> template in this way:</p>
<pre><code><?php
$fields = $checkout->get_checkout_fields( 'billing' );
foreach ( $fields as $key => $field ) {
if ( isset( $field['country_field'], $fields[ $field['country_field'] ] ) ) {
$field['country'] = $checkout->get_value( $field['country_field'] );
}
woocommerce_form_field( $key, $field, $checkout->get_value( $key ) );
}
?>
</code></pre>
<p>So in <code>functions.php</code> I wrote:</p>
<pre><code>function change_woocommerce_field_markup($field, $key, $args, $value){
$field = '<div class="single-field-wrapper">'.$field.'</div>';
if($key === 'billing_first_name') {
$field = '<div class="first-and-second-field-wrapper">'.$field;
}
else if ($key === 'billing_last_name') {
$field = $field.'</div>';
}
else {
$field = $field;
}
return $field;
}
add_filter("woocommerce_form_field","change_woocommerce_field_markup", 10, 4);
</code></pre>
<p>Unexpectedly, I get this markup:</p>
<pre><code><div class="first-and-second-field-wrapper">
<div class="single-field-wrapper">
<div class="single-field-wrapper">
[here there are all the fields, one under the other ]
</div>
<div class="single-field-wrapper"></div>
<div class="single-field-wrapper"></div>
<div class="single-field-wrapper"></div>
<div class="single-field-wrapper"></div>
<div class="single-field-wrapper"></div>
<div class="single-field-wrapper"></div>
<div class="single-field-wrapper"></div>
<div class="single-field-wrapper"></div>
</div>
</code></pre>
<p>Anyone can explain why this unexpected behavior?</p>
| [
{
"answer_id": 309788,
"author": "nmr",
"author_id": 147428,
"author_profile": "https://wordpress.stackexchange.com/users/147428",
"pm_score": 4,
"selected": true,
"text": "<p>There is no hook <code>woocommerce_form_field</code>, there is hook <code>woocommerce_form_field_{$args[type]}</code> <a href=\"https://docs.woocommerce.com/wc-apidocs/hook-docs.html\" rel=\"noreferrer\">(doc)</a>. </p>\n\n<p><code>$args[type]</code> can be (look <a href=\"https://docs.woocommerce.com/wc-apidocs/source-function-woocommerce_form_field.html#2147\" rel=\"noreferrer\">here</a> for available options):</p>\n\n<ul>\n<li>text, </li>\n<li>checkbox, </li>\n<li>country, </li>\n<li>...</li>\n</ul>\n\n<p>Code below will wrap '<em>billing_first_name</em>' and '<em>billing_last_name</em>' fields in a wrapper like <code><div class=\"first-and-second-field-wrapper\"> [...] </div></code>. </p>\n\n<pre><code>function change_woocommerce_field_markup($field, $key, $args, $value) {\n\n $field = '<div class=\"single-field-wrapper\">'.$field.'</div>';\n\n if($key === 'billing_first_name')\n $field = '<div class=\"first-and-second-field-wrapper\">'.$field;\n else if ($key === 'billing_last_name')\n $field = $field.'</div>';\n\n return $field;\n} \n\nadd_filter(\"woocommerce_form_field_text\",\"change_woocommerce_field_markup\", 10, 4);\n</code></pre>\n\n<p>It will also wrap <code>text</code> type fields with <code><div class=\"single-field-wrapper\">...</div></code>.<br>\n<strong>BUT</strong><br>\nsome text fields that have own type (like state or email) require additional hooks, for example: </p>\n\n<pre><code>add_filter(\"woocommerce_form_field_country\",\"change_woocommerce_field_markup\", 10, 4);\nadd_filter(\"woocommerce_form_field_email\",\"change_woocommerce_field_markup\", 10, 4);\n</code></pre>\n\n<hr>\n\n<p><strong>UPDATE #1</strong> </p>\n\n<p>Above code works in WC-v3.3.7.</p>\n\n<p>In WC-v3.4.xx you get this:</p>\n\n<pre><code><div class=\"first-and-second-field-wrapper\">\n <div class=\"single-field-wrapper\">\n <div class=\"single-field-wrapper\">\n [here there are all the fields, one under the other ]\n </div>\n <div class=\"single-field-wrapper\"></div> \n <div class=\"single-field-wrapper\"></div> \n <div class=\"single-field-wrapper\"></div> \n ....\n <div class=\"single-field-wrapper\"></div>\n</div>\n</code></pre>\n\n<p>because javascript sorts form rows inside <code>.woocommerce-billing-fields__field-wrapper</code>. Look at the file <code>woocommerce/assets/js/frontend/address-i18n.js</code>, from line 99.<br>\nJS finds all HTML tags with \".form-row\" class inside wrapper, takes parent of <strong>first</strong> item (tag with class <code>.form-row</code>), sort items by priority and insert them into <strong>previously selected parent element</strong>. </p>\n\n<p>For the test, change in file <code>address-i18.js</code>, in line 99<br>\n <code>var fieldsets = $('.woocommerce-billing-fields__field-wrapper, ...</code><br>\nto<br>\n <code>var fieldsets = $('.woocommerce-billing-fields__field-wrapper2, ...</code><br>\nand upload as <code>address-i18.min.js</code>. </p>\n\n<p><strong>Removing JS sorting is not a solution, it is just a test.</strong> Whithout sorting by JS you will get this:</p>\n\n<pre><code><div class=\"first-and-second-field-wrapper\">\n <div class=\"single-field-wrapper\">\n <p class=\"form-row ...\" id=\"billing_first_name_field\"> <label for=\"billing_first_name\"> ... </p>\n </div>\n <div class=\"single-field-wrapper\">\n <p class=\"form-row ...\" id=\"billing_last_name_field\"> <label for=\"billing_last_name\">... </p>\n </div>\n</div>\n<div class=\"single-field-wrapper\">\n <p class=\"form-row ...\" id=\"billing_company_field\"> <label for=\"billing_company\">... </p>\n</div>\n</code></pre>\n"
},
{
"answer_id": 338984,
"author": "indextwo",
"author_id": 17826,
"author_profile": "https://wordpress.stackexchange.com/users/17826",
"pm_score": 1,
"selected": false,
"text": "<p>I just ran into the exact same issue that I hadn't spotted before. I originally opened <a href=\"https://github.com/woocommerce/woocommerce/issues/7501\" rel=\"nofollow noreferrer\">this ticket on the WC GitHub</a> back in 2015, so it's great that they added the filter... but the JS-based reshuffling is a pain. However, <a href=\"https://wordpress.stackexchange.com/a/309788/17826\">nmr's answer</a> pointed me in the right direction:</p>\n\n<p>As the JS reshuffle works on the <code>.form-row</code> element, you just need to a) remove it from the field you want to wrap, and b) add it to your own new field wrapper:</p>\n\n<pre><code>function change_woocommerce_field_markup( $field, $key, $args, $value ) {\n\n // Remove the .form-row class from the current field wrapper\n\n $field = str_replace('form-row', '', $field);\n\n // Wrap the field (and its wrapper) in a new custom div, adding .form-row so the reshuffling works as expected, and adding the field priority\n\n $field = '<div class=\"form-row single-field-wrapper\" data-priority=\"' . $args['priority'] . '\">' . $field . '</div>';\n\n return $field;\n}\n\nadd_filter( 'woocommerce_form_field', 'change_woocommerce_field_markup', 10, 4 );\n</code></pre>\n"
}
]
| 2018/07/27 | [
"https://wordpress.stackexchange.com/questions/309700",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/100514/"
]
| Each field of the default Woocommerce form checkout has this markup:
```
<p class="form-row form-row-first validate-required" id="billing_first_name_field" data-priority="10">
<label for="billing_first_name" class="">Name
<abbr class="required" title="required">*</abbr>
</label>
<span class="woocommerce-input-wrapper">
<input type="text" class="input-text " name="billing_first_name" id="billing_first_name" placeholder="" value="" autocomplete="given-name">
</span>
</p>
```
Now, I want:
1. Wrap each field in a wrapper like `<div class="single-field-wrapper"><p [...] </div>`
2. Wrap the first two fields, 'billing\_first\_name' and 'billing\_last\_name' in a wrapper like `<div class="first-and-second-field-wrapper"> [...] </div>`
To achieve this, I've tried to use the filter hooks made available by `function woocommerce_form_field( $key, $args, $value = null )` called in `form-billing.php` template in this way:
```
<?php
$fields = $checkout->get_checkout_fields( 'billing' );
foreach ( $fields as $key => $field ) {
if ( isset( $field['country_field'], $fields[ $field['country_field'] ] ) ) {
$field['country'] = $checkout->get_value( $field['country_field'] );
}
woocommerce_form_field( $key, $field, $checkout->get_value( $key ) );
}
?>
```
So in `functions.php` I wrote:
```
function change_woocommerce_field_markup($field, $key, $args, $value){
$field = '<div class="single-field-wrapper">'.$field.'</div>';
if($key === 'billing_first_name') {
$field = '<div class="first-and-second-field-wrapper">'.$field;
}
else if ($key === 'billing_last_name') {
$field = $field.'</div>';
}
else {
$field = $field;
}
return $field;
}
add_filter("woocommerce_form_field","change_woocommerce_field_markup", 10, 4);
```
Unexpectedly, I get this markup:
```
<div class="first-and-second-field-wrapper">
<div class="single-field-wrapper">
<div class="single-field-wrapper">
[here there are all the fields, one under the other ]
</div>
<div class="single-field-wrapper"></div>
<div class="single-field-wrapper"></div>
<div class="single-field-wrapper"></div>
<div class="single-field-wrapper"></div>
<div class="single-field-wrapper"></div>
<div class="single-field-wrapper"></div>
<div class="single-field-wrapper"></div>
<div class="single-field-wrapper"></div>
</div>
```
Anyone can explain why this unexpected behavior? | There is no hook `woocommerce_form_field`, there is hook `woocommerce_form_field_{$args[type]}` [(doc)](https://docs.woocommerce.com/wc-apidocs/hook-docs.html).
`$args[type]` can be (look [here](https://docs.woocommerce.com/wc-apidocs/source-function-woocommerce_form_field.html#2147) for available options):
* text,
* checkbox,
* country,
* ...
Code below will wrap '*billing\_first\_name*' and '*billing\_last\_name*' fields in a wrapper like `<div class="first-and-second-field-wrapper"> [...] </div>`.
```
function change_woocommerce_field_markup($field, $key, $args, $value) {
$field = '<div class="single-field-wrapper">'.$field.'</div>';
if($key === 'billing_first_name')
$field = '<div class="first-and-second-field-wrapper">'.$field;
else if ($key === 'billing_last_name')
$field = $field.'</div>';
return $field;
}
add_filter("woocommerce_form_field_text","change_woocommerce_field_markup", 10, 4);
```
It will also wrap `text` type fields with `<div class="single-field-wrapper">...</div>`.
**BUT**
some text fields that have own type (like state or email) require additional hooks, for example:
```
add_filter("woocommerce_form_field_country","change_woocommerce_field_markup", 10, 4);
add_filter("woocommerce_form_field_email","change_woocommerce_field_markup", 10, 4);
```
---
**UPDATE #1**
Above code works in WC-v3.3.7.
In WC-v3.4.xx you get this:
```
<div class="first-and-second-field-wrapper">
<div class="single-field-wrapper">
<div class="single-field-wrapper">
[here there are all the fields, one under the other ]
</div>
<div class="single-field-wrapper"></div>
<div class="single-field-wrapper"></div>
<div class="single-field-wrapper"></div>
....
<div class="single-field-wrapper"></div>
</div>
```
because javascript sorts form rows inside `.woocommerce-billing-fields__field-wrapper`. Look at the file `woocommerce/assets/js/frontend/address-i18n.js`, from line 99.
JS finds all HTML tags with ".form-row" class inside wrapper, takes parent of **first** item (tag with class `.form-row`), sort items by priority and insert them into **previously selected parent element**.
For the test, change in file `address-i18.js`, in line 99
`var fieldsets = $('.woocommerce-billing-fields__field-wrapper, ...`
to
`var fieldsets = $('.woocommerce-billing-fields__field-wrapper2, ...`
and upload as `address-i18.min.js`.
**Removing JS sorting is not a solution, it is just a test.** Whithout sorting by JS you will get this:
```
<div class="first-and-second-field-wrapper">
<div class="single-field-wrapper">
<p class="form-row ..." id="billing_first_name_field"> <label for="billing_first_name"> ... </p>
</div>
<div class="single-field-wrapper">
<p class="form-row ..." id="billing_last_name_field"> <label for="billing_last_name">... </p>
</div>
</div>
<div class="single-field-wrapper">
<p class="form-row ..." id="billing_company_field"> <label for="billing_company">... </p>
</div>
``` |
309,706 | <p>I have moved my wordpress from one hosting to other but it gives database error </p>
<pre><code>Warning: mysqli_real_connect(): (28000/1045): Access denied for user 'user'@'localhost' (using password: YES) in /home/########/public_html/fvas/wp-includes/wp-db.php on line 1531
</code></pre>
<p>I have change the database name in wp-config.php and user and password too but its always giving this error what should i try?</p>
| [
{
"answer_id": 309788,
"author": "nmr",
"author_id": 147428,
"author_profile": "https://wordpress.stackexchange.com/users/147428",
"pm_score": 4,
"selected": true,
"text": "<p>There is no hook <code>woocommerce_form_field</code>, there is hook <code>woocommerce_form_field_{$args[type]}</code> <a href=\"https://docs.woocommerce.com/wc-apidocs/hook-docs.html\" rel=\"noreferrer\">(doc)</a>. </p>\n\n<p><code>$args[type]</code> can be (look <a href=\"https://docs.woocommerce.com/wc-apidocs/source-function-woocommerce_form_field.html#2147\" rel=\"noreferrer\">here</a> for available options):</p>\n\n<ul>\n<li>text, </li>\n<li>checkbox, </li>\n<li>country, </li>\n<li>...</li>\n</ul>\n\n<p>Code below will wrap '<em>billing_first_name</em>' and '<em>billing_last_name</em>' fields in a wrapper like <code><div class=\"first-and-second-field-wrapper\"> [...] </div></code>. </p>\n\n<pre><code>function change_woocommerce_field_markup($field, $key, $args, $value) {\n\n $field = '<div class=\"single-field-wrapper\">'.$field.'</div>';\n\n if($key === 'billing_first_name')\n $field = '<div class=\"first-and-second-field-wrapper\">'.$field;\n else if ($key === 'billing_last_name')\n $field = $field.'</div>';\n\n return $field;\n} \n\nadd_filter(\"woocommerce_form_field_text\",\"change_woocommerce_field_markup\", 10, 4);\n</code></pre>\n\n<p>It will also wrap <code>text</code> type fields with <code><div class=\"single-field-wrapper\">...</div></code>.<br>\n<strong>BUT</strong><br>\nsome text fields that have own type (like state or email) require additional hooks, for example: </p>\n\n<pre><code>add_filter(\"woocommerce_form_field_country\",\"change_woocommerce_field_markup\", 10, 4);\nadd_filter(\"woocommerce_form_field_email\",\"change_woocommerce_field_markup\", 10, 4);\n</code></pre>\n\n<hr>\n\n<p><strong>UPDATE #1</strong> </p>\n\n<p>Above code works in WC-v3.3.7.</p>\n\n<p>In WC-v3.4.xx you get this:</p>\n\n<pre><code><div class=\"first-and-second-field-wrapper\">\n <div class=\"single-field-wrapper\">\n <div class=\"single-field-wrapper\">\n [here there are all the fields, one under the other ]\n </div>\n <div class=\"single-field-wrapper\"></div> \n <div class=\"single-field-wrapper\"></div> \n <div class=\"single-field-wrapper\"></div> \n ....\n <div class=\"single-field-wrapper\"></div>\n</div>\n</code></pre>\n\n<p>because javascript sorts form rows inside <code>.woocommerce-billing-fields__field-wrapper</code>. Look at the file <code>woocommerce/assets/js/frontend/address-i18n.js</code>, from line 99.<br>\nJS finds all HTML tags with \".form-row\" class inside wrapper, takes parent of <strong>first</strong> item (tag with class <code>.form-row</code>), sort items by priority and insert them into <strong>previously selected parent element</strong>. </p>\n\n<p>For the test, change in file <code>address-i18.js</code>, in line 99<br>\n <code>var fieldsets = $('.woocommerce-billing-fields__field-wrapper, ...</code><br>\nto<br>\n <code>var fieldsets = $('.woocommerce-billing-fields__field-wrapper2, ...</code><br>\nand upload as <code>address-i18.min.js</code>. </p>\n\n<p><strong>Removing JS sorting is not a solution, it is just a test.</strong> Whithout sorting by JS you will get this:</p>\n\n<pre><code><div class=\"first-and-second-field-wrapper\">\n <div class=\"single-field-wrapper\">\n <p class=\"form-row ...\" id=\"billing_first_name_field\"> <label for=\"billing_first_name\"> ... </p>\n </div>\n <div class=\"single-field-wrapper\">\n <p class=\"form-row ...\" id=\"billing_last_name_field\"> <label for=\"billing_last_name\">... </p>\n </div>\n</div>\n<div class=\"single-field-wrapper\">\n <p class=\"form-row ...\" id=\"billing_company_field\"> <label for=\"billing_company\">... </p>\n</div>\n</code></pre>\n"
},
{
"answer_id": 338984,
"author": "indextwo",
"author_id": 17826,
"author_profile": "https://wordpress.stackexchange.com/users/17826",
"pm_score": 1,
"selected": false,
"text": "<p>I just ran into the exact same issue that I hadn't spotted before. I originally opened <a href=\"https://github.com/woocommerce/woocommerce/issues/7501\" rel=\"nofollow noreferrer\">this ticket on the WC GitHub</a> back in 2015, so it's great that they added the filter... but the JS-based reshuffling is a pain. However, <a href=\"https://wordpress.stackexchange.com/a/309788/17826\">nmr's answer</a> pointed me in the right direction:</p>\n\n<p>As the JS reshuffle works on the <code>.form-row</code> element, you just need to a) remove it from the field you want to wrap, and b) add it to your own new field wrapper:</p>\n\n<pre><code>function change_woocommerce_field_markup( $field, $key, $args, $value ) {\n\n // Remove the .form-row class from the current field wrapper\n\n $field = str_replace('form-row', '', $field);\n\n // Wrap the field (and its wrapper) in a new custom div, adding .form-row so the reshuffling works as expected, and adding the field priority\n\n $field = '<div class=\"form-row single-field-wrapper\" data-priority=\"' . $args['priority'] . '\">' . $field . '</div>';\n\n return $field;\n}\n\nadd_filter( 'woocommerce_form_field', 'change_woocommerce_field_markup', 10, 4 );\n</code></pre>\n"
}
]
| 2018/07/27 | [
"https://wordpress.stackexchange.com/questions/309706",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140035/"
]
| I have moved my wordpress from one hosting to other but it gives database error
```
Warning: mysqli_real_connect(): (28000/1045): Access denied for user 'user'@'localhost' (using password: YES) in /home/########/public_html/fvas/wp-includes/wp-db.php on line 1531
```
I have change the database name in wp-config.php and user and password too but its always giving this error what should i try? | There is no hook `woocommerce_form_field`, there is hook `woocommerce_form_field_{$args[type]}` [(doc)](https://docs.woocommerce.com/wc-apidocs/hook-docs.html).
`$args[type]` can be (look [here](https://docs.woocommerce.com/wc-apidocs/source-function-woocommerce_form_field.html#2147) for available options):
* text,
* checkbox,
* country,
* ...
Code below will wrap '*billing\_first\_name*' and '*billing\_last\_name*' fields in a wrapper like `<div class="first-and-second-field-wrapper"> [...] </div>`.
```
function change_woocommerce_field_markup($field, $key, $args, $value) {
$field = '<div class="single-field-wrapper">'.$field.'</div>';
if($key === 'billing_first_name')
$field = '<div class="first-and-second-field-wrapper">'.$field;
else if ($key === 'billing_last_name')
$field = $field.'</div>';
return $field;
}
add_filter("woocommerce_form_field_text","change_woocommerce_field_markup", 10, 4);
```
It will also wrap `text` type fields with `<div class="single-field-wrapper">...</div>`.
**BUT**
some text fields that have own type (like state or email) require additional hooks, for example:
```
add_filter("woocommerce_form_field_country","change_woocommerce_field_markup", 10, 4);
add_filter("woocommerce_form_field_email","change_woocommerce_field_markup", 10, 4);
```
---
**UPDATE #1**
Above code works in WC-v3.3.7.
In WC-v3.4.xx you get this:
```
<div class="first-and-second-field-wrapper">
<div class="single-field-wrapper">
<div class="single-field-wrapper">
[here there are all the fields, one under the other ]
</div>
<div class="single-field-wrapper"></div>
<div class="single-field-wrapper"></div>
<div class="single-field-wrapper"></div>
....
<div class="single-field-wrapper"></div>
</div>
```
because javascript sorts form rows inside `.woocommerce-billing-fields__field-wrapper`. Look at the file `woocommerce/assets/js/frontend/address-i18n.js`, from line 99.
JS finds all HTML tags with ".form-row" class inside wrapper, takes parent of **first** item (tag with class `.form-row`), sort items by priority and insert them into **previously selected parent element**.
For the test, change in file `address-i18.js`, in line 99
`var fieldsets = $('.woocommerce-billing-fields__field-wrapper, ...`
to
`var fieldsets = $('.woocommerce-billing-fields__field-wrapper2, ...`
and upload as `address-i18.min.js`.
**Removing JS sorting is not a solution, it is just a test.** Whithout sorting by JS you will get this:
```
<div class="first-and-second-field-wrapper">
<div class="single-field-wrapper">
<p class="form-row ..." id="billing_first_name_field"> <label for="billing_first_name"> ... </p>
</div>
<div class="single-field-wrapper">
<p class="form-row ..." id="billing_last_name_field"> <label for="billing_last_name">... </p>
</div>
</div>
<div class="single-field-wrapper">
<p class="form-row ..." id="billing_company_field"> <label for="billing_company">... </p>
</div>
``` |
309,727 | <p>Here is the code which gives me only day and month.</p>
<p>I want to show all: year, month, day, hour and minutes.</p>
<p>How can I do this?</p>
<pre><code>print '<time class="entry-date updated" datetime="' . esc_attr( get_the_date( 'c' ) ) . '">' . esc_html( the_date('F j, Y','G:i')) . '</time>';
</code></pre>
| [
{
"answer_id": 309728,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 2,
"selected": false,
"text": "<h2>PHP Date Format in WordPress function:</h2>\n\n<p>You'll have to use the proper <a href=\"http://www.php.net/manual/en/function.date.php\" rel=\"nofollow noreferrer\"><code>date format string</code></a> (as used in PHP <code>date</code> function) in the WordPress <a href=\"https://developer.wordpress.org/reference/functions/get_the_date/\" rel=\"nofollow noreferrer\"><code>get_the_date()</code></a> function's first parameter.</p>\n\n<p>For example, to get the Date & Time in the format like <code>2018-07-23 23:59</code> (i.e. YYYY-MM-DD HH:MM, where hour is in 24 hour format), you need CODE like:</p>\n\n<pre><code>get_the_date('Y-m-d H:i');\n</code></pre>\n\n<p>Or, to get the Date & Time in the format like <code>23-07-2018 11:59 PM</code> (i.e. YYYY-MM-DD HH:MM AM/PM, where hour is in 12 hour format with AM or PM), you need CODE like:</p>\n\n<pre><code>get_the_date('d-m-Y h:i A');\n</code></pre>\n\n<p>So your full example CODE will be:</p>\n\n<pre><code>print '<time class=\"entry-date updated\" datetime=\"' . esc_attr( get_the_date( 'c' ) ) . '\">' . esc_html( get_the_date( 'd-m-Y h:i A' ) ) . '</time>';\n</code></pre>\n\n<h2>Mistakes in your CODE:</h2>\n\n<p>The <strong><em>idea</em></strong> in your CODE is not entirely wrong, only the CODE has two mistakes:</p>\n\n<ol>\n<li><p>You've used the <code>the_date</code> function, instead of <code>get_the_date</code> function. The way you've concatenated the string, <code>the_date</code> will not work as it prints the date immediately, doesn't return as the <code>get_the_date</code> function does.</p></li>\n<li><p>You've used <code>'F j, Y', 'G:i'</code> as two parameters, where as, it should be just one parameter: <code>'F j, Y G:i'</code>. </p></li>\n</ol>\n\n<p>So if you correct these two mistakes, the proper CODE will be:</p>\n\n<pre><code>print '<time class=\"entry-date updated\" datetime=\"' . esc_attr( get_the_date( 'c' ) ) . '\">' . esc_html( get_the_date( 'F j, Y G:i' ) ) . '</time>';\n</code></pre>\n\n<hr>\n\n<h2>Further Reading:</h2>\n\n<p>There are many other possibilities and all are in the <code>Date Format</code> string as described in <a href=\"http://www.php.net/manual/en/function.date.php\" rel=\"nofollow noreferrer\">PHP <code>date</code> function documentation</a>. There are some useful examples in <a href=\"https://codex.wordpress.org/Formatting_Date_and_Time\" rel=\"nofollow noreferrer\">WordPress Codex</a> as well.</p>\n"
},
{
"answer_id": 309729,
"author": "nmr",
"author_id": 147428,
"author_profile": "https://wordpress.stackexchange.com/users/147428",
"pm_score": 1,
"selected": false,
"text": "<p>Change this part <code>the_date('F j, Y','G:i')</code> to <code>get_the_date('F j, Y G:i')</code>.</p>\n\n<p><a href=\"https://codex.wordpress.org/Formatting_Date_and_Time\" rel=\"nofollow noreferrer\">WP - Formatting Date</a></p>\n"
}
]
| 2018/07/27 | [
"https://wordpress.stackexchange.com/questions/309727",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147675/"
]
| Here is the code which gives me only day and month.
I want to show all: year, month, day, hour and minutes.
How can I do this?
```
print '<time class="entry-date updated" datetime="' . esc_attr( get_the_date( 'c' ) ) . '">' . esc_html( the_date('F j, Y','G:i')) . '</time>';
``` | PHP Date Format in WordPress function:
--------------------------------------
You'll have to use the proper [`date format string`](http://www.php.net/manual/en/function.date.php) (as used in PHP `date` function) in the WordPress [`get_the_date()`](https://developer.wordpress.org/reference/functions/get_the_date/) function's first parameter.
For example, to get the Date & Time in the format like `2018-07-23 23:59` (i.e. YYYY-MM-DD HH:MM, where hour is in 24 hour format), you need CODE like:
```
get_the_date('Y-m-d H:i');
```
Or, to get the Date & Time in the format like `23-07-2018 11:59 PM` (i.e. YYYY-MM-DD HH:MM AM/PM, where hour is in 12 hour format with AM or PM), you need CODE like:
```
get_the_date('d-m-Y h:i A');
```
So your full example CODE will be:
```
print '<time class="entry-date updated" datetime="' . esc_attr( get_the_date( 'c' ) ) . '">' . esc_html( get_the_date( 'd-m-Y h:i A' ) ) . '</time>';
```
Mistakes in your CODE:
----------------------
The ***idea*** in your CODE is not entirely wrong, only the CODE has two mistakes:
1. You've used the `the_date` function, instead of `get_the_date` function. The way you've concatenated the string, `the_date` will not work as it prints the date immediately, doesn't return as the `get_the_date` function does.
2. You've used `'F j, Y', 'G:i'` as two parameters, where as, it should be just one parameter: `'F j, Y G:i'`.
So if you correct these two mistakes, the proper CODE will be:
```
print '<time class="entry-date updated" datetime="' . esc_attr( get_the_date( 'c' ) ) . '">' . esc_html( get_the_date( 'F j, Y G:i' ) ) . '</time>';
```
---
Further Reading:
----------------
There are many other possibilities and all are in the `Date Format` string as described in [PHP `date` function documentation](http://www.php.net/manual/en/function.date.php). There are some useful examples in [WordPress Codex](https://codex.wordpress.org/Formatting_Date_and_Time) as well. |
309,735 | <p>I have created a WP loop to display Services from 'Services' Custom Post Type: </p>
<p><strong>Here is the code:</strong></p>
<pre><code><?php
$services_loop = new WP_Query( array( 'post_type' => 'service', 'posts_per_page' => -1 ) );
if ( $services_loop->have_posts() ) :
while ( $services_loop->have_posts() ) : $services_loop->the_post(); ?>
<section class="single-service">
<div class="container">
<div class="row">
<div class="col-md-6">
<?php the_post_thumbnail('full', array('class' => 'img-fluid w-100', 'alt' => get_the_title(), 'title' => get_the_title())); ?>
</div>
<div class="col-md-6">
<h3><?php the_title(); ?></h3>
<?php the_content(); ?></div>
</div>
</div>
</div>
</section>
<?php endwhile;
endif;
wp_reset_postdata();
?>
</code></pre>
<p>It display the list of services. But what I want is, I want to have a custom section within middle of the loop and I am not finding any solution for this. Here I will visualize my problem. </p>
<p><a href="https://i.stack.imgur.com/DXbw5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DXbw5.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 309728,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 2,
"selected": false,
"text": "<h2>PHP Date Format in WordPress function:</h2>\n\n<p>You'll have to use the proper <a href=\"http://www.php.net/manual/en/function.date.php\" rel=\"nofollow noreferrer\"><code>date format string</code></a> (as used in PHP <code>date</code> function) in the WordPress <a href=\"https://developer.wordpress.org/reference/functions/get_the_date/\" rel=\"nofollow noreferrer\"><code>get_the_date()</code></a> function's first parameter.</p>\n\n<p>For example, to get the Date & Time in the format like <code>2018-07-23 23:59</code> (i.e. YYYY-MM-DD HH:MM, where hour is in 24 hour format), you need CODE like:</p>\n\n<pre><code>get_the_date('Y-m-d H:i');\n</code></pre>\n\n<p>Or, to get the Date & Time in the format like <code>23-07-2018 11:59 PM</code> (i.e. YYYY-MM-DD HH:MM AM/PM, where hour is in 12 hour format with AM or PM), you need CODE like:</p>\n\n<pre><code>get_the_date('d-m-Y h:i A');\n</code></pre>\n\n<p>So your full example CODE will be:</p>\n\n<pre><code>print '<time class=\"entry-date updated\" datetime=\"' . esc_attr( get_the_date( 'c' ) ) . '\">' . esc_html( get_the_date( 'd-m-Y h:i A' ) ) . '</time>';\n</code></pre>\n\n<h2>Mistakes in your CODE:</h2>\n\n<p>The <strong><em>idea</em></strong> in your CODE is not entirely wrong, only the CODE has two mistakes:</p>\n\n<ol>\n<li><p>You've used the <code>the_date</code> function, instead of <code>get_the_date</code> function. The way you've concatenated the string, <code>the_date</code> will not work as it prints the date immediately, doesn't return as the <code>get_the_date</code> function does.</p></li>\n<li><p>You've used <code>'F j, Y', 'G:i'</code> as two parameters, where as, it should be just one parameter: <code>'F j, Y G:i'</code>. </p></li>\n</ol>\n\n<p>So if you correct these two mistakes, the proper CODE will be:</p>\n\n<pre><code>print '<time class=\"entry-date updated\" datetime=\"' . esc_attr( get_the_date( 'c' ) ) . '\">' . esc_html( get_the_date( 'F j, Y G:i' ) ) . '</time>';\n</code></pre>\n\n<hr>\n\n<h2>Further Reading:</h2>\n\n<p>There are many other possibilities and all are in the <code>Date Format</code> string as described in <a href=\"http://www.php.net/manual/en/function.date.php\" rel=\"nofollow noreferrer\">PHP <code>date</code> function documentation</a>. There are some useful examples in <a href=\"https://codex.wordpress.org/Formatting_Date_and_Time\" rel=\"nofollow noreferrer\">WordPress Codex</a> as well.</p>\n"
},
{
"answer_id": 309729,
"author": "nmr",
"author_id": 147428,
"author_profile": "https://wordpress.stackexchange.com/users/147428",
"pm_score": 1,
"selected": false,
"text": "<p>Change this part <code>the_date('F j, Y','G:i')</code> to <code>get_the_date('F j, Y G:i')</code>.</p>\n\n<p><a href=\"https://codex.wordpress.org/Formatting_Date_and_Time\" rel=\"nofollow noreferrer\">WP - Formatting Date</a></p>\n"
}
]
| 2018/07/27 | [
"https://wordpress.stackexchange.com/questions/309735",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/137372/"
]
| I have created a WP loop to display Services from 'Services' Custom Post Type:
**Here is the code:**
```
<?php
$services_loop = new WP_Query( array( 'post_type' => 'service', 'posts_per_page' => -1 ) );
if ( $services_loop->have_posts() ) :
while ( $services_loop->have_posts() ) : $services_loop->the_post(); ?>
<section class="single-service">
<div class="container">
<div class="row">
<div class="col-md-6">
<?php the_post_thumbnail('full', array('class' => 'img-fluid w-100', 'alt' => get_the_title(), 'title' => get_the_title())); ?>
</div>
<div class="col-md-6">
<h3><?php the_title(); ?></h3>
<?php the_content(); ?></div>
</div>
</div>
</div>
</section>
<?php endwhile;
endif;
wp_reset_postdata();
?>
```
It display the list of services. But what I want is, I want to have a custom section within middle of the loop and I am not finding any solution for this. Here I will visualize my problem.
[](https://i.stack.imgur.com/DXbw5.png) | PHP Date Format in WordPress function:
--------------------------------------
You'll have to use the proper [`date format string`](http://www.php.net/manual/en/function.date.php) (as used in PHP `date` function) in the WordPress [`get_the_date()`](https://developer.wordpress.org/reference/functions/get_the_date/) function's first parameter.
For example, to get the Date & Time in the format like `2018-07-23 23:59` (i.e. YYYY-MM-DD HH:MM, where hour is in 24 hour format), you need CODE like:
```
get_the_date('Y-m-d H:i');
```
Or, to get the Date & Time in the format like `23-07-2018 11:59 PM` (i.e. YYYY-MM-DD HH:MM AM/PM, where hour is in 12 hour format with AM or PM), you need CODE like:
```
get_the_date('d-m-Y h:i A');
```
So your full example CODE will be:
```
print '<time class="entry-date updated" datetime="' . esc_attr( get_the_date( 'c' ) ) . '">' . esc_html( get_the_date( 'd-m-Y h:i A' ) ) . '</time>';
```
Mistakes in your CODE:
----------------------
The ***idea*** in your CODE is not entirely wrong, only the CODE has two mistakes:
1. You've used the `the_date` function, instead of `get_the_date` function. The way you've concatenated the string, `the_date` will not work as it prints the date immediately, doesn't return as the `get_the_date` function does.
2. You've used `'F j, Y', 'G:i'` as two parameters, where as, it should be just one parameter: `'F j, Y G:i'`.
So if you correct these two mistakes, the proper CODE will be:
```
print '<time class="entry-date updated" datetime="' . esc_attr( get_the_date( 'c' ) ) . '">' . esc_html( get_the_date( 'F j, Y G:i' ) ) . '</time>';
```
---
Further Reading:
----------------
There are many other possibilities and all are in the `Date Format` string as described in [PHP `date` function documentation](http://www.php.net/manual/en/function.date.php). There are some useful examples in [WordPress Codex](https://codex.wordpress.org/Formatting_Date_and_Time) as well. |
309,736 | <p>I have a div and inside I wish display by random a post from category-a or a product from category-b. I'm looking for a query to do that.</p>
<p>I tried this: </p>
<pre><code> <?php
$args = array(
'post_type' => array('product', 'post'),
'posts_per_page' => 1,
'cat' => 1,2,
'orderby' => 'RAND'
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?>
<article class="promo">
<div class="image">
<?php if (is_singular('product')){
echo 'Product';
}else{
echo 'Post';
}?>
</div>
</article>
<?php endwhile; ?>
</code></pre>
<p>Someone knows how to do that ?
thank you :)</p>
<p><strong>EDIT CODE</strong> </p>
<pre><code> <?php
$args = [
'post_type' => ['product','post'],
'posts_per_page' => -1,
'fields' => 'ids',
'post_type' => ['product','post'],
'posts_per_page' => 2,
'fields' => 'ids',
'tax_query' => [
'relation' => 'OR',
'taxonomy' => 'category',
'field' => 'slug',
'terms' => ['promo-distributeur', 'actu-distrib'],
'include_children' => false,
]
]
];
$posts_ids = get_posts($args);
$total = count($posts_ids);
if ($total > 0) {
$rnd = mt_rand(0, $total);
$pid = $posts_ids[$rnd];
$post = get_post( $pid);
while ( $post->have_posts() ) : $post>the_post(); global $product; ?>
<article class="promo">
<div class="image">
<?php if (is_singular('product')){
echo 'Product';
}else{
echo 'Post';
}?>
</div>
</article>
<?php endwhile;
} ?>
</code></pre>
| [
{
"answer_id": 309747,
"author": "Andrea Somovigo",
"author_id": 64435,
"author_profile": "https://wordpress.stackexchange.com/users/64435",
"pm_score": -1,
"selected": false,
"text": "<p>you don't need global $product, and is_singular() is a template function, not usable in the loop, also if you pick only 1 post your orderby rand will not work since the subset of records is always the same 1 element</p>\n\n<pre><code><div class=\"image\">\n <?php \n if ($post->post_type=='product'){\n echo 'Product';\n }\n else{\n echo 'Post';\n }?>\n </div> \n</code></pre>\n"
},
{
"answer_id": 309770,
"author": "nmr",
"author_id": 147428,
"author_profile": "https://wordpress.stackexchange.com/users/147428",
"pm_score": 1,
"selected": false,
"text": "<p>The following code selects IDs of all posts type <code>product</code> and <code>post</code>, which belong to terms <code>category-a</code> or <code>category-b</code>, with <code>taxonomy_01</code> and <code>taxonomy_02</code>, respectively.</p>\n\n<pre><code>$args = [\n 'post_type' => ['product','post'],\n 'posts_per_page' => -1,\n 'fields' => 'ids',\n 'tax_query' => [\n 'relation' => 'OR',\n [\n 'taxonomy' => 'taxonomy_01',\n 'field' => 'slug',\n 'terms' => 'category-a',\n 'include_children' => false,\n ],\n [\n 'taxonomy' => 'taxonomy_02',\n 'field' => 'slug',\n 'terms' => 'category-b',\n // OR by id\n //'field' => 'term_id', // default value\n //'terms' => 2,\n 'include_children' => false,\n ],\n ]\n];\n$posts_ids = get_posts($args); \n$total = count($posts_ids);\nif ($total > 0) { \n $rnd = mt_rand(0, $total - 1);\n $pid = $posts_ids[$rnd];\n $my_post = get_post( $pid);\n // display post\n}\n</code></pre>\n\n<p>I assume that the terms <code>category-a</code>, <code>category-b</code> belongs to different taxonomies. If not, then the <code>tax_query</code> should be:</p>\n\n<pre><code>'tax_query' => [\n [\n 'taxonomy' => 'taxonomy_01',\n 'field' => 'slug',\n 'terms' => ['category-a', 'category-b'],\n 'include_children' => false,\n ],\n]\n</code></pre>\n\n<p><strong>UPDATE</strong><br>\nI changed variable in the above code from <code>$post</code> to <code>my_post</code>. Your code: </p>\n\n<pre><code>$args = [\n 'post_type' => ['product','post'],\n 'posts_per_page' => -1,\n 'fields' => 'ids',\n 'tax_query' => [\n 'relation' => 'OR',\n [\n 'taxonomy' => 'taxonomy_01',\n 'field' => 'slug',\n 'terms' => 'category-a',\n 'include_children' => false,\n ],\n [\n 'taxonomy' => 'taxonomy_02',\n 'field' => 'slug',\n 'terms' => 'category-b',\n // OR by id\n //'field' => 'term_id', // default value\n //'terms' => 2,\n 'include_children' => false,\n ],\n ]\n];\n$posts_ids = get_posts($args); \n$total = count($posts_ids);\nif ($total > 0) {\n // get random post_ID \n $rnd = mt_rand(0, $total - 1);\n $pid = $posts_ids[$rnd];\n $my_post = get_post( $pid);\n\n // display post\n if ( !empty($my_post) ) : ?>\n\n <article class=\"promo\"> \n <div class=\"image\">\n <?php \n if ( $my_post->post_type == 'product' )\n echo 'Product';\n else\n echo 'Post';\n ?>\n </div> \n </article>\n <?php endif;\n}\n</code></pre>\n"
}
]
| 2018/07/27 | [
"https://wordpress.stackexchange.com/questions/309736",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/141407/"
]
| I have a div and inside I wish display by random a post from category-a or a product from category-b. I'm looking for a query to do that.
I tried this:
```
<?php
$args = array(
'post_type' => array('product', 'post'),
'posts_per_page' => 1,
'cat' => 1,2,
'orderby' => 'RAND'
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?>
<article class="promo">
<div class="image">
<?php if (is_singular('product')){
echo 'Product';
}else{
echo 'Post';
}?>
</div>
</article>
<?php endwhile; ?>
```
Someone knows how to do that ?
thank you :)
**EDIT CODE**
```
<?php
$args = [
'post_type' => ['product','post'],
'posts_per_page' => -1,
'fields' => 'ids',
'post_type' => ['product','post'],
'posts_per_page' => 2,
'fields' => 'ids',
'tax_query' => [
'relation' => 'OR',
'taxonomy' => 'category',
'field' => 'slug',
'terms' => ['promo-distributeur', 'actu-distrib'],
'include_children' => false,
]
]
];
$posts_ids = get_posts($args);
$total = count($posts_ids);
if ($total > 0) {
$rnd = mt_rand(0, $total);
$pid = $posts_ids[$rnd];
$post = get_post( $pid);
while ( $post->have_posts() ) : $post>the_post(); global $product; ?>
<article class="promo">
<div class="image">
<?php if (is_singular('product')){
echo 'Product';
}else{
echo 'Post';
}?>
</div>
</article>
<?php endwhile;
} ?>
``` | The following code selects IDs of all posts type `product` and `post`, which belong to terms `category-a` or `category-b`, with `taxonomy_01` and `taxonomy_02`, respectively.
```
$args = [
'post_type' => ['product','post'],
'posts_per_page' => -1,
'fields' => 'ids',
'tax_query' => [
'relation' => 'OR',
[
'taxonomy' => 'taxonomy_01',
'field' => 'slug',
'terms' => 'category-a',
'include_children' => false,
],
[
'taxonomy' => 'taxonomy_02',
'field' => 'slug',
'terms' => 'category-b',
// OR by id
//'field' => 'term_id', // default value
//'terms' => 2,
'include_children' => false,
],
]
];
$posts_ids = get_posts($args);
$total = count($posts_ids);
if ($total > 0) {
$rnd = mt_rand(0, $total - 1);
$pid = $posts_ids[$rnd];
$my_post = get_post( $pid);
// display post
}
```
I assume that the terms `category-a`, `category-b` belongs to different taxonomies. If not, then the `tax_query` should be:
```
'tax_query' => [
[
'taxonomy' => 'taxonomy_01',
'field' => 'slug',
'terms' => ['category-a', 'category-b'],
'include_children' => false,
],
]
```
**UPDATE**
I changed variable in the above code from `$post` to `my_post`. Your code:
```
$args = [
'post_type' => ['product','post'],
'posts_per_page' => -1,
'fields' => 'ids',
'tax_query' => [
'relation' => 'OR',
[
'taxonomy' => 'taxonomy_01',
'field' => 'slug',
'terms' => 'category-a',
'include_children' => false,
],
[
'taxonomy' => 'taxonomy_02',
'field' => 'slug',
'terms' => 'category-b',
// OR by id
//'field' => 'term_id', // default value
//'terms' => 2,
'include_children' => false,
],
]
];
$posts_ids = get_posts($args);
$total = count($posts_ids);
if ($total > 0) {
// get random post_ID
$rnd = mt_rand(0, $total - 1);
$pid = $posts_ids[$rnd];
$my_post = get_post( $pid);
// display post
if ( !empty($my_post) ) : ?>
<article class="promo">
<div class="image">
<?php
if ( $my_post->post_type == 'product' )
echo 'Product';
else
echo 'Post';
?>
</div>
</article>
<?php endif;
}
``` |
309,748 | <p>In my contact form I need a drop down for order quantities. On selection of "other", I want to display a number field for input. Below is my code but it's not working. Can anyone help? Thanks in advance.</p>
<pre><code><script language="javascript" type="text/javascript">
document.getElementById("OrderQuantity").addEventListener("change", displayNumberField);
function displayNumberField() {
var dropDownText = document.getElementById("OrderQuantity").value;
if (dropDownText == "Other") {
document.getElementById("EnterOtherQuantity").style.display = 'block';
} else {
document.getElementById("EnterOtherQuantity").style.display = 'none';
}
}
</script>
<label> Order Quantity
[select* drop-down-menu id=OrderQuantity "Select Quantity" "10" "20" "30" "40" "Other"] </label>
<label id="EnterOtherQuantity" style="display:none;"> Please Specify Your Order Quantity
[number other-order-quantity min:41] </label>
</code></pre>
| [
{
"answer_id": 309769,
"author": "Andrea Somovigo",
"author_id": 64435,
"author_profile": "https://wordpress.stackexchange.com/users/64435",
"pm_score": 0,
"selected": false,
"text": "<p>Note that <strong>[select* drop-down-menu id=\"OrderQuantity\"]</strong> CF7 shortcode will not output any id for the select, so you cannot use <em>document.getElementById</em> but you can rely on the name attribute:</p>\n\n<pre><code><label> Order Quantity\n[select* drop-down-menu id=OrderQuantity \"Select Quantity\" \"10\" \"20\" \"30\" \"40\" \"Other\"] </label>\n\n<label id=\"EnterOtherQuantity\" style=\"display:none;\"> Please Specify Your Order Quantity\n[number other-order-quantity min:41] </label>\n\n[submit \"Send\"]\n\n<script language=\"javascript\" type=\"text/javascript\">\ndocument.getElementsByName(\"drop-down-menu\")[0].addEventListener(\"change\", displayNumberField);\n\nfunction displayNumberField() {\n var dropDownText = document.getElementsByName(\"drop-down-menu\")[0].value;\n if (dropDownText == \"Other\") {\n document.getElementById(\"EnterOtherQuantity\").style.display = 'block';\n } else {\n document.getElementById(\"EnterOtherQuantity\").style.display = 'none';\n }\n}\n</script>\n</code></pre>\n"
},
{
"answer_id": 339547,
"author": "Thessa Verbruggen",
"author_id": 167092,
"author_profile": "https://wordpress.stackexchange.com/users/167092",
"pm_score": 2,
"selected": false,
"text": "<p>You can try this add-on to make conditional fields.\n<a href=\"https://nl.wordpress.org/plugins/cf7-conditional-fields/\" rel=\"nofollow noreferrer\">https://nl.wordpress.org/plugins/cf7-conditional-fields/</a></p>\n"
}
]
| 2018/07/27 | [
"https://wordpress.stackexchange.com/questions/309748",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147684/"
]
| In my contact form I need a drop down for order quantities. On selection of "other", I want to display a number field for input. Below is my code but it's not working. Can anyone help? Thanks in advance.
```
<script language="javascript" type="text/javascript">
document.getElementById("OrderQuantity").addEventListener("change", displayNumberField);
function displayNumberField() {
var dropDownText = document.getElementById("OrderQuantity").value;
if (dropDownText == "Other") {
document.getElementById("EnterOtherQuantity").style.display = 'block';
} else {
document.getElementById("EnterOtherQuantity").style.display = 'none';
}
}
</script>
<label> Order Quantity
[select* drop-down-menu id=OrderQuantity "Select Quantity" "10" "20" "30" "40" "Other"] </label>
<label id="EnterOtherQuantity" style="display:none;"> Please Specify Your Order Quantity
[number other-order-quantity min:41] </label>
``` | You can try this add-on to make conditional fields.
<https://nl.wordpress.org/plugins/cf7-conditional-fields/> |
309,754 | <p>With the latest version of WordPress, how can we publish revisions of a post, in addition to showing the latest post? </p>
<p>I want my front end users to see multiple versions of the same post. The same post is going to change "some" of its content every friday. All weekly versions will then be compared by non-administrators (ie managers and directors) at some point every month. </p>
<p>My goal is to make it as easy as possible for a public user to review revisions.</p>
<p>There doesn't appear to be a plugin concept for this. Can I modify the internal revisions tool to accomplish something like this?</p>
<p>Many thanks!</p>
| [
{
"answer_id": 309761,
"author": "Martin Jarvis",
"author_id": 147693,
"author_profile": "https://wordpress.stackexchange.com/users/147693",
"pm_score": 0,
"selected": false,
"text": "<p>That's an interesting idea. There are, of course, manual ways to do it - e.g. cloning the post, making your changes, giving it a new 'date related?' slug etc., but it sounds like you want something more automated. One thought is whether there are any A/B (or A/B/C/D) split testing plugins (or theme options - Divi?) that allow you to do what you wanted.</p>\n\n<p>One other thought - how about putting the main post content into a tab element, and then copying / pasting / editing the changed content into a new tab at the end of each week? Then, your default post open view would be for the current content, and the user would be able to click on the tabs to view previous week content.</p>\n\n<p>You'll need to take care with this sort of thing if you have any SEO ambitions, as you will end up with a lot of duplicated content across your site.</p>\n"
},
{
"answer_id": 309771,
"author": "Ideatron",
"author_id": 132928,
"author_profile": "https://wordpress.stackexchange.com/users/132928",
"pm_score": 2,
"selected": true,
"text": "<p><strong>I suggest you look at</strong> <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_post_revisions\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_get_post_revisions</a></p>\n\n<pre><code><?php\n // Lets get the revisions of the given $post we are accessing by ID ( you are probably going to want to limit your internal revision count for this\n\n $revisions = wp_get_post_revisions($post->ID);\n // lets just do some formatting here ( your post html content is going to display normally but lets get the var_dump to look decent\n echo '<pre>';\n // print the $revisions variable to look at the internals\n var_dump($revisions);\n echo '</pre>';\n\n // from here i would dig into iterating over the revisions array.\n ?>\n</code></pre>\n\n<p>using the above code inside your loop should get your started to see what kind of data you can return from wp_get_post_revisions(). You are going to need to do some searching on the post_date portion or look at the array key and sort by the integer and push to a custom array where key matches count() to return only the most recent post revision. This query will be huge so i sincerely suggest you limit your wordpress installs revision count.</p>\n"
}
]
| 2018/07/27 | [
"https://wordpress.stackexchange.com/questions/309754",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98671/"
]
| With the latest version of WordPress, how can we publish revisions of a post, in addition to showing the latest post?
I want my front end users to see multiple versions of the same post. The same post is going to change "some" of its content every friday. All weekly versions will then be compared by non-administrators (ie managers and directors) at some point every month.
My goal is to make it as easy as possible for a public user to review revisions.
There doesn't appear to be a plugin concept for this. Can I modify the internal revisions tool to accomplish something like this?
Many thanks! | **I suggest you look at** <https://codex.wordpress.org/Function_Reference/wp_get_post_revisions>
```
<?php
// Lets get the revisions of the given $post we are accessing by ID ( you are probably going to want to limit your internal revision count for this
$revisions = wp_get_post_revisions($post->ID);
// lets just do some formatting here ( your post html content is going to display normally but lets get the var_dump to look decent
echo '<pre>';
// print the $revisions variable to look at the internals
var_dump($revisions);
echo '</pre>';
// from here i would dig into iterating over the revisions array.
?>
```
using the above code inside your loop should get your started to see what kind of data you can return from wp\_get\_post\_revisions(). You are going to need to do some searching on the post\_date portion or look at the array key and sort by the integer and push to a custom array where key matches count() to return only the most recent post revision. This query will be huge so i sincerely suggest you limit your wordpress installs revision count. |
309,780 | <p>I'm having a problem with a custom function. This function counts the post and assigns a number to that post. It then saves the number to a custom field and then updates the permalink to the post.</p>
<p>My problems are:</p>
<p>1). When a post is saved, it saves a post twice (Shows up as 2 revisions). I'm trying to find a way so that it saves it once.</p>
<p>2). I'm also trying to find a way for the function to work only once. I'm noticing that previous posts are getting edited and while they are staying the same, they do show up with lots of revisions. For example: If I have 5 posts, the first post will show up with 10 revisions.</p>
<p>Here's my code:</p>
<pre><code>// opens a function
function updateNumbers( $post_id ){
// sets global
global $pagenow;
// if current page is a new post and in the post CPT
if ($pagenow == 'post.php' && 'post' == get_post_type()) {
// counts all posts
global $wpdb;
$querystr = "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE
$wpdb->posts.post_status = 'publish' AND $wpdb->posts.post_type = 'post' ";
$pageposts = $wpdb->get_results($querystr, OBJECT);
$counts = 0 ;
if ($pageposts):
foreach ($pageposts as $post):
$counts++;
// saves the number to a custom field
add_post_meta($post->ID, 'incr_number', $counts, true);
remove_action('save_post', 'updateNumbers');
wp_update_post(array('ID' => $post->ID,'post_name' => get_post_meta($post->ID,'incr_number', true)));
endforeach;
endif;
}}
// close the function and save
add_action('save_post', 'updateNumbers');
</code></pre>
| [
{
"answer_id": 309786,
"author": "Andrius Vlasovas",
"author_id": 147625,
"author_profile": "https://wordpress.stackexchange.com/users/147625",
"pm_score": 2,
"selected": false,
"text": "<p>Always lean back on WordPress Codex.</p>\n\n<p>In this case, you are using 'save_post' action hook, thus we can consult the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/save_post\" rel=\"nofollow noreferrer\">WordPress Codex</a> and <a href=\"https://developer.wordpress.org/reference/hooks/save_post/\" rel=\"nofollow noreferrer\">WordPress Code Reference</a> pages.</p>\n\n<p>Just by checking these links, we can see that this action have 3 arguments which can be used in the function: $post_ID, $post, $update.</p>\n\n<p>In order to use the last argument <code>$update</code> for example, we have to set <code>$accepted_args</code> parameter in the <code>'save_post'</code> hook. This is the last digit so to say, in the action that you are declaring and modified action would look like this:\nadd_action('save_post', 'updateNumbers', 10, 3);</p>\n\n<p>Now we also see the digit \"10\" just before the last one - this is the priority that decides when will your action be fired.</p>\n\n<p>So if we would like to fire our action earlier, we would modify our action:\nadd_action('save_post', 'updateNumbers', 5, 3);</p>\n\n<p>Looking at your function, there are many ways you could improve it. While the corer of your question is clear, there are a few ways that you could go about optimizing the function. Because currently, you are:</p>\n\n<ol>\n<li><p>Executing an action that is triggered whenever a post is saved or updated (that's good);</p></li>\n<li><p>In your function, you get all posts in the database (seems somewhat okay);</p></li>\n<li><p>You check whether there are any posts in the database with an <code>if ($pageposts):</code> (In some scenarios could be skipped, but let's keep it);</p></li>\n<li><p>Then you perform bellow actions for each post, that you found in database (yes, not just this one, but for each, so basically, when you are updating single post, you are actually updating all of the posts from your query and that's why you are getting multiple revisions generated for other posts as well - this is quite bad as you also expressed that you do not want that):</p></li>\n<li><p>You are updating your custom field with current <code>$count</code> value.</p></li>\n<li><p>You are removing your hooked function by removing <code>'save_post'</code> action, which is great since you are calling <code>'wp_update_post'</code> function that also would call <code>'save_post'</code>, and if you didn't remove your hooked function, it would result in infinite loop. However, you forgot to re-hook it after calling <code>'wp_update_post'</code>.</p></li>\n<li><p>You are updating post slug with the value of custom meta field.</p></li>\n</ol>\n\n<p>You should clarify a few things:</p>\n\n<ul>\n<li><p>Are you re-using <code>'incr_number'</code> custom field anywhere else or is it just to update the slug? If you are not using this custom field anywhere else, then you should get rid of it. Having in mind, that this custom meta field is exactly as your post slug, you should just get rid of it anyway and replace with the value of post slug wherever you need it. That is if you do not intend to change slugs after you initially set them to a number.</p></li>\n<li><p>I see comment:</p>\n\n<p>// if current page is a new post and in the post CPT</p></li>\n</ul>\n\n<p>Is your intention to update permalink only when the post is new? Then I wouldn't say your implementation is optimal for doing so. Actually, this is where you would use the third argument <code>$update</code> that this action offers.</p>\n\n<p>This is how I would modify your function (however due to lack of information and without clear goal of your action, this may not be final).</p>\n\n<pre><code>// Update permalink of newly created Post\nadd_action('save_post', 'theme_save_post_number_to_slug', 12, 3);\n\nfunction theme_save_post_number_to_slug($post_id, $post, $update) {\n\n $post_type = get_post_type($post_id);\n\n // terminate early if post type is not 'post' and if we are updating post object and not creating it.\n if ( \"post\" != $post_type && !$update )\n return;\n\n global $wpdb;\n $count = 0 ;\n\n // Fetches all posts with status 'publish' from the database\n $querystr = \"SELECT $wpdb->posts.* FROM $wpdb->posts WHERE\n $wpdb->posts.post_status = 'publish' AND $wpdb->posts.post_type = 'post' \";\n $dbPosts = $wpdb->get_results($querystr, OBJECT);\n\n if ($dbPosts) {\n foreach ($dbPosts as $p):\n $count++;\n\n // saves the number to a custom field\n add_post_meta($p->ID, 'incr_number', $count, true);\n\n remove_action('save_post', 'theme_save_post_number_to_slug', 12, 3);\n wp_update_post(array('ID' => $p->ID, 'post_name' => get_post_meta($p->ID, 'incr_number', true)));\n add_action('save_post', 'theme_save_post_number_to_slug', 12, 3);\n\n endforeach;\n }\n\n}\n</code></pre>\n\n<p>The function is still not perfect as I do not know what do you want to achieve, plus I want you to figure it out completely (that's how we grow as a developer).</p>\n\n<p>Honestly, there are quite a few quirks that could be sorted out with a detailed explanation. You could even ask that yourself and then consult WordPress Codex.</p>\n\n<p>I hope that I at least steered you to right way.</p>\n"
},
{
"answer_id": 309787,
"author": "Hồ Trọng Linh Ân",
"author_id": 141631,
"author_profile": "https://wordpress.stackexchange.com/users/141631",
"pm_score": 3,
"selected": true,
"text": "<p>It duplicate because when you run the <code>wp_update_post()</code>, it will use the <code>wp_insert_post()</code> function and the action <code>save_post</code> will run again.</p>\n\n<p>please use the filter <code>wp_insert_post_data</code> to filter the value before save. <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_insert_post_data\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_insert_post_data</a></p>\n\n<p>Example:</p>\n\n<pre><code>function wpse309780_filter_post_data($data , $postarr) {\n $data['post_name'] = wp_count_posts( 'post' )->publish;\n return $data;\n}\n\nadd_filter( 'wp_insert_post_data', 'wpse309780_filter_post_data' );\n</code></pre>\n"
}
]
| 2018/07/28 | [
"https://wordpress.stackexchange.com/questions/309780",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/8049/"
]
| I'm having a problem with a custom function. This function counts the post and assigns a number to that post. It then saves the number to a custom field and then updates the permalink to the post.
My problems are:
1). When a post is saved, it saves a post twice (Shows up as 2 revisions). I'm trying to find a way so that it saves it once.
2). I'm also trying to find a way for the function to work only once. I'm noticing that previous posts are getting edited and while they are staying the same, they do show up with lots of revisions. For example: If I have 5 posts, the first post will show up with 10 revisions.
Here's my code:
```
// opens a function
function updateNumbers( $post_id ){
// sets global
global $pagenow;
// if current page is a new post and in the post CPT
if ($pagenow == 'post.php' && 'post' == get_post_type()) {
// counts all posts
global $wpdb;
$querystr = "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE
$wpdb->posts.post_status = 'publish' AND $wpdb->posts.post_type = 'post' ";
$pageposts = $wpdb->get_results($querystr, OBJECT);
$counts = 0 ;
if ($pageposts):
foreach ($pageposts as $post):
$counts++;
// saves the number to a custom field
add_post_meta($post->ID, 'incr_number', $counts, true);
remove_action('save_post', 'updateNumbers');
wp_update_post(array('ID' => $post->ID,'post_name' => get_post_meta($post->ID,'incr_number', true)));
endforeach;
endif;
}}
// close the function and save
add_action('save_post', 'updateNumbers');
``` | It duplicate because when you run the `wp_update_post()`, it will use the `wp_insert_post()` function and the action `save_post` will run again.
please use the filter `wp_insert_post_data` to filter the value before save. <https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_insert_post_data>
Example:
```
function wpse309780_filter_post_data($data , $postarr) {
$data['post_name'] = wp_count_posts( 'post' )->publish;
return $data;
}
add_filter( 'wp_insert_post_data', 'wpse309780_filter_post_data' );
``` |
309,806 | <p>I'm trying to disable all functionality related to pingbacks/trackbacks in WordPress and so far I have this:</p>
<pre><code>add_action( 'pre_ping', 'disable_pingback' );
function disable_pingback( &$links ) {
foreach ( $links as $l => $link ) {
if ( 0 === strpos( $link, get_option( 'home' ) ) ) {
unset( $links[ $l ] );
}
}
}
</code></pre>
<p>However when I open up the page options and enable <em>discussion</em>, I still see this:</p>
<p><a href="https://i.stack.imgur.com/CLug6.png" rel="noreferrer"><img src="https://i.stack.imgur.com/CLug6.png" alt="enter image description here"></a></p>
<p>I found this <a href="https://wordpress.stackexchange.com/a/103511/1839">answer</a> (method 2), but it is over 5 years old now and I wasn't sure if totally replacing the whole section was the best way to do things compatibility wise, so I am asking again...</p>
<p>Is there a <em>cleaner</em> way to accomplish this?</p>
| [
{
"answer_id": 309809,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>Your code is correct, AFAIK. It will disable the ability to do trackback/pings. It doesn't remove that option from the screen, as you have noticed.</p>\n\n<p>Not sure how to test that, though. But your code should work to disable the actual process of allowing trackback/ping.</p>\n\n<p>This site <em>might</em> test trackback/pings <a href=\"https://tech.wizbangblog.com/ping.php\" rel=\"nofollow noreferrer\">https://tech.wizbangblog.com/ping.php</a> . No experience with it, so YMMV.</p>\n"
},
{
"answer_id": 310136,
"author": "Trilok",
"author_id": 145962,
"author_profile": "https://wordpress.stackexchange.com/users/145962",
"pm_score": -1,
"selected": false,
"text": "<blockquote>\n <p>Please put below code on your theme's <code>functions.php</code> file. I hope it will work for you</p>\n</blockquote>\n\n<pre><code>function hide_ping_track() { \n echo \"<style>.meta-options label[for=ping_status], #ping_status{display:none !important;}</style>\"; \n}\nadd_action('admin_head-post.php', 'hide_ping_track');\n</code></pre>\n"
},
{
"answer_id": 310406,
"author": "Ciprian",
"author_id": 7349,
"author_profile": "https://wordpress.stackexchange.com/users/7349",
"pm_score": -1,
"selected": false,
"text": "<p>Here's the WordPress recommended way of doing it:</p>\n\n<pre><code>function remove_post_custom_fields() {\n // Remove Discussion meta box\n remove_meta_box('commentstatusdiv', 'post', 'normal');\n\n // Remove Comments meta box\n remove_meta_box('commentsdiv', 'post', 'normal');\n}\nadd_action('admin_menu', 'remove_post_custom_fields');\n</code></pre>\n\n<p>Replace <code>post</code> with <code>page</code> or with another custom post type if needed.</p>\n\n<p>Relevant codex link:<br>\n<a href=\"https://codex.wordpress.org/Function_Reference/remove_meta_box\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/remove_meta_box</a></p>\n\n<p>Enjoy!</p>\n"
},
{
"answer_id": 310450,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>The way described in the answer you point to is the easier to understand way using PHP. I agree that from a code stability POV it sucks as you need to make sure that nothing else ever changes in that meta box.</p>\n\n<p>The other way to do it in php is to remove the core metabox, and create one of your own, in which you call the original one aand filter out the relevant output. It is still ugly, and you will have to write a long comment for it explaining the WHY of it, but it is more likely to remain stable than the first way.</p>\n\n<p>Using JS or CSS to hide that checkbox is likely to be a much more stable idea. You are still betting against the ID being changed, but this is probably much less likely to happen and produce a much easier to understand code.</p>\n"
},
{
"answer_id": 310625,
"author": "SHA3.org",
"author_id": 138460,
"author_profile": "https://wordpress.stackexchange.com/users/138460",
"pm_score": 2,
"selected": false,
"text": "<p>The WordPress Codex solutions weren't working for me regardless of what parameters I used or the priorities set, probably because my setup is pretty complex or as others have commented. The first chunk of code may work for you but I don't have a default environment at the moment to test. The second chunk of code definitely worked for me. The last chunk of code removes the option from the post's quick edit as well.</p>\n\n<p>You will still need to disable the functionality as you have done.</p>\n\n<p>Wordpress Codex solution, <em>(hooks into add_meta_boxes so it fires last, but you can use admin_menu or do_meta_boxes instead).</em>\nDocumentation <a href=\"https://codex.wordpress.org/Function_Reference/remove_meta_box\" rel=\"nofollow noreferrer\">Here</a></p>\n\n<pre><code>function remove_trackbacks_pingbacks() {\n\n remove_meta_box('trackbacksdiv', 'post', 'normal');\n\n}\nadd_action('add_meta_boxes', 'remove_trackbacks_pingbacks');\n</code></pre>\n\n<p>This may be overkill, but this is what actually worked for me. Note that it will remove the option in the box from displaying everywhere, including pages too. It also allows you to customize the HTML as well just in case you wanted to add a note to tell the user that Pingbacks and Trackbacks have been disabled. <em>(this may or may not suit your needs, but here it is anyway).</em> Documentation <a href=\"https://gist.github.com/eteubert/1327291\" rel=\"nofollow noreferrer\">Here</a></p>\n\n<pre><code> function remove_trackbacks_pingbacks ($post_type, $post) {\n\n global $wp_meta_boxes, $current_screen;\n\n # Remove \"ping_status\" from `commentstatusdiv`:\n $wp_meta_boxes[$current_screen->id]['normal']['core']['commentstatusdiv']['callback'] = function($post) {\n\n ?>\n <input name=\"advanced_view\" type=\"hidden\" value=\"1\">\n <p class=\"meta-options\">\n <label for=\"comment_status\" class=\"selectit\">\n <input id=\"comment_status\" name=\"comment_status\" type=\"checkbox\" value=\"open\" <?php checked($post->comment_status, 'open'); ?>> Allow comments?\n </label>\n <?php do_action('post_comment_status_meta_box-options', $post); ?>\n </p>\n <?php\n\n };\n\n}\n\nadd_action('add_meta_boxes', 'remove_trackbacks_pingbacks', 10, 2);\n</code></pre>\n\n<p>Lastly, since you want to remove the option from your edit screen, I assume you may want to remove from the quick edit screen as well. There are no hooks or classes to hook into that I know of, so a pure jQuery solution is in order. Insert into functions.php</p>\n\n<p>Modified from this solution <a href=\"https://wordpress.stackexchange.com/questions/59871/remove-specific-items-from-quick-edit-menu-of-a-custom-post-type\">Here</a></p>\n\n<pre><code> add_action( 'admin_head-edit.php', 'remove_pings_quickedit' );\n\nfunction remove_pings_quickedit() \n{ \n\n global $current_screen;\n if( 'edit-post' != $current_screen->id )\n return;\n ?>\n <script type=\"text/javascript\"> \n jQuery(document).ready( function($) { \n $('span:contains(\"Allow Pings\")').each(function (i) {\n $(this).remove();\n });\n $('input[name=ping_status]').each(function (i) {\n $(this).remove();\n });\n }); \n </script>\n <?php\n}\n</code></pre>\n"
}
]
| 2018/07/28 | [
"https://wordpress.stackexchange.com/questions/309806",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1839/"
]
| I'm trying to disable all functionality related to pingbacks/trackbacks in WordPress and so far I have this:
```
add_action( 'pre_ping', 'disable_pingback' );
function disable_pingback( &$links ) {
foreach ( $links as $l => $link ) {
if ( 0 === strpos( $link, get_option( 'home' ) ) ) {
unset( $links[ $l ] );
}
}
}
```
However when I open up the page options and enable *discussion*, I still see this:
[](https://i.stack.imgur.com/CLug6.png)
I found this [answer](https://wordpress.stackexchange.com/a/103511/1839) (method 2), but it is over 5 years old now and I wasn't sure if totally replacing the whole section was the best way to do things compatibility wise, so I am asking again...
Is there a *cleaner* way to accomplish this? | The WordPress Codex solutions weren't working for me regardless of what parameters I used or the priorities set, probably because my setup is pretty complex or as others have commented. The first chunk of code may work for you but I don't have a default environment at the moment to test. The second chunk of code definitely worked for me. The last chunk of code removes the option from the post's quick edit as well.
You will still need to disable the functionality as you have done.
Wordpress Codex solution, *(hooks into add\_meta\_boxes so it fires last, but you can use admin\_menu or do\_meta\_boxes instead).*
Documentation [Here](https://codex.wordpress.org/Function_Reference/remove_meta_box)
```
function remove_trackbacks_pingbacks() {
remove_meta_box('trackbacksdiv', 'post', 'normal');
}
add_action('add_meta_boxes', 'remove_trackbacks_pingbacks');
```
This may be overkill, but this is what actually worked for me. Note that it will remove the option in the box from displaying everywhere, including pages too. It also allows you to customize the HTML as well just in case you wanted to add a note to tell the user that Pingbacks and Trackbacks have been disabled. *(this may or may not suit your needs, but here it is anyway).* Documentation [Here](https://gist.github.com/eteubert/1327291)
```
function remove_trackbacks_pingbacks ($post_type, $post) {
global $wp_meta_boxes, $current_screen;
# Remove "ping_status" from `commentstatusdiv`:
$wp_meta_boxes[$current_screen->id]['normal']['core']['commentstatusdiv']['callback'] = function($post) {
?>
<input name="advanced_view" type="hidden" value="1">
<p class="meta-options">
<label for="comment_status" class="selectit">
<input id="comment_status" name="comment_status" type="checkbox" value="open" <?php checked($post->comment_status, 'open'); ?>> Allow comments?
</label>
<?php do_action('post_comment_status_meta_box-options', $post); ?>
</p>
<?php
};
}
add_action('add_meta_boxes', 'remove_trackbacks_pingbacks', 10, 2);
```
Lastly, since you want to remove the option from your edit screen, I assume you may want to remove from the quick edit screen as well. There are no hooks or classes to hook into that I know of, so a pure jQuery solution is in order. Insert into functions.php
Modified from this solution [Here](https://wordpress.stackexchange.com/questions/59871/remove-specific-items-from-quick-edit-menu-of-a-custom-post-type)
```
add_action( 'admin_head-edit.php', 'remove_pings_quickedit' );
function remove_pings_quickedit()
{
global $current_screen;
if( 'edit-post' != $current_screen->id )
return;
?>
<script type="text/javascript">
jQuery(document).ready( function($) {
$('span:contains("Allow Pings")').each(function (i) {
$(this).remove();
});
$('input[name=ping_status]').each(function (i) {
$(this).remove();
});
});
</script>
<?php
}
``` |
309,828 | <p>Question regarding template structure: </p>
<p>In a custom loop, I inserted a get_template_part('resources', 'layout') which contains the following markup:</p>
<pre><code><div class="custom-content">
<?php if ( get_post_type() === 'videos' ) { ?>
<div class="video-popup">
<?php the_field('video_popup'); ?>
</div>
<?php } else { ?>
<div class="featured-image">
<?php the_post_thumbnail('full'); ?>
<?php if ( get_post_type() === 'articles' ) { ?>
<p class="custom-content-btn">
<a href="<?php the_field( 'article_link' )?>" class="btn btn-primary" target="_blank"><?php echo __('READ'); ?></a>
</p>
<?php } ?>
</div>
<?php if ( get_post_type() === 'audio' ) { ?>
<div class="audio-content">
<?php the_field('audio_clip'); ?>
</div>
<?php } ?>
<?php } ?>
</div>
</code></pre>
<p>I have 3 CPT (videos, audio and articles). However I'm not sure if this is the best way to conditionally display the contents; seems a bit messy. I guess the tricky part is that there's some markup that appears for all CPT, that's sitting inbetween those conditional markups.</p>
<p>What would be considered the 'best practice' to tackle this? Appreciate any input!</p>
| [
{
"answer_id": 309809,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>Your code is correct, AFAIK. It will disable the ability to do trackback/pings. It doesn't remove that option from the screen, as you have noticed.</p>\n\n<p>Not sure how to test that, though. But your code should work to disable the actual process of allowing trackback/ping.</p>\n\n<p>This site <em>might</em> test trackback/pings <a href=\"https://tech.wizbangblog.com/ping.php\" rel=\"nofollow noreferrer\">https://tech.wizbangblog.com/ping.php</a> . No experience with it, so YMMV.</p>\n"
},
{
"answer_id": 310136,
"author": "Trilok",
"author_id": 145962,
"author_profile": "https://wordpress.stackexchange.com/users/145962",
"pm_score": -1,
"selected": false,
"text": "<blockquote>\n <p>Please put below code on your theme's <code>functions.php</code> file. I hope it will work for you</p>\n</blockquote>\n\n<pre><code>function hide_ping_track() { \n echo \"<style>.meta-options label[for=ping_status], #ping_status{display:none !important;}</style>\"; \n}\nadd_action('admin_head-post.php', 'hide_ping_track');\n</code></pre>\n"
},
{
"answer_id": 310406,
"author": "Ciprian",
"author_id": 7349,
"author_profile": "https://wordpress.stackexchange.com/users/7349",
"pm_score": -1,
"selected": false,
"text": "<p>Here's the WordPress recommended way of doing it:</p>\n\n<pre><code>function remove_post_custom_fields() {\n // Remove Discussion meta box\n remove_meta_box('commentstatusdiv', 'post', 'normal');\n\n // Remove Comments meta box\n remove_meta_box('commentsdiv', 'post', 'normal');\n}\nadd_action('admin_menu', 'remove_post_custom_fields');\n</code></pre>\n\n<p>Replace <code>post</code> with <code>page</code> or with another custom post type if needed.</p>\n\n<p>Relevant codex link:<br>\n<a href=\"https://codex.wordpress.org/Function_Reference/remove_meta_box\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/remove_meta_box</a></p>\n\n<p>Enjoy!</p>\n"
},
{
"answer_id": 310450,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>The way described in the answer you point to is the easier to understand way using PHP. I agree that from a code stability POV it sucks as you need to make sure that nothing else ever changes in that meta box.</p>\n\n<p>The other way to do it in php is to remove the core metabox, and create one of your own, in which you call the original one aand filter out the relevant output. It is still ugly, and you will have to write a long comment for it explaining the WHY of it, but it is more likely to remain stable than the first way.</p>\n\n<p>Using JS or CSS to hide that checkbox is likely to be a much more stable idea. You are still betting against the ID being changed, but this is probably much less likely to happen and produce a much easier to understand code.</p>\n"
},
{
"answer_id": 310625,
"author": "SHA3.org",
"author_id": 138460,
"author_profile": "https://wordpress.stackexchange.com/users/138460",
"pm_score": 2,
"selected": false,
"text": "<p>The WordPress Codex solutions weren't working for me regardless of what parameters I used or the priorities set, probably because my setup is pretty complex or as others have commented. The first chunk of code may work for you but I don't have a default environment at the moment to test. The second chunk of code definitely worked for me. The last chunk of code removes the option from the post's quick edit as well.</p>\n\n<p>You will still need to disable the functionality as you have done.</p>\n\n<p>Wordpress Codex solution, <em>(hooks into add_meta_boxes so it fires last, but you can use admin_menu or do_meta_boxes instead).</em>\nDocumentation <a href=\"https://codex.wordpress.org/Function_Reference/remove_meta_box\" rel=\"nofollow noreferrer\">Here</a></p>\n\n<pre><code>function remove_trackbacks_pingbacks() {\n\n remove_meta_box('trackbacksdiv', 'post', 'normal');\n\n}\nadd_action('add_meta_boxes', 'remove_trackbacks_pingbacks');\n</code></pre>\n\n<p>This may be overkill, but this is what actually worked for me. Note that it will remove the option in the box from displaying everywhere, including pages too. It also allows you to customize the HTML as well just in case you wanted to add a note to tell the user that Pingbacks and Trackbacks have been disabled. <em>(this may or may not suit your needs, but here it is anyway).</em> Documentation <a href=\"https://gist.github.com/eteubert/1327291\" rel=\"nofollow noreferrer\">Here</a></p>\n\n<pre><code> function remove_trackbacks_pingbacks ($post_type, $post) {\n\n global $wp_meta_boxes, $current_screen;\n\n # Remove \"ping_status\" from `commentstatusdiv`:\n $wp_meta_boxes[$current_screen->id]['normal']['core']['commentstatusdiv']['callback'] = function($post) {\n\n ?>\n <input name=\"advanced_view\" type=\"hidden\" value=\"1\">\n <p class=\"meta-options\">\n <label for=\"comment_status\" class=\"selectit\">\n <input id=\"comment_status\" name=\"comment_status\" type=\"checkbox\" value=\"open\" <?php checked($post->comment_status, 'open'); ?>> Allow comments?\n </label>\n <?php do_action('post_comment_status_meta_box-options', $post); ?>\n </p>\n <?php\n\n };\n\n}\n\nadd_action('add_meta_boxes', 'remove_trackbacks_pingbacks', 10, 2);\n</code></pre>\n\n<p>Lastly, since you want to remove the option from your edit screen, I assume you may want to remove from the quick edit screen as well. There are no hooks or classes to hook into that I know of, so a pure jQuery solution is in order. Insert into functions.php</p>\n\n<p>Modified from this solution <a href=\"https://wordpress.stackexchange.com/questions/59871/remove-specific-items-from-quick-edit-menu-of-a-custom-post-type\">Here</a></p>\n\n<pre><code> add_action( 'admin_head-edit.php', 'remove_pings_quickedit' );\n\nfunction remove_pings_quickedit() \n{ \n\n global $current_screen;\n if( 'edit-post' != $current_screen->id )\n return;\n ?>\n <script type=\"text/javascript\"> \n jQuery(document).ready( function($) { \n $('span:contains(\"Allow Pings\")').each(function (i) {\n $(this).remove();\n });\n $('input[name=ping_status]').each(function (i) {\n $(this).remove();\n });\n }); \n </script>\n <?php\n}\n</code></pre>\n"
}
]
| 2018/07/29 | [
"https://wordpress.stackexchange.com/questions/309828",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/146256/"
]
| Question regarding template structure:
In a custom loop, I inserted a get\_template\_part('resources', 'layout') which contains the following markup:
```
<div class="custom-content">
<?php if ( get_post_type() === 'videos' ) { ?>
<div class="video-popup">
<?php the_field('video_popup'); ?>
</div>
<?php } else { ?>
<div class="featured-image">
<?php the_post_thumbnail('full'); ?>
<?php if ( get_post_type() === 'articles' ) { ?>
<p class="custom-content-btn">
<a href="<?php the_field( 'article_link' )?>" class="btn btn-primary" target="_blank"><?php echo __('READ'); ?></a>
</p>
<?php } ?>
</div>
<?php if ( get_post_type() === 'audio' ) { ?>
<div class="audio-content">
<?php the_field('audio_clip'); ?>
</div>
<?php } ?>
<?php } ?>
</div>
```
I have 3 CPT (videos, audio and articles). However I'm not sure if this is the best way to conditionally display the contents; seems a bit messy. I guess the tricky part is that there's some markup that appears for all CPT, that's sitting inbetween those conditional markups.
What would be considered the 'best practice' to tackle this? Appreciate any input! | The WordPress Codex solutions weren't working for me regardless of what parameters I used or the priorities set, probably because my setup is pretty complex or as others have commented. The first chunk of code may work for you but I don't have a default environment at the moment to test. The second chunk of code definitely worked for me. The last chunk of code removes the option from the post's quick edit as well.
You will still need to disable the functionality as you have done.
Wordpress Codex solution, *(hooks into add\_meta\_boxes so it fires last, but you can use admin\_menu or do\_meta\_boxes instead).*
Documentation [Here](https://codex.wordpress.org/Function_Reference/remove_meta_box)
```
function remove_trackbacks_pingbacks() {
remove_meta_box('trackbacksdiv', 'post', 'normal');
}
add_action('add_meta_boxes', 'remove_trackbacks_pingbacks');
```
This may be overkill, but this is what actually worked for me. Note that it will remove the option in the box from displaying everywhere, including pages too. It also allows you to customize the HTML as well just in case you wanted to add a note to tell the user that Pingbacks and Trackbacks have been disabled. *(this may or may not suit your needs, but here it is anyway).* Documentation [Here](https://gist.github.com/eteubert/1327291)
```
function remove_trackbacks_pingbacks ($post_type, $post) {
global $wp_meta_boxes, $current_screen;
# Remove "ping_status" from `commentstatusdiv`:
$wp_meta_boxes[$current_screen->id]['normal']['core']['commentstatusdiv']['callback'] = function($post) {
?>
<input name="advanced_view" type="hidden" value="1">
<p class="meta-options">
<label for="comment_status" class="selectit">
<input id="comment_status" name="comment_status" type="checkbox" value="open" <?php checked($post->comment_status, 'open'); ?>> Allow comments?
</label>
<?php do_action('post_comment_status_meta_box-options', $post); ?>
</p>
<?php
};
}
add_action('add_meta_boxes', 'remove_trackbacks_pingbacks', 10, 2);
```
Lastly, since you want to remove the option from your edit screen, I assume you may want to remove from the quick edit screen as well. There are no hooks or classes to hook into that I know of, so a pure jQuery solution is in order. Insert into functions.php
Modified from this solution [Here](https://wordpress.stackexchange.com/questions/59871/remove-specific-items-from-quick-edit-menu-of-a-custom-post-type)
```
add_action( 'admin_head-edit.php', 'remove_pings_quickedit' );
function remove_pings_quickedit()
{
global $current_screen;
if( 'edit-post' != $current_screen->id )
return;
?>
<script type="text/javascript">
jQuery(document).ready( function($) {
$('span:contains("Allow Pings")').each(function (i) {
$(this).remove();
});
$('input[name=ping_status]').each(function (i) {
$(this).remove();
});
});
</script>
<?php
}
``` |
309,840 | <p>Hope someone can help, am looking for some suggestions on how to override/replace some functions that are loading in a parent theme and move them into the child theme so we can make alterations to the files themselves in the child theme.</p>
<p>We will "duplicate" the structure and files into the child theme, but can't yet find a way to "unload" the original parent theme files and then load the child theme files we want to alter instead.</p>
<p>Essentially it's all the "require" files listed below that we will duplicate and alter in the child theme, but need to find some way to override the parents functions.php.</p>
<p>We have tried multiple ways to do this but just can't seem to get it to work so far.</p>
<p>THIS IS THE CURRENT PARENT FUNCTIONS.PHP:</p>
<hr>
<pre><code><?php
/**
* moto functions and definitions
*
* @package moto
*/
if ( ! function_exists( 'moto_setup' ) ) :
/**
* Sets up theme defaults and registers support for various WordPress features.
*
* Note that this function is hooked into the after_setup_theme hook, which
* runs before the init hook. The init hook is too late for some features, such
* as indicating support for post thumbnails.
*/
function moto_setup() {
/*
* Make theme available for translation.
* Translations can be filed in the /languages/ directory.
* If you're building a theme based on moto, use a find and replace
* to change 'moto' to the name of your theme in all the template files
*/
load_theme_textdomain( 'moto', get_template_directory() . '/languages' );
// Add default posts and comments RSS feed links to head.
add_theme_support( 'automatic-feed-links' );
/*
* Let WordPress manage the document title.
* By adding theme support, we declare that this theme does not use a
* hard-coded <title> tag in the document head, and expect WordPress to
* provide it for us.
*/
add_theme_support( 'title-tag' );
/*
* Enable support for Post Thumbnails on posts and pages.
*
* @link http://codex.wordpress.org/Function_Reference/add_theme_support#Post_Thumbnails
*/
add_theme_support( 'post-thumbnails' );
// This theme uses wp_nav_menu() in one location.
register_nav_menus( array(
'primary' => esc_html__( 'MOTO Main Menu', 'moto' ),
'pre_header' => esc_html__( 'Preheader Menu(You have to enable Preheader from MOTO Options panel to view this menu.)', 'moto' )
) );
/*
* Switch default core markup for search form, comment form, and comments
* to output valid HTML5.
*/
add_theme_support( 'html5', array(
'search-form',
'comment-form',
'comment-list',
'gallery',
'caption',
) );
/*
* Enable support for Post Formats.
* See http://codex.wordpress.org/Post_Formats
*/
add_theme_support( 'post-formats', array(
'aside',
'image',
'video',
'quote',
'link',
) );
// Set up the WordPress core custom background feature.
add_theme_support( 'custom-background', apply_filters( 'moto_custom_background_args', array(
'default-color' => 'ffffff',
'default-image' => '',
) ) );
add_theme_support( 'woocommerce' );
global $pagenow;
if ( is_admin() && 'themes.php' == $pagenow && isset( $_GET['activated'] ) ) {
wp_redirect(admin_url("options-general.php?page=moto-system-status")); // Your admin page URL
exit();
}
}
endif; // moto_setup
add_action( 'after_setup_theme', 'moto_setup' );
/**
* Set the content width in pixels, based on the theme's design and stylesheet.
*
* Priority 0 to make it available to lower priority callbacks.
*
* @global int $content_width
*/
function moto_content_width() {
$GLOBALS['content_width'] = apply_filters( 'moto_content_width', 640 );
}
add_action( 'after_setup_theme', 'moto_content_width', 0 );
/**
* Register widget area.
*
* @link http://codex.wordpress.org/Function_Reference/register_sidebar
*/
function moto_widgets_init() {
register_sidebar( array(
'name' => esc_html__( 'Sidebar', 'moto' ),
'id' => 'sidebar-1',
'description' => esc_html__( 'Defualt Sidebar', 'moto' ),
'before_widget' => '<div id="%1$s" class="row no-margin widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<hr><h4>',
'after_title' => '</h4>',
) );
register_sidebar( array(
'name' => esc_html__( 'Shop Sidebar', 'moto' ),
'id' => 'shopsidebar',
'description' => esc_html__( 'Shop Sidebar Show Only Shop pages', 'moto' ),
'before_widget' => '<div id="%1$s" class="row no-margin widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<hr><h4>',
'after_title' => '</h4>',
) );
register_sidebar( array(
'name' => esc_html__( 'Footer Sidebar - 1', 'moto' ),
'id' => 'footer-1',
'description' => esc_html__( 'Footer Sidebar - 1', 'moto' ),
'before_widget' => '<div class="col-md-3 col-sm-6 text-left">',
'after_widget' => '</div>',
'before_title' => '<hr><h4>',
'after_title' => '</h4>',
) );
register_sidebar( array(
'name' => esc_html__( 'Footer Sidebar - 2', 'moto' ),
'id' => 'footer-2',
'description' => esc_html__( 'Footer Sidebar - 2', 'moto' ),
'before_widget' => '<div class="col-md-3 col-sm-6 text-left"><div class="mt_footer_content">',
'after_widget' => '</div></div>',
'before_title' => '<hr><h4>',
'after_title' => '</h4>',
) );
}
add_action( 'widgets_init', 'moto_widgets_init' );
/**
* Implement the Custom Header feature.
*/
require get_template_directory() . '/function/custom-header.php';
/**
* Custom template tags for this theme.
*/
require get_template_directory() . '/function/template-tags.php';
/**
* Custom functions that act independently of the theme templates.
*/
require get_template_directory() . '/function/extras.php';
/**
* Customizer additions.
*/
require get_template_directory() . '/function/customizer.php';
/**
* Load Jetpack compatibility file.
*/
require get_template_directory() . '/function/jetpack.php';
require_once get_template_directory() . '/include/aq_resizer.php';
require_once get_template_directory() . '/include/moto-sys-req.php';
require_once get_template_directory() . '/include/moto-enqueue.php';
require_once get_template_directory() . '/include/moto-functions.php';
require_once get_template_directory() . '/include/theme_plugin/plugin-activate-config.php';
require_once get_template_directory() . '/include/wordpress-reset.php';
</code></pre>
<hr>
<p>Any suggestions?</p>
<p>Thank you in advance.</p>
| [
{
"answer_id": 309842,
"author": "Pim",
"author_id": 50432,
"author_profile": "https://wordpress.stackexchange.com/users/50432",
"pm_score": 0,
"selected": false,
"text": "<p>Simply use</p>\n\n<pre><code>function moto_setup() { \n // Your new moto_setup function\n}\n</code></pre>\n\n<p>without checking if the function exists or not. That function will override the <code>moto_setup()</code> declared in the parent theme.</p>\n"
},
{
"answer_id": 309845,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": false,
"text": "<p>You can't necessarily replace entire arbitrary files with a child theme. </p>\n\n<p>WordPress will automatically look in the child theme for replacements for the templates in the <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">template hierarchy</a>, as well as a couple of additional files like searchform.php or comments.php, but any other files that the parent theme loads are only replaceable in a child theme if the parent theme author has built them to be. This includes any files included into functions.php or in templates.</p>\n\n<p>For a file to be replaceable by a child theme it must be loaded using supported functions. For example, if a theme (like yours) loads a file like this:</p>\n\n<pre><code>require_once get_template_directory() . '/include/aq_resizer.php';\n</code></pre>\n\n<p>Then a child theme <em>cannot</em> replace it. This is because the <code>'/include/aq_resizer.php'</code> part of the path is not going through WordPress at all. It's a normal PHP include that WordPress cannot intercept. Additionally, <code>get_template_directory()</code> will only ever be the directory to the parent theme, not the child theme if one is active.</p>\n\n<p>For it to be possible to replace an entire file in a child theme the parent theme must load it with one of these functions:</p>\n\n<pre><code>require_once get_theme_file_path( '/include/aq_resizer.php' );\n</code></pre>\n\n<p>Because the file path is passed as an argument to <code>get_theme_file_path()</code>, rather than just being a concatenated string passed directly to PHP, it's possible for the function to look in the child theme first, which it does.</p>\n\n<p>For templates, if the parent theme uses <code>get_template_part()</code>, like this:</p>\n\n<pre><code>get_template_part( 'partials/content' );\n</code></pre>\n\n<p>Then the child theme can create <code>partials/content.php</code> to replace it, but if the parent theme uses <code>include partials/content.php</code>, then it's not possible to replace with a child theme.</p>\n\n<p><code>get_theme_file_path()</code> is much newer (introduced in <strong>4.7</strong>) than <code>get_template_part()</code> (introduced in <strong>3.0</strong>), so is much less common, and non-existent in older themes. It's also not widely known.</p>\n\n<p>In your code the parent theme doesn't use either of these methods, so it's just not possible to replace the entire file. This means that you will need to replace individual functions one-by-one. The method for doing this will depend on how the function is used.</p>\n\n<p><strong>If the parent theme hooks the function with <code>add_action()</code></strong></p>\n\n<p>If the parent theme hooks the function you want to replace with <code>add_action()</code>, then you can replace the function by creating a new version of the function in your child theme (with a different name), unhooking the original function with <a href=\"https://developer.wordpress.org/reference/functions/remove_action/\" rel=\"nofollow noreferrer\"><code>remove_action()</code></a>, then hooking your new function with <a href=\"https://developer.wordpress.org/reference/functions/add_action/\" rel=\"nofollow noreferrer\"><code>add_action()</code></a>:</p>\n\n<pre><code>remove_action( 'hook_name', 'parent_theme_function_name' );\nadd_action( 'hook_name', 'child_theme_function_name' );\n</code></pre>\n\n<p><strong>If the parent theme uses the function in a template file</strong></p>\n\n<p>If the parent theme has a function you want to replace, and that function is used in a template file, then you will need to create a new version of the function in your child theme (with a different name) then replace the <em>template file</em> in your child theme, then in your child theme's version of the template replace the original function usage with your new function.</p>\n\n<p><strong>If the parent theme function is pluggable</strong></p>\n\n<p>Parent themes are loaded before the child theme. This means that it's possible for theme developers to make functions replaceable by child themes by wrapping then in a <code>function_exists()</code> check. This means that you can replace the function definition with your own function and it won't cause a conflict, because the parent theme won't try to re-define it if you already have.</p>\n\n<p>Your code has an example of this: the <code>moto_setup()</code> function is inside this check:</p>\n\n<pre><code>if ( ! function_exists( 'moto_setup' ) ) :\nendif;\n</code></pre>\n\n<p>This makes the <code>moto_setup()</code> function 'pluggable', which means that you can define a <code>moto_setup()</code> function in your child theme and the parent theme will use it instead. </p>\n\n<p>Whether or not other functions in your theme are 'pluggable' this way is impossible to say without seeing the code.</p>\n\n<p><strong>Conclusion</strong></p>\n\n<ul>\n<li><p>It's not necessarily possible to replace whole files in child themes. Outside of a handful of core WordPress templates, the parent theme has to explicitly support files being replaceable.</p></li>\n<li><p>If the theme has not made functions' files replaceable, there are several options for replacing functions depending on how the parent theme was constructed.</p></li>\n<li><p>Depending on how the parent theme was constructed it is entirely possible that there are parts of it that are impossible to replace with a child theme without replacing huge chunks of the theme that you otherwise don't want to change. This can reach a point where you're better off just forking the theme and creating a new one.</p></li>\n</ul>\n"
},
{
"answer_id": 311110,
"author": "CMYK",
"author_id": 147731,
"author_profile": "https://wordpress.stackexchange.com/users/147731",
"pm_score": 0,
"selected": false,
"text": "<p>OK, after weeks of working with the developers of Moto Theme Pro v3, they are unable to get the child theme working as it should.</p>\n\n<p>The theme doesn't adhere to \"best practice\" coding, the child theme is unable to override the parent theme without extensive additional coding in the functions.php file and overall is a bit of a mess.</p>\n\n<p>We've given up on it.</p>\n"
}
]
| 2018/07/29 | [
"https://wordpress.stackexchange.com/questions/309840",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147731/"
]
| Hope someone can help, am looking for some suggestions on how to override/replace some functions that are loading in a parent theme and move them into the child theme so we can make alterations to the files themselves in the child theme.
We will "duplicate" the structure and files into the child theme, but can't yet find a way to "unload" the original parent theme files and then load the child theme files we want to alter instead.
Essentially it's all the "require" files listed below that we will duplicate and alter in the child theme, but need to find some way to override the parents functions.php.
We have tried multiple ways to do this but just can't seem to get it to work so far.
THIS IS THE CURRENT PARENT FUNCTIONS.PHP:
---
```
<?php
/**
* moto functions and definitions
*
* @package moto
*/
if ( ! function_exists( 'moto_setup' ) ) :
/**
* Sets up theme defaults and registers support for various WordPress features.
*
* Note that this function is hooked into the after_setup_theme hook, which
* runs before the init hook. The init hook is too late for some features, such
* as indicating support for post thumbnails.
*/
function moto_setup() {
/*
* Make theme available for translation.
* Translations can be filed in the /languages/ directory.
* If you're building a theme based on moto, use a find and replace
* to change 'moto' to the name of your theme in all the template files
*/
load_theme_textdomain( 'moto', get_template_directory() . '/languages' );
// Add default posts and comments RSS feed links to head.
add_theme_support( 'automatic-feed-links' );
/*
* Let WordPress manage the document title.
* By adding theme support, we declare that this theme does not use a
* hard-coded <title> tag in the document head, and expect WordPress to
* provide it for us.
*/
add_theme_support( 'title-tag' );
/*
* Enable support for Post Thumbnails on posts and pages.
*
* @link http://codex.wordpress.org/Function_Reference/add_theme_support#Post_Thumbnails
*/
add_theme_support( 'post-thumbnails' );
// This theme uses wp_nav_menu() in one location.
register_nav_menus( array(
'primary' => esc_html__( 'MOTO Main Menu', 'moto' ),
'pre_header' => esc_html__( 'Preheader Menu(You have to enable Preheader from MOTO Options panel to view this menu.)', 'moto' )
) );
/*
* Switch default core markup for search form, comment form, and comments
* to output valid HTML5.
*/
add_theme_support( 'html5', array(
'search-form',
'comment-form',
'comment-list',
'gallery',
'caption',
) );
/*
* Enable support for Post Formats.
* See http://codex.wordpress.org/Post_Formats
*/
add_theme_support( 'post-formats', array(
'aside',
'image',
'video',
'quote',
'link',
) );
// Set up the WordPress core custom background feature.
add_theme_support( 'custom-background', apply_filters( 'moto_custom_background_args', array(
'default-color' => 'ffffff',
'default-image' => '',
) ) );
add_theme_support( 'woocommerce' );
global $pagenow;
if ( is_admin() && 'themes.php' == $pagenow && isset( $_GET['activated'] ) ) {
wp_redirect(admin_url("options-general.php?page=moto-system-status")); // Your admin page URL
exit();
}
}
endif; // moto_setup
add_action( 'after_setup_theme', 'moto_setup' );
/**
* Set the content width in pixels, based on the theme's design and stylesheet.
*
* Priority 0 to make it available to lower priority callbacks.
*
* @global int $content_width
*/
function moto_content_width() {
$GLOBALS['content_width'] = apply_filters( 'moto_content_width', 640 );
}
add_action( 'after_setup_theme', 'moto_content_width', 0 );
/**
* Register widget area.
*
* @link http://codex.wordpress.org/Function_Reference/register_sidebar
*/
function moto_widgets_init() {
register_sidebar( array(
'name' => esc_html__( 'Sidebar', 'moto' ),
'id' => 'sidebar-1',
'description' => esc_html__( 'Defualt Sidebar', 'moto' ),
'before_widget' => '<div id="%1$s" class="row no-margin widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<hr><h4>',
'after_title' => '</h4>',
) );
register_sidebar( array(
'name' => esc_html__( 'Shop Sidebar', 'moto' ),
'id' => 'shopsidebar',
'description' => esc_html__( 'Shop Sidebar Show Only Shop pages', 'moto' ),
'before_widget' => '<div id="%1$s" class="row no-margin widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<hr><h4>',
'after_title' => '</h4>',
) );
register_sidebar( array(
'name' => esc_html__( 'Footer Sidebar - 1', 'moto' ),
'id' => 'footer-1',
'description' => esc_html__( 'Footer Sidebar - 1', 'moto' ),
'before_widget' => '<div class="col-md-3 col-sm-6 text-left">',
'after_widget' => '</div>',
'before_title' => '<hr><h4>',
'after_title' => '</h4>',
) );
register_sidebar( array(
'name' => esc_html__( 'Footer Sidebar - 2', 'moto' ),
'id' => 'footer-2',
'description' => esc_html__( 'Footer Sidebar - 2', 'moto' ),
'before_widget' => '<div class="col-md-3 col-sm-6 text-left"><div class="mt_footer_content">',
'after_widget' => '</div></div>',
'before_title' => '<hr><h4>',
'after_title' => '</h4>',
) );
}
add_action( 'widgets_init', 'moto_widgets_init' );
/**
* Implement the Custom Header feature.
*/
require get_template_directory() . '/function/custom-header.php';
/**
* Custom template tags for this theme.
*/
require get_template_directory() . '/function/template-tags.php';
/**
* Custom functions that act independently of the theme templates.
*/
require get_template_directory() . '/function/extras.php';
/**
* Customizer additions.
*/
require get_template_directory() . '/function/customizer.php';
/**
* Load Jetpack compatibility file.
*/
require get_template_directory() . '/function/jetpack.php';
require_once get_template_directory() . '/include/aq_resizer.php';
require_once get_template_directory() . '/include/moto-sys-req.php';
require_once get_template_directory() . '/include/moto-enqueue.php';
require_once get_template_directory() . '/include/moto-functions.php';
require_once get_template_directory() . '/include/theme_plugin/plugin-activate-config.php';
require_once get_template_directory() . '/include/wordpress-reset.php';
```
---
Any suggestions?
Thank you in advance. | You can't necessarily replace entire arbitrary files with a child theme.
WordPress will automatically look in the child theme for replacements for the templates in the [template hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/), as well as a couple of additional files like searchform.php or comments.php, but any other files that the parent theme loads are only replaceable in a child theme if the parent theme author has built them to be. This includes any files included into functions.php or in templates.
For a file to be replaceable by a child theme it must be loaded using supported functions. For example, if a theme (like yours) loads a file like this:
```
require_once get_template_directory() . '/include/aq_resizer.php';
```
Then a child theme *cannot* replace it. This is because the `'/include/aq_resizer.php'` part of the path is not going through WordPress at all. It's a normal PHP include that WordPress cannot intercept. Additionally, `get_template_directory()` will only ever be the directory to the parent theme, not the child theme if one is active.
For it to be possible to replace an entire file in a child theme the parent theme must load it with one of these functions:
```
require_once get_theme_file_path( '/include/aq_resizer.php' );
```
Because the file path is passed as an argument to `get_theme_file_path()`, rather than just being a concatenated string passed directly to PHP, it's possible for the function to look in the child theme first, which it does.
For templates, if the parent theme uses `get_template_part()`, like this:
```
get_template_part( 'partials/content' );
```
Then the child theme can create `partials/content.php` to replace it, but if the parent theme uses `include partials/content.php`, then it's not possible to replace with a child theme.
`get_theme_file_path()` is much newer (introduced in **4.7**) than `get_template_part()` (introduced in **3.0**), so is much less common, and non-existent in older themes. It's also not widely known.
In your code the parent theme doesn't use either of these methods, so it's just not possible to replace the entire file. This means that you will need to replace individual functions one-by-one. The method for doing this will depend on how the function is used.
**If the parent theme hooks the function with `add_action()`**
If the parent theme hooks the function you want to replace with `add_action()`, then you can replace the function by creating a new version of the function in your child theme (with a different name), unhooking the original function with [`remove_action()`](https://developer.wordpress.org/reference/functions/remove_action/), then hooking your new function with [`add_action()`](https://developer.wordpress.org/reference/functions/add_action/):
```
remove_action( 'hook_name', 'parent_theme_function_name' );
add_action( 'hook_name', 'child_theme_function_name' );
```
**If the parent theme uses the function in a template file**
If the parent theme has a function you want to replace, and that function is used in a template file, then you will need to create a new version of the function in your child theme (with a different name) then replace the *template file* in your child theme, then in your child theme's version of the template replace the original function usage with your new function.
**If the parent theme function is pluggable**
Parent themes are loaded before the child theme. This means that it's possible for theme developers to make functions replaceable by child themes by wrapping then in a `function_exists()` check. This means that you can replace the function definition with your own function and it won't cause a conflict, because the parent theme won't try to re-define it if you already have.
Your code has an example of this: the `moto_setup()` function is inside this check:
```
if ( ! function_exists( 'moto_setup' ) ) :
endif;
```
This makes the `moto_setup()` function 'pluggable', which means that you can define a `moto_setup()` function in your child theme and the parent theme will use it instead.
Whether or not other functions in your theme are 'pluggable' this way is impossible to say without seeing the code.
**Conclusion**
* It's not necessarily possible to replace whole files in child themes. Outside of a handful of core WordPress templates, the parent theme has to explicitly support files being replaceable.
* If the theme has not made functions' files replaceable, there are several options for replacing functions depending on how the parent theme was constructed.
* Depending on how the parent theme was constructed it is entirely possible that there are parts of it that are impossible to replace with a child theme without replacing huge chunks of the theme that you otherwise don't want to change. This can reach a point where you're better off just forking the theme and creating a new one. |
309,849 | <p>I am able to get a list of its subcategories in a category archive page using below code in <code>archive-product.php</code> but I want to display the list of the products currently assigned to each subcategory.</p>
<pre><code><?php
$parentid = get_queried_object_id();
$args = array(
'parent' => $parentid
);
$categories = get_terms(
'product_cat', $args
);
if ( $categories ) {
foreach ( $categories as $category ) {
echo $category->name;
}
}
?>
</code></pre>
<p><strong>Example:</strong></p>
<p>Subcategory 1</p>
<ul>
<li>Product 1 of Subcategory 1</li>
<li>Product 2 of Subcategory 1</li>
</ul>
<p><hr>
Subcategory 2</p>
<ul>
<li>Product 1 of Subcategory 2</li>
<li>Product 2 of Subcategory 2</li>
</ul>
<p>I am still learning WordPress so any help will be highly appreciated.</p>
| [
{
"answer_id": 309859,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 2,
"selected": true,
"text": "<pre><code><?php\n $parentid = get_queried_object_id();\n $args = array(\n 'parent' => $parentid\n );\n $categories = get_terms(\n 'product_cat', $args\n );\n if ( $categories ) :\n foreach ( $categories as $category ) :\n echo esc_html($category->name);\n $products = new WP_Query( array(\n 'post_type' => 'product',\n 'tax_query' => array(\n array(\n 'taxonomy' => 'product_cat',\n 'field' => 'slug',\n 'terms' => $category->slug,\n ),\n ) \n ) );\n if ( $products->have_posts() ) :\n ?>\n <ul>\n <?php while ( $products->have_posts() ) : $products->the_post(); ?>\n <li><?php the_title(); ?></li>\n <?php endwhile; ?>\n </ul>\n <?php\n wp_reset_postdata();\n endif;\n endforeach;\n endif;\n?>\n</code></pre>\n"
},
{
"answer_id": 382927,
"author": "Aleš Sýkora",
"author_id": 201517,
"author_profile": "https://wordpress.stackexchange.com/users/201517",
"pm_score": 0,
"selected": false,
"text": "<p>here is my code for this. You can find it here: [Archive category clustered by child categories][1]</p>\n<p>It also displays number of posts in child category and link to child category.</p>\n<pre><code>$term = get_queried_object(); // Get current archive page\n$children = get_terms($term->taxonomy, array(\n 'parent' => $term->term_id,\n 'hide_empty' => false\n));\n\nif ($children) {\n foreach ($children as $subcat) {\n echo '<h2><a href="' . esc_url(get_term_link($subcat, $subcat->taxonomy)) . '">' . // Display child taxonomy name\n $subcat->name . ' (' . $subcat->count . ')' . '</a></h2>' . $subcat->description; // Display child taxonomy item count\n $kategorie = $subcat->slug; // Set child category slug for each query of products\n $args = array(\n 'post_type' => 'product',\n 'product_cat' => $kategorie, \n );\n $loop = new WP_Query($args);\n if ($loop->have_posts()) {\n while ($loop->have_posts()) : $loop->the_post(); ?>\n <h4><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); //Display product title ?></a></h4>\n <?php $product = wc_get_product(get_the_ID()); // get the WC_Product Object ?>\n <p><?php echo $product->get_price_html(); // Display product Price ?></p>\n <?php endwhile; ?><?php\n } else {\n echo __('No products found');\n }\n wp_reset_postdata(); // Reset Query\n ?>\n <!--/.products-->\n <?php\n\n }\n}\n ?>\n\n\n [1]: https://toolset.wiki/article/woocommerce-category-clustered-by-child-taxonomies-in-wordpress/\n</code></pre>\n"
}
]
| 2018/07/29 | [
"https://wordpress.stackexchange.com/questions/309849",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147735/"
]
| I am able to get a list of its subcategories in a category archive page using below code in `archive-product.php` but I want to display the list of the products currently assigned to each subcategory.
```
<?php
$parentid = get_queried_object_id();
$args = array(
'parent' => $parentid
);
$categories = get_terms(
'product_cat', $args
);
if ( $categories ) {
foreach ( $categories as $category ) {
echo $category->name;
}
}
?>
```
**Example:**
Subcategory 1
* Product 1 of Subcategory 1
* Product 2 of Subcategory 1
---
Subcategory 2
* Product 1 of Subcategory 2
* Product 2 of Subcategory 2
I am still learning WordPress so any help will be highly appreciated. | ```
<?php
$parentid = get_queried_object_id();
$args = array(
'parent' => $parentid
);
$categories = get_terms(
'product_cat', $args
);
if ( $categories ) :
foreach ( $categories as $category ) :
echo esc_html($category->name);
$products = new WP_Query( array(
'post_type' => 'product',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $category->slug,
),
)
) );
if ( $products->have_posts() ) :
?>
<ul>
<?php while ( $products->have_posts() ) : $products->the_post(); ?>
<li><?php the_title(); ?></li>
<?php endwhile; ?>
</ul>
<?php
wp_reset_postdata();
endif;
endforeach;
endif;
?>
``` |
309,862 | <p>How can I check if the editor that is currently being used is Gutenberg in a WordPress plugin?</p>
<p>I need this because Gutenberg lacks <code>post_submitbox_misc_actions</code>, so I need a fallback which will only be used if the current editor is Gutenberg.</p>
| [
{
"answer_id": 309955,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 4,
"selected": false,
"text": "<h2>Necessary API Functions/Methods:</h2>\n<p>You'll need <a href=\"https://developer.wordpress.org/reference/classes/wp_screen/is_block_editor/\" rel=\"nofollow noreferrer\"><code>WP_Screen::is_block_editor()</code></a> method to check if you are currently in the Gutenberg Editor (Since WordPress 5.0).</p>\n<p>Also, if you install Gutenberg as a separate plugin, then you'll have the <code>is_gutenberg_page()</code> function available to do the same check.</p>\n<p>So for an overall solution, you'll need to combine these two.</p>\n<p>Of course, this has to be checked from the admin panel pages and when the internal data is ready to call the function. So <strong>you'll have to do the check using a suitable hook</strong>. For example, <em>if you check this using <strong><code>init</code></strong> hook, it <strong>will not work</strong></em>.</p>\n<p>Gutenberg itself checks the <code>is_gutenberg_page()</code> function from <code>gutenberg_init()</code> function, which is loaded using <code>replace_editor</code> hook. So <code>replace_editor</code> hook is a good place to do this check.</p>\n<p>However, I'd suggest the use of <code>admin_enqueue_scripts</code> for making the check, since:</p>\n<ol>\n<li><p><code>admin_enqueue_scripts</code> is the first hook that is fired after the same <code>is_gutenberg_page()</code> check Gutenberg makes itself.</p>\n</li>\n<li><p>Because of the nature of Gutenberg, you're more likely to load external scripts / styles for your purpose.</p>\n</li>\n<li><p><code>admin_enqueue_scripts</code> is a well known hook and it's only fired from admin panel pages. So front end is not affected by it.</p>\n</li>\n</ol>\n<blockquote>\n<p>Having said that, <strong>if all you need is to enqueue some scripts/styles</strong>, then you may use <a href=\"https://developer.wordpress.org/reference/hooks/enqueue_block_editor_assets/\" rel=\"nofollow noreferrer\"><code>enqueue_block_editor_assets</code></a> hook for editor assets and <a href=\"https://developer.wordpress.org/reference/hooks/enqueue_block_assets/\" rel=\"nofollow noreferrer\"><code>enqueue_block_assets</code></a> hook for both the editor and frontend assets (since WordPress 5.0).</p>\n<p>I'm not providing the related CODE here as it wasn't directly asked in the question, but it may be enough for most purposes.</p>\n</blockquote>\n<h2>Solution:</h2>\n<blockquote>\n<p>Sample CODE for Gutenberg check</p>\n</blockquote>\n<pre><code>add_action( 'admin_enqueue_scripts', 'wpse_gutenberg_editor_action' );\nfunction wpse_is_gutenberg_editor() {\n if( function_exists( 'is_gutenberg_page' ) && is_gutenberg_page() ) { \n return true;\n } \n \n $current_screen = get_current_screen();\n if ( method_exists( $current_screen, 'is_block_editor' ) && $current_screen->is_block_editor() ) {\n return true;\n }\n return false;\n}\nfunction wpse_gutenberg_editor_action() {\n if( wpse_is_gutenberg_editor() ) { \n // your gutenberg editor related CODE here\n } \n else {\n // this is not gutenberg.\n // this may not even be an editor, you need to check the screen if you need to check for another editor.\n }\n}\n</code></pre>\n"
},
{
"answer_id": 312776,
"author": "Andrei",
"author_id": 26395,
"author_profile": "https://wordpress.stackexchange.com/users/26395",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://make.wordpress.org/core/2018/08/17/whats-new-in-gutenberg-17th-august\" rel=\"nofollow noreferrer\">Gutenberg 3.6</a> introduced functions like <code>has_blocks</code> and <code>has_block</code>. They replace the deprecated <code>gutenberg_post_has_blocks</code> function.</p>\n\n<p>If <code>has_blocks</code> returns true than Gutenberg was used while editing the post.</p>\n\n<p>You can either use <code>has_blocks()</code> without params if the <code>$post</code> global is already set(for something like a query loop) or check the post content directly with <code>has_blocks( $content )</code></p>\n"
},
{
"answer_id": 319053,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 2,
"selected": false,
"text": "<p><code>has_blocks</code> is the way to go to check content, but also note if you are just checking if the block editor screen is being used in the admin area, you can do a check like this (to account for both the new block editor and Gutenberg plugin):</p>\n\n<pre><code>if (is_admin()) {\n global $current_screen;\n if (!isset($current_screen)) {$current_screen = get_current_screen();}\n if ( ( method_exists($current_screen, 'is_block_editor') && $current_screen->is_block_editor() )\n || ( function_exists('is_gutenberg_page')) && is_gutenberg_page() ) ) {\n // DO SOMETHING HERE\n }\n}\n</code></pre>\n"
},
{
"answer_id": 324866,
"author": "Benjamin Intal",
"author_id": 27354,
"author_profile": "https://wordpress.stackexchange.com/users/27354",
"pm_score": 3,
"selected": false,
"text": "<p>The function <code>is_gutenberg_page</code> is from the Gutenberg plugin, while the <code>is_block_editor</code> method is available from 5.0. This function below combines both into a single checking function.</p>\n\n<p>The code below is from <a href=\"https://github.com/Freemius/wordpress-sdk/commit/8a87d389c647b4588bfe96fc7d420d62a48cbac5\" rel=\"noreferrer\">Freemius SDK</a>, props to their team:</p>\n\n<pre><code>function is_gutenberg_page() {\n if ( function_exists( 'is_gutenberg_page' ) &&\n is_gutenberg_page()\n ) {\n // The Gutenberg plugin is on.\n return true;\n }\n $current_screen = get_current_screen();\n if ( method_exists( $current_screen, 'is_block_editor' ) &&\n $current_screen->is_block_editor()\n ) {\n // Gutenberg page on 5+.\n return true;\n }\n return false;\n}\n</code></pre>\n"
},
{
"answer_id": 327411,
"author": "Ankit",
"author_id": 51280,
"author_profile": "https://wordpress.stackexchange.com/users/51280",
"pm_score": 3,
"selected": false,
"text": "<ol>\n<li><p>Gutenberg has been integrated in WordPress 5.0 and now you can check by using <code>use_block_editor_for_post</code> function.</p>\n\n<pre><code>if(use_block_editor_for_post($post)){\n //Block editor is active for this post.\n}\n</code></pre></li>\n<li><p>Alternatively, when creating new post you can use <code>use_block_editor_for_post_type</code> function to check if gutenberg is active for this post type.</p>\n\n<pre><code>if(use_block_editor_for_post_type($postType)){\n//Gutenberg is active.\n}\n</code></pre></li>\n</ol>\n"
},
{
"answer_id": 353712,
"author": "Dragan Antonić",
"author_id": 179173,
"author_profile": "https://wordpress.stackexchange.com/users/179173",
"pm_score": 0,
"selected": false,
"text": "<p>In WP 5.0 and higher, a function 'has_blocks' is present in /wp-includes/blocks.php, so you can use:</p>\n\n<pre><code> if ( function_exists('has_blocks')) {\n $this->isGutenberg = true;\n }\n else {\n $this->isGutenberg = false;\n }\n</code></pre>\n"
},
{
"answer_id": 377106,
"author": "Jagir bahesh",
"author_id": 146066,
"author_profile": "https://wordpress.stackexchange.com/users/146066",
"pm_score": 1,
"selected": false,
"text": "<p>Here I have shared the custom function which you can use to check Gutenberg is enable or not.</p>\n<pre><code>if ( is_gutenberg_enable() ) {\n // Do your code\n}\n</code></pre>\n<p>This is a custom function:</p>\n<pre><code>/**\n * Check if Gutenberg is enable.\n * Must be used not earlier than plugins_loaded action fired.\n *\n * @return bool\n */\nfunction is_gutenberg_enable() {\n\n $gutenberg = false;\n $block_editor = false;\n\n if ( has_filter( 'replace_editor', 'gutenberg_init' ) ) {\n // Gutenberg is installed and activated.\n $gutenberg = true;\n }\n\n if ( version_compare( $GLOBALS['wp_version'], '5.0-beta', '>' ) ) {\n // Block editor.\n $block_editor = true;\n }\n\n if ( ! $gutenberg && ! $block_editor ) {\n return false;\n }\n\n include_once ABSPATH . 'wp-admin/includes/plugin.php';\n\n if ( ! is_plugin_active( 'classic-editor/classic-editor.php' ) ) {\n return true;\n }\n\n $use_block_editor = ( get_option( 'classic-editor-replace' ) === 'no-replace' );\n\n return $use_block_editor;\n}\n</code></pre>\n"
},
{
"answer_id": 380531,
"author": "KMcAloon",
"author_id": 135339,
"author_profile": "https://wordpress.stackexchange.com/users/135339",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>WP_Screen Object</code> now contains a boolean property for this. The following is working for me:</p>\n<pre><code>if( ! function_exists( 'get_current_screen' ) ) {\n return false;\n}\n\n$screen = get_current_screen();\n$is_block_editor = $screen->is_block_editor;\n</code></pre>\n<p>See <a href=\"https://developer.wordpress.org/reference/classes/wp_screen/is_block_editor/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/classes/wp_screen/is_block_editor/</a></p>\n"
}
]
| 2018/07/29 | [
"https://wordpress.stackexchange.com/questions/309862",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123649/"
]
| How can I check if the editor that is currently being used is Gutenberg in a WordPress plugin?
I need this because Gutenberg lacks `post_submitbox_misc_actions`, so I need a fallback which will only be used if the current editor is Gutenberg. | Necessary API Functions/Methods:
--------------------------------
You'll need [`WP_Screen::is_block_editor()`](https://developer.wordpress.org/reference/classes/wp_screen/is_block_editor/) method to check if you are currently in the Gutenberg Editor (Since WordPress 5.0).
Also, if you install Gutenberg as a separate plugin, then you'll have the `is_gutenberg_page()` function available to do the same check.
So for an overall solution, you'll need to combine these two.
Of course, this has to be checked from the admin panel pages and when the internal data is ready to call the function. So **you'll have to do the check using a suitable hook**. For example, *if you check this using **`init`** hook, it **will not work***.
Gutenberg itself checks the `is_gutenberg_page()` function from `gutenberg_init()` function, which is loaded using `replace_editor` hook. So `replace_editor` hook is a good place to do this check.
However, I'd suggest the use of `admin_enqueue_scripts` for making the check, since:
1. `admin_enqueue_scripts` is the first hook that is fired after the same `is_gutenberg_page()` check Gutenberg makes itself.
2. Because of the nature of Gutenberg, you're more likely to load external scripts / styles for your purpose.
3. `admin_enqueue_scripts` is a well known hook and it's only fired from admin panel pages. So front end is not affected by it.
>
> Having said that, **if all you need is to enqueue some scripts/styles**, then you may use [`enqueue_block_editor_assets`](https://developer.wordpress.org/reference/hooks/enqueue_block_editor_assets/) hook for editor assets and [`enqueue_block_assets`](https://developer.wordpress.org/reference/hooks/enqueue_block_assets/) hook for both the editor and frontend assets (since WordPress 5.0).
>
>
> I'm not providing the related CODE here as it wasn't directly asked in the question, but it may be enough for most purposes.
>
>
>
Solution:
---------
>
> Sample CODE for Gutenberg check
>
>
>
```
add_action( 'admin_enqueue_scripts', 'wpse_gutenberg_editor_action' );
function wpse_is_gutenberg_editor() {
if( function_exists( 'is_gutenberg_page' ) && is_gutenberg_page() ) {
return true;
}
$current_screen = get_current_screen();
if ( method_exists( $current_screen, 'is_block_editor' ) && $current_screen->is_block_editor() ) {
return true;
}
return false;
}
function wpse_gutenberg_editor_action() {
if( wpse_is_gutenberg_editor() ) {
// your gutenberg editor related CODE here
}
else {
// this is not gutenberg.
// this may not even be an editor, you need to check the screen if you need to check for another editor.
}
}
``` |
309,883 | <p>Say I have a plugin which fires the <code>plugin_1_action</code> when it initializes.</p>
<p>Now, because I wanna extend that plugin, I'll hook into <code>plugin_1_action</code>, but what if my plugin was installed after that plugin? Won't that plugin run first and so, I'll lose the chance to catch the <code>plugin_1_action</code> hook?</p>
<p>It's just weird and magical to me that I can, no matter what, hook into, say, Woo's actions and Woo can hook into mine, even if clearly my plugin has been installed later than it.</p>
<p>Even if most plugins run on the <code>init</code> hook (so they get executed on the same space), they still have priorities set differently. Meaning that plugin1's code will run before plugin2's code and if plugin2 has a hook into plugin1, well, tough luck...or not, apparently WordPress doesn't have this issue.</p>
<p>How does it work?</p>
| [
{
"answer_id": 309884,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p>If the plugin indeed runs <code>plugin_1_action</code> <em>as soon as it's loaded</em>, meaning that the <code>do_action()</code> call is just sitting in the plugin file and not inside a function that's hooked later, then yes, you're correct: you won't be able to hook into it if your plugin is loaded later.</p>\n\n<p>This is almost never how plugins work though. Pretty much all plugins won't actually run any code as soon as they're loaded. Plugins will typically hook all their functionality to occur later, usually no earlier than the <code>init</code> hook, which is run after all plugins and themes have loaded.</p>\n\n<p>So let's say the original plugin has this code:</p>\n\n<pre><code>function og_plugin_initialize() {\n // Does stuff.\n\n do_action( 'og_plugin_initialized' );\n}\n</code></pre>\n\n<p>This code will probably be hooked to run on the <code>init</code> hook:</p>\n\n<pre><code>add_action( 'init', 'og_plugin_initialize', 20 );\n</code></pre>\n\n<p>So the <code>og_plugin_initialized</code> hook won't be executed until the <code>init</code> hook, at priority 20.</p>\n\n<p>If you had a function that you wanted to hook into the <code>og_plugin_initialized</code> hook, then you would add it in your plugin like this:</p>\n\n<pre><code>function my_plugin_init() {\n // Do stuff.\n}\nadd_action( 'og_plugin_initialized', 'my_plugin_init' );\n</code></pre>\n\n<p>When it's done like this it doesn't matter which order the plugins load in, because both plugins and queued up their functions to run later. And since both those functions will run after all plugins have loaded, you can use functions defined in the original plugin without issue.</p>\n"
},
{
"answer_id": 309890,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Important:</strong> Think of actions and hooks instead as events</p>\n\n<p>That mental model will serve you far better.</p>\n\n<blockquote>\n <p>Now, because I wanna extend that plugin, I'll hook into plugin_1_action, but what if my plugin was installed after that plugin?</p>\n</blockquote>\n\n<p>You can install your plugins in any order you want, they are all loaded in the same order regardless. Installing plugin C first doesn't mean its code runs first.</p>\n\n<p>Plugins are loaded alphabetically, so plugin <code>a</code> will load before plugin <code>b</code> because A comes before B, etc</p>\n\n<blockquote>\n <p>Won't that plugin run first and so, I'll lose the chance to catch the plugin_1_action hook?</p>\n</blockquote>\n\n<p>Correct, if the action is fired once, and that event has already occurred, then it's too late. You can still hook into it, but that event has already happened, so it will never run.</p>\n\n<p>Similar to telling somebody to buy milk after they've been to the shop rather than before. You can do it, but it won't get you milk unless they visit the shop a second time.</p>\n\n<p>For it to still work would need to involve some kind of time travel/temporal mechanics. Dr Who might be able to do it, but we'll require refactoring to fix the original plugin.</p>\n\n<blockquote>\n <p>It's just weird and magical to me that I can, no matter what, hook into, say, Woo's actions and Woo can hook into mine,</p>\n</blockquote>\n\n<p>Actions are just actions, they don't belong to anybody. There's no sandboxing of code, and once it's loaded it's loaded. A plugins code shares all the same space as WP Core, and other plugins.</p>\n\n<blockquote>\n <p>even if clearly my plugin has been installed later than it.</p>\n</blockquote>\n\n<p>Installation order is irrelevant. As we learnt earlier too, order of execution matters, once the event/action/hook is fired, you can still hook into it, but your functions won't run until it's fired again which might never happen. WP hooks don't do time travel.</p>\n\n<blockquote>\n <p>Even if most plugins run on the init hook (so they get executed on the same space), they still have priorities set differently.</p>\n</blockquote>\n\n<p>Indeed, if the event hasn't happened yet, you can indicate priority to influence the order the functions are called in.</p>\n\n<blockquote>\n <p>Meaning that plugin1's code will run before plugin2's code and if plugin2 has a hook into plugin1, well, tough luck...or not, apparently WordPress doesn't have this issue.</p>\n</blockquote>\n\n<p>Oh but it does! As I mentioned earlier, you can add functions to a hook that has already fired, that doesn't mean it retroactively applies it to previous times the hook fired. As I mentioned before, that would require time travel technology.</p>\n\n<p>The root problem here is that the plugin is doing work before the <code>init</code> or <code>admin_init</code> hooks happen. When plugins load, they should set up their objects, add their hooks etc, but they shouldn't do work. That's what the lifecycle events of <code>init</code> etc are for</p>\n"
}
]
| 2018/07/30 | [
"https://wordpress.stackexchange.com/questions/309883",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143406/"
]
| Say I have a plugin which fires the `plugin_1_action` when it initializes.
Now, because I wanna extend that plugin, I'll hook into `plugin_1_action`, but what if my plugin was installed after that plugin? Won't that plugin run first and so, I'll lose the chance to catch the `plugin_1_action` hook?
It's just weird and magical to me that I can, no matter what, hook into, say, Woo's actions and Woo can hook into mine, even if clearly my plugin has been installed later than it.
Even if most plugins run on the `init` hook (so they get executed on the same space), they still have priorities set differently. Meaning that plugin1's code will run before plugin2's code and if plugin2 has a hook into plugin1, well, tough luck...or not, apparently WordPress doesn't have this issue.
How does it work? | If the plugin indeed runs `plugin_1_action` *as soon as it's loaded*, meaning that the `do_action()` call is just sitting in the plugin file and not inside a function that's hooked later, then yes, you're correct: you won't be able to hook into it if your plugin is loaded later.
This is almost never how plugins work though. Pretty much all plugins won't actually run any code as soon as they're loaded. Plugins will typically hook all their functionality to occur later, usually no earlier than the `init` hook, which is run after all plugins and themes have loaded.
So let's say the original plugin has this code:
```
function og_plugin_initialize() {
// Does stuff.
do_action( 'og_plugin_initialized' );
}
```
This code will probably be hooked to run on the `init` hook:
```
add_action( 'init', 'og_plugin_initialize', 20 );
```
So the `og_plugin_initialized` hook won't be executed until the `init` hook, at priority 20.
If you had a function that you wanted to hook into the `og_plugin_initialized` hook, then you would add it in your plugin like this:
```
function my_plugin_init() {
// Do stuff.
}
add_action( 'og_plugin_initialized', 'my_plugin_init' );
```
When it's done like this it doesn't matter which order the plugins load in, because both plugins and queued up their functions to run later. And since both those functions will run after all plugins have loaded, you can use functions defined in the original plugin without issue. |
309,896 | <p>How can i echo product id and product_item_key of each cart item instead of total count ?</p>
<pre><code>function iconic_cart_count_fragments( $fragments ) {
$fragments['div.header-cart-count'] = '<div class="header-cart-count">' . WC()->cart->get_cart_contents_count() . '</div>';
return $fragments;
}
</code></pre>
<p>Thank You</p>
| [
{
"answer_id": 309905,
"author": "Techno Deviser",
"author_id": 146401,
"author_profile": "https://wordpress.stackexchange.com/users/146401",
"pm_score": 1,
"selected": false,
"text": "<p>Try something like this</p>\n\n<pre><code>global $woocommerce;\nforeach ( $woocommerce->cart->get_cart() as $cart_item_key => $cart_item ) {\n\necho $cart_item_key;\necho $cart_item['product_id'];\n}\n</code></pre>\n\n<p>OR </p>\n\n<pre><code>foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {\necho $cart_item_key;\necho $cart_item['product_id'];\n}\n</code></pre>\n\n<p>OR </p>\n\n<pre><code> foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {\n $fragments['div.header-cart-count'] = '<div class=\"header-cart-count\">' .$cart_item['product_id']. '</div>'; \n }\n</code></pre>\n\n<p>This will give you product ids, instead of your current output.</p>\n\n<p>Final Working solution.</p>\n\n<pre><code> global $woocommerce; \n add_filter( 'woocommerce_add_to_cart_fragments', 'iconic_cart_count_fragments', 10, 1 ); \n function iconic_cart_count_fragments( $fragments ) {\n foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) { \n $fragments['div.header-cart-count'] = '<div class=\"header-cart-count\">' .$cart_item_key.'<br><br>'. $cart_item['product_id']. '</div>'; \n return $fragments; \n } \n\n } \n</code></pre>\n"
},
{
"answer_id": 309914,
"author": "nmr",
"author_id": 147428,
"author_profile": "https://wordpress.stackexchange.com/users/147428",
"pm_score": 3,
"selected": true,
"text": "<p>Techno Deviser, probably by mistake, in the <code>foreach</code> loop set value to <code>$fragments['div.header-cart-count']</code> instead append it. </p>\n\n<p>Try this modification:</p>\n\n<pre><code>function iconic_cart_count_fragments( $fragments ) {\n\n foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) { \n $fragments['div.header-cart-count'] .= '<div class=\"header-cart-count\">' .$cart_item_key.'<br><br>'. $cart_item['product_id']. '</div>'; \n } \n return $fragments; \n} \n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>function iconic_cart_count_fragments( $fragments ) {\n\n $cart = WC()->cart->get_cart();\n if (!empty($cart)) {\n foreach ( $cart as $cart_item_key => $cart_item )\n $output .= $cart_item_key. ' - ' . $cart_item['product_id'] . '<br>';\n $fragments['div.header-cart-count'] = '<div class=\"header-cart-count\">' . $output . '</div>'; \n }\n return $fragments; \n} \n</code></pre>\n"
}
]
| 2018/07/30 | [
"https://wordpress.stackexchange.com/questions/309896",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147754/"
]
| How can i echo product id and product\_item\_key of each cart item instead of total count ?
```
function iconic_cart_count_fragments( $fragments ) {
$fragments['div.header-cart-count'] = '<div class="header-cart-count">' . WC()->cart->get_cart_contents_count() . '</div>';
return $fragments;
}
```
Thank You | Techno Deviser, probably by mistake, in the `foreach` loop set value to `$fragments['div.header-cart-count']` instead append it.
Try this modification:
```
function iconic_cart_count_fragments( $fragments ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$fragments['div.header-cart-count'] .= '<div class="header-cart-count">' .$cart_item_key.'<br><br>'. $cart_item['product_id']. '</div>';
}
return $fragments;
}
```
Or:
```
function iconic_cart_count_fragments( $fragments ) {
$cart = WC()->cart->get_cart();
if (!empty($cart)) {
foreach ( $cart as $cart_item_key => $cart_item )
$output .= $cart_item_key. ' - ' . $cart_item['product_id'] . '<br>';
$fragments['div.header-cart-count'] = '<div class="header-cart-count">' . $output . '</div>';
}
return $fragments;
}
``` |
309,907 | <p>I'm fairly new to Wordpress. I'm using the shop-isle theme that has a default navigation menu. I'm trying to override this with a fancy ‘Ubermenu’ plugin but the default collapse symbol keeps overriding the plugin. </p>
<p>The theme header is loaded from directory shop-isle/inc/structure/header.php. </p>
<p>I copied the entire directory to my child theme directory and made edit below in /header.php but it only works when I add it to the 'structure' folder in the parent theme NOT the child. </p>
<p>example 1</p>
<pre><code><?php if( function_exists( ‘ubermenu’ ) ): ?>
<?php ubermenu( 'main' , array( 'theme_location' => 'primary' ) ); ?>
<?php else: ?>
<div class="header-menu-wrap">
<div class="collapse navbar-collapse" id="custom-collapse">
<?php
wp_nav_menu(
array(
'theme_location' => 'primary',
'container' => false,
'menu_class' => 'nav navbar-nav navbar-right',
)
);
?>
</div>
</div>
<?php endif; ?>
</code></pre>
<p>I tried unhooking the function that loads the header but that removes the header all together!</p>
<p>The main header.php calls <code>shop-isle/inc/structure/header.php.</code>
using </p>
<pre><code><?php do_action( 'shop_isle_header' ); ?>
</code></pre>
<p>The hooks.php located in <code>shop-isle/inc/structure/hooks.php</code> has the callback function registered using</p>
<pre><code>add_action( 'shop_isle_header', 'shop_isle_primary_navigation', 50 );
</code></pre>
<p>I've copied all the files over to my child theme and kept the directory structure the same but it does not override the parent files.</p>
<p>How do I add the above code (example 1) in 'functions.php' in my child theme to update 'shop-isle/inc/structure/header.php'?</p>
| [
{
"answer_id": 309908,
"author": "Alex Sancho",
"author_id": 2536,
"author_profile": "https://wordpress.stackexchange.com/users/2536",
"pm_score": 1,
"selected": false,
"text": "<p>You need to copy to your child and edit the function where the file is included, probably ´shop_isle_primary_navigation´, to change the path where the file is located. Wordpress only loads automatically from child the default files, that's the ones defined in template hierarchy. You can read more about this at <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/basics/template-hierarchy/</a></p>\n"
},
{
"answer_id": 309909,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 0,
"selected": false,
"text": "<p>You can't replace arbitrary theme files by adding them to your child theme. That will only work for files in the <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">template hierarchy</a> and files that the parent theme has explicitly allowed to be replaced. Please see <a href=\"https://wordpress.stackexchange.com/questions/309840/override-parent-theme-configuration-in-child-functions-php/309845#309845\">my answer to a similar recent question</a> for more on how child themes work.</p>\n\n<p>To figure out exactly how to do what you want you should contact the theme author, but based on what you've posted so far it's possible to say that you need to first remove the original navigation from the header by using <a href=\"https://developer.wordpress.org/reference/functions/remove_action/\" rel=\"nofollow noreferrer\"><code>remove_action()</code></a> with the same arguments originally used to hook it:</p>\n\n<pre><code>remove_action( 'shop_isle_header', 'shop_isle_primary_navigation', 50 );\n</code></pre>\n\n<p>Then in your child theme you need to create a <em>new</em> function in your child theme's functions.php file that outputs the header what you want:</p>\n\n<pre><code>function wpse_309907_primary_navigation() {\n if ( function_exists( ‘ubermenu’ ) ): ?>\n <?php ubermenu( 'main' , array( 'theme_location' => 'primary' ) ); ?>\n <?php else: ?>\n <div class=\"header-menu-wrap\">\n <div class=\"collapse navbar-collapse\" id=\"custom-collapse\">\n <?php\n wp_nav_menu(\n array(\n 'theme_location' => 'primary',\n 'container' => false,\n 'menu_class' => 'nav navbar-nav navbar-right',\n )\n );\n ?>\n </div>\n </div>\n <?php endif;\n}\n</code></pre>\n\n<p>Then hook it in place of the original:</p>\n\n<pre><code>add_action( 'shop_isle_header', 'wpse_309907_primary_navigation', 50 );\n</code></pre>\n"
}
]
| 2018/07/30 | [
"https://wordpress.stackexchange.com/questions/309907",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147762/"
]
| I'm fairly new to Wordpress. I'm using the shop-isle theme that has a default navigation menu. I'm trying to override this with a fancy ‘Ubermenu’ plugin but the default collapse symbol keeps overriding the plugin.
The theme header is loaded from directory shop-isle/inc/structure/header.php.
I copied the entire directory to my child theme directory and made edit below in /header.php but it only works when I add it to the 'structure' folder in the parent theme NOT the child.
example 1
```
<?php if( function_exists( ‘ubermenu’ ) ): ?>
<?php ubermenu( 'main' , array( 'theme_location' => 'primary' ) ); ?>
<?php else: ?>
<div class="header-menu-wrap">
<div class="collapse navbar-collapse" id="custom-collapse">
<?php
wp_nav_menu(
array(
'theme_location' => 'primary',
'container' => false,
'menu_class' => 'nav navbar-nav navbar-right',
)
);
?>
</div>
</div>
<?php endif; ?>
```
I tried unhooking the function that loads the header but that removes the header all together!
The main header.php calls `shop-isle/inc/structure/header.php.`
using
```
<?php do_action( 'shop_isle_header' ); ?>
```
The hooks.php located in `shop-isle/inc/structure/hooks.php` has the callback function registered using
```
add_action( 'shop_isle_header', 'shop_isle_primary_navigation', 50 );
```
I've copied all the files over to my child theme and kept the directory structure the same but it does not override the parent files.
How do I add the above code (example 1) in 'functions.php' in my child theme to update 'shop-isle/inc/structure/header.php'? | You need to copy to your child and edit the function where the file is included, probably ´shop\_isle\_primary\_navigation´, to change the path where the file is located. Wordpress only loads automatically from child the default files, that's the ones defined in template hierarchy. You can read more about this at <https://developer.wordpress.org/themes/basics/template-hierarchy/> |
309,938 | <p>i need to insert wp_users -> user_login field to wp_terms name and slugs field,when a new user registering. </p>
<p>my requirement is admin needs to assign posts to specific users, that is admin need to add a post to user1 ,but user2 should not see that.for this i created a custom post and add taxonomy for that.And the terms are users Usernames .so i need to list the usernames of the users as terms in the taxonomy.when a new user is registered his username should updated in the wp_terms table also,so i will get the usernames as terms.</p>
<p>i stucked here .please suggest some solution for this</p>
| [
{
"answer_id": 309961,
"author": "Souvik Sikdar",
"author_id": 130021,
"author_profile": "https://wordpress.stackexchange.com/users/130021",
"pm_score": 0,
"selected": false,
"text": "<p>There is a simple way to to add username as the term of specific taxonomie.\nYou need to use \"<strong>user_register</strong>\" hook.\nSo the sample code is bellow</p>\n\n<pre><code>add_action( 'user_register', 'add_term_to_taxonomie', 10, 1 );\nfunction myplugin_registration_save( $user_id ) {\n if ( isset( $_POST['user_login'] ) ){\n wp_insert_term(\n $_POST['user_login'], // the term \n 'product', // the taxonomy\n );\n }\n\n}\n</code></pre>\n\n<p>Try the code , and replace \"product\" with your taxonomie name.\nThen let me know the result.\nThanks</p>\n"
},
{
"answer_id": 310008,
"author": "Adarsh",
"author_id": 143452,
"author_profile": "https://wordpress.stackexchange.com/users/143452",
"pm_score": 2,
"selected": true,
"text": "<p>i got the solution for this</p>\n<pre><code>add_action('user_register', function ($user_id) {\n $user_info = get_userdata($user_id);\n $user_name = $user_info->user_login;\n wp_insert_term($user_name, 'user1', array());\n}, 10, 1);\n</code></pre>\n"
}
]
| 2018/07/30 | [
"https://wordpress.stackexchange.com/questions/309938",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143452/"
]
| i need to insert wp\_users -> user\_login field to wp\_terms name and slugs field,when a new user registering.
my requirement is admin needs to assign posts to specific users, that is admin need to add a post to user1 ,but user2 should not see that.for this i created a custom post and add taxonomy for that.And the terms are users Usernames .so i need to list the usernames of the users as terms in the taxonomy.when a new user is registered his username should updated in the wp\_terms table also,so i will get the usernames as terms.
i stucked here .please suggest some solution for this | i got the solution for this
```
add_action('user_register', function ($user_id) {
$user_info = get_userdata($user_id);
$user_name = $user_info->user_login;
wp_insert_term($user_name, 'user1', array());
}, 10, 1);
``` |
309,939 | <p>I'm building a form with Contact Form 7 and I would need to add multiple fields under a single label and I would need to let the user to add more fields under that same label if needed. I'm using 4 fields as a starting point and I'd like to have like a + sign next to the last field which would add another field to the same set. Example:</p>
<pre><code>Prizes:
[ ]
[ ]
[ ]
[ ] +
</code></pre>
<p>When that + sign is clicked another field would appear as 5th field</p>
| [
{
"answer_id": 309961,
"author": "Souvik Sikdar",
"author_id": 130021,
"author_profile": "https://wordpress.stackexchange.com/users/130021",
"pm_score": 0,
"selected": false,
"text": "<p>There is a simple way to to add username as the term of specific taxonomie.\nYou need to use \"<strong>user_register</strong>\" hook.\nSo the sample code is bellow</p>\n\n<pre><code>add_action( 'user_register', 'add_term_to_taxonomie', 10, 1 );\nfunction myplugin_registration_save( $user_id ) {\n if ( isset( $_POST['user_login'] ) ){\n wp_insert_term(\n $_POST['user_login'], // the term \n 'product', // the taxonomy\n );\n }\n\n}\n</code></pre>\n\n<p>Try the code , and replace \"product\" with your taxonomie name.\nThen let me know the result.\nThanks</p>\n"
},
{
"answer_id": 310008,
"author": "Adarsh",
"author_id": 143452,
"author_profile": "https://wordpress.stackexchange.com/users/143452",
"pm_score": 2,
"selected": true,
"text": "<p>i got the solution for this</p>\n<pre><code>add_action('user_register', function ($user_id) {\n $user_info = get_userdata($user_id);\n $user_name = $user_info->user_login;\n wp_insert_term($user_name, 'user1', array());\n}, 10, 1);\n</code></pre>\n"
}
]
| 2018/07/30 | [
"https://wordpress.stackexchange.com/questions/309939",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147779/"
]
| I'm building a form with Contact Form 7 and I would need to add multiple fields under a single label and I would need to let the user to add more fields under that same label if needed. I'm using 4 fields as a starting point and I'd like to have like a + sign next to the last field which would add another field to the same set. Example:
```
Prizes:
[ ]
[ ]
[ ]
[ ] +
```
When that + sign is clicked another field would appear as 5th field | i got the solution for this
```
add_action('user_register', function ($user_id) {
$user_info = get_userdata($user_id);
$user_name = $user_info->user_login;
wp_insert_term($user_name, 'user1', array());
}, 10, 1);
``` |
309,972 | <p>I added this bit of code to my header.php file:</p>
<pre><code><script type="text/javascript">
$(document).ready(function() {
if( $('div').hasClass('icheckbox') && $('div').hasClass('disabled') ) {
$('div').parent().addClass('hide_empty');
}
});
</script>
</code></pre>
<p>My goal is to add the class .hide_empty to the parent of all div elements that have a class .icheckbox AND a class .disabled, in that order, with no other classes. The parent of these div elements is a li element in all cases.</p>
<p>I checked many answers to related questions and tried many variations, but whatever cariation I use, the class .hide_empty is never added to the parent li element.</p>
<p>What am I doing wrong here?</p>
<p>Thanks to the input of both @Andrea and @dhirenpatel22 I came up with the following working code:</p>
<p>In my <code>footer.php</code> I added:</p>
<pre><code><?php
function hide_empty_terms() { ?>
<script type="text/javascript">
jQuery(window).load(function() {
jQuery(".icheckbox.disabled").each(function() {
jQuery(this).parent('li').addClass('hide_empty');
});
});
</script>
<?php }
add_action('wp_footer', 'hide_empty_terms');
?>
</code></pre>
<p>right before <code><?php wp_footer(); ?></code>.
This actually adds the class <code>hide_empty</code> to the parent <code>li</code> element of <code><div class="icheckbox disabled"></code>.</p>
| [
{
"answer_id": 309974,
"author": "dhirenpatel22",
"author_id": 124380,
"author_profile": "https://wordpress.stackexchange.com/users/124380",
"pm_score": 0,
"selected": false,
"text": "<p>I have just updated your code...</p>\n\n<pre><code><script type=\"text/javascript\">\n$(document).ready(function() {\n $('div').each(function() {\n if( $(this).hasClass('icheckbox') && $(this).hasClass('disabled') ) {\n $(this).parent().addClass('hide_empty');\n }\n });\n});\n</script>\n</code></pre>\n\n<p>Hope this works..!!</p>\n"
},
{
"answer_id": 309989,
"author": "Guido",
"author_id": 142885,
"author_profile": "https://wordpress.stackexchange.com/users/142885",
"pm_score": 0,
"selected": false,
"text": "<p>This is the html code I aim to change:</p>\n\n<p><code><div class=\"html_list\">\n <ul class=\"list_checkbox\">\n <li class=\"term_1675 \">\n <div class=\"icheckbox disabled\" style=\"\">\n <input type=\"checkbox\" id=\"term_1675\" class=\"checkbox_term checkbox_term_1675\" data-tax=\"product_tag\" name=\"advies\" data-term-id=\"1675\" value=\"1675\" style=\"\">\n <ins class=\"iCheck-helper\" style=\"\"></ins>\n </div>\n ...some more code...\n </li>\n <li class=\"term_1676 \">\n <div class=\"icheckbox disabled\" style=\"\">\n <input type=\"checkbox\" id=\"term_1676\" class=\"checkbox_term checkbox_term_1676\" data-tax=\"product_tag\" name=\"coaching\" data-term-id=\"1676\" value=\"1676\" style=\"\">\n <ins class=\"iCheck-helper\" style=\"\"></ins>\n </div>\n ...some more code...\n </li>\n ...etc...\n </ul>\n</div></code></p>\n\n<p>So, the <code><div></code> elements should be changed into <code><div class=\"icheckbox disabled hide_empty\" style=\"\"></code></p>\n"
},
{
"answer_id": 309994,
"author": "Andrea Somovigo",
"author_id": 64435,
"author_profile": "https://wordpress.stackexchange.com/users/64435",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>So, the elements should be changed into <code><div class=\"icheckbox disabled hide_empty\" style=\"\"></code></p>\n</blockquote>\n\n<p>that's different from the goal stated in the question where you say you want to add class \"hide_empty\" to the parent <code><li></code> of the <code><div class=\"icheckbox\"></code>. The code posted by @dhirenpatel22 should work to add class hide_empty to the li element, of course if the element you want to add class to is the same div it should be \n<code>$(this).addClass('hide_empty')</code></p>\n\n<p>Also note that hasClass() will return true even if the element has more classes.\nTo find only the divs with both and exclusively icheckbox + disabled I guess the best way is: </p>\n\n<pre><code>$(\".icheckbox, .disabled\").each(function(){\n $(this).parent('li').addClass('hide_empty');\n // or $(this).addClass('hide_empty') \n //if it's the <div> instead of <li> you want to apply the rule\n})\n</code></pre>\n"
}
]
| 2018/07/30 | [
"https://wordpress.stackexchange.com/questions/309972",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/142885/"
]
| I added this bit of code to my header.php file:
```
<script type="text/javascript">
$(document).ready(function() {
if( $('div').hasClass('icheckbox') && $('div').hasClass('disabled') ) {
$('div').parent().addClass('hide_empty');
}
});
</script>
```
My goal is to add the class .hide\_empty to the parent of all div elements that have a class .icheckbox AND a class .disabled, in that order, with no other classes. The parent of these div elements is a li element in all cases.
I checked many answers to related questions and tried many variations, but whatever cariation I use, the class .hide\_empty is never added to the parent li element.
What am I doing wrong here?
Thanks to the input of both @Andrea and @dhirenpatel22 I came up with the following working code:
In my `footer.php` I added:
```
<?php
function hide_empty_terms() { ?>
<script type="text/javascript">
jQuery(window).load(function() {
jQuery(".icheckbox.disabled").each(function() {
jQuery(this).parent('li').addClass('hide_empty');
});
});
</script>
<?php }
add_action('wp_footer', 'hide_empty_terms');
?>
```
right before `<?php wp_footer(); ?>`.
This actually adds the class `hide_empty` to the parent `li` element of `<div class="icheckbox disabled">`. | >
> So, the elements should be changed into `<div class="icheckbox disabled hide_empty" style="">`
>
>
>
that's different from the goal stated in the question where you say you want to add class "hide\_empty" to the parent `<li>` of the `<div class="icheckbox">`. The code posted by @dhirenpatel22 should work to add class hide\_empty to the li element, of course if the element you want to add class to is the same div it should be
`$(this).addClass('hide_empty')`
Also note that hasClass() will return true even if the element has more classes.
To find only the divs with both and exclusively icheckbox + disabled I guess the best way is:
```
$(".icheckbox, .disabled").each(function(){
$(this).parent('li').addClass('hide_empty');
// or $(this).addClass('hide_empty')
//if it's the <div> instead of <li> you want to apply the rule
})
``` |
309,973 | <p>In WordPress I want to schedule an Event which will run my function (hook) at a specific time (let's say at 6PM) and then it will run again after 15 minutes (means at 6:15 PM) and keep running after every 15 minutes for 3 hours (till 9 PM) and then it dies.</p>
<pre><code>// I have the following code which run after every 6 hours
function myprefix_custom_cron_schedule( $schedules ) {
$schedules['every_six_hours'] = array(
'interval' => 21600, // Every 6 hours
'display' => __( 'Every 6 hours' ),
);
return $schedules;
}
add_filter( 'cron_schedules', 'myprefix_custom_cron_schedule' );
// Schedule an action if it's not already scheduled
if ( ! wp_next_scheduled( 'myprefix_cron_hook' ) ) {
wp_schedule_event( time(), 'every_six_hours', 'myprefix_cron_hook' );
}
// Hook into that action that'll fire every six hours
add_action( 'myprefix_cron_hook', 'myprefix_cron_function' );
// create your function, that runs on cron
function myprefix_cron_function() {
// your function...
}
</code></pre>
| [
{
"answer_id": 309988,
"author": "Kaperto",
"author_id": 147795,
"author_profile": "https://wordpress.stackexchange.com/users/147795",
"pm_score": 0,
"selected": false,
"text": "<p>to do that, it's better to have a cron that is fired every 15 minutes and then you test if it's time to do the treatments or if it's time to wait.</p>\n\n<p>you can try something like that : </p>\n\n<pre><code>const ACTIVE_PERIOD = 3 * HOUR_IN_SECONDS;\nconst WAITING_PERIOD = 6 * HOUR_IN_SECONDS;\n\nconst TRANSIENT_STATE = \"TestCron__state\";\nconst TRANSIENT_TIMEOUT = \"TestCron__timeout\";\n\n\nadd_action(\"TestCron/cron/execution\", function () {\n\n\n $state = get_transient(TRANSIENT_STATE);\n\n if (FALSE === $state) {\n set_transient(TRANSIENT_STATE, \"waiting\");\n set_transient(TRANSIENT_TIMEOUT, time() + WAITING_PERIOD);\n }\n\n\n if (get_transient(TRANSIENT_TIMEOUT) < time()) { // state change\n\n if (\"waiting\" === get_transient(TRANSIENT_STATE)) {\n set_transient(TRANSIENT_STATE, \"active\");\n set_transient(TRANSIENT_TIMEOUT, time() + ACTIVE_PERIOD);\n } else {\n set_transient(TRANSIENT_STATE, \"waiting\");\n set_transient(TRANSIENT_TIMEOUT, time() + WAITING_PERIOD);\n }\n\n }\n\n\n if (\"waiting\" === get_transient(TRANSIENT_STATE)) {\n // continue to sleep\n return;\n }\n\n\n // here actions to do\n do_action(\"myprefix_cron_hook\");\n\n\n\n});\n\n\nadd_action(\"wp_loaded\", function () {\n\n if (!wp_next_scheduled(\"TestCron/cron/execution\")) {\n wp_schedule_event(1, \"15_minutes\", \"TestCron/cron/execution\");\n }\n\n});\n\n\nadd_filter(\"cron_schedules\", function ($cron_schedules) {\n\n $cron_schedules[\"15_minutes\"] = [\n \"display\" => \"15 minutes\",\n \"interval\" => 15 * MINUTE_IN_SECONDS,\n ];\n\n return $cron_schedules;\n\n});\n</code></pre>\n"
},
{
"answer_id": 310006,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 4,
"selected": true,
"text": "<h2>Setup WordPress Cron Events</h2>\n\n<p>Let's say you want to start the cron at 6PM and keep running the cron after every 15 minutes till 9PM (for 3 hours). Then all cron stops.</p>\n\n<blockquote>\n <p><strong>Note:</strong> for the simplicity of implementation, all time entry in the CODE is considered to be GMT/UTC.</p>\n</blockquote>\n\n<p>For this, you need to schedule two cron events, one will start at 6PM and keep running at every 15 minutes from 6PM. The other one will be one time cron event that'll run at 9PM. This one will stop the other cron.</p>\n\n<p>The plugin CODE will be something like the following:</p>\n\n<pre><code><?php\n/*\nPlugin Name: WPSE Custom Cron\nPlugin URI: https://wordpress.stackexchange.com/a/309973/110572\nDescription: Custom Cron Plugin\nVersion: 1.0.0\nAuthor: Fayaz Ahmed\nAuthor URI: https://www.fayazmiraz.com/\n*/\n\nadd_action( 'wpse_custom_cron_event', 'wpse_custom_cron' );\nadd_action( 'wpse_custom_cron_event_stop', 'wpse_custom_cron_stop' );\n\nfunction wpse_custom_cron() {\n // Your Custom Cron CODE HERE\n}\n\nfunction wpse_custom_cron_start() {\n // Calculate the start time: e.g. whenever the next 6:00PM (UTC) is.\n $cron_start_time = strtotime( \"today 6:00pm\" );\n // If 6PM has already passed today, set it to 6PM next day\n if( $cron_start_time < time() ) {\n $cron_start_time = $cron_start_time + 24 * HOUR_IN_SECONDS;\n }\n\n if ( ! wp_next_scheduled( 'wpse_custom_cron_event' ) ) {\n wp_schedule_event( $cron_start_time, 'fifteen_minutes', 'wpse_custom_cron_event' );\n }\n\n if ( ! wp_next_scheduled( 'wpse_custom_cron_event_stop' ) ) {\n // this 1 time cron will stop the original cron 'wpse_custom_cron_event' after 3 hours of starting \n $cron_stop_time = $cron_start_time + 3 * HOUR_IN_SECONDS;\n wp_schedule_single_event( $cron_stop_time, 'wpse_custom_cron_event_stop' );\n }\n}\n\nfunction wpse_custom_cron_stop() {\n // removing all possible custom cron events named 'wpse_custom_cron_event'\n while( false !== wp_unschedule_event( wp_next_scheduled( 'wpse_custom_cron_event' ), 'wpse_custom_cron_event' ) ) {}\n}\n\n// Add a 15 minutes custom cron schedule\nadd_filter( 'cron_schedules', 'wpse_custom_cron_schedule' );\nfunction wpse_custom_cron_schedule( $schedules ) {\n $schedules['fifteen_minutes'] = array(\n 'interval' => 15 * 60,\n 'display' => esc_html__( 'Every Fifteen Minutes' ),\n );\n return $schedules;\n}\n\n// schedule the cron event on plugin activation\nregister_activation_hook( __FILE__, 'wpse_custom_cron_plugin_activation' );\nfunction wpse_custom_cron_plugin_activation() {\n wpse_custom_cron_start();\n}\n// remove the cron event on plugin deactivation\nregister_deactivation_hook( __FILE__, 'wpse_custom_cron_plugin_deactivation' );\nfunction wpse_custom_cron_plugin_deactivation() {\n wpse_custom_cron_stop();\n\n // in case the stop event didn't run yet\n while( false !== wp_unschedule_event( wp_next_scheduled( 'wpse_custom_cron_event_stop' ), 'wpse_custom_cron_event_stop' ) ) {}\n}\n</code></pre>\n\n<p>This sample plugin will start the cron on plugin activation, but if needed, you can edit the CODE to start the cron by other means as well (say using a button click in admin panel) using the <code>wpse_custom_cron_start()</code> function.</p>\n\n<p>Also, if you want to run the same cron everyday 6PM (not just one time after activation), then simply change the <code>wp_schedule_single_event</code> call in <code>wpse_custom_cron_start()</code> function to:</p>\n\n<pre><code>wp_schedule_event( $cron_stop_time, 'daily', 'wpse_custom_cron_event_stop' );\n</code></pre>\n\n<blockquote>\n <p><strong><em>Note:</em> Event/Cron created with arguments</strong></p>\n \n <p>If you create the event/cron with an argument, <strong>you must also stop the event with the exact same argument.</strong></p>\n \n <p>For example, if you created the event like this (in <code>wpse_custom_cron_start()</code> function of the above CODE):</p>\n\n<pre><code>....\nwp_schedule_event( $cron_start_time, 'fifteen_minutes', 'wpse_custom_cron_event', $args1 );\n....\nwp_schedule_single_event( $cron_stop_time, 'wpse_custom_cron_event_stop', $args2 );\n</code></pre>\n \n <p>then when stopping the events, you must also use the exact same argument in <code>wp_next_scheduled()</code> function call. So the stop CODE will become like:</p>\n\n<pre><code>....\nwhile( false !== wp_unschedule_event( wp_next_scheduled( 'wpse_custom_cron_event', $args1 ), 'wpse_custom_cron_event' ) ) {}\n....\nwhile( false !== wp_unschedule_event( wp_next_scheduled( 'wpse_custom_cron_event_stop', $args2 ), 'wpse_custom_cron_event_stop' ) ) {} \n</code></pre>\n \n <p>Again, remember, it has to be the <strong>exact same argument</strong>, even different data type will not work. For example, in the following CODE, <code>$args1</code> and <code>$args2</code> are <strong>NOT</strong> the same, but <code>$args1</code> and <code>$args3</code> are same:</p>\n\n<pre><code>$args1 = array( 'key' => 1 );\n$args2 = array( 'key' => '1' );\n$args3 = array( 'key' => 1 );\n</code></pre>\n \n <p>because <code>'1'</code> is string and <code>1</code> is a number.</p>\n \n <p>This is important because, <strong>sometimes people save the arguments in database as key value pairs</strong>, & when they use it again later, the value from database doesn't work for arguments that were numbers, as the numbers are converted to strings when retrieved from database. So you must convert them back to numbers when passing the argument to the <code>wp_next_scheduled()</code> function.</p>\n \n <p>for more information, check the documentation:</p>\n \n <ul>\n <li><a href=\"https://developer.wordpress.org/reference/functions/wp_schedule_event/\" rel=\"nofollow noreferrer\">wp_schedule_event()</a></li>\n <li><a href=\"https://developer.wordpress.org/reference/functions/wp_unschedule_event/\" rel=\"nofollow noreferrer\">wp_unschedule_event()</a></li>\n <li><a href=\"https://developer.wordpress.org/reference/functions/wp_schedule_single_event/\" rel=\"nofollow noreferrer\">wp_schedule_single_event()</a></li>\n <li><a href=\"https://developer.wordpress.org/reference/functions/wp_next_scheduled/\" rel=\"nofollow noreferrer\">wp_next_scheduled()</a></li>\n </ul>\n</blockquote>\n\n<h2>Running the Cron:</h2>\n\n<p>The best way to run WordPress cron is to set <code>define('DISABLE_WP_CRON', true);</code> in <code>wp-config.php</code> file and then run the cron from system crontab as described <a href=\"https://wordpress.stackexchange.com/a/253331/110572\">in this post</a>.</p>\n\n<h2>Use external cron service:</h2>\n\n<p>In case you cannot set crontab, you may use an external cron service like <a href=\"https://cron-job.org/en/\" rel=\"nofollow noreferrer\">cron-job.org</a> and set the cron accordingly.</p>\n\n<p>For example, for the above cron events, you may set a single cron job there with a setting like:</p>\n\n<p><a href=\"https://i.stack.imgur.com/uUVll.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/uUVll.png\" alt=\"cron-job.org settings\"></a></p>\n\n<blockquote>\n <p>Here, all the values of <code>Days of Month</code>, <code>Days of Week</code> & <code>Months</code> are selected; and <code>Hours</code> selected to <code>18, 19, 20</code> and <code>Minutes</code> selected to <code>0, 15, 30, 45</code>. Which means: run cron Everyday from 6PM to 9PM (GTM is set as time zone from account setting) on 0th, 15th, 30th and 45th minute (i.e. at 15 minutes interval).</p>\n</blockquote>\n\n<h2>Cron Check + Manual Cron:</h2>\n\n<p>You may check if your cron schedules properly using <a href=\"https://wordpress.org/plugins/wp-crontrol/\" rel=\"nofollow noreferrer\">WP Control</a> plugin. This plugin can also be used to set up custom cron events and intervals.</p>\n"
}
]
| 2018/07/30 | [
"https://wordpress.stackexchange.com/questions/309973",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147498/"
]
| In WordPress I want to schedule an Event which will run my function (hook) at a specific time (let's say at 6PM) and then it will run again after 15 minutes (means at 6:15 PM) and keep running after every 15 minutes for 3 hours (till 9 PM) and then it dies.
```
// I have the following code which run after every 6 hours
function myprefix_custom_cron_schedule( $schedules ) {
$schedules['every_six_hours'] = array(
'interval' => 21600, // Every 6 hours
'display' => __( 'Every 6 hours' ),
);
return $schedules;
}
add_filter( 'cron_schedules', 'myprefix_custom_cron_schedule' );
// Schedule an action if it's not already scheduled
if ( ! wp_next_scheduled( 'myprefix_cron_hook' ) ) {
wp_schedule_event( time(), 'every_six_hours', 'myprefix_cron_hook' );
}
// Hook into that action that'll fire every six hours
add_action( 'myprefix_cron_hook', 'myprefix_cron_function' );
// create your function, that runs on cron
function myprefix_cron_function() {
// your function...
}
``` | Setup WordPress Cron Events
---------------------------
Let's say you want to start the cron at 6PM and keep running the cron after every 15 minutes till 9PM (for 3 hours). Then all cron stops.
>
> **Note:** for the simplicity of implementation, all time entry in the CODE is considered to be GMT/UTC.
>
>
>
For this, you need to schedule two cron events, one will start at 6PM and keep running at every 15 minutes from 6PM. The other one will be one time cron event that'll run at 9PM. This one will stop the other cron.
The plugin CODE will be something like the following:
```
<?php
/*
Plugin Name: WPSE Custom Cron
Plugin URI: https://wordpress.stackexchange.com/a/309973/110572
Description: Custom Cron Plugin
Version: 1.0.0
Author: Fayaz Ahmed
Author URI: https://www.fayazmiraz.com/
*/
add_action( 'wpse_custom_cron_event', 'wpse_custom_cron' );
add_action( 'wpse_custom_cron_event_stop', 'wpse_custom_cron_stop' );
function wpse_custom_cron() {
// Your Custom Cron CODE HERE
}
function wpse_custom_cron_start() {
// Calculate the start time: e.g. whenever the next 6:00PM (UTC) is.
$cron_start_time = strtotime( "today 6:00pm" );
// If 6PM has already passed today, set it to 6PM next day
if( $cron_start_time < time() ) {
$cron_start_time = $cron_start_time + 24 * HOUR_IN_SECONDS;
}
if ( ! wp_next_scheduled( 'wpse_custom_cron_event' ) ) {
wp_schedule_event( $cron_start_time, 'fifteen_minutes', 'wpse_custom_cron_event' );
}
if ( ! wp_next_scheduled( 'wpse_custom_cron_event_stop' ) ) {
// this 1 time cron will stop the original cron 'wpse_custom_cron_event' after 3 hours of starting
$cron_stop_time = $cron_start_time + 3 * HOUR_IN_SECONDS;
wp_schedule_single_event( $cron_stop_time, 'wpse_custom_cron_event_stop' );
}
}
function wpse_custom_cron_stop() {
// removing all possible custom cron events named 'wpse_custom_cron_event'
while( false !== wp_unschedule_event( wp_next_scheduled( 'wpse_custom_cron_event' ), 'wpse_custom_cron_event' ) ) {}
}
// Add a 15 minutes custom cron schedule
add_filter( 'cron_schedules', 'wpse_custom_cron_schedule' );
function wpse_custom_cron_schedule( $schedules ) {
$schedules['fifteen_minutes'] = array(
'interval' => 15 * 60,
'display' => esc_html__( 'Every Fifteen Minutes' ),
);
return $schedules;
}
// schedule the cron event on plugin activation
register_activation_hook( __FILE__, 'wpse_custom_cron_plugin_activation' );
function wpse_custom_cron_plugin_activation() {
wpse_custom_cron_start();
}
// remove the cron event on plugin deactivation
register_deactivation_hook( __FILE__, 'wpse_custom_cron_plugin_deactivation' );
function wpse_custom_cron_plugin_deactivation() {
wpse_custom_cron_stop();
// in case the stop event didn't run yet
while( false !== wp_unschedule_event( wp_next_scheduled( 'wpse_custom_cron_event_stop' ), 'wpse_custom_cron_event_stop' ) ) {}
}
```
This sample plugin will start the cron on plugin activation, but if needed, you can edit the CODE to start the cron by other means as well (say using a button click in admin panel) using the `wpse_custom_cron_start()` function.
Also, if you want to run the same cron everyday 6PM (not just one time after activation), then simply change the `wp_schedule_single_event` call in `wpse_custom_cron_start()` function to:
```
wp_schedule_event( $cron_stop_time, 'daily', 'wpse_custom_cron_event_stop' );
```
>
> ***Note:* Event/Cron created with arguments**
>
>
> If you create the event/cron with an argument, **you must also stop the event with the exact same argument.**
>
>
> For example, if you created the event like this (in `wpse_custom_cron_start()` function of the above CODE):
>
>
>
> ```
> ....
> wp_schedule_event( $cron_start_time, 'fifteen_minutes', 'wpse_custom_cron_event', $args1 );
> ....
> wp_schedule_single_event( $cron_stop_time, 'wpse_custom_cron_event_stop', $args2 );
>
> ```
>
> then when stopping the events, you must also use the exact same argument in `wp_next_scheduled()` function call. So the stop CODE will become like:
>
>
>
> ```
> ....
> while( false !== wp_unschedule_event( wp_next_scheduled( 'wpse_custom_cron_event', $args1 ), 'wpse_custom_cron_event' ) ) {}
> ....
> while( false !== wp_unschedule_event( wp_next_scheduled( 'wpse_custom_cron_event_stop', $args2 ), 'wpse_custom_cron_event_stop' ) ) {}
>
> ```
>
> Again, remember, it has to be the **exact same argument**, even different data type will not work. For example, in the following CODE, `$args1` and `$args2` are **NOT** the same, but `$args1` and `$args3` are same:
>
>
>
> ```
> $args1 = array( 'key' => 1 );
> $args2 = array( 'key' => '1' );
> $args3 = array( 'key' => 1 );
>
> ```
>
> because `'1'` is string and `1` is a number.
>
>
> This is important because, **sometimes people save the arguments in database as key value pairs**, & when they use it again later, the value from database doesn't work for arguments that were numbers, as the numbers are converted to strings when retrieved from database. So you must convert them back to numbers when passing the argument to the `wp_next_scheduled()` function.
>
>
> for more information, check the documentation:
>
>
> * [wp\_schedule\_event()](https://developer.wordpress.org/reference/functions/wp_schedule_event/)
> * [wp\_unschedule\_event()](https://developer.wordpress.org/reference/functions/wp_unschedule_event/)
> * [wp\_schedule\_single\_event()](https://developer.wordpress.org/reference/functions/wp_schedule_single_event/)
> * [wp\_next\_scheduled()](https://developer.wordpress.org/reference/functions/wp_next_scheduled/)
>
>
>
Running the Cron:
-----------------
The best way to run WordPress cron is to set `define('DISABLE_WP_CRON', true);` in `wp-config.php` file and then run the cron from system crontab as described [in this post](https://wordpress.stackexchange.com/a/253331/110572).
Use external cron service:
--------------------------
In case you cannot set crontab, you may use an external cron service like [cron-job.org](https://cron-job.org/en/) and set the cron accordingly.
For example, for the above cron events, you may set a single cron job there with a setting like:
[](https://i.stack.imgur.com/uUVll.png)
>
> Here, all the values of `Days of Month`, `Days of Week` & `Months` are selected; and `Hours` selected to `18, 19, 20` and `Minutes` selected to `0, 15, 30, 45`. Which means: run cron Everyday from 6PM to 9PM (GTM is set as time zone from account setting) on 0th, 15th, 30th and 45th minute (i.e. at 15 minutes interval).
>
>
>
Cron Check + Manual Cron:
-------------------------
You may check if your cron schedules properly using [WP Control](https://wordpress.org/plugins/wp-crontrol/) plugin. This plugin can also be used to set up custom cron events and intervals. |
309,981 | <p>It seems by default WordPress provides fields for site-title and tagline.</p>
<p>I understand how to add (for example) the option to chose a logo, adding <code>add_theme_support( 'custom-logo' );</code> to the functions.php file. However, how do I add fields for 'company name' and 'company division' or for any text field that is not already part of the WordPress theme support?</p>
| [
{
"answer_id": 309982,
"author": "David Sword",
"author_id": 132362,
"author_profile": "https://wordpress.stackexchange.com/users/132362",
"pm_score": 3,
"selected": false,
"text": "<p>This is all part of the <a href=\"https://codex.wordpress.org/Theme_Customization_API\" rel=\"noreferrer\">Customizer API</a>; you'll create a <a href=\"https://codex.wordpress.org/Class_Reference/WP_Customize_Manager/add_section\" rel=\"noreferrer\">section</a>, add a <a href=\"https://codex.wordpress.org/Class_Reference%5CWP_Customize_Manager%5Cadd_setting\" rel=\"noreferrer\">setting</a> to the section, then add a <a href=\"https://codex.wordpress.org/Class_Reference%5CWP_Customize_Manager%5Cadd_control\" rel=\"noreferrer\">controller</a> to the setting. Once complete you'll show it on your theme using <a href=\"https://codex.wordpress.org/Function_Reference/get_theme_mod\" rel=\"noreferrer\"><code>get_theme_mod()</code></a></p>\n\n<p>For your example, you would add the 'company name' to the Customizer like so:</p>\n\n<pre><code>function mytheme_customize_register( $wp_customize ) {\n\n $wp_customize->add_section( 'mytheme_company_section' , array(\n 'title' => __( 'Additional Company Info', 'mytheme' ),\n 'priority' => 30,\n ));\n\n $wp_customize->add_setting( 'mytheme_company-name', array());\n $wp_customize->add_control( new WP_Customize_Control(\n $wp_customize,\n 'mytheme_company_control',\n array(\n 'label' => __( 'Company Name', 'mytheme' ),\n 'section' => 'mytheme_company_section',\n 'settings' => 'mytheme_company-name',\n 'priority' => 1\n )\n )\n );\n\n // ..repeat ->add_setting() and ->add_control() for mytheme_company-division\n}\nadd_action( 'customize_register', 'mytheme_customize_register' );\n</code></pre>\n\n<p>Then to show this dynamic value in the theme, you'd go into a file like <code>header.php</code> or wherever you want it, and use:</p>\n\n<pre><code>echo get_theme_mod( \"mytheme_company-name\" );\n</code></pre>\n"
},
{
"answer_id": 309983,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 4,
"selected": false,
"text": "<p>You'll have to add your own customizer controls to achieve that.</p>\n\n<p>So for example, if you want to add Company Name, you can use this code:</p>\n\n<pre><code>function my_register_additional_customizer_settings( $wp_customize ) {\n $wp_customize->add_setting(\n 'my_company_name',\n array(\n 'default' => '',\n 'type' => 'option', // you can also use 'theme_mod'\n 'capability' => 'edit_theme_options'\n ),\n );\n\n $wp_customize->add_control( new WP_Customize_Control(\n $wp_customize,\n 'my_company_name',\n array(\n 'label' => __( 'Company name', 'textdomain' ),\n 'description' => __( 'Description for your field', 'textdomain' ),\n 'settings' => 'my_company_name',\n 'priority' => 10,\n 'section' => 'title_tagline',\n 'type' => 'text',\n )\n ) );\n}\nadd_action( 'customize_register', 'my_register_additional_customizer_settings' );\n</code></pre>\n\n<p>PS. Here you can find more docs regarding this topic: <a href=\"https://codex.wordpress.org/Theme_Customization_API\" rel=\"noreferrer\">Theme Customization API</a></p>\n"
}
]
| 2018/07/30 | [
"https://wordpress.stackexchange.com/questions/309981",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147800/"
]
| It seems by default WordPress provides fields for site-title and tagline.
I understand how to add (for example) the option to chose a logo, adding `add_theme_support( 'custom-logo' );` to the functions.php file. However, how do I add fields for 'company name' and 'company division' or for any text field that is not already part of the WordPress theme support? | You'll have to add your own customizer controls to achieve that.
So for example, if you want to add Company Name, you can use this code:
```
function my_register_additional_customizer_settings( $wp_customize ) {
$wp_customize->add_setting(
'my_company_name',
array(
'default' => '',
'type' => 'option', // you can also use 'theme_mod'
'capability' => 'edit_theme_options'
),
);
$wp_customize->add_control( new WP_Customize_Control(
$wp_customize,
'my_company_name',
array(
'label' => __( 'Company name', 'textdomain' ),
'description' => __( 'Description for your field', 'textdomain' ),
'settings' => 'my_company_name',
'priority' => 10,
'section' => 'title_tagline',
'type' => 'text',
)
) );
}
add_action( 'customize_register', 'my_register_additional_customizer_settings' );
```
PS. Here you can find more docs regarding this topic: [Theme Customization API](https://codex.wordpress.org/Theme_Customization_API) |
310,013 | <p><code>wp_delete_user()</code> function requires user ID and [optional] reassign ID if the content is to be reassigned to another user.</p>
<p>All users' user names are also unique as WP doesn't allow duplicate user names. If I know username, is there no way with just one PHP/mysqli query I can delete the user instead of run one query to find ID of that user first and then tell wordpress to delete that user ?</p>
| [
{
"answer_id": 310016,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>There is no way to do this with only one query. But to be honest - deleting user takes more than one query itself...</p>\n\n<p>You shouldn’t use custom SQL for that, because there are many things you could break this way... Always use WP functions, if they exists (what if some plugin logs every deleted user, or what if some other action is needed, etc.)</p>\n\n<p>You can use <a href=\"https://developer.wordpress.org/reference/functions/get_user_by/\" rel=\"nofollow noreferrer\"><code>get_user_by</code></a> to achieve that. Here's the example:</p>\n\n<pre><code>$user = get_user_by( 'login', 'john' );\nif ( $user ) { // get_user_by can return false, if no such user exists\n wp_delete_user( $user->ID );\n}\n</code></pre>\n\n<p>The fields you can get user by are: <code>ID</code> | <code>slug</code> | <code>email</code> | <code>login</code>.</p>\n"
},
{
"answer_id": 310017,
"author": "Vatsh Patel",
"author_id": 129705,
"author_profile": "https://wordpress.stackexchange.com/users/129705",
"pm_score": 1,
"selected": false,
"text": "<p>It is a good practice to use WordPress function wp_delete_user() as it will delete user meta as well by running multiple queries on WordPress Database. </p>\n\n<p>Check WordPress codex for more info: <a href=\"https://developer.wordpress.org/reference/functions/wp_delete_user/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_delete_user/</a></p>\n\n<p>Also it's easy to get user id and then delete user by adding something like</p>\n\n<pre><code> $user = get_userdatabylogin('loginname');\n if($user){\n //delete user if exists\n wp_delete_user($user->ID);\n }\n</code></pre>\n\n<p>Or Else, You have to run multiple queries of generate a very complex query to properly remove user from WordPress database</p>\n"
}
]
| 2018/07/31 | [
"https://wordpress.stackexchange.com/questions/310013",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147821/"
]
| `wp_delete_user()` function requires user ID and [optional] reassign ID if the content is to be reassigned to another user.
All users' user names are also unique as WP doesn't allow duplicate user names. If I know username, is there no way with just one PHP/mysqli query I can delete the user instead of run one query to find ID of that user first and then tell wordpress to delete that user ? | There is no way to do this with only one query. But to be honest - deleting user takes more than one query itself...
You shouldn’t use custom SQL for that, because there are many things you could break this way... Always use WP functions, if they exists (what if some plugin logs every deleted user, or what if some other action is needed, etc.)
You can use [`get_user_by`](https://developer.wordpress.org/reference/functions/get_user_by/) to achieve that. Here's the example:
```
$user = get_user_by( 'login', 'john' );
if ( $user ) { // get_user_by can return false, if no such user exists
wp_delete_user( $user->ID );
}
```
The fields you can get user by are: `ID` | `slug` | `email` | `login`. |
310,026 | <p>I am trying to enqueuer a script after registering it but I am getting an error.</p>
<p>This is the script:</p>
<pre><code>function _test() {
console.log("Test");
}
</code></pre>
<p>That's the PHP:</p>
<pre><code>function fsg_shortURL() {
echo "Funtion Called";
wp_register_script('_test','/wp-content/themes/theme-child/js/test.js');
wp_enqueue_script('_test');
}
add_shortcode( 'fsg', 'fsg_shortURL' );
</code></pre>
<p>The console's suppouse to log <code>Test</code> but nothing happens..</p>
<p>Thanks!</p>
| [
{
"answer_id": 310029,
"author": "Kaperto",
"author_id": 147795,
"author_profile": "https://wordpress.stackexchange.com/users/147795",
"pm_score": 0,
"selected": false,
"text": "<p>To add a file located in a directory of the active theme, you have to use <a href=\"https://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri</a></p>\n\n<pre><code>wp_register_script(\n \"idScript\"\n , get_stylesheet_directory_uri() . \"/js/script.js\"\n);\n</code></pre>\n\n<p>In you question, you speak about a shortcode.<br>\nIt's better to store shortcode in a plugin. then, you can get the file URL with <a href=\"https://codex.wordpress.org/Function_Reference/plugins_url\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/plugins_url</a></p>\n\n<pre><code>wp_enqueue_script(\n \"pluginScript\"\n , plugins_url(\"js/script.js\", __FILE__)\n);\n</code></pre>\n"
},
{
"answer_id": 310030,
"author": "Andrea Somovigo",
"author_id": 64435,
"author_profile": "https://wordpress.stackexchange.com/users/64435",
"pm_score": 2,
"selected": true,
"text": "<p>Simply you've to call the function to execute it:</p>\n\n<pre><code>function _test() {\n console.log(\"Test\");\n}\n_test();\n</code></pre>\n"
}
]
| 2018/07/31 | [
"https://wordpress.stackexchange.com/questions/310026",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147331/"
]
| I am trying to enqueuer a script after registering it but I am getting an error.
This is the script:
```
function _test() {
console.log("Test");
}
```
That's the PHP:
```
function fsg_shortURL() {
echo "Funtion Called";
wp_register_script('_test','/wp-content/themes/theme-child/js/test.js');
wp_enqueue_script('_test');
}
add_shortcode( 'fsg', 'fsg_shortURL' );
```
The console's suppouse to log `Test` but nothing happens..
Thanks! | Simply you've to call the function to execute it:
```
function _test() {
console.log("Test");
}
_test();
``` |
310,036 | <p>I have 4 posts and I displaying 2 posts per page.</p>
<pre><code>$ids = array('16085','16088','16083','16091');
$options = array(
'post_type' => $post_type,
'posts_per_page' => $posts_per_page,
'paged' => $paged,
'meta_query' => $meta_query,
'tax_query' => $tax_query,
'post__in ' => $ids,
'orderby' => 'post__in',
);
$get_properties = new WP_Query( $options );
</code></pre>
<p>I want to display posts in a specific order is given $ids array.</p>
| [
{
"answer_id": 310047,
"author": "VinothRaja",
"author_id": 146008,
"author_profile": "https://wordpress.stackexchange.com/users/146008",
"pm_score": 0,
"selected": false,
"text": "<p>Try this below code</p>\n\n<pre><code>$get_properties = new WP_Query( array( 'post_type' => 'page','posts_per_page' => $posts_per_page,'paged' => $paged,'meta_query' => $meta_query,'tax_query' => $tax_query, 'post__in' => array( 32, 30, 27, 45) ,'orderby' => 'post__in' ) );\n\n\necho \"<pre>\";print_r($get_properties);exit;\n</code></pre>\n"
},
{
"answer_id": 310050,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>OK, so you want to define posts order by yourself. WP_Query allows you to do that - you'll have to use <code>orderby</code> => <code>post__in</code> to achieve it. And that's what you do.</p>\n\n<p>So why isn't it working? Because of a typo ;)</p>\n\n<p>Ordering posts by <code>post__in</code> preserves post ID order given in the 'post__in' array. But you don't pass <code>post__in</code> param in your query (you pass <code>post__in</code> - additional space at the end).</p>\n\n<pre><code>$ids = array('16085','16088','16083','16091');\n\n$options = array(\n 'post_type' => $post_type,\n 'posts_per_page' => $posts_per_page,\n 'paged' => $paged,\n 'meta_query' => $meta_query,\n 'tax_query' => $tax_query,\n 'post__in ' => $ids, // <-- here is the additional space\n 'orderby' => 'post__in',\n);\n$get_properties = new WP_Query( $options ); \n</code></pre>\n\n<p>So this should work just fine:</p>\n\n<pre><code>$ids = array('16085','16088','16083','16091');\n\n$options = array(\n 'post_type' => $post_type,\n 'posts_per_page' => $posts_per_page,\n 'paged' => $paged,\n 'meta_query' => $meta_query,\n 'tax_query' => $tax_query,\n 'post__in' => $ids, // <-- there is no space anymore in here\n 'orderby' => 'post__in',\n);\n$get_properties = new WP_Query( $options ); \n</code></pre>\n"
}
]
| 2018/07/31 | [
"https://wordpress.stackexchange.com/questions/310036",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/127648/"
]
| I have 4 posts and I displaying 2 posts per page.
```
$ids = array('16085','16088','16083','16091');
$options = array(
'post_type' => $post_type,
'posts_per_page' => $posts_per_page,
'paged' => $paged,
'meta_query' => $meta_query,
'tax_query' => $tax_query,
'post__in ' => $ids,
'orderby' => 'post__in',
);
$get_properties = new WP_Query( $options );
```
I want to display posts in a specific order is given $ids array. | OK, so you want to define posts order by yourself. WP\_Query allows you to do that - you'll have to use `orderby` => `post__in` to achieve it. And that's what you do.
So why isn't it working? Because of a typo ;)
Ordering posts by `post__in` preserves post ID order given in the 'post\_\_in' array. But you don't pass `post__in` param in your query (you pass `post__in` - additional space at the end).
```
$ids = array('16085','16088','16083','16091');
$options = array(
'post_type' => $post_type,
'posts_per_page' => $posts_per_page,
'paged' => $paged,
'meta_query' => $meta_query,
'tax_query' => $tax_query,
'post__in ' => $ids, // <-- here is the additional space
'orderby' => 'post__in',
);
$get_properties = new WP_Query( $options );
```
So this should work just fine:
```
$ids = array('16085','16088','16083','16091');
$options = array(
'post_type' => $post_type,
'posts_per_page' => $posts_per_page,
'paged' => $paged,
'meta_query' => $meta_query,
'tax_query' => $tax_query,
'post__in' => $ids, // <-- there is no space anymore in here
'orderby' => 'post__in',
);
$get_properties = new WP_Query( $options );
``` |
310,058 | <p>I downloaded my wordpress site and using it on localhost, but I couldn't. I changed my url in mysql db and followed <a href="https://stackoverflow.com/questions/15557718/after-migration-of-wordpress-website-i-cant-access-the-admin-white-page">this</a> . still I do not have access to my website or wp-admin. </p>
<p>I have <a href="https://localhost:8888/nofel/invest/davids/wp-admin/" rel="nofollow noreferrer">https://localhost:8888/nofel/invest/davids/wp-admin/</a></p>
<p>I get 404 but when I do <a href="https://localhost:8888/nofel/invest/davids" rel="nofollow noreferrer">https://localhost:8888/nofel/invest/davids</a> I get a lot of error in console about css, images and other things.</p>
<p>What am I missing? </p>
| [
{
"answer_id": 310047,
"author": "VinothRaja",
"author_id": 146008,
"author_profile": "https://wordpress.stackexchange.com/users/146008",
"pm_score": 0,
"selected": false,
"text": "<p>Try this below code</p>\n\n<pre><code>$get_properties = new WP_Query( array( 'post_type' => 'page','posts_per_page' => $posts_per_page,'paged' => $paged,'meta_query' => $meta_query,'tax_query' => $tax_query, 'post__in' => array( 32, 30, 27, 45) ,'orderby' => 'post__in' ) );\n\n\necho \"<pre>\";print_r($get_properties);exit;\n</code></pre>\n"
},
{
"answer_id": 310050,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>OK, so you want to define posts order by yourself. WP_Query allows you to do that - you'll have to use <code>orderby</code> => <code>post__in</code> to achieve it. And that's what you do.</p>\n\n<p>So why isn't it working? Because of a typo ;)</p>\n\n<p>Ordering posts by <code>post__in</code> preserves post ID order given in the 'post__in' array. But you don't pass <code>post__in</code> param in your query (you pass <code>post__in</code> - additional space at the end).</p>\n\n<pre><code>$ids = array('16085','16088','16083','16091');\n\n$options = array(\n 'post_type' => $post_type,\n 'posts_per_page' => $posts_per_page,\n 'paged' => $paged,\n 'meta_query' => $meta_query,\n 'tax_query' => $tax_query,\n 'post__in ' => $ids, // <-- here is the additional space\n 'orderby' => 'post__in',\n);\n$get_properties = new WP_Query( $options ); \n</code></pre>\n\n<p>So this should work just fine:</p>\n\n<pre><code>$ids = array('16085','16088','16083','16091');\n\n$options = array(\n 'post_type' => $post_type,\n 'posts_per_page' => $posts_per_page,\n 'paged' => $paged,\n 'meta_query' => $meta_query,\n 'tax_query' => $tax_query,\n 'post__in' => $ids, // <-- there is no space anymore in here\n 'orderby' => 'post__in',\n);\n$get_properties = new WP_Query( $options ); \n</code></pre>\n"
}
]
| 2018/07/31 | [
"https://wordpress.stackexchange.com/questions/310058",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147453/"
]
| I downloaded my wordpress site and using it on localhost, but I couldn't. I changed my url in mysql db and followed [this](https://stackoverflow.com/questions/15557718/after-migration-of-wordpress-website-i-cant-access-the-admin-white-page) . still I do not have access to my website or wp-admin.
I have <https://localhost:8888/nofel/invest/davids/wp-admin/>
I get 404 but when I do <https://localhost:8888/nofel/invest/davids> I get a lot of error in console about css, images and other things.
What am I missing? | OK, so you want to define posts order by yourself. WP\_Query allows you to do that - you'll have to use `orderby` => `post__in` to achieve it. And that's what you do.
So why isn't it working? Because of a typo ;)
Ordering posts by `post__in` preserves post ID order given in the 'post\_\_in' array. But you don't pass `post__in` param in your query (you pass `post__in` - additional space at the end).
```
$ids = array('16085','16088','16083','16091');
$options = array(
'post_type' => $post_type,
'posts_per_page' => $posts_per_page,
'paged' => $paged,
'meta_query' => $meta_query,
'tax_query' => $tax_query,
'post__in ' => $ids, // <-- here is the additional space
'orderby' => 'post__in',
);
$get_properties = new WP_Query( $options );
```
So this should work just fine:
```
$ids = array('16085','16088','16083','16091');
$options = array(
'post_type' => $post_type,
'posts_per_page' => $posts_per_page,
'paged' => $paged,
'meta_query' => $meta_query,
'tax_query' => $tax_query,
'post__in' => $ids, // <-- there is no space anymore in here
'orderby' => 'post__in',
);
$get_properties = new WP_Query( $options );
``` |
310,064 | <p>When I logged in on my site this morning I noticed that my user can’t publish anything. I am administrator and the only user on the site.</p>
<p>On Posts and Pages instead of “Publish” I have the “Submit for review” button and if I click on it the page is blank and displays “Sorry you are not allowed to modify this post”.</p>
<p>I have the same issue with all my plugins disabled and even after cache reset.</p>
<p>Can you help me?</p>
<p>Edit: Thanks for the answers i finally managed to fix everything</p>
<p>I found the answer ! After wandering on the Internets I found this page : <a href="https://wpindexfixer.tools.managedwphosting.nl/wpindexfixer/" rel="nofollow noreferrer">https://wpindexfixer.tools.managedwphosting.nl/wpindexfixer/</a></p>
<p>So here is what I gave SQL:</p>
<pre><code> DELETE FROM wp_users WHERE ID = 0;
ALTER TABLE wp_users ADD PRIMARY KEY (ID);
ALTER TABLE wp_users ADD KEY user_login_key (user_login);
ALTER TABLE wp_users ADD KEY user_nicename (user_nicename);
ALTER TABLE wp_users ADD KEY user_email (user_email);
ALTER TABLE wp_users MODIFY ID bigint(20) unsigned NOT NULL auto_increment;
DELETE FROM wp_usermeta WHERE umeta_id = 0;
ALTER TABLE wp_usermeta ADD PRIMARY KEY (umeta_id);
ALTER TABLE wp_usermeta ADD KEY user_id (user_id);
ALTER TABLE wp_usermeta ADD KEY meta_key (meta_key(191));
ALTER TABLE wp_usermeta MODIFY umeta_id bigint(20) unsigned NOT NULL auto_increment;
DELETE FROM wp_posts WHERE ID = 0;
ALTER TABLE wp_posts ADD PRIMARY KEY (ID);
ALTER TABLE wp_posts ADD KEY post_name (post_name(191));
ALTER TABLE wp_posts ADD KEY type_status_date (post_type,post_status,post_date,ID);
ALTER TABLE wp_posts ADD KEY post_parent (post_parent);
ALTER TABLE wp_posts ADD KEY post_author (post_author);
ALTER TABLE wp_posts MODIFY ID bigint(20) unsigned NOT NULL auto_increment;
DELETE FROM wp_comments WHERE comment_ID = 0;
ALTER TABLE wp_comments ADD PRIMARY KEY (comment_ID);
ALTER TABLE wp_comments ADD KEY comment_post_ID (comment_post_ID);
ALTER TABLE wp_comments ADD KEY comment_approved_date_gmt (comment_approved,comment_date_gmt);
ALTER TABLE wp_comments ADD KEY comment_date_gmt (comment_date_gmt);
ALTER TABLE wp_comments ADD KEY comment_parent (comment_parent);
ALTER TABLE wp_comments ADD KEY comment_author_email (comment_author_email(10));
ALTER TABLE wp_comments MODIFY comment_ID bigint(20) unsigned NOT NULL auto_increment;
DELETE FROM wp_links WHERE link_id = 0;
ALTER TABLE wp_links ADD PRIMARY KEY (link_id);
ALTER TABLE wp_links ADD KEY link_visible (link_visible);
ALTER TABLE wp_links MODIFY link_id bigint(20) unsigned NOT NULL auto_increment;
DELETE FROM wp_options WHERE option_id = 0;
ALTER TABLE wp_options ADD PRIMARY KEY (option_id);
ALTER TABLE wp_options ADD UNIQUE KEY option_name (option_name);
ALTER TABLE wp_options MODIFY option_id bigint(20) unsigned NOT NULL auto_increment;
DELETE FROM wp_postmeta WHERE meta_id = 0;
ALTER TABLE wp_postmeta ADD PRIMARY KEY (meta_id);
ALTER TABLE wp_postmeta ADD KEY post_id (post_id);
ALTER TABLE wp_postmeta ADD KEY meta_key (meta_key(191));
ALTER TABLE wp_postmeta MODIFY meta_id bigint(20) unsigned NOT NULL auto_increment;
DELETE FROM wp_terms WHERE term_id = 0;
ALTER TABLE wp_terms ADD PRIMARY KEY (term_id);
ALTER TABLE wp_terms ADD KEY slug (slug(191));
ALTER TABLE wp_terms ADD KEY name (name(191));
ALTER TABLE wp_terms MODIFY term_id bigint(20) unsigned NOT NULL auto_increment;
DELETE FROM wp_term_taxonomy WHERE term_taxonomy_id = 0;
ALTER TABLE wp_term_taxonomy ADD PRIMARY KEY (term_taxonomy_id);
ALTER TABLE wp_term_taxonomy ADD UNIQUE KEY term_id_taxonomy (term_id,taxonomy);
ALTER TABLE wp_term_taxonomy ADD KEY taxonomy (taxonomy);
ALTER TABLE wp_term_taxonomy MODIFY term_taxonomy_id bigint(20) unsigned NOT NULL auto_increment;
DELETE FROM wp_term_relationships WHERE object_id = 0;
DELETE FROM wp_term_relationships WHERE term_taxonomy_id = 0;
ALTER TABLE wp_term_relationships ADD PRIMARY KEY (object_id,term_taxonomy_id);
ALTER TABLE wp_term_relationships ADD KEY term_taxonomy_id (term_taxonomy_id);
DELETE FROM wp_termmeta WHERE meta_id = 0;
ALTER TABLE wp_termmeta ADD PRIMARY KEY (meta_id);
ALTER TABLE wp_termmeta ADD KEY term_id (term_id);
ALTER TABLE wp_termmeta ADD KEY meta_key (meta_key(191));
ALTER TABLE wp_termmeta MODIFY meta_id bigint(20) unsigned NOT NULL auto_increment;
DELETE FROM wp_commentmeta WHERE meta_id = 0;
ALTER TABLE wp_commentmeta ADD PRIMARY KEY (meta_id);
ALTER TABLE wp_commentmeta ADD KEY comment_id (comment_id);
ALTER TABLE wp_commentmeta ADD KEY meta_key (meta_key(191));
ALTER TABLE wp_commentmeta MODIFY meta_id bigint(20) unsigned NOT NULL auto_increment;
</code></pre>
<p>Despite an error on the primary key for table wp_usermeta this went well and everything is back to normal.</p>
| [
{
"answer_id": 310047,
"author": "VinothRaja",
"author_id": 146008,
"author_profile": "https://wordpress.stackexchange.com/users/146008",
"pm_score": 0,
"selected": false,
"text": "<p>Try this below code</p>\n\n<pre><code>$get_properties = new WP_Query( array( 'post_type' => 'page','posts_per_page' => $posts_per_page,'paged' => $paged,'meta_query' => $meta_query,'tax_query' => $tax_query, 'post__in' => array( 32, 30, 27, 45) ,'orderby' => 'post__in' ) );\n\n\necho \"<pre>\";print_r($get_properties);exit;\n</code></pre>\n"
},
{
"answer_id": 310050,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>OK, so you want to define posts order by yourself. WP_Query allows you to do that - you'll have to use <code>orderby</code> => <code>post__in</code> to achieve it. And that's what you do.</p>\n\n<p>So why isn't it working? Because of a typo ;)</p>\n\n<p>Ordering posts by <code>post__in</code> preserves post ID order given in the 'post__in' array. But you don't pass <code>post__in</code> param in your query (you pass <code>post__in</code> - additional space at the end).</p>\n\n<pre><code>$ids = array('16085','16088','16083','16091');\n\n$options = array(\n 'post_type' => $post_type,\n 'posts_per_page' => $posts_per_page,\n 'paged' => $paged,\n 'meta_query' => $meta_query,\n 'tax_query' => $tax_query,\n 'post__in ' => $ids, // <-- here is the additional space\n 'orderby' => 'post__in',\n);\n$get_properties = new WP_Query( $options ); \n</code></pre>\n\n<p>So this should work just fine:</p>\n\n<pre><code>$ids = array('16085','16088','16083','16091');\n\n$options = array(\n 'post_type' => $post_type,\n 'posts_per_page' => $posts_per_page,\n 'paged' => $paged,\n 'meta_query' => $meta_query,\n 'tax_query' => $tax_query,\n 'post__in' => $ids, // <-- there is no space anymore in here\n 'orderby' => 'post__in',\n);\n$get_properties = new WP_Query( $options ); \n</code></pre>\n"
}
]
| 2018/07/31 | [
"https://wordpress.stackexchange.com/questions/310064",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147835/"
]
| When I logged in on my site this morning I noticed that my user can’t publish anything. I am administrator and the only user on the site.
On Posts and Pages instead of “Publish” I have the “Submit for review” button and if I click on it the page is blank and displays “Sorry you are not allowed to modify this post”.
I have the same issue with all my plugins disabled and even after cache reset.
Can you help me?
Edit: Thanks for the answers i finally managed to fix everything
I found the answer ! After wandering on the Internets I found this page : <https://wpindexfixer.tools.managedwphosting.nl/wpindexfixer/>
So here is what I gave SQL:
```
DELETE FROM wp_users WHERE ID = 0;
ALTER TABLE wp_users ADD PRIMARY KEY (ID);
ALTER TABLE wp_users ADD KEY user_login_key (user_login);
ALTER TABLE wp_users ADD KEY user_nicename (user_nicename);
ALTER TABLE wp_users ADD KEY user_email (user_email);
ALTER TABLE wp_users MODIFY ID bigint(20) unsigned NOT NULL auto_increment;
DELETE FROM wp_usermeta WHERE umeta_id = 0;
ALTER TABLE wp_usermeta ADD PRIMARY KEY (umeta_id);
ALTER TABLE wp_usermeta ADD KEY user_id (user_id);
ALTER TABLE wp_usermeta ADD KEY meta_key (meta_key(191));
ALTER TABLE wp_usermeta MODIFY umeta_id bigint(20) unsigned NOT NULL auto_increment;
DELETE FROM wp_posts WHERE ID = 0;
ALTER TABLE wp_posts ADD PRIMARY KEY (ID);
ALTER TABLE wp_posts ADD KEY post_name (post_name(191));
ALTER TABLE wp_posts ADD KEY type_status_date (post_type,post_status,post_date,ID);
ALTER TABLE wp_posts ADD KEY post_parent (post_parent);
ALTER TABLE wp_posts ADD KEY post_author (post_author);
ALTER TABLE wp_posts MODIFY ID bigint(20) unsigned NOT NULL auto_increment;
DELETE FROM wp_comments WHERE comment_ID = 0;
ALTER TABLE wp_comments ADD PRIMARY KEY (comment_ID);
ALTER TABLE wp_comments ADD KEY comment_post_ID (comment_post_ID);
ALTER TABLE wp_comments ADD KEY comment_approved_date_gmt (comment_approved,comment_date_gmt);
ALTER TABLE wp_comments ADD KEY comment_date_gmt (comment_date_gmt);
ALTER TABLE wp_comments ADD KEY comment_parent (comment_parent);
ALTER TABLE wp_comments ADD KEY comment_author_email (comment_author_email(10));
ALTER TABLE wp_comments MODIFY comment_ID bigint(20) unsigned NOT NULL auto_increment;
DELETE FROM wp_links WHERE link_id = 0;
ALTER TABLE wp_links ADD PRIMARY KEY (link_id);
ALTER TABLE wp_links ADD KEY link_visible (link_visible);
ALTER TABLE wp_links MODIFY link_id bigint(20) unsigned NOT NULL auto_increment;
DELETE FROM wp_options WHERE option_id = 0;
ALTER TABLE wp_options ADD PRIMARY KEY (option_id);
ALTER TABLE wp_options ADD UNIQUE KEY option_name (option_name);
ALTER TABLE wp_options MODIFY option_id bigint(20) unsigned NOT NULL auto_increment;
DELETE FROM wp_postmeta WHERE meta_id = 0;
ALTER TABLE wp_postmeta ADD PRIMARY KEY (meta_id);
ALTER TABLE wp_postmeta ADD KEY post_id (post_id);
ALTER TABLE wp_postmeta ADD KEY meta_key (meta_key(191));
ALTER TABLE wp_postmeta MODIFY meta_id bigint(20) unsigned NOT NULL auto_increment;
DELETE FROM wp_terms WHERE term_id = 0;
ALTER TABLE wp_terms ADD PRIMARY KEY (term_id);
ALTER TABLE wp_terms ADD KEY slug (slug(191));
ALTER TABLE wp_terms ADD KEY name (name(191));
ALTER TABLE wp_terms MODIFY term_id bigint(20) unsigned NOT NULL auto_increment;
DELETE FROM wp_term_taxonomy WHERE term_taxonomy_id = 0;
ALTER TABLE wp_term_taxonomy ADD PRIMARY KEY (term_taxonomy_id);
ALTER TABLE wp_term_taxonomy ADD UNIQUE KEY term_id_taxonomy (term_id,taxonomy);
ALTER TABLE wp_term_taxonomy ADD KEY taxonomy (taxonomy);
ALTER TABLE wp_term_taxonomy MODIFY term_taxonomy_id bigint(20) unsigned NOT NULL auto_increment;
DELETE FROM wp_term_relationships WHERE object_id = 0;
DELETE FROM wp_term_relationships WHERE term_taxonomy_id = 0;
ALTER TABLE wp_term_relationships ADD PRIMARY KEY (object_id,term_taxonomy_id);
ALTER TABLE wp_term_relationships ADD KEY term_taxonomy_id (term_taxonomy_id);
DELETE FROM wp_termmeta WHERE meta_id = 0;
ALTER TABLE wp_termmeta ADD PRIMARY KEY (meta_id);
ALTER TABLE wp_termmeta ADD KEY term_id (term_id);
ALTER TABLE wp_termmeta ADD KEY meta_key (meta_key(191));
ALTER TABLE wp_termmeta MODIFY meta_id bigint(20) unsigned NOT NULL auto_increment;
DELETE FROM wp_commentmeta WHERE meta_id = 0;
ALTER TABLE wp_commentmeta ADD PRIMARY KEY (meta_id);
ALTER TABLE wp_commentmeta ADD KEY comment_id (comment_id);
ALTER TABLE wp_commentmeta ADD KEY meta_key (meta_key(191));
ALTER TABLE wp_commentmeta MODIFY meta_id bigint(20) unsigned NOT NULL auto_increment;
```
Despite an error on the primary key for table wp\_usermeta this went well and everything is back to normal. | OK, so you want to define posts order by yourself. WP\_Query allows you to do that - you'll have to use `orderby` => `post__in` to achieve it. And that's what you do.
So why isn't it working? Because of a typo ;)
Ordering posts by `post__in` preserves post ID order given in the 'post\_\_in' array. But you don't pass `post__in` param in your query (you pass `post__in` - additional space at the end).
```
$ids = array('16085','16088','16083','16091');
$options = array(
'post_type' => $post_type,
'posts_per_page' => $posts_per_page,
'paged' => $paged,
'meta_query' => $meta_query,
'tax_query' => $tax_query,
'post__in ' => $ids, // <-- here is the additional space
'orderby' => 'post__in',
);
$get_properties = new WP_Query( $options );
```
So this should work just fine:
```
$ids = array('16085','16088','16083','16091');
$options = array(
'post_type' => $post_type,
'posts_per_page' => $posts_per_page,
'paged' => $paged,
'meta_query' => $meta_query,
'tax_query' => $tax_query,
'post__in' => $ids, // <-- there is no space anymore in here
'orderby' => 'post__in',
);
$get_properties = new WP_Query( $options );
``` |
310,074 | <p>I'm trying to concatenate my <strong>site_url</strong> and a string, but it doesn't work. This is what I'm doing:</p>
<pre><code>$myurl = site_url();
var_dump($myurl);
$url = "https" . $myurl . "/inbox/?fepaction=viewmessage&fep_id=" . $inserted_message->ID;
var_dump($url); die;
</code></pre>
<p>The output looks like this:</p>
<blockquote>
<p>string(31) "//zgp.mydomain.be" string(78) "https:/inbox/?fepaction=viewmessage&fep_id=4813"</p>
</blockquote>
<p>As you can see it isn't merged. How can this be?</p>
| [
{
"answer_id": 310087,
"author": "helle",
"author_id": 32871,
"author_profile": "https://wordpress.stackexchange.com/users/32871",
"pm_score": 0,
"selected": false,
"text": "<p>What you are lookgin for is <a href=\"https://codex.wordpress.org/Function_Reference/home_url\" rel=\"nofollow noreferrer\"><code>home_url()</code></a>.</p>\n\n<p>This will return the address of the Site and not the path to your WP installation.</p>\n"
},
{
"answer_id": 310088,
"author": "jdm2112",
"author_id": 45202,
"author_profile": "https://wordpress.stackexchange.com/users/45202",
"pm_score": 3,
"selected": true,
"text": "<p>Without knowing exactly what you are trying to do, it seems you want to append query variables to the URL. WordPress has methods for handling that properly, without manual string concatenation.</p>\n\n<p>Look at the documentation for <code>add_query_arg()</code> for details: \n<a href=\"https://developer.wordpress.org/reference/functions/add_query_arg/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/add_query_arg/</a></p>\n\n<p>You can rebuild the URL and append query variables to the URL query by using this function. There are two ways to use this function; either a single key and value, or an associative array.</p>\n\n<p>Using a single key and value:</p>\n\n<pre><code>add_query_arg( 'key', 'value', 'http://example.com' );\n</code></pre>\n\n<p>Would create <code>http://example.com/?key=value</code></p>\n\n<p>Using an associative array:</p>\n\n<pre><code>add_query_arg( array(\n 'key1' => 'value1',\n 'key2' => 'value2',\n), 'http://example.com' );\n</code></pre>\n\n<p>This would create <code>http://example.com/?key1=value1&key2=value2</code></p>\n"
},
{
"answer_id": 310106,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>Sometimes the easiest solutions are the best...</p>\n\n<p>Take a look at <a href=\"https://codex.wordpress.org/Function_Reference/site_url\" rel=\"nofollow noreferrer\"><code>site_url</code> reference</a>.</p>\n\n<p>It takes two params:</p>\n\n<blockquote>\n <p><strong>$path</strong> <em>(string) (optional)</em> Path to be appended to the site url.\n Default: None</p>\n \n <p><strong>$scheme</strong> <em>(string) (optional)</em> Context for the protocol for\n the url returned. Setting $scheme will override the default context.\n Allowed values are 'http', 'https', 'login', 'login_post', 'admin', or\n 'relative'. Default: null</p>\n</blockquote>\n\n<p>As you can see, you don't need all that code...</p>\n\n<p>You can simply use:</p>\n\n<pre><code>$url = site_url('/inbox/?fepaction=viewmessage&fep_id=' . esc_url($inserted_message->ID), 'https');\n</code></pre>\n"
}
]
| 2018/07/31 | [
"https://wordpress.stackexchange.com/questions/310074",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/65180/"
]
| I'm trying to concatenate my **site\_url** and a string, but it doesn't work. This is what I'm doing:
```
$myurl = site_url();
var_dump($myurl);
$url = "https" . $myurl . "/inbox/?fepaction=viewmessage&fep_id=" . $inserted_message->ID;
var_dump($url); die;
```
The output looks like this:
>
> string(31) "//zgp.mydomain.be" string(78) "https:/inbox/?fepaction=viewmessage&fep\_id=4813"
>
>
>
As you can see it isn't merged. How can this be? | Without knowing exactly what you are trying to do, it seems you want to append query variables to the URL. WordPress has methods for handling that properly, without manual string concatenation.
Look at the documentation for `add_query_arg()` for details:
<https://developer.wordpress.org/reference/functions/add_query_arg/>
You can rebuild the URL and append query variables to the URL query by using this function. There are two ways to use this function; either a single key and value, or an associative array.
Using a single key and value:
```
add_query_arg( 'key', 'value', 'http://example.com' );
```
Would create `http://example.com/?key=value`
Using an associative array:
```
add_query_arg( array(
'key1' => 'value1',
'key2' => 'value2',
), 'http://example.com' );
```
This would create `http://example.com/?key1=value1&key2=value2` |
310,081 | <p>I am trying to make an ajax call and I am getting the error:</p>
<pre><code>TypeError: $ is undefined
</code></pre>
<p>This is my function.php file:</p>
<pre><code><?php
// Add custom Theme Functions here
//
function gear_guide_product_view( $atts ) {
$a = shortcode_atts( array(
'id' => '0'
), $atts );
wp_register_script( 'load_product_info' , '/wp-content/themes/theme-child/js/test.js' , array( 'jquery' ) );
wp_enqueue_script( 'load_product_info' );
wp_localize_script( 'load_product_info' , 'para' , $atts);
}
add_shortcode( 'fsg' , 'gear_guide_product_view' );
</code></pre>
<p>this is the ajax:</p>
<pre><code>function load_product_info() {
console.log(para.id);
$.ajax({
type: 'POST',
url: '/wp-content/themes/flatsome-child/js/controllers/get_product_info.php',
data: para,
dataType: 'json',
success: function (data) {
console.log(data);
}
});
}
load_product_info();
</code></pre>
<p>I have declared the use of jquery and from what I read on google it's all I need in order to make an ajax call.</p>
<p>If there is any more information needed tell me and I'll do my best to provide it.</p>
<p>Thanks!</p>
| [
{
"answer_id": 310089,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>As Milo already said in comment, jQuery is in noConflict mode in WordPress. This way other JS libraries can also use $ character...</p>\n\n<p>One way to solve it is using jQuery everywhere in your JS files.</p>\n\n<p>Another is to create block and define $ variable in it:</p>\n\n<pre><code>jQuery(function ($) {\n\n $.ajax(...); // here you can use $ since it is already defined and won’t cause conflicts\n\n});\n</code></pre>\n"
},
{
"answer_id": 310154,
"author": "Svetoslav Marinov",
"author_id": 26487,
"author_profile": "https://wordpress.stackexchange.com/users/26487",
"pm_score": 0,
"selected": false,
"text": "<p>You're using very specific URLs for ajax endpoint. When you change your theme your functionality WILL break. Do check how the WP codex how to make ajax calls properly and hook into wp_ajax actions.</p>\n"
}
]
| 2018/07/31 | [
"https://wordpress.stackexchange.com/questions/310081",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147331/"
]
| I am trying to make an ajax call and I am getting the error:
```
TypeError: $ is undefined
```
This is my function.php file:
```
<?php
// Add custom Theme Functions here
//
function gear_guide_product_view( $atts ) {
$a = shortcode_atts( array(
'id' => '0'
), $atts );
wp_register_script( 'load_product_info' , '/wp-content/themes/theme-child/js/test.js' , array( 'jquery' ) );
wp_enqueue_script( 'load_product_info' );
wp_localize_script( 'load_product_info' , 'para' , $atts);
}
add_shortcode( 'fsg' , 'gear_guide_product_view' );
```
this is the ajax:
```
function load_product_info() {
console.log(para.id);
$.ajax({
type: 'POST',
url: '/wp-content/themes/flatsome-child/js/controllers/get_product_info.php',
data: para,
dataType: 'json',
success: function (data) {
console.log(data);
}
});
}
load_product_info();
```
I have declared the use of jquery and from what I read on google it's all I need in order to make an ajax call.
If there is any more information needed tell me and I'll do my best to provide it.
Thanks! | As Milo already said in comment, jQuery is in noConflict mode in WordPress. This way other JS libraries can also use $ character...
One way to solve it is using jQuery everywhere in your JS files.
Another is to create block and define $ variable in it:
```
jQuery(function ($) {
$.ajax(...); // here you can use $ since it is already defined and won’t cause conflicts
});
``` |
310,101 | <p>I am developing a section on the front of our website. Our users submit properties to our directory. we would like to show how many properties they have listed and what types. I have got this code but it shows all post counts by all users I just want to show their post count so it would be like Residential Properties: 15. This is the code I am using can anyone tell me where I have gone wrong.</p>
<pre><code>$term = get_term( 110, 'property_type' );
// WP_Term_Query arguments
$args = array(
'taxonomy' => array( 'property_type' ),
'name' => array( 'Residential' ),
'slug' => array( 'residential' ),
'author' => $userID,
'pad_counts' => false,
'fields' => 'count',
'hide_empty' => true,
);
// The Term Query
$term_query = new WP_Term_Query( $args );
echo 'Residential Properties: '. $term->count;
</code></pre>
| [
{
"answer_id": 310109,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>It's a little bit hard to guess, what are you trying to do exactly, but let me try to answer...</p>\n\n<p>My best guess is that you want to tell, how many properties has given user published in given property type.</p>\n\n<h2>So first - why your code doesn't work...</h2>\n\n<p><code>get_term</code> will get the term info and there is no user context in it, so it will get count of all posts published in this term... So this won't help you.</p>\n\n<p><code>WP_Term_Query</code> is almost the same function. And, if you'll take a look at <a href=\"https://developer.wordpress.org/reference/classes/wp_term_query/__construct/\" rel=\"nofollow noreferrer\">its reference</a>, then you'll notice, that there is no <code>author</code> param. So it also won't help you. </p>\n\n<p><strong>Why is it so?</strong></p>\n\n<p>Because these functions are getting terms info and terms don't have authors...</p>\n\n<h2>So how to get the count of posts in given term authored by given user?</h2>\n\n<p>The easiest ways will be to use WP_Query and use its <code>found_posts</code> field (which stores the total number of posts found matching the current query parameters)...</p>\n\n<pre><code>$posts = new WP_Query( array(\n 'author' => $userID,\n 'post_type' => 'property', // I'm guessing that is your post type\n 'tax_query' => array( // here goes your taxonomy query\n array( 'taxonomy' => 'property_type', 'field' => 'slug', 'terms' => 'residential' ),\n ),\n 'fields' => 'ids', // we don't need content of posts\n 'posts_per_page' => 1, // We don't need to get these posts \n) );\n\necho 'Residential Properties: '. $posts->found_posts;\n</code></pre>\n"
},
{
"answer_id": 310353,
"author": "DirectWeb",
"author_id": 147857,
"author_profile": "https://wordpress.stackexchange.com/users/147857",
"pm_score": 0,
"selected": false,
"text": "<p>Good call Krzysiek Dróżdż, as a ref i would like to share this code as someone may require any of this.</p>\n\n<p>` $userID,\n 'post_type' => 'listings', \n 'post_status' => 'published',\n 'fields' => 'ids',\n 'posts_per_page' => 1,<br>\n ) );</p>\n\n<pre><code> echo 'Published Properties: '. $posts->found_posts;\n ?>`\n</code></pre>\n"
}
]
| 2018/07/31 | [
"https://wordpress.stackexchange.com/questions/310101",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147857/"
]
| I am developing a section on the front of our website. Our users submit properties to our directory. we would like to show how many properties they have listed and what types. I have got this code but it shows all post counts by all users I just want to show their post count so it would be like Residential Properties: 15. This is the code I am using can anyone tell me where I have gone wrong.
```
$term = get_term( 110, 'property_type' );
// WP_Term_Query arguments
$args = array(
'taxonomy' => array( 'property_type' ),
'name' => array( 'Residential' ),
'slug' => array( 'residential' ),
'author' => $userID,
'pad_counts' => false,
'fields' => 'count',
'hide_empty' => true,
);
// The Term Query
$term_query = new WP_Term_Query( $args );
echo 'Residential Properties: '. $term->count;
``` | It's a little bit hard to guess, what are you trying to do exactly, but let me try to answer...
My best guess is that you want to tell, how many properties has given user published in given property type.
So first - why your code doesn't work...
----------------------------------------
`get_term` will get the term info and there is no user context in it, so it will get count of all posts published in this term... So this won't help you.
`WP_Term_Query` is almost the same function. And, if you'll take a look at [its reference](https://developer.wordpress.org/reference/classes/wp_term_query/__construct/), then you'll notice, that there is no `author` param. So it also won't help you.
**Why is it so?**
Because these functions are getting terms info and terms don't have authors...
So how to get the count of posts in given term authored by given user?
----------------------------------------------------------------------
The easiest ways will be to use WP\_Query and use its `found_posts` field (which stores the total number of posts found matching the current query parameters)...
```
$posts = new WP_Query( array(
'author' => $userID,
'post_type' => 'property', // I'm guessing that is your post type
'tax_query' => array( // here goes your taxonomy query
array( 'taxonomy' => 'property_type', 'field' => 'slug', 'terms' => 'residential' ),
),
'fields' => 'ids', // we don't need content of posts
'posts_per_page' => 1, // We don't need to get these posts
) );
echo 'Residential Properties: '. $posts->found_posts;
``` |
310,126 | <p>i need to Delete wp_terms -> name field when a user is delete .</p>
<p>my requirement is admin needs to assign posts to specific users, that is admin need to add a post to user1 ,but user2 should not see that.for this i created a custom post and add taxonomy for that.And the terms are users Usernames .so i need to list the usernames of the users as terms in the taxonomy.when a new user is registered his username should updated in the wp_terms table also,so i will get the usernames as terms. this is working well ,now i need to delete the term from taxonomy when the user is removed.</p>
<p>i stucked here .please suggest some solution for this</p>
<p>what i have done is</p>
<pre><code>add_action( 'delete_user', 'yg_user_delete', 10, 1 );
function yg_user_delete( $user_id ) {
$user_info = get_userdata($user_id); $user_name = $user_info->user_login;
wp_delete_term( $user_name, 'user1', array() );
}
</code></pre>
<p>here 'user1' is my taxonomy</p>
| [
{
"answer_id": 310128,
"author": "Andrea Somovigo",
"author_id": 64435,
"author_profile": "https://wordpress.stackexchange.com/users/64435",
"pm_score": 1,
"selected": false,
"text": "<p>If I understand well you have a <code>custom_taxonomy</code> and the terms slugs of it correspond to the usernames..in this case try </p>\n\n<pre><code>function yg_user_delete( $user_id ) {\n $user_info = get_userdata($user_id); \n $user_name = $user_info->user_login;\n\n wp_delete_term(get_term_by('slug', $user_name)->term_id,'custom_taxonomy');\n}\n</code></pre>\n"
},
{
"answer_id": 310130,
"author": "Siavash1991",
"author_id": 35070,
"author_profile": "https://wordpress.stackexchange.com/users/35070",
"pm_score": 1,
"selected": true,
"text": "<p>Replace this with yours:</p>\n\n<pre><code>add_action( 'delete_user', 'yg_user_delete', 10, 1 );\n\nfunction yg_user_delete( $user_id ) {\n\n $user_info = get_userdata($user_id); \n $user_name = $user_info->user_login;\n\n print_r($user_info);\n\n wp_delete_term( get_term_by('name', $user_name, 'user1')->term_id, 'user1', array() );\n\n}\n</code></pre>\n"
}
]
| 2018/08/01 | [
"https://wordpress.stackexchange.com/questions/310126",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143452/"
]
| i need to Delete wp\_terms -> name field when a user is delete .
my requirement is admin needs to assign posts to specific users, that is admin need to add a post to user1 ,but user2 should not see that.for this i created a custom post and add taxonomy for that.And the terms are users Usernames .so i need to list the usernames of the users as terms in the taxonomy.when a new user is registered his username should updated in the wp\_terms table also,so i will get the usernames as terms. this is working well ,now i need to delete the term from taxonomy when the user is removed.
i stucked here .please suggest some solution for this
what i have done is
```
add_action( 'delete_user', 'yg_user_delete', 10, 1 );
function yg_user_delete( $user_id ) {
$user_info = get_userdata($user_id); $user_name = $user_info->user_login;
wp_delete_term( $user_name, 'user1', array() );
}
```
here 'user1' is my taxonomy | Replace this with yours:
```
add_action( 'delete_user', 'yg_user_delete', 10, 1 );
function yg_user_delete( $user_id ) {
$user_info = get_userdata($user_id);
$user_name = $user_info->user_login;
print_r($user_info);
wp_delete_term( get_term_by('name', $user_name, 'user1')->term_id, 'user1', array() );
}
``` |
310,127 | <p>I have a user registration form implemented and working correctly on the front end of a website. My main issue is that I would like to redirect a user after completing the profile form. </p>
<p>My idea would be to show a page with some content to let the user know that their account is being reviewed. So this kind of users will have a new role called "members-in-approval" and once the admin reviews their profile and approve them, they would get the role "active member".</p>
<p>Everything is working fine right now but I cannot redirect them to the page I mention before after completing the profile.</p>
<p>I'm pretty new using WP so any help or advice would be appreciated. Thanks!</p>
| [
{
"answer_id": 310128,
"author": "Andrea Somovigo",
"author_id": 64435,
"author_profile": "https://wordpress.stackexchange.com/users/64435",
"pm_score": 1,
"selected": false,
"text": "<p>If I understand well you have a <code>custom_taxonomy</code> and the terms slugs of it correspond to the usernames..in this case try </p>\n\n<pre><code>function yg_user_delete( $user_id ) {\n $user_info = get_userdata($user_id); \n $user_name = $user_info->user_login;\n\n wp_delete_term(get_term_by('slug', $user_name)->term_id,'custom_taxonomy');\n}\n</code></pre>\n"
},
{
"answer_id": 310130,
"author": "Siavash1991",
"author_id": 35070,
"author_profile": "https://wordpress.stackexchange.com/users/35070",
"pm_score": 1,
"selected": true,
"text": "<p>Replace this with yours:</p>\n\n<pre><code>add_action( 'delete_user', 'yg_user_delete', 10, 1 );\n\nfunction yg_user_delete( $user_id ) {\n\n $user_info = get_userdata($user_id); \n $user_name = $user_info->user_login;\n\n print_r($user_info);\n\n wp_delete_term( get_term_by('name', $user_name, 'user1')->term_id, 'user1', array() );\n\n}\n</code></pre>\n"
}
]
| 2018/08/01 | [
"https://wordpress.stackexchange.com/questions/310127",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147869/"
]
| I have a user registration form implemented and working correctly on the front end of a website. My main issue is that I would like to redirect a user after completing the profile form.
My idea would be to show a page with some content to let the user know that their account is being reviewed. So this kind of users will have a new role called "members-in-approval" and once the admin reviews their profile and approve them, they would get the role "active member".
Everything is working fine right now but I cannot redirect them to the page I mention before after completing the profile.
I'm pretty new using WP so any help or advice would be appreciated. Thanks! | Replace this with yours:
```
add_action( 'delete_user', 'yg_user_delete', 10, 1 );
function yg_user_delete( $user_id ) {
$user_info = get_userdata($user_id);
$user_name = $user_info->user_login;
print_r($user_info);
wp_delete_term( get_term_by('name', $user_name, 'user1')->term_id, 'user1', array() );
}
``` |
310,138 | <pre><code> <?php
wp_nav_menu(array(
'theme_location' => 'primary',
'container' => 'ul',
'menu_class'=> 'top-menu'
/* 'walker' => new Walker_nav_Primary() */
)
);
?>
</code></pre>
<p>This is a simple wp_nav_menu </p>
<p><a href="https://i.stack.imgur.com/ElDeP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ElDeP.png" alt="enter image description here"></a></p>
<p>You can see ascending order from above example </p>
<p>I have done this in WP. </p>
<p><a href="https://i.stack.imgur.com/Z05LZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Z05LZ.png" alt="enter image description here"></a> </p>
<p>wp_nav_menu gives me ascending order menu. How can I arrange as dashboard?</p>
<p>Please help.</p>
| [
{
"answer_id": 310134,
"author": "Siavash1991",
"author_id": 35070,
"author_profile": "https://wordpress.stackexchange.com/users/35070",
"pm_score": 0,
"selected": false,
"text": "<p>Replace this with your search form and products will show in results:</p>\n\n<pre><code> <form method=\"get\" id=\"searchform\" action=\"<?php echo esc_url( home_url( '/' ) ); ?>\">\n <label for=\"s\">Search</label>\n <input type=\"text\" class=\"field\" name=\"s\" id=\"s\" placeholder=\"Search Something\" />\n <input type=\"submit\" class=\"submit\" name=\"submit\" id=\"searchsubmit\" value=\"Search\" />\n <input type=\"hidden\" name=\"post_type\" id=\"post_type\" value=\"product\" />\n</form>\n</code></pre>\n"
},
{
"answer_id": 310135,
"author": "nmr",
"author_id": 147428,
"author_profile": "https://wordpress.stackexchange.com/users/147428",
"pm_score": 1,
"selected": false,
"text": "<p>You have in your query <code>WHERE p.post_type IN ('post', 'page')</code>, that is why it shows only the posts and pages. Add post type <strong>product</strong> to query:\n<code>WHERE p.post_type IN ('post', 'page', 'product')</code></p>\n"
}
]
| 2018/08/01 | [
"https://wordpress.stackexchange.com/questions/310138",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
]
| ```
<?php
wp_nav_menu(array(
'theme_location' => 'primary',
'container' => 'ul',
'menu_class'=> 'top-menu'
/* 'walker' => new Walker_nav_Primary() */
)
);
?>
```
This is a simple wp\_nav\_menu
[](https://i.stack.imgur.com/ElDeP.png)
You can see ascending order from above example
I have done this in WP.
[](https://i.stack.imgur.com/Z05LZ.png)
wp\_nav\_menu gives me ascending order menu. How can I arrange as dashboard?
Please help. | You have in your query `WHERE p.post_type IN ('post', 'page')`, that is why it shows only the posts and pages. Add post type **product** to query:
`WHERE p.post_type IN ('post', 'page', 'product')` |
310,165 | <p>I am creating a custom user role with the code below in functions.php, however WordPress only allows the user to create draft pages, they can't then edit draft pages or publish pages even though I have set the capabilities to true?</p>
<p>Any help is much appreciated!. Thanks in advance.</p>
<pre><code>add_action('admin_init', 'user_custom_roles');
function user_custom_roles() {
add_role(
'editor_limited',
'Editor Limited',
array(
'read' => true,
'edit_pages' => true,
'edit_posts' => true,
'edit_published_pages' => true,
'edit_published_posts' => true,
'edit_others_pages' => true,
'edit_others_posts' => true,
'publish_pages' => true,
'publish_posts' => true,
'upload_files' => true,
'unfiltered_html' => true
)
);
}
</code></pre>
| [
{
"answer_id": 310134,
"author": "Siavash1991",
"author_id": 35070,
"author_profile": "https://wordpress.stackexchange.com/users/35070",
"pm_score": 0,
"selected": false,
"text": "<p>Replace this with your search form and products will show in results:</p>\n\n<pre><code> <form method=\"get\" id=\"searchform\" action=\"<?php echo esc_url( home_url( '/' ) ); ?>\">\n <label for=\"s\">Search</label>\n <input type=\"text\" class=\"field\" name=\"s\" id=\"s\" placeholder=\"Search Something\" />\n <input type=\"submit\" class=\"submit\" name=\"submit\" id=\"searchsubmit\" value=\"Search\" />\n <input type=\"hidden\" name=\"post_type\" id=\"post_type\" value=\"product\" />\n</form>\n</code></pre>\n"
},
{
"answer_id": 310135,
"author": "nmr",
"author_id": 147428,
"author_profile": "https://wordpress.stackexchange.com/users/147428",
"pm_score": 1,
"selected": false,
"text": "<p>You have in your query <code>WHERE p.post_type IN ('post', 'page')</code>, that is why it shows only the posts and pages. Add post type <strong>product</strong> to query:\n<code>WHERE p.post_type IN ('post', 'page', 'product')</code></p>\n"
}
]
| 2018/08/01 | [
"https://wordpress.stackexchange.com/questions/310165",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/116154/"
]
| I am creating a custom user role with the code below in functions.php, however WordPress only allows the user to create draft pages, they can't then edit draft pages or publish pages even though I have set the capabilities to true?
Any help is much appreciated!. Thanks in advance.
```
add_action('admin_init', 'user_custom_roles');
function user_custom_roles() {
add_role(
'editor_limited',
'Editor Limited',
array(
'read' => true,
'edit_pages' => true,
'edit_posts' => true,
'edit_published_pages' => true,
'edit_published_posts' => true,
'edit_others_pages' => true,
'edit_others_posts' => true,
'publish_pages' => true,
'publish_posts' => true,
'upload_files' => true,
'unfiltered_html' => true
)
);
}
``` | You have in your query `WHERE p.post_type IN ('post', 'page')`, that is why it shows only the posts and pages. Add post type **product** to query:
`WHERE p.post_type IN ('post', 'page', 'product')` |
310,173 | <p>I am using <code>woocommerce_admin_order_actions</code> hook to add an additional action like Invoice. But it is repeating many many times whereas others button are repeating once.</p>
<pre class="lang-php prettyprint-override"><code>public function add_new_list_for_action($actions, $the_order) {
if ( $the_order->has_status( array( 'processing' ) ) ) {
$status = $_GET['status'];
$order_id = method_exists($the_order, 'get_id') ? $the_order->get_id() : $the_order->id;
$actions[] = ["action" => "invoice",
"url" => wp_nonce_url(admin_url('admin-ajax.php?action=wip_pdf_generator&status=invoice'.$status.'&order_id=' . $order_id), 'wip_pdf_generator'),
"name" => "Invoice"];
}
return $actions;
}
add_filter( 'woocommerce_admin_order_actions', array($this, 'add_new_list_for_action'),1, 2);
</code></pre>
| [
{
"answer_id": 310175,
"author": "VinothRaja",
"author_id": 146008,
"author_profile": "https://wordpress.stackexchange.com/users/146008",
"pm_score": 1,
"selected": false,
"text": "<p>Add this below code your current active theme functions.php file</p>\n\n<pre><code>add_filter( 'woocommerce_admin_order_actions', 'add_custom_order_status_actions_button', 100, 2 );\nfunction add_custom_order_status_actions_button( $actions, $order ) {\n\n if ( $order->has_status( array( 'processing' ) ) ) {\n\n // The key slug defined for your action button\n $action_slug = 'invoice';\n $status = $_GET['status'];\n $order_id = method_exists($the_order, 'get_id') ? $the_order->get_id() : $the_order->id;\n // Set the action button\n $actions[$action_slug] = array(\n 'url' => wp_nonce_url(admin_url('admin-ajax.php?action=wip_pdf_generator&status=invoice'.$status.'&order_id=' . $order_id), 'wip_pdf_generator'),\n 'name' => __( 'Invoice', 'woocommerce' ),\n 'action' => $action_slug,\n );\n }\n return $actions;\n}\n\n\nadd_action( 'admin_head', 'add_custom_order_status_actions_button_css' );\nfunction add_custom_order_status_actions_button_css() {\n $action_slug = \"invoice\"; // The key slug defined for your action button\n\n echo '<style>.wc-action-button-'.$action_slug.'::after { font-family: woocommerce !important; content: \"\\e029\" !important; }</style>';\n}\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/1GTMe.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1GTMe.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 409217,
"author": "Hasan Baig",
"author_id": 109317,
"author_profile": "https://wordpress.stackexchange.com/users/109317",
"pm_score": 0,
"selected": false,
"text": "<p>Its a common error which you are facing, infect when you attached some code with WordPress action hock, that action hock called many time in loop so best practice which I have observed in such case it to attached the code with some conditional if/else statement which executes the code when conditions comes true. Right now in your case I have not any code to share but it will work if you know some specific condition in your code context.</p>\n"
}
]
| 2018/08/01 | [
"https://wordpress.stackexchange.com/questions/310173",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/141331/"
]
| I am using `woocommerce_admin_order_actions` hook to add an additional action like Invoice. But it is repeating many many times whereas others button are repeating once.
```php
public function add_new_list_for_action($actions, $the_order) {
if ( $the_order->has_status( array( 'processing' ) ) ) {
$status = $_GET['status'];
$order_id = method_exists($the_order, 'get_id') ? $the_order->get_id() : $the_order->id;
$actions[] = ["action" => "invoice",
"url" => wp_nonce_url(admin_url('admin-ajax.php?action=wip_pdf_generator&status=invoice'.$status.'&order_id=' . $order_id), 'wip_pdf_generator'),
"name" => "Invoice"];
}
return $actions;
}
add_filter( 'woocommerce_admin_order_actions', array($this, 'add_new_list_for_action'),1, 2);
``` | Add this below code your current active theme functions.php file
```
add_filter( 'woocommerce_admin_order_actions', 'add_custom_order_status_actions_button', 100, 2 );
function add_custom_order_status_actions_button( $actions, $order ) {
if ( $order->has_status( array( 'processing' ) ) ) {
// The key slug defined for your action button
$action_slug = 'invoice';
$status = $_GET['status'];
$order_id = method_exists($the_order, 'get_id') ? $the_order->get_id() : $the_order->id;
// Set the action button
$actions[$action_slug] = array(
'url' => wp_nonce_url(admin_url('admin-ajax.php?action=wip_pdf_generator&status=invoice'.$status.'&order_id=' . $order_id), 'wip_pdf_generator'),
'name' => __( 'Invoice', 'woocommerce' ),
'action' => $action_slug,
);
}
return $actions;
}
add_action( 'admin_head', 'add_custom_order_status_actions_button_css' );
function add_custom_order_status_actions_button_css() {
$action_slug = "invoice"; // The key slug defined for your action button
echo '<style>.wc-action-button-'.$action_slug.'::after { font-family: woocommerce !important; content: "\e029" !important; }</style>';
}
```
[](https://i.stack.imgur.com/1GTMe.png) |
310,201 | <p>Simple task, but it isn't working:</p>
<pre><code><?php
$content = apply_filters( 'the_content', get_the_content() );
$contentWithoutHTML = wp_strip_all_tags($content);
$pos = strpos($contentWithoutHTML, " ", 100);
$contentFinal = substr($contentWithoutHTML,0,$pos );
echo $contentFinal . "...";
?>
</code></pre>
<p>My post is way over 100 characters long (with spaces), and yet I get <code>strpos(): Offset not contained in string</code> error, which leads me to believe it isn't actually pulling the entire content string. But I applied filters like I believe I should... please assist. Also sometimes even if I get no offset error I just get <code>...</code> even though again, over 100 characters with spaces... although sometimes it works. Why the inconsistency?</p>
<p>This is in a <code>WP_Query</code> loop in which most of them work, but some of them do not... so I am pretty sure it is being fed a string because I see it happening to the other posts in the loop...</p>
<p>Full Loop:</p>
<pre><code><?php
$args = array(
'orderby' => 'ID',
'order' => 'ASC',
'posts_per_page' => 7,
'meta_query' => array(
array(
'key' => '_thumbnail_id'
)
)
);
$query = new WP_Query($args);
while ($query->have_posts()):
$query->the_post();
?>
<div class="articleboxs boxs">
<div class="col-sm-4 noleft">
<div class="aricleleft boxs">
<?php the_post_thumbnail('medium', array(
'class' => 'img-responsive'
)) ?>
</div>
</div>
<div class="col-sm-8 noright">
<div class="aricleright boxs">
<div class="boxs">
<a href="<?php echo get_permalink(); ?>"><h2 class="heading font_Libre"><?php the_title(); ?></h2></a>
<?php
$content = apply_filters('the_content', get_the_content('', true));
print_r($content);
$contentWithoutHTML = wp_strip_all_tags($content);
$pos = strpos($contentWithoutHTML, " ", 100);
$contentFinal = substr($contentWithoutHTML, 0, $pos);
?>
<p class="font_Roboto"><?php echo $contentFinal . "..."; ?></p>
</div>
</div>
</div>
</div>
<?php
endwhile;
wp_reset_postdata();
?>
</code></pre>
| [
{
"answer_id": 310177,
"author": "Martin Jarvis",
"author_id": 147693,
"author_profile": "https://wordpress.stackexchange.com/users/147693",
"pm_score": 2,
"selected": true,
"text": "<p>If you want all of the product meta to be styled in the same way, then add the following to your theme custom CSS or style.css in your child theme, and edit as required...</p>\n\n<p>.product_meta {\n padding-top: 6px;\n border-top: 1px solid #dadada;\n color: #666;\n font-size: 18px;\n}</p>\n\n<p>If you want something different for each of the product meta elements, then you would add something like the following...</p>\n\n<p>.sku_wrapper {\n padding-top: 6px;\n border-top: 1px solid #dadada;\n color: #666;\n font-size: 18px;\n}</p>\n\n<p>and </p>\n\n<p>.posted_in {\n padding-top: 6px;\n border-top: 1px solid #dadada;\n color: #666;\n font-size: 18px;\n}</p>\n"
},
{
"answer_id": 310178,
"author": "VinothRaja",
"author_id": 146008,
"author_profile": "https://wordpress.stackexchange.com/users/146008",
"pm_score": 0,
"selected": false,
"text": "<p>Add the your custom style for this below \"product_meta\" class in your active theme css file</p>\n\n<pre><code> .product_meta\n {\n /// Here add your custom css code\n font-size: small;\n color : red\n }\n</code></pre>\n"
}
]
| 2018/08/01 | [
"https://wordpress.stackexchange.com/questions/310201",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77764/"
]
| Simple task, but it isn't working:
```
<?php
$content = apply_filters( 'the_content', get_the_content() );
$contentWithoutHTML = wp_strip_all_tags($content);
$pos = strpos($contentWithoutHTML, " ", 100);
$contentFinal = substr($contentWithoutHTML,0,$pos );
echo $contentFinal . "...";
?>
```
My post is way over 100 characters long (with spaces), and yet I get `strpos(): Offset not contained in string` error, which leads me to believe it isn't actually pulling the entire content string. But I applied filters like I believe I should... please assist. Also sometimes even if I get no offset error I just get `...` even though again, over 100 characters with spaces... although sometimes it works. Why the inconsistency?
This is in a `WP_Query` loop in which most of them work, but some of them do not... so I am pretty sure it is being fed a string because I see it happening to the other posts in the loop...
Full Loop:
```
<?php
$args = array(
'orderby' => 'ID',
'order' => 'ASC',
'posts_per_page' => 7,
'meta_query' => array(
array(
'key' => '_thumbnail_id'
)
)
);
$query = new WP_Query($args);
while ($query->have_posts()):
$query->the_post();
?>
<div class="articleboxs boxs">
<div class="col-sm-4 noleft">
<div class="aricleleft boxs">
<?php the_post_thumbnail('medium', array(
'class' => 'img-responsive'
)) ?>
</div>
</div>
<div class="col-sm-8 noright">
<div class="aricleright boxs">
<div class="boxs">
<a href="<?php echo get_permalink(); ?>"><h2 class="heading font_Libre"><?php the_title(); ?></h2></a>
<?php
$content = apply_filters('the_content', get_the_content('', true));
print_r($content);
$contentWithoutHTML = wp_strip_all_tags($content);
$pos = strpos($contentWithoutHTML, " ", 100);
$contentFinal = substr($contentWithoutHTML, 0, $pos);
?>
<p class="font_Roboto"><?php echo $contentFinal . "..."; ?></p>
</div>
</div>
</div>
</div>
<?php
endwhile;
wp_reset_postdata();
?>
``` | If you want all of the product meta to be styled in the same way, then add the following to your theme custom CSS or style.css in your child theme, and edit as required...
.product\_meta {
padding-top: 6px;
border-top: 1px solid #dadada;
color: #666;
font-size: 18px;
}
If you want something different for each of the product meta elements, then you would add something like the following...
.sku\_wrapper {
padding-top: 6px;
border-top: 1px solid #dadada;
color: #666;
font-size: 18px;
}
and
.posted\_in {
padding-top: 6px;
border-top: 1px solid #dadada;
color: #666;
font-size: 18px;
} |
310,213 | <p>I have a very simple plugin with a javascript file and a PHP file. I want to call the PHP file from my javascript code and get the output. The javascript functions is something like the following:</p>
<pre><code>function img_upload(){
var ajax = new XMLHttpRequest();
ajax.open('GET', 'http://My_Domain_Name.com/wp-content/plugins/My_Plugin/auth.php', false);
ajax.send();
if (ajax.status === 200) {
console.log(ajax.responseText);
}
</code></pre>
<p>and the PHP file which returns the results:</p>
<pre><code><?php
$token=Get_Token();
echo $token;
function Get_Token()
{
//Do some stuff
return $token;
}
?>
</code></pre>
<p>both files (auth.php and myjs.js) are in the root directory of the plugin.</p>
<pre><code>/home/My_Username/public_html/wp-content/plugins/My_Plugin
</code></pre>
<p>If I use the domain name I can call the php file in ajax.open() and get the results, but I know this is not the right way to do that. How can I call the php file inside my javascrip code via ajax.open('path_to_php') in Wordpress properly without indicating the domain name?</p>
| [
{
"answer_id": 310215,
"author": "Adam Mellen",
"author_id": 147913,
"author_profile": "https://wordpress.stackexchange.com/users/147913",
"pm_score": -1,
"selected": false,
"text": "<p>Use <code>plugins_url()</code> to get the location of <code>site/wp-content/plugins</code>:</p>\n\n<pre><code>ajax.open('GET', '<?php echo plugins_url(); ?>/My_Plugin/auth.php', false);\n</code></pre>\n\n<p>This will put the following HTML code in:</p>\n\n<pre><code>ajax.open('GET', 'http://my.domain.com/wp-content/plugins/My_Plugin/auth.php', false);\n</code></pre>\n\n<p>If your file is a full JavaScript file and not part of a template, you can make your JavaScript file in to a PHP file like so:</p>\n\n<pre><code><?php\nheader('Content-Type: application/javascript'); //mark this PHP file as a JS file\n?>\nvar pluginUrl = '<?php echo plugins_url(); ?>';\n\najax.open('GET', pluginUrl + '/My_Plugin/auth.php', false);\n//.....\n</code></pre>\n\n<p>Save this with the name <code>image_upload.js.php</code> (or whatever you are naming it) and then just include it normally:</p>\n\n<pre><code>wp_enqueue_script('image_upload', plugins_url() . '/My_Plugin/image_upload.js.php');\n</code></pre>\n"
},
{
"answer_id": 310217,
"author": "Ciprian",
"author_id": 7349,
"author_profile": "https://wordpress.stackexchange.com/users/7349",
"pm_score": 1,
"selected": false,
"text": "<p>Here's an example:</p>\n\n<p>Use this sample JavaScript code:</p>\n\n<pre><code>jQuery(document).on('click', '.some-element', function(e){\n var ipc = jQuery(this).data('collection-id');\n jQuery('.some-other-element').show();\n\n jQuery.ajax({\n method: 'post',\n url: ipAjaxVar.ajaxurl,\n data: {\n collection_id: ipc,\n action: 'my_function',\n }\n }).done(function(msg) {\n // Do something when done\n });\n\n e.preventDefault();\n});\n</code></pre>\n\n<p>PHP (include the function in your plugin, do not use a separate file):</p>\n\n<pre><code>// Include the JavaScript above in your plugin\nwp_enqueue_script('main', plugins_url('js/jquery.main.js', __FILE__), array('jquery'), '', true);\n\nwp_localize_script('main', 'ipAjaxVar', array(\n 'ajaxurl' => admin_url('admin-ajax.php')\n));\n\nadd_action('wp_ajax_my_function', 'my_function');\n</code></pre>\n\n<p><strong>UPDATE:</strong></p>\n\n<p>Add the PHP code to your main plugin file. Create a JavaScript file - <code>js/jquery.main.js</code> - and add the code above. That should do the trick.</p>\n"
}
]
| 2018/08/01 | [
"https://wordpress.stackexchange.com/questions/310213",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122813/"
]
| I have a very simple plugin with a javascript file and a PHP file. I want to call the PHP file from my javascript code and get the output. The javascript functions is something like the following:
```
function img_upload(){
var ajax = new XMLHttpRequest();
ajax.open('GET', 'http://My_Domain_Name.com/wp-content/plugins/My_Plugin/auth.php', false);
ajax.send();
if (ajax.status === 200) {
console.log(ajax.responseText);
}
```
and the PHP file which returns the results:
```
<?php
$token=Get_Token();
echo $token;
function Get_Token()
{
//Do some stuff
return $token;
}
?>
```
both files (auth.php and myjs.js) are in the root directory of the plugin.
```
/home/My_Username/public_html/wp-content/plugins/My_Plugin
```
If I use the domain name I can call the php file in ajax.open() and get the results, but I know this is not the right way to do that. How can I call the php file inside my javascrip code via ajax.open('path\_to\_php') in Wordpress properly without indicating the domain name? | Here's an example:
Use this sample JavaScript code:
```
jQuery(document).on('click', '.some-element', function(e){
var ipc = jQuery(this).data('collection-id');
jQuery('.some-other-element').show();
jQuery.ajax({
method: 'post',
url: ipAjaxVar.ajaxurl,
data: {
collection_id: ipc,
action: 'my_function',
}
}).done(function(msg) {
// Do something when done
});
e.preventDefault();
});
```
PHP (include the function in your plugin, do not use a separate file):
```
// Include the JavaScript above in your plugin
wp_enqueue_script('main', plugins_url('js/jquery.main.js', __FILE__), array('jquery'), '', true);
wp_localize_script('main', 'ipAjaxVar', array(
'ajaxurl' => admin_url('admin-ajax.php')
));
add_action('wp_ajax_my_function', 'my_function');
```
**UPDATE:**
Add the PHP code to your main plugin file. Create a JavaScript file - `js/jquery.main.js` - and add the code above. That should do the trick. |
310,214 | <p>I have 2 custom post types, <code>project</code> and <code>person</code>. Both have several custom fields.
I'm working on a template for the <code>project</code> custom post type.</p>
<p>In the <code>project</code> custom fields I have several fields of type relation, as seen in this screenshot. Unfortunately I don't really undestand what they mean and how to use them, but that is not my main question.<a href="https://i.stack.imgur.com/sEPPx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sEPPx.png" alt="enter image description here"></a></p>
<p>Next, inside the <code>person</code> custom fields, I have only text fields, like <code>first_name</code>, <code>last_name</code>, etc.</p>
<p>Now let's say I have one custom post type of type <code>person</code>. That person has contributed to a project, which is a custom post type of type <code>project</code>. </p>
<p>How can I now, when working on the template of the <code>project</code> posts, include an [acf field] shortcode to a custom field of type <code>person</code>?</p>
<p>Here is a screenshot/concept of what I want to do: Circled in red are information pulled from the <code>project</code> custom fields, whereas circled in blue are information pulled from the <code>person</code> custom fields.
<a href="https://i.stack.imgur.com/j0vhJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/j0vhJ.png" alt="enter image description here"></a></p>
<p>Notes:</p>
<ul>
<li><p>I'm fairly new to wordpress and have no knowledge in php</p></li>
<li><p>Ideally a solution to my problem should not need me to add code to php files as that is not desired by my client. Preferably it should be doable inside the WPBakery template editor.</p>
<ul>
<li>Installed and usable plugins are ACF, WPBakery, toolset, salient, acf-vc, custom post type UI</li>
</ul></li>
</ul>
<p>Thank you for your help, I hope I succeeded to phrase my problem in an understandable manner.</p>
<h2>UPDATE</h2>
<p>I found this plugin, which seems to do provide one solution: nested shortcodes: <a href="https://wordpress.org/plugins/nested-shortcodes/" rel="nofollow noreferrer">https://wordpress.org/plugins/nested-shortcodes/</a></p>
<p>Unfortunately, it also poses constraints, and has not allowed me to find a solution. What I want to do is this: </p>
<p>Input: <code>[acf field="first_name" post_id=[acf field="student"]]</code></p>
<p>With the expected output being: <code>John Doe</code></p>
<p>Unfortunately the output I get is: <code>]</code></p>
<p>Which according to them is partly due to shortcode limitations listed here <a href="https://codex.wordpress.org/Shortcode_API#Limitations" rel="nofollow noreferrer">https://codex.wordpress.org/Shortcode_API#Limitations</a></p>
<p>On the other hand, this hardcoded workaround works:</p>
<p>Input: <code>[acf field="student"]</code> Output: <code>89</code></p>
<p>Input: <code>[acf field="first_name" post_id=89]</code> Output: <code>John Doe</code></p>
<p>Unfortunately this workaround has the hardcoded unique ID 89, which makes it thus unable to use as a template for future usage.</p>
<p>Does anyone have a solution or better workaround that does not necessite me to hardcode? I'm also open for completely new ideas and directions, as long as it helps me solve this problem</p>
| [
{
"answer_id": 310215,
"author": "Adam Mellen",
"author_id": 147913,
"author_profile": "https://wordpress.stackexchange.com/users/147913",
"pm_score": -1,
"selected": false,
"text": "<p>Use <code>plugins_url()</code> to get the location of <code>site/wp-content/plugins</code>:</p>\n\n<pre><code>ajax.open('GET', '<?php echo plugins_url(); ?>/My_Plugin/auth.php', false);\n</code></pre>\n\n<p>This will put the following HTML code in:</p>\n\n<pre><code>ajax.open('GET', 'http://my.domain.com/wp-content/plugins/My_Plugin/auth.php', false);\n</code></pre>\n\n<p>If your file is a full JavaScript file and not part of a template, you can make your JavaScript file in to a PHP file like so:</p>\n\n<pre><code><?php\nheader('Content-Type: application/javascript'); //mark this PHP file as a JS file\n?>\nvar pluginUrl = '<?php echo plugins_url(); ?>';\n\najax.open('GET', pluginUrl + '/My_Plugin/auth.php', false);\n//.....\n</code></pre>\n\n<p>Save this with the name <code>image_upload.js.php</code> (or whatever you are naming it) and then just include it normally:</p>\n\n<pre><code>wp_enqueue_script('image_upload', plugins_url() . '/My_Plugin/image_upload.js.php');\n</code></pre>\n"
},
{
"answer_id": 310217,
"author": "Ciprian",
"author_id": 7349,
"author_profile": "https://wordpress.stackexchange.com/users/7349",
"pm_score": 1,
"selected": false,
"text": "<p>Here's an example:</p>\n\n<p>Use this sample JavaScript code:</p>\n\n<pre><code>jQuery(document).on('click', '.some-element', function(e){\n var ipc = jQuery(this).data('collection-id');\n jQuery('.some-other-element').show();\n\n jQuery.ajax({\n method: 'post',\n url: ipAjaxVar.ajaxurl,\n data: {\n collection_id: ipc,\n action: 'my_function',\n }\n }).done(function(msg) {\n // Do something when done\n });\n\n e.preventDefault();\n});\n</code></pre>\n\n<p>PHP (include the function in your plugin, do not use a separate file):</p>\n\n<pre><code>// Include the JavaScript above in your plugin\nwp_enqueue_script('main', plugins_url('js/jquery.main.js', __FILE__), array('jquery'), '', true);\n\nwp_localize_script('main', 'ipAjaxVar', array(\n 'ajaxurl' => admin_url('admin-ajax.php')\n));\n\nadd_action('wp_ajax_my_function', 'my_function');\n</code></pre>\n\n<p><strong>UPDATE:</strong></p>\n\n<p>Add the PHP code to your main plugin file. Create a JavaScript file - <code>js/jquery.main.js</code> - and add the code above. That should do the trick.</p>\n"
}
]
| 2018/08/01 | [
"https://wordpress.stackexchange.com/questions/310214",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147919/"
]
| I have 2 custom post types, `project` and `person`. Both have several custom fields.
I'm working on a template for the `project` custom post type.
In the `project` custom fields I have several fields of type relation, as seen in this screenshot. Unfortunately I don't really undestand what they mean and how to use them, but that is not my main question.[](https://i.stack.imgur.com/sEPPx.png)
Next, inside the `person` custom fields, I have only text fields, like `first_name`, `last_name`, etc.
Now let's say I have one custom post type of type `person`. That person has contributed to a project, which is a custom post type of type `project`.
How can I now, when working on the template of the `project` posts, include an [acf field] shortcode to a custom field of type `person`?
Here is a screenshot/concept of what I want to do: Circled in red are information pulled from the `project` custom fields, whereas circled in blue are information pulled from the `person` custom fields.
[](https://i.stack.imgur.com/j0vhJ.png)
Notes:
* I'm fairly new to wordpress and have no knowledge in php
* Ideally a solution to my problem should not need me to add code to php files as that is not desired by my client. Preferably it should be doable inside the WPBakery template editor.
+ Installed and usable plugins are ACF, WPBakery, toolset, salient, acf-vc, custom post type UI
Thank you for your help, I hope I succeeded to phrase my problem in an understandable manner.
UPDATE
------
I found this plugin, which seems to do provide one solution: nested shortcodes: <https://wordpress.org/plugins/nested-shortcodes/>
Unfortunately, it also poses constraints, and has not allowed me to find a solution. What I want to do is this:
Input: `[acf field="first_name" post_id=[acf field="student"]]`
With the expected output being: `John Doe`
Unfortunately the output I get is: `]`
Which according to them is partly due to shortcode limitations listed here <https://codex.wordpress.org/Shortcode_API#Limitations>
On the other hand, this hardcoded workaround works:
Input: `[acf field="student"]` Output: `89`
Input: `[acf field="first_name" post_id=89]` Output: `John Doe`
Unfortunately this workaround has the hardcoded unique ID 89, which makes it thus unable to use as a template for future usage.
Does anyone have a solution or better workaround that does not necessite me to hardcode? I'm also open for completely new ideas and directions, as long as it helps me solve this problem | Here's an example:
Use this sample JavaScript code:
```
jQuery(document).on('click', '.some-element', function(e){
var ipc = jQuery(this).data('collection-id');
jQuery('.some-other-element').show();
jQuery.ajax({
method: 'post',
url: ipAjaxVar.ajaxurl,
data: {
collection_id: ipc,
action: 'my_function',
}
}).done(function(msg) {
// Do something when done
});
e.preventDefault();
});
```
PHP (include the function in your plugin, do not use a separate file):
```
// Include the JavaScript above in your plugin
wp_enqueue_script('main', plugins_url('js/jquery.main.js', __FILE__), array('jquery'), '', true);
wp_localize_script('main', 'ipAjaxVar', array(
'ajaxurl' => admin_url('admin-ajax.php')
));
add_action('wp_ajax_my_function', 'my_function');
```
**UPDATE:**
Add the PHP code to your main plugin file. Create a JavaScript file - `js/jquery.main.js` - and add the code above. That should do the trick. |
310,226 | <p>I am using this code and I am not sure why the script is not loaded. I believe the syntax is correct since I am trying to load the script only on the "events" custom post type single posts.</p>
<pre><code>add_action( 'login_enqueue_scripts', 'wpse_login_enqueue_scripts', 10 );
function wpse_login_enqueue_scripts() {
if( is_single() && get_post_type()=='events' ){
wp_enqueue_script( 'bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js', array('jquery'), '3.3.5', true );
}
}
</code></pre>
| [
{
"answer_id": 310227,
"author": "Kaperto",
"author_id": 147795,
"author_profile": "https://wordpress.stackexchange.com/users/147795",
"pm_score": 0,
"selected": false,
"text": "<p>this hook is only fired on the login page :<br>\n<a href=\"https://developer.wordpress.org/reference/hooks/login_enqueue_scripts/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/login_enqueue_scripts/</a></p>\n\n<p>to use on a custom post page, use the action <code>wp_enqueue_scripts</code>.</p>\n"
},
{
"answer_id": 310228,
"author": "Iceable",
"author_id": 136263,
"author_profile": "https://wordpress.stackexchange.com/users/136263",
"pm_score": 0,
"selected": false,
"text": "<p>You are hooking this function to <code>'login_enqueue_scripts'</code> (which only runs on the login page) ; you sould hook it to <code>'wp_enqueue_scripts'</code> instead.</p>\n\n<p>Also <code>( is_single() && get_post_type()=='events' )</code> would work, but as Jacob Peattie pointed out in another answer, <code>is_singular( 'events' )</code> is the best way to check for a custom post type single post.</p>\n\n<p>Lastly you should rename the function from <code>wpse_login_enqueue_scripts()</code> to something like <code>wpse_events_enqueue_scripts()</code> to make it more descriptive and less confusing:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'wpse_events_enqueue_scripts', 10 );\nfunction wpse_events_enqueue_scripts() {\n if ( is_single() && 'events' == get_post_type() ) {\n wp_enqueue_script( 'bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js', array('jquery'), '3.3.5', true );\n }\n}\n</code></pre>\n"
},
{
"answer_id": 310229,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>To enqueue scripts on the front-end, the hook should be <code>wp_enqueue_scripts</code>, not <code>login_enqueue_scripts</code>.</p>\n\n<p>Also, a better way to see if you’re on a single custom post type is to use <code>is_singular()</code> and pass the post type you want to check:</p>\n\n<pre><code>if ( is_singular( 'events' ) ) {\n}\n</code></pre>\n\n<p><code>get_post_type()</code> relies on the global <code>$post</code> object, and not the main query. They're often the same but under some circumstances the <code>$post</code> object might not be the same post as the current single post.</p>\n"
}
]
| 2018/08/01 | [
"https://wordpress.stackexchange.com/questions/310226",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40727/"
]
| I am using this code and I am not sure why the script is not loaded. I believe the syntax is correct since I am trying to load the script only on the "events" custom post type single posts.
```
add_action( 'login_enqueue_scripts', 'wpse_login_enqueue_scripts', 10 );
function wpse_login_enqueue_scripts() {
if( is_single() && get_post_type()=='events' ){
wp_enqueue_script( 'bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js', array('jquery'), '3.3.5', true );
}
}
``` | To enqueue scripts on the front-end, the hook should be `wp_enqueue_scripts`, not `login_enqueue_scripts`.
Also, a better way to see if you’re on a single custom post type is to use `is_singular()` and pass the post type you want to check:
```
if ( is_singular( 'events' ) ) {
}
```
`get_post_type()` relies on the global `$post` object, and not the main query. They're often the same but under some circumstances the `$post` object might not be the same post as the current single post. |
310,243 | <p>I used this code for changing the email sender name from Wordpress to my own title.</p>
<pre><code>function wpb_sender_email($original_email_address)
{
return '[email protected]';
}
// Function to change sender name
function wpb_sender_name($original_email_from)
{
return 'mydomain.com';
}
// Hooking up our functions to WordPress filters
add_filter('wp_mail_from', 'wpb_sender_email');
add_filter('wp_mail_from_name', 'wpb_sender_name');
</code></pre>
<p>But it just changes welcome emails. when a user wants to change his/her email, the email notification send by <code>[email protected]</code>
So how can I change it too?</p>
| [
{
"answer_id": 310250,
"author": "John Dee",
"author_id": 131224,
"author_profile": "https://wordpress.stackexchange.com/users/131224",
"pm_score": 2,
"selected": false,
"text": "<p>As of version 4.9 there is a dubious \"feature\" that prevents you from changing the site email without a confirmation email going out, and the admin confirming his own change. Those filters, as you've discovered, won't work.</p>\n\n<p>For instance, from now on, if you're using WordPress for an IOT device or on localhost, it's impossible for an admin to change the site admin address on a single site.</p>\n\n<p>You'll have to remove the new hooks, and plop in your own. \nI put a plugin on the .org repo that does this. You can use that and just put your own values in. \n<a href=\"https://wordpress.org/plugins/change-admin-email-setting-without-outbound-email/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/change-admin-email-setting-without-outbound-email/</a></p>\n\n<p>Here is the code on Github:\n<a href=\"https://github.com/JohnDeeBDD/change-admin-email/blob/master/change-admin-email.php\" rel=\"nofollow noreferrer\">https://github.com/JohnDeeBDD/change-admin-email/blob/master/change-admin-email.php</a></p>\n"
},
{
"answer_id": 310272,
"author": "VinothRaja",
"author_id": 146008,
"author_profile": "https://wordpress.stackexchange.com/users/146008",
"pm_score": 0,
"selected": false,
"text": "<p>Paste this below code your current active functions.php file</p>\n\n<pre><code>function custom_wp_mail_from_name($from_name){\nreturn “Custom Name”;\n}\n\nadd_filter(“wp_mail_from_name”, “custom_wp_mail_from_name”);\n\n\nfunction custom_wp_mail_from($email){\nreturn “[email protected]”;\n}\nadd_filter(“wp_mail_from”, “custom_wp_mail_from”);\n</code></pre>\n"
},
{
"answer_id": 409636,
"author": "Chester",
"author_id": 225925,
"author_profile": "https://wordpress.stackexchange.com/users/225925",
"pm_score": 0,
"selected": false,
"text": "<p>Try this in your functions.php file: (Although it adds spaces between CamelCase words -- does anybody know how to remedy that?)</p>\n<pre><code>function wpb_sender_email( $original_email_address ) {\nreturn '[email protected]';\n}\nfunction wpb_sender_name( $original_email_from ) {\nreturn 'MySiteAdmin';\n}\nadd_filter( 'wp_mail_from', 'wpb_sender_email' );\nadd_filter( 'wp_mail_from_name', 'wpb_sender_name' );\n</code></pre>\n"
}
]
| 2018/08/01 | [
"https://wordpress.stackexchange.com/questions/310243",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/141105/"
]
| I used this code for changing the email sender name from Wordpress to my own title.
```
function wpb_sender_email($original_email_address)
{
return '[email protected]';
}
// Function to change sender name
function wpb_sender_name($original_email_from)
{
return 'mydomain.com';
}
// Hooking up our functions to WordPress filters
add_filter('wp_mail_from', 'wpb_sender_email');
add_filter('wp_mail_from_name', 'wpb_sender_name');
```
But it just changes welcome emails. when a user wants to change his/her email, the email notification send by `[email protected]`
So how can I change it too? | As of version 4.9 there is a dubious "feature" that prevents you from changing the site email without a confirmation email going out, and the admin confirming his own change. Those filters, as you've discovered, won't work.
For instance, from now on, if you're using WordPress for an IOT device or on localhost, it's impossible for an admin to change the site admin address on a single site.
You'll have to remove the new hooks, and plop in your own.
I put a plugin on the .org repo that does this. You can use that and just put your own values in.
<https://wordpress.org/plugins/change-admin-email-setting-without-outbound-email/>
Here is the code on Github:
<https://github.com/JohnDeeBDD/change-admin-email/blob/master/change-admin-email.php> |
310,264 | <p>I have <code>process_ipn</code> method that runs on <code>init</code> action hook. Looks like it is fired after PayPal returns to merchant. Under this method, I could find out the payment status such as <code>completed</code>, <code>pending</code>, <code>failed</code>
from PayPal. And, save it to the database.</p>
<pre><code>update_user_meta( $user_id, 'status', 'completed' );
</code></pre>
<p>I am redirecting back to login page from PayPal's return to merchant with added <code>user_id</code> and <code>form_id</code> in return url. I used the <code>login_message</code> filter to override message depending upon payment status.</p>
<pre><code>add_filter( 'login_message', array( $this,'custom_login_message' ) );
public function custom_login_message() {
$return = base64_decode ( $_GET['wdb_return'] );
$return = explode( '&', $return );
$return = explode( '=', $return[1] );
$user_id = isset( $return[1] ) ? $return[1] : -1;
if( 'completed' === get_user_meta( $user_id, 'status', true ) ) {
return print_notice( __( 'Payment Completed. Now login.','wdp' ) );
} else {
return print_notice( __( 'Payment Failed','wdp' ) );
}
}
</code></pre>
<p>The return to merchant will return to login page. The problem the status is updated too late after the login page appears. So, <code>Payment Failed</code> appears if I click on return to merchant instantly after payment. If I waited a few minutes after payment and then return to merchant, It's okay.</p>
<p>Note that <code>$user_id</code> is grabbed from return url from PayPal and is valid.</p>
<p>What could be the solution?</p>
<p>Thanks!</p>
| [
{
"answer_id": 310447,
"author": "Sanzeeb Aryal",
"author_id": 126847,
"author_profile": "https://wordpress.stackexchange.com/users/126847",
"pm_score": 0,
"selected": false,
"text": "<p><code>sleep()</code> function can be used to delay the execution.</p>\n\n<pre><code>add_filter( 'login_message', array( $this,'custom_login_message' ) );\n\npublic function custom_login_message() {\n sleep(5);\n\n $return = base64_decode ( $_GET['wdb_return'] );\n $return = explode( '&', $return );\n $return = explode( '=', $return[1] ); \n $user_id = isset( $return[1] ) ? $return[1] : -1;\n .\n .\n</code></pre>\n\n<p>Now, the notice is 'Payment Completed. Now login.' on successful payment. Because the execution is delayed in reponse to PayPal's delayed process. However <strong>I think I need more genuine answer.</strong></p>\n"
},
{
"answer_id": 310486,
"author": "firxworx",
"author_id": 134244,
"author_profile": "https://wordpress.stackexchange.com/users/134244",
"pm_score": 2,
"selected": false,
"text": "<p>If I understand your question, the race condition you describe between WordPress knowing the transaction was \"complete\" and the user returning to your site is the problem.</p>\n\n<p>Regarding a potential solution, what about changing the way you're approaching this such that this race condition is accepted as a real possibility rather than something that you can avoid? You do mention one of the possible Paypal status is \"pending\"...</p>\n\n<p>Its been years since I've worked with Paypal, but I recall the IPN feed can sometimes lag for quite a while.</p>\n\n<p>Suppose you use ajax: you could show the login page with a conditional box, or you could use an interstitial 'transaction processing' page that redirects to the login. Your process could thank your customer, show a throbber animation, and explain that you're processing the transaction / waiting for payment confirmation from Paypal. </p>\n\n<p>Your page can keep polling WordPress and when the user's meta <code>status</code> is \"complete\" you can update the user and show them the login form, and if it \"failed\" you can handle accordingly. </p>\n\n<p>I'm not sure if you're setting the Paypal \"pending\" status in the user meta, but regardless an easy way to trigger this case is by checking for the presence of the <code>user_id</code> and <code>form_id</code> in the request from Paypal. </p>\n\n<p>In cases where IPN is updated quick and/or the user pauses before returning to your site, the 'payment success' case could already work seamlessly as you desire: no need to show any throbbers or anything like that. </p>\n\n<p>I think ajax is the best approach. A continuous poll every couple seconds might sound like you're generating a lot of requests, but I doubt you will have scores of users waiting to find out their transaction outcome at any one time. If you do, congratulations, you're making lots of money :)</p>\n\n<p>WordPress also has a Heartbeat API but the fastest this can poll is 15 seconds. Web Sockets is another approach but is probably overkill and introduces its own complexities. </p>\n\n<p>Here is a tutorial that covers an example implementation: <a href=\"https://premium.wpmudev.org/blog/using-ajax-with-wordpress/\" rel=\"nofollow noreferrer\">https://premium.wpmudev.org/blog/using-ajax-with-wordpress/</a></p>\n\n<p>For a docs reference: <a href=\"https://developer.wordpress.org/plugins/javascript/ajax/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/plugins/javascript/ajax/</a></p>\n\n<p>To have javascript check continuously every few seconds, see <code>setInterval()</code> and <code>setTimeout()</code>, references: <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval</a> and there's always: <a href=\"https://www.w3schools.com/js/js_timing.asp\" rel=\"nofollow noreferrer\">https://www.w3schools.com/js/js_timing.asp</a></p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 310516,
"author": "Paul Burilichev",
"author_id": 122299,
"author_profile": "https://wordpress.stackexchange.com/users/122299",
"pm_score": 0,
"selected": false,
"text": "<p>Another native Wordpress way is to use the WP_Cron scheduling. \nConsider <code>wp_schedule_event()</code> and <code>wp_unschedule_event()</code> fuction, which runs under your hooks of login. Each time user will ask the page the Cron will check remote status and update your database on success. In the last case, you can do unscheduling of the event and show to your user an appropriate message or a page.</p>\n\n<p>Pros of the solution:\n* the client doesn't repeatedly send ajax requests\n* no need to know JS, just assign your existing function to another hook and add a few more easy logic.\n* use of native Wordpress features</p>\n\n<p>Cons of the solution:\n* if you have a large traffic on the website, consider using another CRON-library instead Wordpress</p>\n\n<p>links:\n<a href=\"https://codex.wordpress.org/Function_Reference/wp_schedule_event\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_schedule_event</a>\n<a href=\"https://code.tutsplus.com/articles/insights-into-wp-cron-an-introduction-to-scheduling-tasks-in-wordpress--wp-23119\" rel=\"nofollow noreferrer\">https://code.tutsplus.com/articles/insights-into-wp-cron-an-introduction-to-scheduling-tasks-in-wordpress--wp-23119</a></p>\n"
}
]
| 2018/08/02 | [
"https://wordpress.stackexchange.com/questions/310264",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/126847/"
]
| I have `process_ipn` method that runs on `init` action hook. Looks like it is fired after PayPal returns to merchant. Under this method, I could find out the payment status such as `completed`, `pending`, `failed`
from PayPal. And, save it to the database.
```
update_user_meta( $user_id, 'status', 'completed' );
```
I am redirecting back to login page from PayPal's return to merchant with added `user_id` and `form_id` in return url. I used the `login_message` filter to override message depending upon payment status.
```
add_filter( 'login_message', array( $this,'custom_login_message' ) );
public function custom_login_message() {
$return = base64_decode ( $_GET['wdb_return'] );
$return = explode( '&', $return );
$return = explode( '=', $return[1] );
$user_id = isset( $return[1] ) ? $return[1] : -1;
if( 'completed' === get_user_meta( $user_id, 'status', true ) ) {
return print_notice( __( 'Payment Completed. Now login.','wdp' ) );
} else {
return print_notice( __( 'Payment Failed','wdp' ) );
}
}
```
The return to merchant will return to login page. The problem the status is updated too late after the login page appears. So, `Payment Failed` appears if I click on return to merchant instantly after payment. If I waited a few minutes after payment and then return to merchant, It's okay.
Note that `$user_id` is grabbed from return url from PayPal and is valid.
What could be the solution?
Thanks! | If I understand your question, the race condition you describe between WordPress knowing the transaction was "complete" and the user returning to your site is the problem.
Regarding a potential solution, what about changing the way you're approaching this such that this race condition is accepted as a real possibility rather than something that you can avoid? You do mention one of the possible Paypal status is "pending"...
Its been years since I've worked with Paypal, but I recall the IPN feed can sometimes lag for quite a while.
Suppose you use ajax: you could show the login page with a conditional box, or you could use an interstitial 'transaction processing' page that redirects to the login. Your process could thank your customer, show a throbber animation, and explain that you're processing the transaction / waiting for payment confirmation from Paypal.
Your page can keep polling WordPress and when the user's meta `status` is "complete" you can update the user and show them the login form, and if it "failed" you can handle accordingly.
I'm not sure if you're setting the Paypal "pending" status in the user meta, but regardless an easy way to trigger this case is by checking for the presence of the `user_id` and `form_id` in the request from Paypal.
In cases where IPN is updated quick and/or the user pauses before returning to your site, the 'payment success' case could already work seamlessly as you desire: no need to show any throbbers or anything like that.
I think ajax is the best approach. A continuous poll every couple seconds might sound like you're generating a lot of requests, but I doubt you will have scores of users waiting to find out their transaction outcome at any one time. If you do, congratulations, you're making lots of money :)
WordPress also has a Heartbeat API but the fastest this can poll is 15 seconds. Web Sockets is another approach but is probably overkill and introduces its own complexities.
Here is a tutorial that covers an example implementation: <https://premium.wpmudev.org/blog/using-ajax-with-wordpress/>
For a docs reference: <https://developer.wordpress.org/plugins/javascript/ajax/>
To have javascript check continuously every few seconds, see `setInterval()` and `setTimeout()`, references: <https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval> and there's always: <https://www.w3schools.com/js/js_timing.asp>
Good luck! |
310,298 | <p>I want to show HTML text after the short description on the product page, but only on specific products that are in a specific category (categories).</p>
<p>I think I have to use in_category, but I can't figure out how to display the text right after the short description.</p>
<p>My preference is to work with a function/filter/action.</p>
<p>This code works:</p>
<pre><code>function filter_woocommerce_short_description( $post_excerpt ) {
$your_msg='Test';
return $post_excerpt.'<br>'.$your_msg;
};
add_filter( 'woocommerce_short_description','filter_woocommerce_short_description',10, 1 );
</code></pre>
<p>But this one works on all product pages..</p>
| [
{
"answer_id": 310338,
"author": "Peter HvD",
"author_id": 134918,
"author_profile": "https://wordpress.stackexchange.com/users/134918",
"pm_score": 3,
"selected": true,
"text": "<p>Woocommerce's product categories are custom taxonomy terms, so you need to use the taxonomy functions (eg, <a href=\"https://codex.wordpress.org/has_term\" rel=\"nofollow noreferrer\"><code>has_term()</code></a>) rather than WordPress' category ones.</p>\n\n<pre><code>function filter_woocommerce_short_description( $post_excerpt ) {\n global $post;\n if ( has_term( \"term-name\", \"product_cat\", $post->ID ) ) {\n $post_excerpt .= \"<br/>\" . \"Test\";\n }\n return $post_excerpt; \n};\nadd_filter( 'woocommerce_short_description','filter_woocommerce_short_description',10, 1 ); \n</code></pre>\n"
},
{
"answer_id": 310453,
"author": "Kevinn02",
"author_id": 147900,
"author_profile": "https://wordpress.stackexchange.com/users/147900",
"pm_score": 0,
"selected": false,
"text": "<pre><code>function filter_woocommerce_short_description( $post_excerpt ) {\nglobal $post;\nif ( has_term( \"axtschlag\", \"product_cat\", $post->ID ) || has_term( \"grate-goods\", \"product_cat\", $post->ID ) ) {\n $post_excerpt .= \"<br/>\" . \"<strong>Pick 'n Mix actie!</strong><br> Kies & mix de merken <a href=\"/axtschlag\">Axtschlag</a> en Grate Goods en ontvang korting! Kies je 3 tot 5 producten dan ontvang je 5% korting, kies je 6 tot 10 producten dan ontvang je maar liefst 10% korting direct in je winkelwagen. Geldt ook i.c.m. met lopende acties.\";\n}\nreturn $post_excerpt; \n};\nadd_filter( 'woocommerce_short_description','filter_woocommerce_short_description',10, 1 );\n</code></pre>\n"
}
]
| 2018/08/02 | [
"https://wordpress.stackexchange.com/questions/310298",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147900/"
]
| I want to show HTML text after the short description on the product page, but only on specific products that are in a specific category (categories).
I think I have to use in\_category, but I can't figure out how to display the text right after the short description.
My preference is to work with a function/filter/action.
This code works:
```
function filter_woocommerce_short_description( $post_excerpt ) {
$your_msg='Test';
return $post_excerpt.'<br>'.$your_msg;
};
add_filter( 'woocommerce_short_description','filter_woocommerce_short_description',10, 1 );
```
But this one works on all product pages.. | Woocommerce's product categories are custom taxonomy terms, so you need to use the taxonomy functions (eg, [`has_term()`](https://codex.wordpress.org/has_term)) rather than WordPress' category ones.
```
function filter_woocommerce_short_description( $post_excerpt ) {
global $post;
if ( has_term( "term-name", "product_cat", $post->ID ) ) {
$post_excerpt .= "<br/>" . "Test";
}
return $post_excerpt;
};
add_filter( 'woocommerce_short_description','filter_woocommerce_short_description',10, 1 );
``` |
310,301 | <p>I'm working on a design that has different styling if a certain Gutenberg block is present on a page. In other words, if the first block is a custom built Gutenberg block, the post_title is rendered elsewhere due to design choices made.</p>
<p>Is there any function in WordPress to get a list of all Gutenberg blocks present in the post_content?</p>
| [
{
"answer_id": 310309,
"author": "Jebble",
"author_id": 81939,
"author_profile": "https://wordpress.stackexchange.com/users/81939",
"pm_score": 2,
"selected": false,
"text": "<p>The solution I'm using as of writing check the post_content for the Gutenberg HTML comments. Due to future Gutenberg changes this might not work in the future.</p>\n\n<pre><code><?php \n$post_content = get_the_content( get_the_ID() ); // Get the post_content\npreg_match_all('<!-- /wp:(.*?) -->', $post_content, $blocks); // Get all matches in between <!-- /wp: --> strings\n\n// $blocks[1] contains the names of all the blocks present in the post_content\nif ( in_array( 'heading', $blocks[1] ) ) {\n // Post content contains a wp:heading block\n}\nelse {\n // Post content does not contain a wp:heading block\n}\n</code></pre>\n"
},
{
"answer_id": 310318,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 6,
"selected": true,
"text": "<p>WordPress 5.0+ has a function for this: <code>parse_blocks()</code>. To see if the first block in the post is the Heading block, you'd do this:</p>\n\n<pre><code>$post = get_post(); \n\nif ( has_blocks( $post->post_content ) ) {\n $blocks = parse_blocks( $post->post_content );\n\n if ( $blocks[0]['blockName'] === 'core/heading' ) {\n }\n}\n</code></pre>\n"
},
{
"answer_id": 321224,
"author": "ian-hoyte",
"author_id": 155421,
"author_profile": "https://wordpress.stackexchange.com/users/155421",
"pm_score": 0,
"selected": false,
"text": "<p>As of the release of 5.0 these functions have been deprecated with Gutenberg now integrated into the core. I imagine, but have not confirmed that these functions still exist in the Gutenberg standalone plugin.</p>\n\n<p>Instead of <code>gutenberg_content_has_blocks</code> use <code>has_blocks</code></p>\n\n<p>Instead of <code>gutenberg_parse_blocks</code> use <code>parse_blocks</code></p>\n"
}
]
| 2018/08/02 | [
"https://wordpress.stackexchange.com/questions/310301",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81939/"
]
| I'm working on a design that has different styling if a certain Gutenberg block is present on a page. In other words, if the first block is a custom built Gutenberg block, the post\_title is rendered elsewhere due to design choices made.
Is there any function in WordPress to get a list of all Gutenberg blocks present in the post\_content? | WordPress 5.0+ has a function for this: `parse_blocks()`. To see if the first block in the post is the Heading block, you'd do this:
```
$post = get_post();
if ( has_blocks( $post->post_content ) ) {
$blocks = parse_blocks( $post->post_content );
if ( $blocks[0]['blockName'] === 'core/heading' ) {
}
}
``` |
310,304 | <p>I have this layout I am trying to implement - <a href="https://drive.google.com/file/d/1cP831xAM1F5CT3HEmedCBkINwiCC18Rb/view" rel="nofollow noreferrer">https://drive.google.com/file/d/1cP831xAM1F5CT3HEmedCBkINwiCC18Rb/view</a></p>
<p>And I have created a news template, but I need to get the posts to display like my example where the first bootstrap row displays 3 posts then beneath that it displays 4 posts.</p>
<p>Is this possible, I cant seem to find the relevant information for me to achieve this.</p>
<p>Really hoping someone can point me in the right direction, on how I would code my template for this layout.</p>
<p>Many Thanks</p>
<p>Here is my current code</p>
<pre><code><div class="container">
<div class="row">
<?php
while ( have_posts() ) {
the_post();
$class = 'col-md-4';
if( $counter < 3 ) {
$class = 'col-md-3';
}
?>
<div class="col-12 <?php echo $class; ?>">
<?php the_post_thumbnail(', '); ?>
<h3><a href="<?php the_permalink(); ?>" title="Read more"><?php the_title(); ?></a></h3>
</div> <!-- .col-12 -->
<?php
$counter++;
} // end while
?>
</div><!-- .row -->
</div><!-- .container -->
</code></pre>
| [
{
"answer_id": 310310,
"author": "Lisa",
"author_id": 113452,
"author_profile": "https://wordpress.stackexchange.com/users/113452",
"pm_score": 0,
"selected": false,
"text": "<p>try to take a look at this <a href=\"https://stackoverflow.com/questions/38304093/wordpress-blog-first-row-2-column-second-and-continuing-rows-3-columns\">https://stackoverflow.com/questions/38304093/wordpress-blog-first-row-2-column-second-and-continuing-rows-3-columns</a></p>\n\n<p>Is it similar to what you want to achieve?</p>\n"
},
{
"answer_id": 310312,
"author": "mrmadhat",
"author_id": 68703,
"author_profile": "https://wordpress.stackexchange.com/users/68703",
"pm_score": 1,
"selected": false,
"text": "<p>You can accomplish this by using a counter then updating the class according to your needs. The code below will create a variable <code>$counter</code> and assign it to <code>0</code> if posts exist. By default a <code>'col-md-4'</code> is bound to <code>$class</code>, if the <code>$counter</code> is less than <code>3</code> <code>$class</code> will be updated to <code>'col-md-3'</code> (making it fill 4 columns instead of 3). Then we output the html including the stored class. Finally, the <code>$counter</code> is incremented ready for the next post item.</p>\n\n<pre><code><?php \nif ( have_posts() ) {\n $counter = 0;\n\n ?>\n\n <div class=\"container\">\n <div class=\"row\">\n <?php\n while ( have_posts() ) {\n the_post(); \n\n $class = 'col-md-4';\n\n if( $counter < 3 ) {\n $class = 'col-md-3';\n }\n\n ?>\n <div class=\"col-12 <?php echo $class; ?>\">\n <?php // content etc here ?>\n </div> <!-- .col-12 -->\n <?php\n\n $counter++;\n\n } // end while\n ?>\n </div><!-- .row -->\n </div><!-- .container -->\n<?php } else { // end if ?>\n <p>There are no posts to display</p>\n<?php } ?>\n</code></pre>\n"
}
]
| 2018/08/02 | [
"https://wordpress.stackexchange.com/questions/310304",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147953/"
]
| I have this layout I am trying to implement - <https://drive.google.com/file/d/1cP831xAM1F5CT3HEmedCBkINwiCC18Rb/view>
And I have created a news template, but I need to get the posts to display like my example where the first bootstrap row displays 3 posts then beneath that it displays 4 posts.
Is this possible, I cant seem to find the relevant information for me to achieve this.
Really hoping someone can point me in the right direction, on how I would code my template for this layout.
Many Thanks
Here is my current code
```
<div class="container">
<div class="row">
<?php
while ( have_posts() ) {
the_post();
$class = 'col-md-4';
if( $counter < 3 ) {
$class = 'col-md-3';
}
?>
<div class="col-12 <?php echo $class; ?>">
<?php the_post_thumbnail(', '); ?>
<h3><a href="<?php the_permalink(); ?>" title="Read more"><?php the_title(); ?></a></h3>
</div> <!-- .col-12 -->
<?php
$counter++;
} // end while
?>
</div><!-- .row -->
</div><!-- .container -->
``` | You can accomplish this by using a counter then updating the class according to your needs. The code below will create a variable `$counter` and assign it to `0` if posts exist. By default a `'col-md-4'` is bound to `$class`, if the `$counter` is less than `3` `$class` will be updated to `'col-md-3'` (making it fill 4 columns instead of 3). Then we output the html including the stored class. Finally, the `$counter` is incremented ready for the next post item.
```
<?php
if ( have_posts() ) {
$counter = 0;
?>
<div class="container">
<div class="row">
<?php
while ( have_posts() ) {
the_post();
$class = 'col-md-4';
if( $counter < 3 ) {
$class = 'col-md-3';
}
?>
<div class="col-12 <?php echo $class; ?>">
<?php // content etc here ?>
</div> <!-- .col-12 -->
<?php
$counter++;
} // end while
?>
</div><!-- .row -->
</div><!-- .container -->
<?php } else { // end if ?>
<p>There are no posts to display</p>
<?php } ?>
``` |
310,333 | <p>When I click the "Add to cart" button on a variable product, with no variation selected, the WooCommerce pops up an alert: "Please select some product options before adding this product to your cart.".</p>
<p>The problem is, it shows up as an Alert (browser window with Ok button). I would like to display it as a classic WooCommerce notice box within the page (or possibly to do some custom actions), but I am unable to find the responsible actions. </p>
<p>I tried to look for "single_add_to_cart_button". The theme is Shopkeeper, but I've looked for other themes and they seem to display it in the same manner - so I believe it is WooCommerce's default.</p>
<p>Any hints on how to achieve this?</p>
| [
{
"answer_id": 310310,
"author": "Lisa",
"author_id": 113452,
"author_profile": "https://wordpress.stackexchange.com/users/113452",
"pm_score": 0,
"selected": false,
"text": "<p>try to take a look at this <a href=\"https://stackoverflow.com/questions/38304093/wordpress-blog-first-row-2-column-second-and-continuing-rows-3-columns\">https://stackoverflow.com/questions/38304093/wordpress-blog-first-row-2-column-second-and-continuing-rows-3-columns</a></p>\n\n<p>Is it similar to what you want to achieve?</p>\n"
},
{
"answer_id": 310312,
"author": "mrmadhat",
"author_id": 68703,
"author_profile": "https://wordpress.stackexchange.com/users/68703",
"pm_score": 1,
"selected": false,
"text": "<p>You can accomplish this by using a counter then updating the class according to your needs. The code below will create a variable <code>$counter</code> and assign it to <code>0</code> if posts exist. By default a <code>'col-md-4'</code> is bound to <code>$class</code>, if the <code>$counter</code> is less than <code>3</code> <code>$class</code> will be updated to <code>'col-md-3'</code> (making it fill 4 columns instead of 3). Then we output the html including the stored class. Finally, the <code>$counter</code> is incremented ready for the next post item.</p>\n\n<pre><code><?php \nif ( have_posts() ) {\n $counter = 0;\n\n ?>\n\n <div class=\"container\">\n <div class=\"row\">\n <?php\n while ( have_posts() ) {\n the_post(); \n\n $class = 'col-md-4';\n\n if( $counter < 3 ) {\n $class = 'col-md-3';\n }\n\n ?>\n <div class=\"col-12 <?php echo $class; ?>\">\n <?php // content etc here ?>\n </div> <!-- .col-12 -->\n <?php\n\n $counter++;\n\n } // end while\n ?>\n </div><!-- .row -->\n </div><!-- .container -->\n<?php } else { // end if ?>\n <p>There are no posts to display</p>\n<?php } ?>\n</code></pre>\n"
}
]
| 2018/08/02 | [
"https://wordpress.stackexchange.com/questions/310333",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/138610/"
]
| When I click the "Add to cart" button on a variable product, with no variation selected, the WooCommerce pops up an alert: "Please select some product options before adding this product to your cart.".
The problem is, it shows up as an Alert (browser window with Ok button). I would like to display it as a classic WooCommerce notice box within the page (or possibly to do some custom actions), but I am unable to find the responsible actions.
I tried to look for "single\_add\_to\_cart\_button". The theme is Shopkeeper, but I've looked for other themes and they seem to display it in the same manner - so I believe it is WooCommerce's default.
Any hints on how to achieve this? | You can accomplish this by using a counter then updating the class according to your needs. The code below will create a variable `$counter` and assign it to `0` if posts exist. By default a `'col-md-4'` is bound to `$class`, if the `$counter` is less than `3` `$class` will be updated to `'col-md-3'` (making it fill 4 columns instead of 3). Then we output the html including the stored class. Finally, the `$counter` is incremented ready for the next post item.
```
<?php
if ( have_posts() ) {
$counter = 0;
?>
<div class="container">
<div class="row">
<?php
while ( have_posts() ) {
the_post();
$class = 'col-md-4';
if( $counter < 3 ) {
$class = 'col-md-3';
}
?>
<div class="col-12 <?php echo $class; ?>">
<?php // content etc here ?>
</div> <!-- .col-12 -->
<?php
$counter++;
} // end while
?>
</div><!-- .row -->
</div><!-- .container -->
<?php } else { // end if ?>
<p>There are no posts to display</p>
<?php } ?>
``` |
310,360 | <p>I've read alot, I've tried a bunch of different things, I still can't get my query to order posts by acf's datepicker field. This is what my code looks like:</p>
<pre><code>$args = array(
'post_type' => 'arm_careers',
'post_status' => 'publish',
'posts_per_page' => -1,
'meta_key' => 'post_date',
'orderby' => 'meta_value_num',
'meta_type' => 'DATE',
'order' => 'ASC',
);
</code></pre>
<p>I'm not using PRO, I'm using the free one. The save format is <code>yymmdd</code>, I've also tried <code>YYYYMMDD</code> but neither worked.</p>
<p>Here is what it currently looks like:
August 14, 2018
August 2, 2018
August 9, 2018</p>
<p>when I want it to look like:
August 2, 2018
August 9, 2018
August 14, 2018</p>
<p>The display format is <code>MM d, yy</code>.</p>
| [
{
"answer_id": 310361,
"author": "Nicholas Koskowski",
"author_id": 92318,
"author_profile": "https://wordpress.stackexchange.com/users/92318",
"pm_score": 2,
"selected": false,
"text": "<p>You need to convert your saved format to the post_date format which is in </p>\n\n<p><code>Y-m-d H:i:s</code></p>\n\n<p>Only then will the comparators work properly with automatically generated query objects.</p>\n"
},
{
"answer_id": 310375,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>ACF stores dates as yyyymmdd in meta values, so it's very probable that casting it to DATE won't work properly...</p>\n\n<p>And there is no need to compare it as number - dictionary sorting will work here.</p>\n\n<p>Try this:</p>\n\n<pre><code>$args = array(\n 'post_type' => 'arm_careers',\n 'post_status' => 'publish',\n 'posts_per_page' => -1,\n 'meta_key' => 'post_date',\n 'orderby' => 'meta_value',\n 'order' => 'ASC',\n);\n</code></pre>\n\n<p>PS. I'm pretty sure that you can't set the format that ACF will use to store dates. You can set the format for showing these values or for getting them.</p>\n"
}
]
| 2018/08/02 | [
"https://wordpress.stackexchange.com/questions/310360",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/138558/"
]
| I've read alot, I've tried a bunch of different things, I still can't get my query to order posts by acf's datepicker field. This is what my code looks like:
```
$args = array(
'post_type' => 'arm_careers',
'post_status' => 'publish',
'posts_per_page' => -1,
'meta_key' => 'post_date',
'orderby' => 'meta_value_num',
'meta_type' => 'DATE',
'order' => 'ASC',
);
```
I'm not using PRO, I'm using the free one. The save format is `yymmdd`, I've also tried `YYYYMMDD` but neither worked.
Here is what it currently looks like:
August 14, 2018
August 2, 2018
August 9, 2018
when I want it to look like:
August 2, 2018
August 9, 2018
August 14, 2018
The display format is `MM d, yy`. | You need to convert your saved format to the post\_date format which is in
`Y-m-d H:i:s`
Only then will the comparators work properly with automatically generated query objects. |
310,393 | <p>I am trying to build a plugin and at the moment my plugin contains only <code>plugin.php</code> file.</p>
<p>There is not a real code in it yet:</p>
<pre><code><?
/*
Plugin Name: Plugin Name
Plugin URI: https://www.example.info
description: A description about the plugin
Version: 1.0.0
Author: Author Name
Author URI: https://www.example.info
License: GPL2
*/
</code></pre>
<p>And I am getting these errors as long as the plugin is activated:</p>
<blockquote>
<p>Warning: session_start(): Cannot send session cache limiter - headers
already sent - (output started at
/home1/website/public_html/wp-content/plugins/plugin-name/plugin-name.php:1)
in
/home1/website/public_html/wp-content/plugins/flexible-shipping/classes/flexible-shipping-plugin.php
on line 169</p>
<p>Warning: Cannot modify header information - headers already sent by
(output started at
/home1/website/public_html/wp-content/plugins/plugin-name/plugin-name.php:1)
in /home1/website/public_html/wp-admin/includes/misc.php on line 1124</p>
</blockquote>
<p>I already faced an issue like this and it was due to whitespaces, but I don't have any whitespaces this time... I barely have a plugin...</p>
<p>Thanks.</p>
| [
{
"answer_id": 310401,
"author": "Kaperto",
"author_id": 147795,
"author_profile": "https://wordpress.stackexchange.com/users/147795",
"pm_score": 0,
"selected": false,
"text": "<p>You start the PHP code with short tags <code><?</code>.<br>\nIf it is on a server with short tags disabled, the PHP code is not rendered and is outputted.</p>\n\n<p>Then it's better to use complete tags <code><?php</code>.</p>\n"
},
{
"answer_id": 310410,
"author": "maverick",
"author_id": 132953,
"author_profile": "https://wordpress.stackexchange.com/users/132953",
"pm_score": -1,
"selected": false,
"text": "<p>Follow these approaches to build wordpress plugin</p>\n\n<ul>\n<li>Always create a separate directory for holding plugin files</li>\n<li>always include index.php file ( it contains nothing ) in folders that hold important assets ( classes, and admin files )</li>\n<li>restrict direct access to files using</li>\n<li>`if(!defined('ABSPATH'){ exit; }</li>\n<li>always include files conditionally e.g. if ( is_admin() ){ require_once '...'; }</li>\n</ul>\n\n<p>Above points are just few points that you can follow in order to develop wordpress plugins.</p>\n\n<p>Regarding your question, I think that should have worked</p>\n\n<pre><code><?php\n/*\nPlugin Name: WordPress.org Plugin\nPlugin URI: https://developer.wordpress.org/plugins/the-basics/\nDescription: Basic WordPress Plugin Header Comment\nVersion: 20160911\nAuthor: WordPress.org\nAuthor URI: https://developer.wordpress.org/\nText Domain: wporg\nDomain Path: /languages\nLicense: GPL2\n\n{Plugin Name} is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 2 of the License, or\nany later version.\n\n{Plugin Name} is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with {Plugin Name}. If not, see {License URI}.\n*/\n</code></pre>\n\n<p>`You can restart web server, go to settings>permalinks then save settings.\nLets see if that helps</p>\n"
},
{
"answer_id": 310423,
"author": "Rajesh Kakkad",
"author_id": 147821,
"author_profile": "https://wordpress.stackexchange.com/users/147821",
"pm_score": -1,
"selected": false,
"text": "<p>As there is no usable code at this time, it can not generate errors and warnings you have reported.</p>\n\n<p>It is also reporting errors from two .php files. </p>\n\n<p>Had you plugin file with same name before ? One time I kept changing code but it made no difference to output. I even tried <code><? die();</code> as first command but no effect. Page refreshing was also not helping. I changed name of that file and it worked. Server <strong>insisted</strong> on serving output it had saved somewhere.</p>\n\n<p>I would suggest you to change name of the plugin file to be sure.</p>\n"
}
]
| 2018/08/03 | [
"https://wordpress.stackexchange.com/questions/310393",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147331/"
]
| I am trying to build a plugin and at the moment my plugin contains only `plugin.php` file.
There is not a real code in it yet:
```
<?
/*
Plugin Name: Plugin Name
Plugin URI: https://www.example.info
description: A description about the plugin
Version: 1.0.0
Author: Author Name
Author URI: https://www.example.info
License: GPL2
*/
```
And I am getting these errors as long as the plugin is activated:
>
> Warning: session\_start(): Cannot send session cache limiter - headers
> already sent - (output started at
> /home1/website/public\_html/wp-content/plugins/plugin-name/plugin-name.php:1)
> in
> /home1/website/public\_html/wp-content/plugins/flexible-shipping/classes/flexible-shipping-plugin.php
> on line 169
>
>
> Warning: Cannot modify header information - headers already sent by
> (output started at
> /home1/website/public\_html/wp-content/plugins/plugin-name/plugin-name.php:1)
> in /home1/website/public\_html/wp-admin/includes/misc.php on line 1124
>
>
>
I already faced an issue like this and it was due to whitespaces, but I don't have any whitespaces this time... I barely have a plugin...
Thanks. | You start the PHP code with short tags `<?`.
If it is on a server with short tags disabled, the PHP code is not rendered and is outputted.
Then it's better to use complete tags `<?php`. |
310,394 | <p>I want to get posts of a specific date, I tried the following code but I did not get the result what I wanted.</p>
<pre><code><?php
$mil = 1532996880000;
$seconds = $mil / 1000;
$dt = date( "Y-m-d", $seconds );
$post_by_date = $wpdb->get_row("
SELECT * FROM {$wpdb->posts}
WHERE post_date = $dt
AND post_status = 'publish'
");
</code></pre>
<p><strong>WP QUERY</strong></p>
<pre><code>$posts = get_posts(array(
'post_type' => 'post',
'date' => $dt,
'posts_per_page' => 1
));
</code></pre>
<hr>
<p>This did not work because, the output of <code>$dt = 2018-07-31</code>, but the output shows no results. Because it compares with <code>2018-07-31 09:09:40</code>. So is there any way to get posts of a specific date?</p>
| [
{
"answer_id": 310396,
"author": "Trilok",
"author_id": 145962,
"author_profile": "https://wordpress.stackexchange.com/users/145962",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>Please use date query for that also use below code hope it will work for you</p>\n</blockquote>\n\n<pre><code>$mil = 1532996880000;\n$seconds = $mil / 1000;\n$dt = date( \"Y-m-d\", $seconds );\n $year = date( \"Y\", $seconds );\n $month = date( \"m\", $seconds ); \n $day = date( \"d\", $seconds );\n\n\n$args = array(\n 'date_query' => array(\n array(\n 'year' => $year,\n 'month' => $month,\n 'day' =>$day,\n ),\n ),\n);\n$query = new WP_Query( $args );\n\n// The Loop\nif ( $query->have_posts() ) {\n echo '<ul>';\n while ( $query->have_posts() ) {\n $query->the_post();\n echo '<li>' . get_the_title() . '</li>';\n }\n echo '</ul>';\n /* Restore original Post Data */\n wp_reset_postdata();\n} else {\n // no posts found\n}\n</code></pre>\n"
},
{
"answer_id": 310398,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 3,
"selected": true,
"text": "<pre><code><?php\n// primarily get $year, $month and $day\n$args = array(\n 'date_query' => array(\n 'year' => $year,\n 'month' => $month,\n 'day' => $day,\n )\n);\n\n$query = new WP_Query( $args );\n\nif ( $query->have_posts() ) {\n while ( $query->have_posts() ) {\n\n // do whatever here\n\n }\n}\n</code></pre>\n"
}
]
| 2018/08/03 | [
"https://wordpress.stackexchange.com/questions/310394",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/129128/"
]
| I want to get posts of a specific date, I tried the following code but I did not get the result what I wanted.
```
<?php
$mil = 1532996880000;
$seconds = $mil / 1000;
$dt = date( "Y-m-d", $seconds );
$post_by_date = $wpdb->get_row("
SELECT * FROM {$wpdb->posts}
WHERE post_date = $dt
AND post_status = 'publish'
");
```
**WP QUERY**
```
$posts = get_posts(array(
'post_type' => 'post',
'date' => $dt,
'posts_per_page' => 1
));
```
---
This did not work because, the output of `$dt = 2018-07-31`, but the output shows no results. Because it compares with `2018-07-31 09:09:40`. So is there any way to get posts of a specific date? | ```
<?php
// primarily get $year, $month and $day
$args = array(
'date_query' => array(
'year' => $year,
'month' => $month,
'day' => $day,
)
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
// do whatever here
}
}
``` |
310,400 | <p>I have an inline SVG tag with an embedded <USE> tag.</p>
<p><strong>HTML:</strong></p>
<pre><code><ul>
<li><svg class="icon-user"><use xlink:href="#icon-user"></use></svg> My Account</li>
</ul>
</code></pre>
<p>I have created a filter function to force the Tiny MCE editor to leave SVG tags alone. The code was adapted from post: <a href="https://wordpress.stackexchange.com/questions/185234/use-of-svg-tag-into-wordpress">use of <svg> tag into wordpress</a>.</p>
<p><strong>Filter function:</strong></p>
<pre><code>add_filter( 'tiny_mce_before_init', 'fb_tinymce_add_pre' );
function fb_tinymce_add_pre( $initArray ) {
// Command separated string of extended elements
$ext = 'svg[preserveAspectRatio|class|style|version|viewbox|xmlns],defs,use[xlink:href|x|y],linearGradient[id|x1|y1|z1]';
if ( isset( $initArray['extended_valid_elements'] ) ) {
$initArray['extended_valid_elements'] .= ',' . $ext;
} else {
$initArray['extended_valid_elements'] = $ext;
}
// maybe; set tiny paramter verify_html
//$initArray['verify_html'] = false;
return $initArray;
}
</code></pre>
<p>I adapted the posted solution to add SVG CLASS, the USE tag and its XLINK:HREF, X and Y parameters.</p>
<p>Problem is the xlink:href parameter is being miss-interpreted resulting in code butchery upon switching to VISUAL mode in the editor.</p>
<p><strong>HTML before switch to visual mode:</strong></p>
<pre><code> <svg class="icon-user"><use xlink:href="#icon-user"></use></svg>
</code></pre>
<p><strong>HTML after switch to visual mode:</strong></p>
<pre><code> <svg class="icon-user"><use xlink="href"></use></svg>
</code></pre>
<p>I have tried escaping the colon in the <code>xlink:href</code> function parameter like this: <code>xlink\:href</code>, tried an encoded value for the colon like this: <code>xlink%3Ahref</code> and using quotes around it like this <code>"xlink:href"</code> but all failed.</p>
<p>I know you can embed svg using HTML5 markup, but I would like to try this method if I can get a solution that sticks.</p>
| [
{
"answer_id": 310426,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 3,
"selected": true,
"text": "<p>Unfortunately the colon is <a href=\"https://www.tiny.cloud/docs/configure/content-filtering/#valid_elements\" rel=\"nofollow noreferrer\">a TinyMCE control character</a></p>\n\n<blockquote>\n <p>Forces the attribute to the specified value. For example, 'border:0'</p>\n</blockquote>\n\n<p>...hence the switch to <code>xlink=href</code>. <strike>The only apparent solution is the wildcard <code>use[*]</code></strike></p>\n\n<p>Use the control character <code>?</code> which \"separates attribute verification values\" i.e. <code>use[xlink?href]</code></p>\n"
},
{
"answer_id": 407617,
"author": "Илюшка",
"author_id": 224016,
"author_profile": "https://wordpress.stackexchange.com/users/224016",
"pm_score": 0,
"selected": false,
"text": "<p>You can used js for added in the beginning of the line</p>\n<pre><code>$(document).ready(function () {\n $("li").prepend('<svg class="icon-user"><use xlink:href="#icon-user"></use></svg>');\n});\n</code></pre>\n<p>Or assign a class to the li tag</p>\n"
}
]
| 2018/08/03 | [
"https://wordpress.stackexchange.com/questions/310400",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/148020/"
]
| I have an inline SVG tag with an embedded <USE> tag.
**HTML:**
```
<ul>
<li><svg class="icon-user"><use xlink:href="#icon-user"></use></svg> My Account</li>
</ul>
```
I have created a filter function to force the Tiny MCE editor to leave SVG tags alone. The code was adapted from post: [use of <svg> tag into wordpress](https://wordpress.stackexchange.com/questions/185234/use-of-svg-tag-into-wordpress).
**Filter function:**
```
add_filter( 'tiny_mce_before_init', 'fb_tinymce_add_pre' );
function fb_tinymce_add_pre( $initArray ) {
// Command separated string of extended elements
$ext = 'svg[preserveAspectRatio|class|style|version|viewbox|xmlns],defs,use[xlink:href|x|y],linearGradient[id|x1|y1|z1]';
if ( isset( $initArray['extended_valid_elements'] ) ) {
$initArray['extended_valid_elements'] .= ',' . $ext;
} else {
$initArray['extended_valid_elements'] = $ext;
}
// maybe; set tiny paramter verify_html
//$initArray['verify_html'] = false;
return $initArray;
}
```
I adapted the posted solution to add SVG CLASS, the USE tag and its XLINK:HREF, X and Y parameters.
Problem is the xlink:href parameter is being miss-interpreted resulting in code butchery upon switching to VISUAL mode in the editor.
**HTML before switch to visual mode:**
```
<svg class="icon-user"><use xlink:href="#icon-user"></use></svg>
```
**HTML after switch to visual mode:**
```
<svg class="icon-user"><use xlink="href"></use></svg>
```
I have tried escaping the colon in the `xlink:href` function parameter like this: `xlink\:href`, tried an encoded value for the colon like this: `xlink%3Ahref` and using quotes around it like this `"xlink:href"` but all failed.
I know you can embed svg using HTML5 markup, but I would like to try this method if I can get a solution that sticks. | Unfortunately the colon is [a TinyMCE control character](https://www.tiny.cloud/docs/configure/content-filtering/#valid_elements)
>
> Forces the attribute to the specified value. For example, 'border:0'
>
>
>
...hence the switch to `xlink=href`. The only apparent solution is the wildcard `use[*]`
Use the control character `?` which "separates attribute verification values" i.e. `use[xlink?href]` |
310,411 | <p>I have a function in my functions.php file that is supossed to update my post status once the expiry date has passed. I call this function in a test.php file that is also a template page with url /test-search-results/. If I access this url via my browser the function fires and does what it supposed to do. </p>
<p>I want to create a server side cronjob to do this but I cant seem to get this right. I have contacted my host and they confirm that the path is correct and that the cron is executing si the problem has to be with my script. </p>
<p>Can someone please advise what I have to change in my script to have the cronjob execute it.</p>
<p>Function in my functions.php file:</p>
<pre><code> function expire_posts () {
$args = array (
'post_type' => 'post',
'meta_key' => 'Expiry Date',
'meta_value' => date('Y-m-d'),
'meta_compare' => '<',
);
$query = new WP_Query($args);
if( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();
$post_id = get_the_ID();
$post_data = array(
'ID' => $post_id,
'post_type' => 'post',
'post_status' => 'expired',
'post_modified' => current_time ( 'mysql' ),
);
wp_update_post($post_data);
endwhile;
wp_reset_postdata();
endif;
}
</code></pre>
<p>I call the function in my test.php file like this:</p>
<pre><code>expire_posts();
</code></pre>
<p>The path my cronjob is following is:</p>
<pre><code>/home/userID/public_html/wp-content/themes/twentyseventeen-child/test.php
</code></pre>
<p>I am hoping someone can shed some light as to why my script isn't executing via the cronjob.</p>
| [
{
"answer_id": 310430,
"author": "Kaperto",
"author_id": 147795,
"author_profile": "https://wordpress.stackexchange.com/users/147795",
"pm_score": 0,
"selected": false,
"text": "<p>With WP cron, you can launch a action daily, twice daily or hourly :<br>\n<a href=\"https://codex.wordpress.org/Function_Reference/wp_schedule_event\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_schedule_event</a></p>\n\n<p>If you need another period, you can define it with the filter <code>cron_schedules</code> like that : </p>\n\n<pre><code>// execute the function \"expire_posts\" when the action \"MyPlugin__cron_clean_post\" is launched\nadd_action(\"MyPlugin__cron_clean_post\", \"expire_posts\");\n\nadd_action(\"wp_loaded\", function () {\n\n // launch the action \"MyPlugin__cron_clean_post\" every 15 minutes\n if (!wp_next_scheduled(\"MyPlugin__cron_clean_post\")) {\n wp_schedule_event(1, \"15_minutes\", \"MyPlugin__cron_clean_post\");\n }\n\n});\n\n\nadd_filter(\"cron_schedules\", function ($cron_schedules) {\n\n $cron_schedules[\"15_minutes\"] = [\n \"display\" => \"15 minutes\",\n \"interval\" => 15 * MINUTE_IN_SECONDS,\n ];\n\n return $cron_schedules;\n\n});\n</code></pre>\n"
},
{
"answer_id": 310435,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 2,
"selected": false,
"text": "<p>When you use *nix cron to run a PHP file like that it won't have WordPress loaded. You can load it manually, but a better method is to use WordPress' own <a href=\"https://developer.wordpress.org/plugins/cron/\" rel=\"nofollow noreferrer\">cron API</a>.</p>\n\n<p>Schedule the event in your <code>functions.php</code>:</p>\n\n<pre><code>if ( ! wp_next_scheduled( 'expire_posts' ) ) {\n wp_schedule_event( time(), 'hourly', 'expire_posts' );\n}\n</code></pre>\n\n<p>I've used <code>hourly</code>, the other available defaults are <code>daily</code> & <code>twicedaily</code> (<a href=\"https://developer.wordpress.org/plugins/cron/understanding-wp-cron-scheduling/\" rel=\"nofollow noreferrer\">more on scheduling</a>).</p>\n\n<p>Now let's hook up your <code>expire_posts</code> <em>function</em> to our newly created <code>expire_posts</code> <em>event</em>:</p>\n\n<pre><code>add_action( 'expire_posts', 'expire_posts' );\n</code></pre>\n\n<p>Tada!</p>\n\n<p>NB: WordPress cron relies on a request (i.e. a user or bot visiting the site) at least as often as your schedule to run smoothly. If your site is quiet we can use *nix cron to trigger the WordPress cron API every 15 minutes and let WordPress handle its own internal events.</p>\n\n<p>First, disable the default request-based cron behaviour in <code>wp-config.php</code>:</p>\n\n<pre><code>define( 'DISABLE_WP_CRON', true );\n</code></pre>\n\n<p>Now set up a *nix cron to trigger WordPress' cron:</p>\n\n<pre><code>/15 * * * wget -q -O - http://yourdomain.com/wp-cron.php?doing_wp_cron\n</code></pre>\n"
}
]
| 2018/08/03 | [
"https://wordpress.stackexchange.com/questions/310411",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107025/"
]
| I have a function in my functions.php file that is supossed to update my post status once the expiry date has passed. I call this function in a test.php file that is also a template page with url /test-search-results/. If I access this url via my browser the function fires and does what it supposed to do.
I want to create a server side cronjob to do this but I cant seem to get this right. I have contacted my host and they confirm that the path is correct and that the cron is executing si the problem has to be with my script.
Can someone please advise what I have to change in my script to have the cronjob execute it.
Function in my functions.php file:
```
function expire_posts () {
$args = array (
'post_type' => 'post',
'meta_key' => 'Expiry Date',
'meta_value' => date('Y-m-d'),
'meta_compare' => '<',
);
$query = new WP_Query($args);
if( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();
$post_id = get_the_ID();
$post_data = array(
'ID' => $post_id,
'post_type' => 'post',
'post_status' => 'expired',
'post_modified' => current_time ( 'mysql' ),
);
wp_update_post($post_data);
endwhile;
wp_reset_postdata();
endif;
}
```
I call the function in my test.php file like this:
```
expire_posts();
```
The path my cronjob is following is:
```
/home/userID/public_html/wp-content/themes/twentyseventeen-child/test.php
```
I am hoping someone can shed some light as to why my script isn't executing via the cronjob. | When you use \*nix cron to run a PHP file like that it won't have WordPress loaded. You can load it manually, but a better method is to use WordPress' own [cron API](https://developer.wordpress.org/plugins/cron/).
Schedule the event in your `functions.php`:
```
if ( ! wp_next_scheduled( 'expire_posts' ) ) {
wp_schedule_event( time(), 'hourly', 'expire_posts' );
}
```
I've used `hourly`, the other available defaults are `daily` & `twicedaily` ([more on scheduling](https://developer.wordpress.org/plugins/cron/understanding-wp-cron-scheduling/)).
Now let's hook up your `expire_posts` *function* to our newly created `expire_posts` *event*:
```
add_action( 'expire_posts', 'expire_posts' );
```
Tada!
NB: WordPress cron relies on a request (i.e. a user or bot visiting the site) at least as often as your schedule to run smoothly. If your site is quiet we can use \*nix cron to trigger the WordPress cron API every 15 minutes and let WordPress handle its own internal events.
First, disable the default request-based cron behaviour in `wp-config.php`:
```
define( 'DISABLE_WP_CRON', true );
```
Now set up a \*nix cron to trigger WordPress' cron:
```
/15 * * * wget -q -O - http://yourdomain.com/wp-cron.php?doing_wp_cron
``` |
310,439 | <p>I've created the following pages and hierarchy:</p>
<ul>
<li>Grandparent
<ul>
<li>Parent</li>
<li>Parent</li>
<li>Parent
<ul>
<li>Child</li>
<li>Child</li>
<li>Child</li>
</ul></li>
<li>Parent</li>
<li>Parent</li>
</ul></li>
<li>Grandparent</li>
</ul>
<p>The Grandparent pages have an ACF custom field to pick the colour.
<a href="https://i.stack.imgur.com/2pBfg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2pBfg.png" alt="ACF Page Type"></a></p>
<p>I'd like that colour selection to be applied for the Grandparent, Parent and Child pages.</p>
<p>Within the loop, I've written the following code to grab the Grandparent colour selection:</p>
<pre><code><div class="<?= get_field('colour', $post->post_parent); ?>">
</code></pre>
<p>Let's say I've picked the colour "red".</p>
<p>Here's the front-end result:</p>
<ul>
<li>Grandparent (Red)
<ul>
<li>Parent (Red)</li>
<li>Parent (Red)</li>
<li>Parent (Red)
<ul>
<li>Child (Null)</li>
<li>Child (Null)</li>
<li>Child (Null)</li>
</ul></li>
<li>Parent (Red)</li>
<li>Parent (Red)</li>
</ul></li>
<li>Grandparent</li>
</ul>
<p>The colour is only being applied to the Grandparent and Parent Pages. Child pages are returning no colour (null).</p>
<p>How do I include the Child pages too?</p>
| [
{
"answer_id": 310442,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>As far as I'm aware there's no limit to how many levels of ancestry Pages can have, so any solution should not depend on specifically referencing a particular ancestor. The best solution would be to get a list of all ancestors for the page and loop over them until you find a value for your field. Then stop looping over them and return the found value. The function <code>get_post_ancestors()</code> can be used for this:</p>\n\n<pre><code>$colour = null;\n\n/**\n * Get the IDs of the page's ancestors into a list.\n */\n$page_ids = get_post_ancestors( $post );\n\n/**\n * Put the current page's ID at the beginning of the list so we don't have to \n * handle it separately.\n */\narray_unshift( $page_ids, $post->ID );\n\n/**\n * Loop over pages and find the first one with a colour.\n */\nforeach ( $page_ids as $page_id ) {\n $maybe_colour = get_post_meta( 'colour', $page_id, true );\n\n /**\n * If the page has a value for colour, put it in the colour variable and \n * stop the loop.\n */\n if ( $maybe_colour ) {\n $colour = $maybe_colour;\n break;\n }\n}\n\necho $colour;\n</code></pre>\n\n<p>To save space in your template you could add this to a function and use the function in your template instead:</p>\n\n<pre><code>function wpse_310439_get_the_colour( $post = 0 ) {\n $post = get_post( $post );\n\n $page_ids = get_post_ancestors( $post );\n\n array_unshift( $page_ids, $post->ID );\n\n $colour = null;\n\n foreach ( $page_ids as $page_id ) {\n $maybe_colour = get_post_meta( 'colour', $page_id, true );\n\n if ( $maybe_colour ) {\n $colour = $maybe_colour;\n break;\n }\n }\n\n return $colour;\n}\n</code></pre>\n\n<p>Then in your template:</p>\n\n<pre><code><div class=\"<?php echo esc_attr( wpse_310439_get_the_colour() ); ?>\">\n</code></pre>\n"
},
{
"answer_id": 310444,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not quite sure how your grandparent pages are getting the style since your code says to grab the field from the parent. The grandparents' post parents should be 0, meaning they don't have parents. Perhaps there's something I'm missing about your hierarchy.</p>\n\n<p>A conditional should work here:</p>\n\n<p>(assumes you've already specified <code>global $post</code> in your template):</p>\n\n<pre><code><div class=\"<?php\n// if this is a top-level post, grab its field\nif($post->post_parent == 0) { ?>\n // output the field - no need to pass an ID as it is the ID of this post\n the_field('colour');\n// if this is not a top-level post (child, grandchild, or so forth)\n} else {\n // get all of this post's ancestors: parent, grandparent, and so forth\n $ancestors = get_post_ancestors();\n // get the last item in the array - the \"top\" parent (grandparent)\n $id = end($ancestors);\n // now pull its field\n the_field('colour', $id);\n} ?>\n\">\n</code></pre>\n\n<p>A non-ACF way to achieve the same effect would be to add your desired classes to the <code><body></code> class in <code>functions.php</code>:</p>\n\n<pre><code><?php // add a filter to the body_class() function\nadd_filter('body_class', 'wpse_310439');\nfunction wpse_310429($classes) {\n // pull ancestors of the current page/post/cpt\n $ancestors = get_post_ancestors();\n // if this is a particular page ID, or a child of that ID\n if(is_page('12345') || end($ancestors) == '12345') {\n // add a class to the <body>\n $classes[] = 'blue';\n } elseif(is_page('54321') || end($ancestors == '54321') {\n $classes[] = 'yellow';\n }\n // always return $classes so body gets regular classes\n return $classes;\n} ?>\n</code></pre>\n\n<p>With this way you're setting the classes in theme files, and you'll also need to use the cascade to target whichever div needs the coloring (instead of <code>.blue</code> you would use something like <code>body.blue div.styleme</code>), but no plugin is needed. :)</p>\n"
}
]
| 2018/08/03 | [
"https://wordpress.stackexchange.com/questions/310439",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37548/"
]
| I've created the following pages and hierarchy:
* Grandparent
+ Parent
+ Parent
+ Parent
- Child
- Child
- Child
+ Parent
+ Parent
* Grandparent
The Grandparent pages have an ACF custom field to pick the colour.
[](https://i.stack.imgur.com/2pBfg.png)
I'd like that colour selection to be applied for the Grandparent, Parent and Child pages.
Within the loop, I've written the following code to grab the Grandparent colour selection:
```
<div class="<?= get_field('colour', $post->post_parent); ?>">
```
Let's say I've picked the colour "red".
Here's the front-end result:
* Grandparent (Red)
+ Parent (Red)
+ Parent (Red)
+ Parent (Red)
- Child (Null)
- Child (Null)
- Child (Null)
+ Parent (Red)
+ Parent (Red)
* Grandparent
The colour is only being applied to the Grandparent and Parent Pages. Child pages are returning no colour (null).
How do I include the Child pages too? | As far as I'm aware there's no limit to how many levels of ancestry Pages can have, so any solution should not depend on specifically referencing a particular ancestor. The best solution would be to get a list of all ancestors for the page and loop over them until you find a value for your field. Then stop looping over them and return the found value. The function `get_post_ancestors()` can be used for this:
```
$colour = null;
/**
* Get the IDs of the page's ancestors into a list.
*/
$page_ids = get_post_ancestors( $post );
/**
* Put the current page's ID at the beginning of the list so we don't have to
* handle it separately.
*/
array_unshift( $page_ids, $post->ID );
/**
* Loop over pages and find the first one with a colour.
*/
foreach ( $page_ids as $page_id ) {
$maybe_colour = get_post_meta( 'colour', $page_id, true );
/**
* If the page has a value for colour, put it in the colour variable and
* stop the loop.
*/
if ( $maybe_colour ) {
$colour = $maybe_colour;
break;
}
}
echo $colour;
```
To save space in your template you could add this to a function and use the function in your template instead:
```
function wpse_310439_get_the_colour( $post = 0 ) {
$post = get_post( $post );
$page_ids = get_post_ancestors( $post );
array_unshift( $page_ids, $post->ID );
$colour = null;
foreach ( $page_ids as $page_id ) {
$maybe_colour = get_post_meta( 'colour', $page_id, true );
if ( $maybe_colour ) {
$colour = $maybe_colour;
break;
}
}
return $colour;
}
```
Then in your template:
```
<div class="<?php echo esc_attr( wpse_310439_get_the_colour() ); ?>">
``` |
310,465 | <p>I'm trying to unregister core block types in WordPress Gutenberg. </p>
<p>I've used the code provided here:
<a href="https://github.com/WordPress/gutenberg/blob/master/docs/extensibility/extending-blocks.md#removing-blocks" rel="noreferrer">https://github.com/WordPress/gutenberg/blob/master/docs/extensibility/extending-blocks.md#removing-blocks</a></p>
<p>But I can't get it to work. I feel like there may be a simple step I am missing? </p>
<ol>
<li>I created a plugin which I activated in my WP theme. </li>
<li>In my plugin [clore-blocks] folder I created "clore-blocks.php". It contains:</li>
</ol>
<pre>
/**
* Remove certain blocks.
*/
function clore_blacklist_blocks() {
wp_enqueue_script(
'clore-blacklist-blocks',
plugins_url( 'blocks.js', __FILE__ ),
array( 'wp-blocks' ),
filemtime( plugin_dir_path( __FILE__ ) . 'blocks.js' ) // Version: filemtime - Gets file modification time.
);
}
add_action( 'enqueue_block_editor_assets', 'clore_blacklist_blocks' );
</pre>
<ol start="3">
<li>In blocks.js I have only: </li>
</ol>
<pre>
wp.blocks.unregisterBlockType( 'core/verse' );
</pre>
<p>I thought this would remove the "Verse" block type from being used, but when I go to edit a page with the Gutenberg editor, "Verse" is still there. </p>
<p>When I view the page source from the WP edit page, I can see that my "blocks.js" file is being referenced correctly, but It's just not doing anything... or at least not what I want it to do. Do you have any idea why that is?</p>
| [
{
"answer_id": 311633,
"author": "Misha Rudrastyh",
"author_id": 85985,
"author_profile": "https://wordpress.stackexchange.com/users/85985",
"pm_score": 2,
"selected": false,
"text": "<p>Everything works for me with <code>allowed_block_types</code> hook.</p>\n\n<p>Example:</p>\n\n<pre><code>add_filter( 'allowed_block_types', 'my_function' );\n\nfunction my_function( $allowed_block_types ) {\n\n return array(\n 'core/paragraph'\n );\n\n}\n</code></pre>\n\n<p>You can insert the above code to your <code>functions.php</code> file to a custom plugin. It removes all blocks except the Paragraph block. </p>\n\n<p>More examples here <a href=\"https://rudrastyh.com/gutenberg/remove-default-blocks.html\" rel=\"nofollow noreferrer\">https://rudrastyh.com/gutenberg/remove-default-blocks.html</a></p>\n"
},
{
"answer_id": 324289,
"author": "Fat Pixel",
"author_id": 158027,
"author_profile": "https://wordpress.stackexchange.com/users/158027",
"pm_score": 2,
"selected": false,
"text": "<p>Had the same problem following the code suggestion in the Gutenberg docs.</p>\n<p>I solved this by adding a <code>wp.domReady()</code> call to the JavaScript code. So, like this:</p>\n<pre><code>wp.domReady( function() {\n wp.blocks.unregisterBlockType( 'core/verse' );\n});\n</code></pre>\n<p>Now, the 'verse' block is gone from the block editor.</p>\n<p>I think this has to do with the order of loading javascript files in the admin. The <code>unregisterBlockType</code> should be called after the block editor has loaded.</p>\n<p>Hope this helps!</p>\n<p>Thanks to PayteR for the suggestion and see <a href=\"https://wordpress.org/gutenberg/handbook/designers-developers/developers/filters/block-filters/#using-a-blacklist\" rel=\"nofollow noreferrer\">https://wordpress.org/gutenberg/handbook/designers-developers/developers/filters/block-filters/#using-a-blacklist</a> for more info.</p>\n"
}
]
| 2018/08/03 | [
"https://wordpress.stackexchange.com/questions/310465",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/148068/"
]
| I'm trying to unregister core block types in WordPress Gutenberg.
I've used the code provided here:
<https://github.com/WordPress/gutenberg/blob/master/docs/extensibility/extending-blocks.md#removing-blocks>
But I can't get it to work. I feel like there may be a simple step I am missing?
1. I created a plugin which I activated in my WP theme.
2. In my plugin [clore-blocks] folder I created "clore-blocks.php". It contains:
```
/**
* Remove certain blocks.
*/
function clore_blacklist_blocks() {
wp_enqueue_script(
'clore-blacklist-blocks',
plugins_url( 'blocks.js', __FILE__ ),
array( 'wp-blocks' ),
filemtime( plugin_dir_path( __FILE__ ) . 'blocks.js' ) // Version: filemtime - Gets file modification time.
);
}
add_action( 'enqueue_block_editor_assets', 'clore_blacklist_blocks' );
```
3. In blocks.js I have only:
```
wp.blocks.unregisterBlockType( 'core/verse' );
```
I thought this would remove the "Verse" block type from being used, but when I go to edit a page with the Gutenberg editor, "Verse" is still there.
When I view the page source from the WP edit page, I can see that my "blocks.js" file is being referenced correctly, but It's just not doing anything... or at least not what I want it to do. Do you have any idea why that is? | Everything works for me with `allowed_block_types` hook.
Example:
```
add_filter( 'allowed_block_types', 'my_function' );
function my_function( $allowed_block_types ) {
return array(
'core/paragraph'
);
}
```
You can insert the above code to your `functions.php` file to a custom plugin. It removes all blocks except the Paragraph block.
More examples here <https://rudrastyh.com/gutenberg/remove-default-blocks.html> |
310,508 | <p>I have a radio control in the theme customizer. The code for that control is like below:</p>
<pre><code>$wp_customize->add_setting( 'post_layout', array(
'capability' => 'edit_theme_options',
'default' => 'cover',
'sanitize_callback' => 'sanitize_text_field',
) );
$wp_customize->add_control( 'post_layout', array(
'type' => 'radio',
'section' => 'post_options',
'label' => __( 'Post Layout', 'mytheme' ),
'choices' => array(
'cover' => __( 'Cover', 'mytheme' ),
'thumbnail' => __( 'Thumbnail', 'mytheme' ),
'default' => __( 'Default', 'mytheme' ),
),
) );
</code></pre>
<p>And the complete code responsible to render the post meta-box is:</p>
<pre><code><?php
/**
* Add the meta box
*
* @return void
*/
function mytheme_add_custom_box() {
add_meta_box(
'mytheme_sectionid',
__( 'Post Options', 'mytheme' ),
'mytheme_build_custom_box',
'post',
'side',
'low'
);
}
add_action( 'add_meta_boxes', 'mytheme_add_custom_box' );
/**
* Prints the box content.
*
* @param WP_Post $post The object for the current post/page.
* @return void
*/
function mytheme_build_custom_box( $post ) {
// Add an nonce field so we can check for it later.
wp_nonce_field( 'mytheme_build_custom_box', 'mytheme_build_custom_box_nonce' );
/*
* Use get_post_meta() to retrieve an existing value
* from the database and use the value for the form.
*/
$value = get_post_meta( $post->ID, '_my_meta_value_key', true );
$loxxo_post_header_layout = get_theme_mod( 'loxxo_post_header', 'cover' );
?>
<p><?php __( 'Select a style', 'mytheme' ); ?></p>
<input type="radio" id="mytheme_post_layout-cover" name="mytheme_post_layout" value="cover" <?php checked( $value, 'cover' ) ?> /><label for="mytheme_post_layout-cover"><?php _e( 'Cover/Fullscreen', 'mytheme' ); ?></label>
<br>
<input type="radio" id="mytheme_post_layout-thumbnail" name="mytheme_post_layout" value="thumbnail" <?php checked( $value, 'thumbnail' ) ?> /><label for="mytheme_post_layout-thumbnail"><?php _e( 'Regular', 'mytheme' ) ?></label>
<br>
<input type="radio" id="mytheme_post_layout-default" name="mytheme_post_layout" value="default" <?php checked( $value, 'default' ) ?> /><label for="mytheme_post_layout-default"><?php _e( 'Default', 'mytheme' ) ?></label>
<?php
}
/**
* When the post is saved, saves our custom data.
*
* @param int $post_id The ID of the post being saved.
* @return void
*/
function mytheme_save_postdata( $post_id ) {
/*
* We need to verify this came from the our screen and with proper authorization,
* because save_post can be triggered at other times.
*/
// Check if our nonce is set.
if ( ! isset( $_POST['mytheme_build_custom_box_nonce'] ) )
return $post_id;
$nonce = $_POST['mytheme_build_custom_box_nonce'];
// Verify that the nonce is valid.
if ( ! wp_verify_nonce( $nonce, 'mytheme_build_custom_box' ) )
return $post_id;
// If this is an autosave, our form has not been submitted, so we don't want to do anything.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return $post_id;
// Check the user's permissions.
if ( 'page' == $_POST['post_type'] ) {
if ( ! current_user_can( 'edit_page', $post_id ) )
return $post_id;
} else {
if ( ! current_user_can( 'edit_post', $post_id ) )
return $post_id;
}
// Sanitize user input.
$mydata = sanitize_text_field( $_POST['mytheme_post_layout'] );
// Update the meta field in the database.
update_post_meta( $post_id, '_my_meta_value_key', $mydata );
}
add_action( 'save_post', 'mytheme_save_postdata' );
</code></pre>
<p>Above is a bit lengthy code, sorry about that. The options are rendering correctly, and everything looks fine in the customizer and the meta-box.</p>
<p>The problem is, that I'm confused about making the default value of the meta-box radio options go hand-in-hand with the customizer's. Any clues and ideas will be appreciated.</p>
| [
{
"answer_id": 310509,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>You're getting the saved value here:</p>\n\n<pre><code>$value = get_post_meta( $post->ID, '_my_meta_value_key', true );\n</code></pre>\n\n<p>All you need to do is check if the value contains anything. If it doesn't, set the value to the option from the customiser:</p>\n\n<pre><code>$value = get_post_meta( $post->ID, '_my_meta_value_key', true );\n\nif ( ! $value ) {\n $value = get_theme_mod( 'loxxo_post_header', 'cover' );\n}\n</code></pre>\n\n<p>Which can be accomplished in one line of code with the <a href=\"http://php.net/manual/en/language.operators.comparison.php\" rel=\"nofollow noreferrer\">ternary operator</a> (<code>?:</code>):</p>\n\n<pre><code>$value = get_post_meta( $post->ID, '_my_meta_value_key', true ) ?: get_theme_mod( 'loxxo_post_header', 'cover' );\n</code></pre>\n"
},
{
"answer_id": 310512,
"author": "Kaperto",
"author_id": 147795,
"author_profile": "https://wordpress.stackexchange.com/users/147795",
"pm_score": 1,
"selected": true,
"text": "<p>Before to handle the defaut value, there is a lot of changes that you can do for the hook \"save_post\" and the first one is to no more use it.<br>\nYou add the metabox only on post type <code>post</code>, then you can use the hook <code>save_post_post</code> to only doing the treatment for this custom post :<br>\n<a href=\"https://developer.wordpress.org/reference/hooks/save_post_post-post_type/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/save_post_post-post_type/</a></p>\n\n<p>After that, you don't need to test the capability <code>edit_post</code> because the backend page \"edit.php\" does the test before to save.\nAnd you don't need to test DOING_AUTOSAVE because in the autosave case, the metabox values are not send. And then you just have to test the nonce.</p>\n\n<p>Finally, to set a default value in the metabox, you can do it when <code>$update === FALSE</code> which is called when you click on the link \"create a new post\".</p>\n\n<p>and then try this code : </p>\n\n<pre><code>add_action(\"save_post_post\", function ($post_ID, $post, $update) {\n\n\n if (!$update) {\n\n // default values here\n\n $mydata = get_theme_mod( 'post_layout', 'cover' );\n update_post_meta( $post_ID, '_my_meta_value_key', $mydata );\n\n return;\n\n }\n\n\n if ( ! isset( $_POST['mytheme_build_custom_box_nonce'] ) ) {\n return;\n }\n\n // check the nonce\n check_admin_referer(\n \"mytheme_build_custom_box\"\n , \"mytheme_build_custom_box_nonce\"\n );\n\n\n // save the values\n\n // Sanitize user input.\n $mydata = sanitize_text_field( $_POST['mytheme_post_layout'] );\n\n // Update the meta field in the database.\n update_post_meta( $post_ID, '_my_meta_value_key', $mydata );\n\n\n}, 10, 3);\n</code></pre>\n"
}
]
| 2018/08/04 | [
"https://wordpress.stackexchange.com/questions/310508",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67150/"
]
| I have a radio control in the theme customizer. The code for that control is like below:
```
$wp_customize->add_setting( 'post_layout', array(
'capability' => 'edit_theme_options',
'default' => 'cover',
'sanitize_callback' => 'sanitize_text_field',
) );
$wp_customize->add_control( 'post_layout', array(
'type' => 'radio',
'section' => 'post_options',
'label' => __( 'Post Layout', 'mytheme' ),
'choices' => array(
'cover' => __( 'Cover', 'mytheme' ),
'thumbnail' => __( 'Thumbnail', 'mytheme' ),
'default' => __( 'Default', 'mytheme' ),
),
) );
```
And the complete code responsible to render the post meta-box is:
```
<?php
/**
* Add the meta box
*
* @return void
*/
function mytheme_add_custom_box() {
add_meta_box(
'mytheme_sectionid',
__( 'Post Options', 'mytheme' ),
'mytheme_build_custom_box',
'post',
'side',
'low'
);
}
add_action( 'add_meta_boxes', 'mytheme_add_custom_box' );
/**
* Prints the box content.
*
* @param WP_Post $post The object for the current post/page.
* @return void
*/
function mytheme_build_custom_box( $post ) {
// Add an nonce field so we can check for it later.
wp_nonce_field( 'mytheme_build_custom_box', 'mytheme_build_custom_box_nonce' );
/*
* Use get_post_meta() to retrieve an existing value
* from the database and use the value for the form.
*/
$value = get_post_meta( $post->ID, '_my_meta_value_key', true );
$loxxo_post_header_layout = get_theme_mod( 'loxxo_post_header', 'cover' );
?>
<p><?php __( 'Select a style', 'mytheme' ); ?></p>
<input type="radio" id="mytheme_post_layout-cover" name="mytheme_post_layout" value="cover" <?php checked( $value, 'cover' ) ?> /><label for="mytheme_post_layout-cover"><?php _e( 'Cover/Fullscreen', 'mytheme' ); ?></label>
<br>
<input type="radio" id="mytheme_post_layout-thumbnail" name="mytheme_post_layout" value="thumbnail" <?php checked( $value, 'thumbnail' ) ?> /><label for="mytheme_post_layout-thumbnail"><?php _e( 'Regular', 'mytheme' ) ?></label>
<br>
<input type="radio" id="mytheme_post_layout-default" name="mytheme_post_layout" value="default" <?php checked( $value, 'default' ) ?> /><label for="mytheme_post_layout-default"><?php _e( 'Default', 'mytheme' ) ?></label>
<?php
}
/**
* When the post is saved, saves our custom data.
*
* @param int $post_id The ID of the post being saved.
* @return void
*/
function mytheme_save_postdata( $post_id ) {
/*
* We need to verify this came from the our screen and with proper authorization,
* because save_post can be triggered at other times.
*/
// Check if our nonce is set.
if ( ! isset( $_POST['mytheme_build_custom_box_nonce'] ) )
return $post_id;
$nonce = $_POST['mytheme_build_custom_box_nonce'];
// Verify that the nonce is valid.
if ( ! wp_verify_nonce( $nonce, 'mytheme_build_custom_box' ) )
return $post_id;
// If this is an autosave, our form has not been submitted, so we don't want to do anything.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return $post_id;
// Check the user's permissions.
if ( 'page' == $_POST['post_type'] ) {
if ( ! current_user_can( 'edit_page', $post_id ) )
return $post_id;
} else {
if ( ! current_user_can( 'edit_post', $post_id ) )
return $post_id;
}
// Sanitize user input.
$mydata = sanitize_text_field( $_POST['mytheme_post_layout'] );
// Update the meta field in the database.
update_post_meta( $post_id, '_my_meta_value_key', $mydata );
}
add_action( 'save_post', 'mytheme_save_postdata' );
```
Above is a bit lengthy code, sorry about that. The options are rendering correctly, and everything looks fine in the customizer and the meta-box.
The problem is, that I'm confused about making the default value of the meta-box radio options go hand-in-hand with the customizer's. Any clues and ideas will be appreciated. | Before to handle the defaut value, there is a lot of changes that you can do for the hook "save\_post" and the first one is to no more use it.
You add the metabox only on post type `post`, then you can use the hook `save_post_post` to only doing the treatment for this custom post :
<https://developer.wordpress.org/reference/hooks/save_post_post-post_type/>
After that, you don't need to test the capability `edit_post` because the backend page "edit.php" does the test before to save.
And you don't need to test DOING\_AUTOSAVE because in the autosave case, the metabox values are not send. And then you just have to test the nonce.
Finally, to set a default value in the metabox, you can do it when `$update === FALSE` which is called when you click on the link "create a new post".
and then try this code :
```
add_action("save_post_post", function ($post_ID, $post, $update) {
if (!$update) {
// default values here
$mydata = get_theme_mod( 'post_layout', 'cover' );
update_post_meta( $post_ID, '_my_meta_value_key', $mydata );
return;
}
if ( ! isset( $_POST['mytheme_build_custom_box_nonce'] ) ) {
return;
}
// check the nonce
check_admin_referer(
"mytheme_build_custom_box"
, "mytheme_build_custom_box_nonce"
);
// save the values
// Sanitize user input.
$mydata = sanitize_text_field( $_POST['mytheme_post_layout'] );
// Update the meta field in the database.
update_post_meta( $post_ID, '_my_meta_value_key', $mydata );
}, 10, 3);
``` |
310,513 | <p>I'm trying to create a new og:image for author avatar when the users sharing their author profile page to Facebook.</p>
<p>I'm a newbie with WordPress, After searching for more than 6 months but i'm always failing.</p>
<p>My site is multi-authors and all what i need to add og:image meta tag for author.php "author profile", I'm stuck and I really get tired from searching.</p>
<p>When our users trying to share his profile..the avatar image not coming up! because Facebook can't find the author avatar og:image!</p>
<p>Plugins i'm using : <a href="https://yoast.com/" rel="nofollow noreferrer">Yoast SEO</a>, <a href="https://wordpress.org/plugins/simple-local-avatars/" rel="nofollow noreferrer">Simple Local Avatars</a>, <a href="https://wordpress.org/plugins/add-to-any/" rel="nofollow noreferrer">AddToAny Share Buttons</a>.</p>
<p>I tried to use wpseo_opengraph_image filter, but not working.</p>
<p>This is code I'm using:</p>
<pre><code>function custom_author_og_image() {
if ( is_author ( ) ) {
$author = get_queried_object();
$image_attributes = get_avatar_url( $author->user_email, 'full' );
if ( $image_attributes !== false ) {
return $image_attributes[0];
}
}
}
add_filter('wpseo_opengraph_image', 'custom_author_og_image', 10, 0);
</code></pre>
| [
{
"answer_id": 310509,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>You're getting the saved value here:</p>\n\n<pre><code>$value = get_post_meta( $post->ID, '_my_meta_value_key', true );\n</code></pre>\n\n<p>All you need to do is check if the value contains anything. If it doesn't, set the value to the option from the customiser:</p>\n\n<pre><code>$value = get_post_meta( $post->ID, '_my_meta_value_key', true );\n\nif ( ! $value ) {\n $value = get_theme_mod( 'loxxo_post_header', 'cover' );\n}\n</code></pre>\n\n<p>Which can be accomplished in one line of code with the <a href=\"http://php.net/manual/en/language.operators.comparison.php\" rel=\"nofollow noreferrer\">ternary operator</a> (<code>?:</code>):</p>\n\n<pre><code>$value = get_post_meta( $post->ID, '_my_meta_value_key', true ) ?: get_theme_mod( 'loxxo_post_header', 'cover' );\n</code></pre>\n"
},
{
"answer_id": 310512,
"author": "Kaperto",
"author_id": 147795,
"author_profile": "https://wordpress.stackexchange.com/users/147795",
"pm_score": 1,
"selected": true,
"text": "<p>Before to handle the defaut value, there is a lot of changes that you can do for the hook \"save_post\" and the first one is to no more use it.<br>\nYou add the metabox only on post type <code>post</code>, then you can use the hook <code>save_post_post</code> to only doing the treatment for this custom post :<br>\n<a href=\"https://developer.wordpress.org/reference/hooks/save_post_post-post_type/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/save_post_post-post_type/</a></p>\n\n<p>After that, you don't need to test the capability <code>edit_post</code> because the backend page \"edit.php\" does the test before to save.\nAnd you don't need to test DOING_AUTOSAVE because in the autosave case, the metabox values are not send. And then you just have to test the nonce.</p>\n\n<p>Finally, to set a default value in the metabox, you can do it when <code>$update === FALSE</code> which is called when you click on the link \"create a new post\".</p>\n\n<p>and then try this code : </p>\n\n<pre><code>add_action(\"save_post_post\", function ($post_ID, $post, $update) {\n\n\n if (!$update) {\n\n // default values here\n\n $mydata = get_theme_mod( 'post_layout', 'cover' );\n update_post_meta( $post_ID, '_my_meta_value_key', $mydata );\n\n return;\n\n }\n\n\n if ( ! isset( $_POST['mytheme_build_custom_box_nonce'] ) ) {\n return;\n }\n\n // check the nonce\n check_admin_referer(\n \"mytheme_build_custom_box\"\n , \"mytheme_build_custom_box_nonce\"\n );\n\n\n // save the values\n\n // Sanitize user input.\n $mydata = sanitize_text_field( $_POST['mytheme_post_layout'] );\n\n // Update the meta field in the database.\n update_post_meta( $post_ID, '_my_meta_value_key', $mydata );\n\n\n}, 10, 3);\n</code></pre>\n"
}
]
| 2018/08/04 | [
"https://wordpress.stackexchange.com/questions/310513",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/146329/"
]
| I'm trying to create a new og:image for author avatar when the users sharing their author profile page to Facebook.
I'm a newbie with WordPress, After searching for more than 6 months but i'm always failing.
My site is multi-authors and all what i need to add og:image meta tag for author.php "author profile", I'm stuck and I really get tired from searching.
When our users trying to share his profile..the avatar image not coming up! because Facebook can't find the author avatar og:image!
Plugins i'm using : [Yoast SEO](https://yoast.com/), [Simple Local Avatars](https://wordpress.org/plugins/simple-local-avatars/), [AddToAny Share Buttons](https://wordpress.org/plugins/add-to-any/).
I tried to use wpseo\_opengraph\_image filter, but not working.
This is code I'm using:
```
function custom_author_og_image() {
if ( is_author ( ) ) {
$author = get_queried_object();
$image_attributes = get_avatar_url( $author->user_email, 'full' );
if ( $image_attributes !== false ) {
return $image_attributes[0];
}
}
}
add_filter('wpseo_opengraph_image', 'custom_author_og_image', 10, 0);
``` | Before to handle the defaut value, there is a lot of changes that you can do for the hook "save\_post" and the first one is to no more use it.
You add the metabox only on post type `post`, then you can use the hook `save_post_post` to only doing the treatment for this custom post :
<https://developer.wordpress.org/reference/hooks/save_post_post-post_type/>
After that, you don't need to test the capability `edit_post` because the backend page "edit.php" does the test before to save.
And you don't need to test DOING\_AUTOSAVE because in the autosave case, the metabox values are not send. And then you just have to test the nonce.
Finally, to set a default value in the metabox, you can do it when `$update === FALSE` which is called when you click on the link "create a new post".
and then try this code :
```
add_action("save_post_post", function ($post_ID, $post, $update) {
if (!$update) {
// default values here
$mydata = get_theme_mod( 'post_layout', 'cover' );
update_post_meta( $post_ID, '_my_meta_value_key', $mydata );
return;
}
if ( ! isset( $_POST['mytheme_build_custom_box_nonce'] ) ) {
return;
}
// check the nonce
check_admin_referer(
"mytheme_build_custom_box"
, "mytheme_build_custom_box_nonce"
);
// save the values
// Sanitize user input.
$mydata = sanitize_text_field( $_POST['mytheme_post_layout'] );
// Update the meta field in the database.
update_post_meta( $post_ID, '_my_meta_value_key', $mydata );
}, 10, 3);
``` |
310,524 | <p>There are specific plugins that I want to use my own repo for for updating my sites. How can I identify the plugin to target and what server they should be looking at?</p>
| [
{
"answer_id": 310509,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>You're getting the saved value here:</p>\n\n<pre><code>$value = get_post_meta( $post->ID, '_my_meta_value_key', true );\n</code></pre>\n\n<p>All you need to do is check if the value contains anything. If it doesn't, set the value to the option from the customiser:</p>\n\n<pre><code>$value = get_post_meta( $post->ID, '_my_meta_value_key', true );\n\nif ( ! $value ) {\n $value = get_theme_mod( 'loxxo_post_header', 'cover' );\n}\n</code></pre>\n\n<p>Which can be accomplished in one line of code with the <a href=\"http://php.net/manual/en/language.operators.comparison.php\" rel=\"nofollow noreferrer\">ternary operator</a> (<code>?:</code>):</p>\n\n<pre><code>$value = get_post_meta( $post->ID, '_my_meta_value_key', true ) ?: get_theme_mod( 'loxxo_post_header', 'cover' );\n</code></pre>\n"
},
{
"answer_id": 310512,
"author": "Kaperto",
"author_id": 147795,
"author_profile": "https://wordpress.stackexchange.com/users/147795",
"pm_score": 1,
"selected": true,
"text": "<p>Before to handle the defaut value, there is a lot of changes that you can do for the hook \"save_post\" and the first one is to no more use it.<br>\nYou add the metabox only on post type <code>post</code>, then you can use the hook <code>save_post_post</code> to only doing the treatment for this custom post :<br>\n<a href=\"https://developer.wordpress.org/reference/hooks/save_post_post-post_type/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/save_post_post-post_type/</a></p>\n\n<p>After that, you don't need to test the capability <code>edit_post</code> because the backend page \"edit.php\" does the test before to save.\nAnd you don't need to test DOING_AUTOSAVE because in the autosave case, the metabox values are not send. And then you just have to test the nonce.</p>\n\n<p>Finally, to set a default value in the metabox, you can do it when <code>$update === FALSE</code> which is called when you click on the link \"create a new post\".</p>\n\n<p>and then try this code : </p>\n\n<pre><code>add_action(\"save_post_post\", function ($post_ID, $post, $update) {\n\n\n if (!$update) {\n\n // default values here\n\n $mydata = get_theme_mod( 'post_layout', 'cover' );\n update_post_meta( $post_ID, '_my_meta_value_key', $mydata );\n\n return;\n\n }\n\n\n if ( ! isset( $_POST['mytheme_build_custom_box_nonce'] ) ) {\n return;\n }\n\n // check the nonce\n check_admin_referer(\n \"mytheme_build_custom_box\"\n , \"mytheme_build_custom_box_nonce\"\n );\n\n\n // save the values\n\n // Sanitize user input.\n $mydata = sanitize_text_field( $_POST['mytheme_post_layout'] );\n\n // Update the meta field in the database.\n update_post_meta( $post_ID, '_my_meta_value_key', $mydata );\n\n\n}, 10, 3);\n</code></pre>\n"
}
]
| 2018/08/04 | [
"https://wordpress.stackexchange.com/questions/310524",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/116443/"
]
| There are specific plugins that I want to use my own repo for for updating my sites. How can I identify the plugin to target and what server they should be looking at? | Before to handle the defaut value, there is a lot of changes that you can do for the hook "save\_post" and the first one is to no more use it.
You add the metabox only on post type `post`, then you can use the hook `save_post_post` to only doing the treatment for this custom post :
<https://developer.wordpress.org/reference/hooks/save_post_post-post_type/>
After that, you don't need to test the capability `edit_post` because the backend page "edit.php" does the test before to save.
And you don't need to test DOING\_AUTOSAVE because in the autosave case, the metabox values are not send. And then you just have to test the nonce.
Finally, to set a default value in the metabox, you can do it when `$update === FALSE` which is called when you click on the link "create a new post".
and then try this code :
```
add_action("save_post_post", function ($post_ID, $post, $update) {
if (!$update) {
// default values here
$mydata = get_theme_mod( 'post_layout', 'cover' );
update_post_meta( $post_ID, '_my_meta_value_key', $mydata );
return;
}
if ( ! isset( $_POST['mytheme_build_custom_box_nonce'] ) ) {
return;
}
// check the nonce
check_admin_referer(
"mytheme_build_custom_box"
, "mytheme_build_custom_box_nonce"
);
// save the values
// Sanitize user input.
$mydata = sanitize_text_field( $_POST['mytheme_post_layout'] );
// Update the meta field in the database.
update_post_meta( $post_ID, '_my_meta_value_key', $mydata );
}, 10, 3);
``` |
310,535 | <p>I created my own category selection widget. So i used <code><select></code> but i want to use with <code>multiple</code> attribute. </p>
<p>Here is my widget class. It works perfect without <code>multiple</code> attr. But i want to use it. And it must be return category ids in array.</p>
<pre><code><?php
class myCatWidget extends WP_Widget {
function myCatWidget() {
parent::WP_Widget( false, $name = 'My cat widget' );
}
function form( $instance ) {
$title = esc_attr( $instance[ 'title' ] );
$postCats = $instance[ 'postCats' ];
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>">Title</label>
<input type="text" class="widfat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" style="width: 100%;" value="<?php echo $title; ?>"/>
</p>
<p>
<label for="<?php echo $this->get_field_id( 'postCats' ); ?>">Categories</label>
<select name="<?php echo $this->get_field_name( 'postCats' ); ?>" id="<?php echo $this->get_field_id( 'postCats' ); ?>" style="width: 100%;" multiple>
<?php
$args = array(
'taxonomy' => 'category',
);
$terms = get_terms( $args );
foreach( $terms as $term ) { ?>
<option <?php selected( $instance[ 'postCats' ], $term->term_id ); ?> value="<?php echo esc_attr( $term->term_id ); ?>">
<?php echo esc_html( $term->name ); ?>
</option>
<?php } ?>
</select>
</p>
<?php
}
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance[ 'title' ] = strip_tags( $new_instance[ 'title' ] );
$instance[ 'postCats' ] = esc_sql( $new_instance[ 'postCats' ] );
return $instance;
}
function widget( $args, $instance ) {
extract( $args );
$title = apply_filters( 'widget_title', $instance[ 'title' ] );
$postCats = $instance[ 'postCats' ];
echo $before_widget;
if( $title ) {
echo $before_title . $title . $after_title;
}
echo $postCats;
echo $after_widget;
}
}
add_action( 'widgets_init', create_function( '', 'return register_widget("myCatWidget");' ) );
?>
</code></pre>
| [
{
"answer_id": 310595,
"author": "Nilesh Sanura",
"author_id": 148097,
"author_profile": "https://wordpress.stackexchange.com/users/148097",
"pm_score": 2,
"selected": true,
"text": "<p>Hi why don't you used multiple check-box instead of select option field. As well as you have used deprecated functions like \"create_function\". I have modified your code which replaced select option with multiple check-box selection.</p>\n\n<pre><code>function myCatWidget() {\n register_widget( 'my_custom_cat_widget' );\n}\nadd_action( 'widgets_init', 'myCatWidget' );\n\nclass my_custom_cat_widget extends WP_Widget {\n\n function __construct() { \n parent::__construct('my_custom_cat_widget', __('My cat widget', 'wpb_widget_domain'), \n array( 'description' => __( 'Your description', 'wpb_widget_domain' ), ) \n );\n }\n\npublic function form( $instance ) {\n $title = isset($instance[ 'title' ]) ? $instance[ 'title' ] : 'Categories';\n $instance['postCats'] = !empty($instance['postCats']) ? explode(\",\",$instance['postCats']) : array();\n ?>\n\n <p>\n <label for=\"<?php echo $this->get_field_id( 'title' ); ?>\">Title</label>\n <input type=\"text\" class=\"widfat\" id=\"<?php echo $this->get_field_id( 'title' ); ?>\" name=\"<?php echo $this->get_field_name( 'title' ); ?>\" style=\"width: 100%;\" value=\"<?php echo $title; ?>\"/>\n </p>\n\n <p>\n <label for=\"<?php echo $this->get_field_id( 'postCats' ); ?>\"><?php _e( 'Select Categories you want to show:' ); ?></label><br />\n <?php $args = array(\n 'post_type' => 'post',\n 'taxonomy' => 'category',\n );\n $terms = get_terms( $args );\n //print_r($terms);\n foreach( $terms as $id => $name ) { \n $checked = \"\";\n if(in_array($name->name,$instance['postCats'])){\n $checked = \"checked='checked'\";\n }\n ?>\n <input type=\"checkbox\" class=\"checkbox\" id=\"<?php echo $this->get_field_id('postCats'); ?>\" name=\"<?php echo $this->get_field_name('postCats[]'); ?>\" value=\"<?php echo $name->name; ?>\" <?php echo $checked; ?>/>\n <label for=\"<?php echo $this->get_field_id('postCats'); ?>\"><?php echo $name->name; ?></label><br />\n <?php } ?>\n </p>\n\n <?php\n\n}\n\npublic function update( $new_instance, $old_instance ) {\n $instance = $old_instance;\n\n $instance[ 'title' ] = strip_tags( $new_instance[ 'title' ] );\n $instance['postCats'] = !empty($new_instance['postCats']) ? implode(\",\",$new_instance['postCats']) : 0;\n return $instance;\n}\n\npublic function widget( $args, $instance ) {\n extract( $args );\n\n $title = apply_filters( 'widget_title', $instance[ 'title' ] );\n $postCats = $instance[ 'postCats' ];\n $categories_list = explode(\",\", $postCats);\n\n echo $before_widget;\n\n if( $title ) {\n echo $before_title . $title . $after_title;\n }\n\n $args = array('post_type' => 'post','taxonomy' => 'category',);\n $terms = get_terms( $args );\n ?>\n <ul>\n <?php\n foreach ($categories_list as $cat) {\n foreach($terms as $term) {\n if($cat === $term->name) {\n echo \"<li>\".$term->name.\"</li>\"; \n }\n }\n }\n ?>\n </ul>\n <?php\n echo $after_widget;\n}\n}\n</code></pre>\n\n<p>Hope it will help to solved your problem. :)</p>\n"
},
{
"answer_id": 378140,
"author": "Matteus Barbosa",
"author_id": 195975,
"author_profile": "https://wordpress.stackexchange.com/users/195975",
"pm_score": 0,
"selected": false,
"text": "<p>Simple. Put two brackets right after the select name like</p>\n<pre><code>name="<?php echo $this->get_field_name( 'postCats' ); ?>"\n</code></pre>\n<p>will be named as</p>\n<pre><code>name="<?php echo $this->get_field_name( 'postCats' ); ?>[]"\n</code></pre>\n<p>The complete array of options will then be returned as you expect.</p>\n"
}
]
| 2018/08/04 | [
"https://wordpress.stackexchange.com/questions/310535",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133897/"
]
| I created my own category selection widget. So i used `<select>` but i want to use with `multiple` attribute.
Here is my widget class. It works perfect without `multiple` attr. But i want to use it. And it must be return category ids in array.
```
<?php
class myCatWidget extends WP_Widget {
function myCatWidget() {
parent::WP_Widget( false, $name = 'My cat widget' );
}
function form( $instance ) {
$title = esc_attr( $instance[ 'title' ] );
$postCats = $instance[ 'postCats' ];
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>">Title</label>
<input type="text" class="widfat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" style="width: 100%;" value="<?php echo $title; ?>"/>
</p>
<p>
<label for="<?php echo $this->get_field_id( 'postCats' ); ?>">Categories</label>
<select name="<?php echo $this->get_field_name( 'postCats' ); ?>" id="<?php echo $this->get_field_id( 'postCats' ); ?>" style="width: 100%;" multiple>
<?php
$args = array(
'taxonomy' => 'category',
);
$terms = get_terms( $args );
foreach( $terms as $term ) { ?>
<option <?php selected( $instance[ 'postCats' ], $term->term_id ); ?> value="<?php echo esc_attr( $term->term_id ); ?>">
<?php echo esc_html( $term->name ); ?>
</option>
<?php } ?>
</select>
</p>
<?php
}
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance[ 'title' ] = strip_tags( $new_instance[ 'title' ] );
$instance[ 'postCats' ] = esc_sql( $new_instance[ 'postCats' ] );
return $instance;
}
function widget( $args, $instance ) {
extract( $args );
$title = apply_filters( 'widget_title', $instance[ 'title' ] );
$postCats = $instance[ 'postCats' ];
echo $before_widget;
if( $title ) {
echo $before_title . $title . $after_title;
}
echo $postCats;
echo $after_widget;
}
}
add_action( 'widgets_init', create_function( '', 'return register_widget("myCatWidget");' ) );
?>
``` | Hi why don't you used multiple check-box instead of select option field. As well as you have used deprecated functions like "create\_function". I have modified your code which replaced select option with multiple check-box selection.
```
function myCatWidget() {
register_widget( 'my_custom_cat_widget' );
}
add_action( 'widgets_init', 'myCatWidget' );
class my_custom_cat_widget extends WP_Widget {
function __construct() {
parent::__construct('my_custom_cat_widget', __('My cat widget', 'wpb_widget_domain'),
array( 'description' => __( 'Your description', 'wpb_widget_domain' ), )
);
}
public function form( $instance ) {
$title = isset($instance[ 'title' ]) ? $instance[ 'title' ] : 'Categories';
$instance['postCats'] = !empty($instance['postCats']) ? explode(",",$instance['postCats']) : array();
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>">Title</label>
<input type="text" class="widfat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" style="width: 100%;" value="<?php echo $title; ?>"/>
</p>
<p>
<label for="<?php echo $this->get_field_id( 'postCats' ); ?>"><?php _e( 'Select Categories you want to show:' ); ?></label><br />
<?php $args = array(
'post_type' => 'post',
'taxonomy' => 'category',
);
$terms = get_terms( $args );
//print_r($terms);
foreach( $terms as $id => $name ) {
$checked = "";
if(in_array($name->name,$instance['postCats'])){
$checked = "checked='checked'";
}
?>
<input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id('postCats'); ?>" name="<?php echo $this->get_field_name('postCats[]'); ?>" value="<?php echo $name->name; ?>" <?php echo $checked; ?>/>
<label for="<?php echo $this->get_field_id('postCats'); ?>"><?php echo $name->name; ?></label><br />
<?php } ?>
</p>
<?php
}
public function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance[ 'title' ] = strip_tags( $new_instance[ 'title' ] );
$instance['postCats'] = !empty($new_instance['postCats']) ? implode(",",$new_instance['postCats']) : 0;
return $instance;
}
public function widget( $args, $instance ) {
extract( $args );
$title = apply_filters( 'widget_title', $instance[ 'title' ] );
$postCats = $instance[ 'postCats' ];
$categories_list = explode(",", $postCats);
echo $before_widget;
if( $title ) {
echo $before_title . $title . $after_title;
}
$args = array('post_type' => 'post','taxonomy' => 'category',);
$terms = get_terms( $args );
?>
<ul>
<?php
foreach ($categories_list as $cat) {
foreach($terms as $term) {
if($cat === $term->name) {
echo "<li>".$term->name."</li>";
}
}
}
?>
</ul>
<?php
echo $after_widget;
}
}
```
Hope it will help to solved your problem. :) |
310,628 | <p>I have created a custom banner image block for Gutenberg, which works great, but
I want to know if it is possible to use the page title as the current banner text
placeholder until it has been edited?</p>
<p><a href="https://i.stack.imgur.com/GRkwW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GRkwW.png" alt="enter image description here"></a></p>
<p>My Edit function is</p>
<pre><code> return [
el('div', {className:'header-banner'},
el(
element.Fragment,
null,
controls,
el( "div",{
className: 'banner-image',
style: { backgroundImage: 'url('+attributes.mediaURL+')' }
},
attributes.title || isSelected ? el(RichText, {
key: 'editable',
tagName: "h1",
className: "banner-title",
//Can i add the page title in here if it is avaiable??
//placeholder: i18n.__('Write title…'),
value: attributes.title,
onChange: function onChange(value) {
return props.setAttributes({ title: value });
},
inlineToolbar: true
}) : null
)
)
)//header-banner
];
</code></pre>
<p>Thanks :)</p>
| [
{
"answer_id": 311271,
"author": "Jim-miraidev",
"author_id": 130369,
"author_profile": "https://wordpress.stackexchange.com/users/130369",
"pm_score": 2,
"selected": false,
"text": "<p>Thanks to the answer in this post i have managed to add the title into the banner and it updates as the post title is being updated.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/51674293/use-page-title-in-gutenberg-custom-banner-block/51792096#51792096\">https://stackoverflow.com/questions/51674293/use-page-title-in-gutenberg-custom-banner-block/51792096#51792096</a></p>\n\n<pre><code>var withSelect = wp.data.withSelect;\n\nvar GetTitle = function GetTitle(props) {\n return el(\"h1\",{className: \"jab-banner-title\"},props.title);\n};\n\nvar selectTitle = withSelect(function (select) {\n return {\n title: select(\"core/editor\").getDocumentTitle()\n };\n});\nvar PostTitle = selectTitle(GetTitle);\n</code></pre>\n\n<p>.....</p>\n\n<pre><code> return [\n el('div', {className:'jab-header-banner '+classes+''},\n el(\n element.Fragment,\n null,\n controls,\n el( \"div\",{\n className: 'jab-banner-image',\n style: { backgroundImage: 'url('+attributes.mediaURL+')' }\n },\n el(PostTitle,{className: \"jab-banner-title\"})\n )\n )\n )//header-banner\n ]; \n</code></pre>\n"
},
{
"answer_id": 330562,
"author": "codekipple",
"author_id": 14557,
"author_profile": "https://wordpress.stackexchange.com/users/14557",
"pm_score": 3,
"selected": true,
"text": "<p>Due to the <code>getDocumentTitle</code> selector being deprecated as mentioned here <a href=\"https://stackoverflow.com/questions/51674293/use-page-title-in-gutenberg-custom-banner-block/51792096#comment92130728_51792096\">https://stackoverflow.com/questions/51674293/use-page-title-in-gutenberg-custom-banner-block/51792096#comment92130728_51792096</a></p>\n\n<p>I managed to get it working with a slight tweak to the code by Jim-miraidev</p>\n\n<pre><code>var GetTitle = function GetTitle(props) {\n return el(\"h1\", {className: \"jab-banner-title\"}, props.title);\n};\n\nvar selectTitle = withSelect(function (select) {\n var title;\n\n if (typeof select(\"core/editor\").getPostEdits().title !== 'undefined') {\n title = select(\"core/editor\").getPostEdits().title;\n } else {\n title = select(\"core/editor\").getCurrentPost().title;\n }\n\n return {\n title: title\n };\n});\nvar PostTitle = selectTitle(GetTitle);\n</code></pre>\n\n<p>.....</p>\n\n<pre><code>return [\n el('div', {className:'jab-header-banner '+classes+''},\n el(\n element.Fragment,\n null,\n controls,\n el( \"div\",{\n className: 'jab-banner-image',\n style: { backgroundImage: 'url('+attributes.mediaURL+')' }\n },\n el(PostTitle,{className: \"jab-banner-title\"})\n )\n )\n )//header-banner\n]; \n</code></pre>\n"
},
{
"answer_id": 359932,
"author": "BenB",
"author_id": 62909,
"author_profile": "https://wordpress.stackexchange.com/users/62909",
"pm_score": 0,
"selected": false,
"text": "<p>This worked for me</p>\n\n<pre><code>let title = typeof select(\"core/editor\").getPostEdits().title !== 'undefined' ? select(\"core/editor\").getPostEdits().title : select(\"core/editor\").getCurrentPost().title;\n\n</code></pre>\n"
}
]
| 2018/08/06 | [
"https://wordpress.stackexchange.com/questions/310628",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/130369/"
]
| I have created a custom banner image block for Gutenberg, which works great, but
I want to know if it is possible to use the page title as the current banner text
placeholder until it has been edited?
[](https://i.stack.imgur.com/GRkwW.png)
My Edit function is
```
return [
el('div', {className:'header-banner'},
el(
element.Fragment,
null,
controls,
el( "div",{
className: 'banner-image',
style: { backgroundImage: 'url('+attributes.mediaURL+')' }
},
attributes.title || isSelected ? el(RichText, {
key: 'editable',
tagName: "h1",
className: "banner-title",
//Can i add the page title in here if it is avaiable??
//placeholder: i18n.__('Write title…'),
value: attributes.title,
onChange: function onChange(value) {
return props.setAttributes({ title: value });
},
inlineToolbar: true
}) : null
)
)
)//header-banner
];
```
Thanks :) | Due to the `getDocumentTitle` selector being deprecated as mentioned here <https://stackoverflow.com/questions/51674293/use-page-title-in-gutenberg-custom-banner-block/51792096#comment92130728_51792096>
I managed to get it working with a slight tweak to the code by Jim-miraidev
```
var GetTitle = function GetTitle(props) {
return el("h1", {className: "jab-banner-title"}, props.title);
};
var selectTitle = withSelect(function (select) {
var title;
if (typeof select("core/editor").getPostEdits().title !== 'undefined') {
title = select("core/editor").getPostEdits().title;
} else {
title = select("core/editor").getCurrentPost().title;
}
return {
title: title
};
});
var PostTitle = selectTitle(GetTitle);
```
.....
```
return [
el('div', {className:'jab-header-banner '+classes+''},
el(
element.Fragment,
null,
controls,
el( "div",{
className: 'jab-banner-image',
style: { backgroundImage: 'url('+attributes.mediaURL+')' }
},
el(PostTitle,{className: "jab-banner-title"})
)
)
)//header-banner
];
``` |
310,668 | <p>I want to redirect users to account details after registering, by default it is redirecting to my account dashboard.</p>
<p>This is where I want users to be redirected</p>
<blockquote>
<p>mydomain.com/my-account/edit-account/</p>
</blockquote>
<p>I found something like this, but I think it won't work</p>
<pre><code>function iconic_register_redirect( $redirect ) {
return wc_get_page_permalink( '' );
}
add_filter( 'woocommerce_registration_redirect', 'iconic_register_redirect' );
</code></pre>
| [
{
"answer_id": 310697,
"author": "Suraj Rathod",
"author_id": 141555,
"author_profile": "https://wordpress.stackexchange.com/users/141555",
"pm_score": 0,
"selected": false,
"text": "<pre><code>function woo_login_redirect( $redirect, $user ) {\n$redirect_page_id = url_to_postid( $redirect );\n$checkout_page_id = wc_get_page_id( 'checkout' );\n\nif( $redirect_page_id == $checkout_page_id ) {\n return $redirect;\n}\n\nreturn wc_get_page_permalink( 'shop' );\n}\nadd_filter( 'woocommerce_login_redirect', 'woo_login_redirect' );\n</code></pre>\n\n<p>Use this function to redirect users after login </p>\n"
},
{
"answer_id": 312107,
"author": "nmr",
"author_id": 147428,
"author_profile": "https://wordpress.stackexchange.com/users/147428",
"pm_score": 2,
"selected": true,
"text": "<p>To get \"<em>Account details</em>\" permalink (endpoint <code>edit-account</code>) you need to use function <code>wc_get_account_endpoint_url</code>. </p>\n\n<pre><code>function wc_redirect_to_account_details( $redirect ) {\n $redirect = wc_get_account_endpoint_url('edit-account');\n return $redirect;\n}\nadd_filter( 'woocommerce_registration_redirect', 'wc_redirect_to_account_details' );\n</code></pre>\n"
}
]
| 2018/08/06 | [
"https://wordpress.stackexchange.com/questions/310668",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/148207/"
]
| I want to redirect users to account details after registering, by default it is redirecting to my account dashboard.
This is where I want users to be redirected
>
> mydomain.com/my-account/edit-account/
>
>
>
I found something like this, but I think it won't work
```
function iconic_register_redirect( $redirect ) {
return wc_get_page_permalink( '' );
}
add_filter( 'woocommerce_registration_redirect', 'iconic_register_redirect' );
``` | To get "*Account details*" permalink (endpoint `edit-account`) you need to use function `wc_get_account_endpoint_url`.
```
function wc_redirect_to_account_details( $redirect ) {
$redirect = wc_get_account_endpoint_url('edit-account');
return $redirect;
}
add_filter( 'woocommerce_registration_redirect', 'wc_redirect_to_account_details' );
``` |
310,685 | <p>I am trying to enqueue a js file (calculator.js) from my theme's functions.php file.</p>
<p>I have a desktop theme and a smartphone theme, and I am using a plugin to switch between the two themes depending on the user's device.</p>
<p>I have the exact same code on my desktop theme and it works perfectly, however when I copied it to my smartphone theme, it just seems to ignore the enqueue script.</p>
<p>Here is my code:</p>
<pre><code>function wpb_adding_scripts() {
wp_register_script('calculator_script', get_template_directory_uri() . '/js/calculator.js', array( 'jquery' ), NULL, 'all');
wp_enqueue_script('calculator_script');
wp_enqueue_style( 'slider', get_template_directory_uri() . '/css/calculator.css',false,'1.1','all');
}
add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' );
</code></pre>
<p>What I have done/notes: </p>
<ul>
<li>Made sure functions.php file does indeed start with a opening php tag</li>
<li>Made sure all files are in their correct directories</li>
<li>Console is not flagging any errors</li>
<li>Sources does not show my js file being loaded, however the css file (calculator.css) is being loaded correctly..</li>
</ul>
<p>Any insights as to what might be the cause of this issue?</p>
<p>Thank you very much.</p>
| [
{
"answer_id": 310690,
"author": "maverick",
"author_id": 132953,
"author_profile": "https://wordpress.stackexchange.com/users/132953",
"pm_score": 1,
"selected": false,
"text": "<p>Just some modifications</p>\n\n<pre><code>function wpb_adding_scripts() {\n wp_enqueue_script( 'calculator_script', get_template_directory_uri() . '/js/calculator.js', array( 'jquery' ), '', true );\n wp_enqueue_style( 'slider', get_template_directory_uri() . '/css/calculator.css' );\n} \nadd_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' ); \n</code></pre>\n\n<p>use get_stylesheet_directory_uri() instead of get_template_directory_uri() if your functions.php file is in child theme.</p>\n\n<p>See if this works or not ( normally this way, it does )</p>\n"
},
{
"answer_id": 310691,
"author": "Balas",
"author_id": 17849,
"author_profile": "https://wordpress.stackexchange.com/users/17849",
"pm_score": 2,
"selected": true,
"text": "<pre><code>You can better try this way and let me know.\n\nfunction wpb_adding_scripts() {\n wp_enqueue_style( 'slider', get_stylesheet_directory_uri() . '/css/calculator.css');\n wp_enqueue_script('jquery');\n wp_enqueue_script('calculator_script', get_stylesheet_directory_uri() . '/js/calculator.js');\n\n} \nadd_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' ); \n</code></pre>\n"
},
{
"answer_id": 310695,
"author": "Harsh",
"author_id": 131853,
"author_profile": "https://wordpress.stackexchange.com/users/131853",
"pm_score": 0,
"selected": false,
"text": "<p>get_template_directory_uri will always refer to the parent theme folder for assets.</p>\n\n<p>get_stylesheet_directory_uri will refer to the \"current\" theme folder for assets (which could be the parent or the child, depending on where it is called).</p>\n"
}
]
| 2018/08/07 | [
"https://wordpress.stackexchange.com/questions/310685",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/148215/"
]
| I am trying to enqueue a js file (calculator.js) from my theme's functions.php file.
I have a desktop theme and a smartphone theme, and I am using a plugin to switch between the two themes depending on the user's device.
I have the exact same code on my desktop theme and it works perfectly, however when I copied it to my smartphone theme, it just seems to ignore the enqueue script.
Here is my code:
```
function wpb_adding_scripts() {
wp_register_script('calculator_script', get_template_directory_uri() . '/js/calculator.js', array( 'jquery' ), NULL, 'all');
wp_enqueue_script('calculator_script');
wp_enqueue_style( 'slider', get_template_directory_uri() . '/css/calculator.css',false,'1.1','all');
}
add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' );
```
What I have done/notes:
* Made sure functions.php file does indeed start with a opening php tag
* Made sure all files are in their correct directories
* Console is not flagging any errors
* Sources does not show my js file being loaded, however the css file (calculator.css) is being loaded correctly..
Any insights as to what might be the cause of this issue?
Thank you very much. | ```
You can better try this way and let me know.
function wpb_adding_scripts() {
wp_enqueue_style( 'slider', get_stylesheet_directory_uri() . '/css/calculator.css');
wp_enqueue_script('jquery');
wp_enqueue_script('calculator_script', get_stylesheet_directory_uri() . '/js/calculator.js');
}
add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' );
``` |
310,698 | <p>I have a <strong>notmytheme</strong>, the original css load order is like so:</p>
<pre><code><link rel='stylesheet' id='something' href='http://localhost/mywp/wp-content/themes/notmytheme/something.css' type='text/css' media='all' />
<link rel='stylesheet' id='notmytheme-style-css' href='http://localhost/mywp/wp-content/themes/notmytheme/style.css?ver=1.0.9' type='text/css' media='all' />
</code></pre>
<p>When I created a child theme called the <strong>notmytheme-child</strong>, and enqueue the child style, it became like this:</p>
<pre><code><link rel='stylesheet' id='notmytheme-style-css' href='http://localhost/mywp/wp-content/themes/notmytheme/style.css?ver=1.0.9' type='text/css' media='all' />
<link rel='stylesheet' id='child-style-css' href='http://localhost/mywp/wp-content/themes/notmytheme-child/style.css?ver=18.08.07' type='text/css' media='all' />
<link rel='stylesheet' id='something' href='http://localhost/mywp/wp-content/themes/notmytheme/something.css' type='text/css' media='all' />
</code></pre>
<p>I want the parent and child style to be loaded after other styles like how the parent theme did it, so I moved it down with priority ( <code>add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles', 999 );</code> ), now it became like this:</p>
<pre><code><link rel='stylesheet' id='something' href='http://localhost/mywp/wp-content/themes/notmytheme/something.css' type='text/css' media='all' />
<link rel='stylesheet' id='notmytheme-style-css' href='http://localhost/mywp/wp-content/themes/notmytheme-child/style.css?ver=1.0.9' type='text/css' media='all' />
<link rel='stylesheet' id='child-style-css' href='http://localhost/mywp/wp-content/themes/notmytheme-child/style.css?ver=18.08.07' type='text/css' media='all' />
</code></pre>
<p>I do not know why but now the <code>get_template_directory_uri()</code> now points to <strong>notmytheme-child</strong> instead of <strong>notmytheme</strong>.</p>
<p>My current enqueue script is like so:</p>
<pre><code>add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles', 999 );
function my_theme_enqueue_styles() {
$parent_style = 'notmytheme-style';
wp_enqueue_style( $parent_style,
get_template_directory_uri() . '/style.css',
array(),
'1.0.9' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
array( $parent_style ),
'18.08.07',
'all' );
}
</code></pre>
<p>Adjusting the priority changes the position of where the css are loaded, and also which directory <code>get_template_directory_uri()</code> points to.</p>
<p><strong>EDIT/SOLUTION</strong></p>
<p>My codes are now:</p>
<pre><code>add_action( 'wp_enqueue_scripts', 'my_enqueue_child', 999 );
function my_enqueue_child() {
wp_dequeue_style( 'notmytheme-style' );
wp_enqueue_style( 'parent-style',
get_template_directory_uri() . '/style.css',
array(),
'1.0.9' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
array( 'parent-style' ),
'18.08.07',
'all' );
}
</code></pre>
| [
{
"answer_id": 310700,
"author": "Nilesh Sanura",
"author_id": 148097,
"author_profile": "https://wordpress.stackexchange.com/users/148097",
"pm_score": -1,
"selected": false,
"text": "<p>Please use get_stylesheet_directory_uri() instead of get_template_directory_uri() when you have to enqueue stylesheet form the child theme. Thanks!</p>\n"
},
{
"answer_id": 310701,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 4,
"selected": true,
"text": "<p>It's very common for themes to enqueue their stylesheet like this:</p>\n\n<pre><code>wp_enqueue_style( 'notmytheme-style', get_stylesheet_uri() );\n</code></pre>\n\n<p>When you activate a child theme for a theme that does this, <code>get_stylesheet_uri()</code> becomes the <em>child theme's</em> stylesheet URL. This means that the parent theme will enqueue the <em>child theme's</em> stylesheet (with <code>notmytheme-style</code> as the ID), but <em>not</em> it's own stylesheet. </p>\n\n<p>That's where this would be coming from:</p>\n\n<pre><code><link rel='stylesheet' id='notmytheme-style-css' href='http://localhost/mywp/wp-content/themes/notmytheme-child/style.css?ver=1.0.9' type='text/css' media='all' />\n</code></pre>\n\n<p>It's the parent theme's ID with the child theme's URL.</p>\n\n<p>The issue with your code is that you're using the same handle (<code>notmytheme-style</code>) to enqueue the parent theme stylesheet as the parent theme is using the load the child theme's stylesheet. When you do this it will be ignored and enqueue the first version defined. This is why changing the priority affected the result. Whichever <code>notmytheme-style</code> is defined first is loaded.</p>\n\n<p>So the proper way to enqueue the CSS in this circumstance would be to not enqueue the child theme stylesheet, and enqueue the parent theme's stylesheet with a different handle and higher priority (lower number):</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles', 9 );\nfunction my_theme_enqueue_styles() {\n $parent_style = 'notmytheme-parent-style'; // New handle.\n\n wp_enqueue_style( $parent_style,\n get_template_directory_uri() . '/style.css',\n array(),\n '1.0.9' );\n}\n</code></pre>\n\n<p>This does mean that your child theme stylesheet will be using the version number of the parent theme. This could be avoided by instead dequeuing the parent theme's original style and re-enqueuing it:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles', 999 );\nfunction my_theme_enqueue_styles() {\n $parent_style = 'notmytheme-style';\n\n wp_dequeue_style( $parent_style );\n wp_enqueue_style( $parent_style,\n get_template_directory_uri() . '/style.css',\n array(),\n '1.0.9' );\n\n wp_enqueue_style( 'child-style',\n get_stylesheet_directory_uri() . '/style.css',\n array( $parent_style ),\n '18.08.07',\n 'all' );\n}\n</code></pre>\n"
},
{
"answer_id": 310705,
"author": "maverick",
"author_id": 132953,
"author_profile": "https://wordpress.stackexchange.com/users/132953",
"pm_score": 0,
"selected": false,
"text": "<p>try enqueuing styles ( take care of dependencies as well ) in the order of the parent theme </p>\n\n<p>Make sure your child theme have necessary files ( index.php, functions.php )\nand the above code goes inside functions.php file. Usually your code should work.</p>\n\n<p>Just some modifications, see if this works</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );\nfunction my_theme_enqueue_styles() {\n $parent_style = 'notmytheme-style';\n\n wp_enqueue_style( $parent_style,\n get_template_directory_uri() . '/style.css' );\n\n wp_enqueue_style( 'child-style',\n get_stylesheet_directory_uri() . '/style.css',\n array( $parent_style ) );\n}\n</code></pre>\n\n<p>make sure your index.php file have necessary headers</p>\n\n<pre><code>/*\n Theme Name: Child Theme Name\n Theme URI: \n Description: \n Author: \n Author URI: \n Template: notmytheme\n Version: 1.0.0\n License: GNU General Public License v2 or later\n License URI: http://www.gnu.org/licenses/gpl-2.0.html\n*/\n</code></pre>\n"
}
]
| 2018/08/07 | [
"https://wordpress.stackexchange.com/questions/310698",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/117364/"
]
| I have a **notmytheme**, the original css load order is like so:
```
<link rel='stylesheet' id='something' href='http://localhost/mywp/wp-content/themes/notmytheme/something.css' type='text/css' media='all' />
<link rel='stylesheet' id='notmytheme-style-css' href='http://localhost/mywp/wp-content/themes/notmytheme/style.css?ver=1.0.9' type='text/css' media='all' />
```
When I created a child theme called the **notmytheme-child**, and enqueue the child style, it became like this:
```
<link rel='stylesheet' id='notmytheme-style-css' href='http://localhost/mywp/wp-content/themes/notmytheme/style.css?ver=1.0.9' type='text/css' media='all' />
<link rel='stylesheet' id='child-style-css' href='http://localhost/mywp/wp-content/themes/notmytheme-child/style.css?ver=18.08.07' type='text/css' media='all' />
<link rel='stylesheet' id='something' href='http://localhost/mywp/wp-content/themes/notmytheme/something.css' type='text/css' media='all' />
```
I want the parent and child style to be loaded after other styles like how the parent theme did it, so I moved it down with priority ( `add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles', 999 );` ), now it became like this:
```
<link rel='stylesheet' id='something' href='http://localhost/mywp/wp-content/themes/notmytheme/something.css' type='text/css' media='all' />
<link rel='stylesheet' id='notmytheme-style-css' href='http://localhost/mywp/wp-content/themes/notmytheme-child/style.css?ver=1.0.9' type='text/css' media='all' />
<link rel='stylesheet' id='child-style-css' href='http://localhost/mywp/wp-content/themes/notmytheme-child/style.css?ver=18.08.07' type='text/css' media='all' />
```
I do not know why but now the `get_template_directory_uri()` now points to **notmytheme-child** instead of **notmytheme**.
My current enqueue script is like so:
```
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles', 999 );
function my_theme_enqueue_styles() {
$parent_style = 'notmytheme-style';
wp_enqueue_style( $parent_style,
get_template_directory_uri() . '/style.css',
array(),
'1.0.9' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
array( $parent_style ),
'18.08.07',
'all' );
}
```
Adjusting the priority changes the position of where the css are loaded, and also which directory `get_template_directory_uri()` points to.
**EDIT/SOLUTION**
My codes are now:
```
add_action( 'wp_enqueue_scripts', 'my_enqueue_child', 999 );
function my_enqueue_child() {
wp_dequeue_style( 'notmytheme-style' );
wp_enqueue_style( 'parent-style',
get_template_directory_uri() . '/style.css',
array(),
'1.0.9' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
array( 'parent-style' ),
'18.08.07',
'all' );
}
``` | It's very common for themes to enqueue their stylesheet like this:
```
wp_enqueue_style( 'notmytheme-style', get_stylesheet_uri() );
```
When you activate a child theme for a theme that does this, `get_stylesheet_uri()` becomes the *child theme's* stylesheet URL. This means that the parent theme will enqueue the *child theme's* stylesheet (with `notmytheme-style` as the ID), but *not* it's own stylesheet.
That's where this would be coming from:
```
<link rel='stylesheet' id='notmytheme-style-css' href='http://localhost/mywp/wp-content/themes/notmytheme-child/style.css?ver=1.0.9' type='text/css' media='all' />
```
It's the parent theme's ID with the child theme's URL.
The issue with your code is that you're using the same handle (`notmytheme-style`) to enqueue the parent theme stylesheet as the parent theme is using the load the child theme's stylesheet. When you do this it will be ignored and enqueue the first version defined. This is why changing the priority affected the result. Whichever `notmytheme-style` is defined first is loaded.
So the proper way to enqueue the CSS in this circumstance would be to not enqueue the child theme stylesheet, and enqueue the parent theme's stylesheet with a different handle and higher priority (lower number):
```
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles', 9 );
function my_theme_enqueue_styles() {
$parent_style = 'notmytheme-parent-style'; // New handle.
wp_enqueue_style( $parent_style,
get_template_directory_uri() . '/style.css',
array(),
'1.0.9' );
}
```
This does mean that your child theme stylesheet will be using the version number of the parent theme. This could be avoided by instead dequeuing the parent theme's original style and re-enqueuing it:
```
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles', 999 );
function my_theme_enqueue_styles() {
$parent_style = 'notmytheme-style';
wp_dequeue_style( $parent_style );
wp_enqueue_style( $parent_style,
get_template_directory_uri() . '/style.css',
array(),
'1.0.9' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
array( $parent_style ),
'18.08.07',
'all' );
}
``` |
310,761 | <p>I have the following setup in my <code>.htaccess</code> file, but I am still able to go to my site via <code>http:</code></p>
<pre><code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# Rewrite HTTP to HTTPS
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L]
</IfModule>
# END WordPress
</code></pre>
<p>Any idea what I could be doing wrong?</p>
| [
{
"answer_id": 310763,
"author": "MrWhite",
"author_id": 8259,
"author_profile": "https://wordpress.stackexchange.com/users/8259",
"pm_score": 3,
"selected": true,
"text": "<p>You've put the code in the wrong place. The HTTP to HTTPS directives must go <em>before</em> the WordPress front-controller, otherwise it's simply never going to get processed for anything other than direct file requests.</p>\n\n<p>Your custom directives should also be outside the <code># BEGIN WordPress</code> block, otherwise WordPress itself is likely to override your directives in a future update.</p>\n\n<p>For example:</p>\n\n<pre><code># Redirect HTTP to HTTPS\nRewriteCond %{HTTPS} !=on\nRewriteRule (.*) https://%{SERVER_NAME}/$1 [R,L]\n\n# BEGIN WordPress\n<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L] \n</IfModule>\n# END WordPress\n</code></pre>\n\n<p>It is a \"redirect\", not a \"rewrite\". Change the <code>R</code> to <code>R=301</code> when you are sure it's working OK (as this should ultimately be a <em>permanent</em> redirect).</p>\n"
},
{
"answer_id": 310764,
"author": "firxworx",
"author_id": 134244,
"author_profile": "https://wordpress.stackexchange.com/users/134244",
"pm_score": 1,
"selected": false,
"text": "<p>Are you familiar with the <code>[L]</code> flag for mod_rewrite? It \"causes mod_rewrite to stop processing the rule set. In most contexts, this means that if the rule matches, no further rules will be processed\". </p>\n\n<p>See: <a href=\"https://httpd.apache.org/docs/2.4/rewrite/flags.html#flag_l\" rel=\"nofollow noreferrer\">https://httpd.apache.org/docs/2.4/rewrite/flags.html#flag_l</a> </p>\n\n<p>Note that that your rewrite rules above the http->https rule employ this flag. These rules look like WordPress' rules that redirect requests that aren't for a specific file or directory to <code>index.php</code> for handling. </p>\n\n<p>One idea is changing the order so your rules appear after <code>Rewrite Engine On</code> so the http-vs-https check is performed first, the redirect can take place, and <em>then</em> on the following redirected request (which will now be https) the following set of rules related to WordPress functionality can apply. </p>\n\n<p>You could also try writing <code>RewriteCond {HTTPS} != on</code> as <code>RewriteCond %{HTTPS} off</code> and your <code>RewriteRule</code> line as <code>RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]</code> to be more explicit and send an http 301 (permanent) redirect status code back. </p>\n\n<p>EDIT: I just saw MrWhite's comment, we were writing at the same time. He also has good advice: put your revised rules outside of the #WORDPRESS comment block so future WordPress updates will not clobber them! </p>\n"
}
]
| 2018/08/07 | [
"https://wordpress.stackexchange.com/questions/310761",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145165/"
]
| I have the following setup in my `.htaccess` file, but I am still able to go to my site via `http:`
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# Rewrite HTTP to HTTPS
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L]
</IfModule>
# END WordPress
```
Any idea what I could be doing wrong? | You've put the code in the wrong place. The HTTP to HTTPS directives must go *before* the WordPress front-controller, otherwise it's simply never going to get processed for anything other than direct file requests.
Your custom directives should also be outside the `# BEGIN WordPress` block, otherwise WordPress itself is likely to override your directives in a future update.
For example:
```
# Redirect HTTP to HTTPS
RewriteCond %{HTTPS} !=on
RewriteRule (.*) https://%{SERVER_NAME}/$1 [R,L]
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
```
It is a "redirect", not a "rewrite". Change the `R` to `R=301` when you are sure it's working OK (as this should ultimately be a *permanent* redirect). |
310,774 | <p>I have a Custom Post Type all set up. I would like the slug to be the same as a page name, because all of these CPT's will be queried on that particular page (/team-members).</p>
<p>If I set the Custom Post Type slug to the page URL, that particular page doesn't load the page template anymore. It loads a broken post template.</p>
<p>My Custom Post Type rewrite:</p>
<pre><code>$rewrite = array(
'slug' => 'team-members',
'with_front' => false,
'pages' => false,
'feeds' => false,
);
</code></pre>
<p>This allows me to generate the <strong>proper URL</strong> of: <a href="http://www.example.org/team-members/bob-jones" rel="nofollow noreferrer">http://www.example.org/team-members/bob-jones</a></p>
<p>The problem now is when I try to access the page: <a href="http://www.example.org/team-members/" rel="nofollow noreferrer">http://www.example.org/team-members/</a>, it does not render the correct page template file (aptly titled <code>page-team-members.php</code>). Saving permalink settings didn't work.</p>
<p><strong>How can I create the URL slug of my Custom Post Type to not interfere with a page titled the exact same thing?</strong></p>
| [
{
"answer_id": 310802,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>What is appearing at <a href=\"http://www.example.org/team-members/\" rel=\"nofollow noreferrer\">http://www.example.org/team-members/</a> is the 'post type archive' for your post type. It's the automatically generated list of posts created by WordPress. If you don't want the post type to have an archive you can disable the archive by setting the <code>has_archive</code> argument to false:</p>\n\n<pre><code>register_post_type( 'post_type_name', array(\n 'has_archive' => false,\n) );\n</code></pre>\n\n<p>Now you can create a page at /team-members without a conflict.</p>\n"
},
{
"answer_id": 310837,
"author": "Peter HvD",
"author_id": 134918,
"author_profile": "https://wordpress.stackexchange.com/users/134918",
"pm_score": 1,
"selected": false,
"text": "<p>I've found over the years that the easiest way to avoid this sort of conflict is to separate the CPT posts from the page by adding in an additional step in the URL.</p>\n\n<p>For example, change <code>'slug' => 'team-members',</code> to <code>'slug' => 'team-members/member',</code> so your URL will become <code>http://www.example.org/team-members/member/bob-jones</code></p>\n\n<p>Sure, it's not ideal, and I'd rather the URL be cleaner, but sometimes you have to compromise for an easy life :-)</p>\n"
}
]
| 2018/08/07 | [
"https://wordpress.stackexchange.com/questions/310774",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122225/"
]
| I have a Custom Post Type all set up. I would like the slug to be the same as a page name, because all of these CPT's will be queried on that particular page (/team-members).
If I set the Custom Post Type slug to the page URL, that particular page doesn't load the page template anymore. It loads a broken post template.
My Custom Post Type rewrite:
```
$rewrite = array(
'slug' => 'team-members',
'with_front' => false,
'pages' => false,
'feeds' => false,
);
```
This allows me to generate the **proper URL** of: <http://www.example.org/team-members/bob-jones>
The problem now is when I try to access the page: <http://www.example.org/team-members/>, it does not render the correct page template file (aptly titled `page-team-members.php`). Saving permalink settings didn't work.
**How can I create the URL slug of my Custom Post Type to not interfere with a page titled the exact same thing?** | What is appearing at <http://www.example.org/team-members/> is the 'post type archive' for your post type. It's the automatically generated list of posts created by WordPress. If you don't want the post type to have an archive you can disable the archive by setting the `has_archive` argument to false:
```
register_post_type( 'post_type_name', array(
'has_archive' => false,
) );
```
Now you can create a page at /team-members without a conflict. |
310,865 | <p>I am creating a theme and i have added custom hooks to make the developement easier.
when using the code in functions it works in all pages. the code is below</p>
<pre><code>add_action('before_footer','post_prev_nex');
function post_prev_nex(){
the_post_navigation();
}
</code></pre>
<p>But when i try to put a conditional, it doesnt work.</p>
<pre><code>if (is_singular()) {
add_action('before_footer','post_prev_nex');
function post_prev_nex(){
the_post_navigation();
}
}
</code></pre>
<p>what is the problem here.
Thanks in advance</p>
| [
{
"answer_id": 310867,
"author": "nmr",
"author_id": 147428,
"author_profile": "https://wordpress.stackexchange.com/users/147428",
"pm_score": 3,
"selected": true,
"text": "<p>Put condition inside your function:</p>\n\n<pre><code>add_action('before_footer','post_prev_nex');\nfunction post_prev_nex() {\n if (is_singular())\n the_post_navigation();\n}\n</code></pre>\n\n<p>In your version <code>is_singular()</code> is executed when <code>functions.php</code> file is loaded, not while displaying the page.</p>\n"
},
{
"answer_id": 310868,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p><code>is_singular()</code> won't work when placed directly into functions.php or a plugin, because WordPress has not determined what content is actually being requested when it loads themes and plugins. You need to perform the check later by putting it inside an action callback that occurs after WordPress has determined what the content is.</p>\n\n<p>The simplest solution then is just to use the function inside the callback:</p>\n\n<pre><code>function post_prev_nex() {\n if ( is_singular() ) {\n the_post_navigation();\n }\n}\nadd_action('before_footer','post_prev_nex');\n</code></pre>\n"
}
]
| 2018/08/08 | [
"https://wordpress.stackexchange.com/questions/310865",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140102/"
]
| I am creating a theme and i have added custom hooks to make the developement easier.
when using the code in functions it works in all pages. the code is below
```
add_action('before_footer','post_prev_nex');
function post_prev_nex(){
the_post_navigation();
}
```
But when i try to put a conditional, it doesnt work.
```
if (is_singular()) {
add_action('before_footer','post_prev_nex');
function post_prev_nex(){
the_post_navigation();
}
}
```
what is the problem here.
Thanks in advance | Put condition inside your function:
```
add_action('before_footer','post_prev_nex');
function post_prev_nex() {
if (is_singular())
the_post_navigation();
}
```
In your version `is_singular()` is executed when `functions.php` file is loaded, not while displaying the page. |
310,866 | <p>I am using contact for 7 to create form. Currently I am auto completing value under text name field from Custom post type title, see below:</p>
<pre><code>$post_ids = new WP_Query(array(
'post_type' => 'Buyers', // replace with CPT name
'fields' => 'fname' // replace with custom field name
));
$name = array();
// go through each of the retrieved ids and get the title
if ($post_ids->have_posts()):
foreach( $post_ids->posts as $id):
// get the post title, and apply any filters which plugins may have added
// (get_the_title returns unfiltered value)
$name[] = apply_filters('the_title', get_the_title($id));
endforeach;
endif;
<script>
$( "#autocomplete" ).autocomplete({
source: <?php echo json_encode($name); ?>
});
</script>
</code></pre>
<p>Now I want to auto fill other form fields(i.e last name, address, contact info etc. ) with custom field values from post, based on above selected post title. How can we achieve this? </p>
<p>I want something below:</p>
<pre><code><label> Your Name </label>
<input type="text" id="name" name="name" />
<input readonly="readonly" type="text" id="iprice" name="iprice" size="5">
<input readonly="readonly" type="text" id="icode" name="icode" size="3">
[submit "Send"]
$(function() {
$('#iprice').val("");
$('#icode').val("");
$("#name").autocomplete({
source: [{"label":"Air Soft Gun","price":"212","abbrev":"BMW"},
{"label":"Pepsi Cola Hat","price":"24","abbrev":"CRY"},
{"label":"Candle Lights Dinner","price":"780","abbrev":"NSS"},
{"label":"Pork Meat Ball","price":"178","abbrev":"SZK"},
{"label":"Granny Health Supplement","price":"24","abbrev":"TYT"}],
minLength: 2,
select: function(event, ui) {
$('#iprice').val(ui.item.price);
$('#icode').val(ui.item.abbrev);
}
});
$["ui"]["autocomplete"].prototype["_renderItem"] = function( ul, item) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( $( "<a></a>" ).html( item.label ) )
.appendTo( ul );
};
});
</code></pre>
<p>Label will be my post title and based on selected post tiltle, display custom fields value under price and icode.</p>
<p>Any help would be appreciated. Thank you in advance.</p>
| [
{
"answer_id": 310867,
"author": "nmr",
"author_id": 147428,
"author_profile": "https://wordpress.stackexchange.com/users/147428",
"pm_score": 3,
"selected": true,
"text": "<p>Put condition inside your function:</p>\n\n<pre><code>add_action('before_footer','post_prev_nex');\nfunction post_prev_nex() {\n if (is_singular())\n the_post_navigation();\n}\n</code></pre>\n\n<p>In your version <code>is_singular()</code> is executed when <code>functions.php</code> file is loaded, not while displaying the page.</p>\n"
},
{
"answer_id": 310868,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p><code>is_singular()</code> won't work when placed directly into functions.php or a plugin, because WordPress has not determined what content is actually being requested when it loads themes and plugins. You need to perform the check later by putting it inside an action callback that occurs after WordPress has determined what the content is.</p>\n\n<p>The simplest solution then is just to use the function inside the callback:</p>\n\n<pre><code>function post_prev_nex() {\n if ( is_singular() ) {\n the_post_navigation();\n }\n}\nadd_action('before_footer','post_prev_nex');\n</code></pre>\n"
}
]
| 2018/08/08 | [
"https://wordpress.stackexchange.com/questions/310866",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123547/"
]
| I am using contact for 7 to create form. Currently I am auto completing value under text name field from Custom post type title, see below:
```
$post_ids = new WP_Query(array(
'post_type' => 'Buyers', // replace with CPT name
'fields' => 'fname' // replace with custom field name
));
$name = array();
// go through each of the retrieved ids and get the title
if ($post_ids->have_posts()):
foreach( $post_ids->posts as $id):
// get the post title, and apply any filters which plugins may have added
// (get_the_title returns unfiltered value)
$name[] = apply_filters('the_title', get_the_title($id));
endforeach;
endif;
<script>
$( "#autocomplete" ).autocomplete({
source: <?php echo json_encode($name); ?>
});
</script>
```
Now I want to auto fill other form fields(i.e last name, address, contact info etc. ) with custom field values from post, based on above selected post title. How can we achieve this?
I want something below:
```
<label> Your Name </label>
<input type="text" id="name" name="name" />
<input readonly="readonly" type="text" id="iprice" name="iprice" size="5">
<input readonly="readonly" type="text" id="icode" name="icode" size="3">
[submit "Send"]
$(function() {
$('#iprice').val("");
$('#icode').val("");
$("#name").autocomplete({
source: [{"label":"Air Soft Gun","price":"212","abbrev":"BMW"},
{"label":"Pepsi Cola Hat","price":"24","abbrev":"CRY"},
{"label":"Candle Lights Dinner","price":"780","abbrev":"NSS"},
{"label":"Pork Meat Ball","price":"178","abbrev":"SZK"},
{"label":"Granny Health Supplement","price":"24","abbrev":"TYT"}],
minLength: 2,
select: function(event, ui) {
$('#iprice').val(ui.item.price);
$('#icode').val(ui.item.abbrev);
}
});
$["ui"]["autocomplete"].prototype["_renderItem"] = function( ul, item) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( $( "<a></a>" ).html( item.label ) )
.appendTo( ul );
};
});
```
Label will be my post title and based on selected post tiltle, display custom fields value under price and icode.
Any help would be appreciated. Thank you in advance. | Put condition inside your function:
```
add_action('before_footer','post_prev_nex');
function post_prev_nex() {
if (is_singular())
the_post_navigation();
}
```
In your version `is_singular()` is executed when `functions.php` file is loaded, not while displaying the page. |
310,874 | <p>I have created a post taxonomy in functions.php called 'leadership' and then tagged posts with three different labels. I have a team page on which I want to place three links (each slugged to a label in the taxonomy).</p>
<ul>
<li>Corporate</li>
<li>Sales</li>
<li>Support</li>
</ul>
<p>So that when the above word is clicked, the featured image for each post with that label becomes visible on the page.</p>
<p>So there's three basic elements (I think):</p>
<ol>
<li>Calling all the post data for the specified taxonomic label</li>
<li>Generating a link that calls the featured images for those posts</li>
<li>Having the content appear/disappear based on which link is clicked</li>
</ol>
<p><em>While I've done #2 and #3 individually before, my head is swimming trying to figure out how to merge all the elements together.</em></p>
<p>Can someone give me some pointers, beyond the codex which I've read thru already? And maybe even some sample code - especially for #1 and #2?</p>
<p><strong>And the dream...</strong> I'd love to implement it as two shortcodes - one for the link and one for the display - so that I can reuse it in other areas of the website.</p>
| [
{
"answer_id": 310896,
"author": "Andrea Somovigo",
"author_id": 64435,
"author_profile": "https://wordpress.stackexchange.com/users/64435",
"pm_score": 3,
"selected": true,
"text": "<p>Something quite rough that needs improvement but can give you a starting point, if I've understood your needs: use <code>[dr]</code> as shortcode marker where you want </p>\n\n<pre><code>function my_dream_shortcode($atts, $content = null) {\n ob_start(); ?>\n <ul>\n <li class=\"button\" onClick=\"get_data('corporate')\">Corporate</li>\n <li class=\"button\" onClick=\"get_data('sales')\">Sales</li>\n <li class=\"button\" onClick=\"get_data('support')\">Support</li>\n </ul>\n<div class=\"my_plugin_result\"></div>\n<style>\n li.button{\n list-style:none;\n padding:4px 10px; \n background-color:cadetblue;\n margin:10px;\n float:left;\n min-width: 160px;\n text-align: center;\n cursor:pointer;\n }\n .my_plugin_result figure{\n float:left;\n padding:4px;\n background:#ccc;\n}\n</style>\n<script>\n var myPluginAjaxUrl = '<?php echo admin_url( 'admin-ajax.php'); ?>';\n function get_data(term) {\n jQuery.ajax({\n url: myPluginAjaxUrl,\n data: {\n action: 'get_data_for_my_shortcode',\n term: term\n }\n }).done(function (response) {\n console.log(response)\n jQuery(\".my_plugin_result\").html(response);\n });\n }\n</script>\n\n<?php\n return ob_get_clean();\n}\nadd_shortcode(\"dr\", \"my_dream_shortcode\");\n\nadd_action('wp_ajax_nopriv_get_data_for_my_shortcode', 'get_data_for_my_shortcode');\n//add_action('wp_ajax_get_data_for_my_shortcode', 'get_data_for_my_shortcode');\nfunction get_data_for_my_shortcode(){\n global $wpdb;\n $args = array(\n 'post_type' => 'post',\n 'tax_query' => array(\n array(\n 'taxonomy' => 'leadership',\n 'field' => 'slug',\n 'terms' => $_REQUEST['term']\n )\n )\n );\n $response=\"\";\n $query = new WP_Query( $args );\n\n while($query->have_posts() ):\n if($query->have_posts() ):\n $query->the_post();\n $response.='<figure><img src=\"'.get_the_post_thumbnail_url(get_the_ID(),'medium').'\"/></figure>';\n endif;\n endwhile;\n echo $response;\n die();\n}\n</code></pre>\n\n<p>Thanks to <a href=\"https://wordpress.stackexchange.com/users/35991/bulldog\">@bulldog</a> edited code to work effectively in front-end</p>\n"
},
{
"answer_id": 314733,
"author": "bulldog",
"author_id": 35991,
"author_profile": "https://wordpress.stackexchange.com/users/35991",
"pm_score": 0,
"selected": false,
"text": "<p>For future readers, <strong>the above code will display when logged in</strong>, but not for users logged out.</p>\n\n<p><strong>If you want site visitors to see output</strong>, then you need to add:</p>\n\n<pre><code>add_action('wp_ajax_nopriv_get_data_for_my_shortcode', 'get_data_for_my_shortcode');\n</code></pre>\n\n<p>It took me a while to troubleshoot this issue. <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">Thank you WP Codex.</a></p>\n"
}
]
| 2018/08/08 | [
"https://wordpress.stackexchange.com/questions/310874",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/35991/"
]
| I have created a post taxonomy in functions.php called 'leadership' and then tagged posts with three different labels. I have a team page on which I want to place three links (each slugged to a label in the taxonomy).
* Corporate
* Sales
* Support
So that when the above word is clicked, the featured image for each post with that label becomes visible on the page.
So there's three basic elements (I think):
1. Calling all the post data for the specified taxonomic label
2. Generating a link that calls the featured images for those posts
3. Having the content appear/disappear based on which link is clicked
*While I've done #2 and #3 individually before, my head is swimming trying to figure out how to merge all the elements together.*
Can someone give me some pointers, beyond the codex which I've read thru already? And maybe even some sample code - especially for #1 and #2?
**And the dream...** I'd love to implement it as two shortcodes - one for the link and one for the display - so that I can reuse it in other areas of the website. | Something quite rough that needs improvement but can give you a starting point, if I've understood your needs: use `[dr]` as shortcode marker where you want
```
function my_dream_shortcode($atts, $content = null) {
ob_start(); ?>
<ul>
<li class="button" onClick="get_data('corporate')">Corporate</li>
<li class="button" onClick="get_data('sales')">Sales</li>
<li class="button" onClick="get_data('support')">Support</li>
</ul>
<div class="my_plugin_result"></div>
<style>
li.button{
list-style:none;
padding:4px 10px;
background-color:cadetblue;
margin:10px;
float:left;
min-width: 160px;
text-align: center;
cursor:pointer;
}
.my_plugin_result figure{
float:left;
padding:4px;
background:#ccc;
}
</style>
<script>
var myPluginAjaxUrl = '<?php echo admin_url( 'admin-ajax.php'); ?>';
function get_data(term) {
jQuery.ajax({
url: myPluginAjaxUrl,
data: {
action: 'get_data_for_my_shortcode',
term: term
}
}).done(function (response) {
console.log(response)
jQuery(".my_plugin_result").html(response);
});
}
</script>
<?php
return ob_get_clean();
}
add_shortcode("dr", "my_dream_shortcode");
add_action('wp_ajax_nopriv_get_data_for_my_shortcode', 'get_data_for_my_shortcode');
//add_action('wp_ajax_get_data_for_my_shortcode', 'get_data_for_my_shortcode');
function get_data_for_my_shortcode(){
global $wpdb;
$args = array(
'post_type' => 'post',
'tax_query' => array(
array(
'taxonomy' => 'leadership',
'field' => 'slug',
'terms' => $_REQUEST['term']
)
)
);
$response="";
$query = new WP_Query( $args );
while($query->have_posts() ):
if($query->have_posts() ):
$query->the_post();
$response.='<figure><img src="'.get_the_post_thumbnail_url(get_the_ID(),'medium').'"/></figure>';
endif;
endwhile;
echo $response;
die();
}
```
Thanks to [@bulldog](https://wordpress.stackexchange.com/users/35991/bulldog) edited code to work effectively in front-end |
310,881 | <p>I have a Custom Post Type called <code>books</code>. This Custom Post Type has a taxonomy called <code>book_category</code>. As of now, and in the foreseeable future, there are 5 categories each book can be filtered under.</p>
<p>Now, each of these categories have their own respective page that will query the books based on respective category (among other ancillary information pertaining to each category).</p>
<p>In my code below, I made an attempt to query posts based on <code>is_page()</code>. While this DOES work... something is telling me there's a more efficient / proper way of handling this.</p>
<pre><code><?php
if (is_page('horror')) {
$theTermBasedOnPage = 'horror';
} elseif (is_page('comedy')) {
$theTermBasedOnPage = 'comedy';
} elseif (is_page('romantic')) {
$theTermBasedOnPage = 'romantic';
} elseif (is_page('nonfiction')) {
$theTermBasedOnPage = 'nonfiction';
} elseif (is_page('drama')) {
$theTermBasedOnPage = 'drama';
}
$args = array(
'posts_per_page' => -1,
'post_type' => 'books',
'post_status' => 'publish',
'tax_query' => array(
array(
'taxonomy' => 'book_category',
'terms' => $theTermBasedOnPage,
),
),
);
?>
</code></pre>
<p><strong>What is the best way to query posts (Custom Post Type > Taxonomy) based on page?</strong></p>
| [
{
"answer_id": 310882,
"author": "David Sword",
"author_id": 132362,
"author_profile": "https://wordpress.stackexchange.com/users/132362",
"pm_score": 3,
"selected": true,
"text": "<p>To make that more efficient, instead of arguing the current page slug, you just place the current slug as the tax_query's terms value. Something like:</p>\n\n<pre><code>global $post;\n$args = array(\n 'posts_per_page' => -1,\n 'post_type' => 'books',\n 'post_status' => 'publish',\n 'tax_query' => array(\n array(\n 'taxonomy' => 'book_category',\n 'field' => 'slug',\n 'terms' => $post->post_name, // which'd be `horror` or `comedy`, etc\n ),\n ),\n);\n</code></pre>\n\n<p>Note that there's high probability of human error doing things this way: for example having a page of <code>nonfiction</code> but a book_category term of <code>non-fiction</code> could break the logic and cause problems.</p>\n\n<p>I don't know the context of what you're working on, but if the goal is just <em>\"each of these categories have their own respective page\"</em> you do not need to build this custom-query-with-manual-page-relation for each term. WordPress taxonomies and terms will have their own URLs if you've <a href=\"https://codex.wordpress.org/Function_Reference/register_taxonomy\" rel=\"nofollow noreferrer\">registered</a> the taxonomy as <code>public</code> and <code>publicly_queryable</code>. (Guessing here, but) You can probably visit <code>your-site.com/book_category/horror/</code> and see the list of horror books. You can then customize the template files for all terms or individually using the <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">WordPress template hierarchy</a> as reference. </p>\n"
},
{
"answer_id": 310884,
"author": "Scott",
"author_id": 111485,
"author_profile": "https://wordpress.stackexchange.com/users/111485",
"pm_score": 2,
"selected": false,
"text": "<h2>Custom Taxonomy Pages:</h2>\n\n<p>You shouldn't have to create custom query with <code>$args</code> for getting the custom taxonomy pages. You can simply follow WordPress provided URL structure for that.</p>\n\n<p>For example, let's say:</p>\n\n<ol>\n<li><p>You've selected the following Permalink Structure:\n<a href=\"https://i.stack.imgur.com/fwsEN.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/fwsEN.png\" alt=\"enter image description here\"></a></p></li>\n<li><p>Then you've created a custom post type <code>Book</code></p></li>\n<li><p>Created custom taxonomy <code>Book Category</code> and linked with <code>Book</code>.</p></li>\n<li><p>Then created a new <code>Book</code> titled <code>My Horror Story</code> under <code>Horror</code> as <code>Book Category</code>.</p></li>\n<li><p>And, created another new <code>Book</code> titled <code>My Comedy Story</code> under <code>Comedy</code> as <code>Book Category</code>.</p></li>\n</ol>\n\n<p>With all the other default settings, WordPress will automatically generate the following URL(s) for you:</p>\n\n<pre><code>// Book Links\nhttps://example.com/book/my-comedy-story/\nhttps://example.com/book/my-horror-story/\n\n// Book Category Links\nhttps://example.com/book-category/comedy/\nhttps://example.com/book-category/horror/\n</code></pre>\n\n<p>Use these URL(s) for your desired custom taxonomy pages.</p>\n\n<h2>Template</h2>\n\n<p>Also, you may edit the theme template files to create the desired design.\nCheck out <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">WordPress Template Hierarchy</a> to learn how to do that.</p>\n\n<p>For example, you may create a template file named <code>taxonomy-book-category.php</code> to design <code>Book Category</code> custom taxonomy pages.</p>\n\n<p>In that template file, use WordPress <a href=\"https://developer.wordpress.org/themes/basics/template-tags/\" rel=\"nofollow noreferrer\">Template Tags</a> and <a href=\"https://developer.wordpress.org/themes/basics/the-loop/\" rel=\"nofollow noreferrer\">The Loop</a> for necessary queries.</p>\n\n<p>For example, a very simple template file can be like:</p>\n\n<pre><code><?php\n if ( have_posts() ) : while ( have_posts() ) : the_post();\n the_content();\n endwhile;\n else :\n _e( 'Sorry, no book matched your criteria.', 'textdomain' );\n endif;\n?>\n</code></pre>\n"
},
{
"answer_id": 310885,
"author": "wpdev",
"author_id": 133897,
"author_profile": "https://wordpress.stackexchange.com/users/133897",
"pm_score": 0,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code><?php\n// Get post's all terms.\n$terms = wp_get_post_terms( get_the_ID(), 'book_category' );\n\n// Get first term ID\n$currentPostTermID = $terms[ 0 ]->term_id;\n\n$args = array(\n 'posts_per_page' => -1,\n 'post_type' => 'books',\n 'post_status' => 'publish',\n 'tax_query' => array(\n array(\n 'taxonomy' => 'book_category',\n\n 'terms' => $currentPostTermID,\n ),\n ),\n);\n?>\n</code></pre>\n"
}
]
| 2018/08/08 | [
"https://wordpress.stackexchange.com/questions/310881",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122225/"
]
| I have a Custom Post Type called `books`. This Custom Post Type has a taxonomy called `book_category`. As of now, and in the foreseeable future, there are 5 categories each book can be filtered under.
Now, each of these categories have their own respective page that will query the books based on respective category (among other ancillary information pertaining to each category).
In my code below, I made an attempt to query posts based on `is_page()`. While this DOES work... something is telling me there's a more efficient / proper way of handling this.
```
<?php
if (is_page('horror')) {
$theTermBasedOnPage = 'horror';
} elseif (is_page('comedy')) {
$theTermBasedOnPage = 'comedy';
} elseif (is_page('romantic')) {
$theTermBasedOnPage = 'romantic';
} elseif (is_page('nonfiction')) {
$theTermBasedOnPage = 'nonfiction';
} elseif (is_page('drama')) {
$theTermBasedOnPage = 'drama';
}
$args = array(
'posts_per_page' => -1,
'post_type' => 'books',
'post_status' => 'publish',
'tax_query' => array(
array(
'taxonomy' => 'book_category',
'terms' => $theTermBasedOnPage,
),
),
);
?>
```
**What is the best way to query posts (Custom Post Type > Taxonomy) based on page?** | To make that more efficient, instead of arguing the current page slug, you just place the current slug as the tax\_query's terms value. Something like:
```
global $post;
$args = array(
'posts_per_page' => -1,
'post_type' => 'books',
'post_status' => 'publish',
'tax_query' => array(
array(
'taxonomy' => 'book_category',
'field' => 'slug',
'terms' => $post->post_name, // which'd be `horror` or `comedy`, etc
),
),
);
```
Note that there's high probability of human error doing things this way: for example having a page of `nonfiction` but a book\_category term of `non-fiction` could break the logic and cause problems.
I don't know the context of what you're working on, but if the goal is just *"each of these categories have their own respective page"* you do not need to build this custom-query-with-manual-page-relation for each term. WordPress taxonomies and terms will have their own URLs if you've [registered](https://codex.wordpress.org/Function_Reference/register_taxonomy) the taxonomy as `public` and `publicly_queryable`. (Guessing here, but) You can probably visit `your-site.com/book_category/horror/` and see the list of horror books. You can then customize the template files for all terms or individually using the [WordPress template hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/) as reference. |
310,886 | <p>I'm creating a shipping method where the customer can choose a time for the delivery to happen. This choice can be made on product page, cart and checkout. When chosen, it updates a session value with ajax. </p>
<p>The problem however is that I need to re-calculate shipping on cart and checkout if the time is changed, but woocommerce is not calculating shipping unless items are added or removed from the cart.</p>
<p>It wont even recalculate if i refresh the page, I have to manually change the content of the cart for it to fire.</p>
<p>Any suggestions?</p>
| [
{
"answer_id": 332944,
"author": "user164084",
"author_id": 164084,
"author_profile": "https://wordpress.stackexchange.com/users/164084",
"pm_score": 2,
"selected": false,
"text": "<p>I also have the same issue when I created a shipping method and what I did is on my function for the ajax call I add something just to have an update on the cart:</p>\n\n<pre><code>global $woocommerce;\n$packages = $woocommerce->cart->get_shipping_packages();\nforeach( $packages as $package_key => $package ) {\n $session_key = 'shipping_for_package_'.$package_key;\n $stored_rates = WC()->session->__unset( $session_key );\n}\n</code></pre>\n"
},
{
"answer_id": 333859,
"author": "djboris",
"author_id": 152412,
"author_profile": "https://wordpress.stackexchange.com/users/152412",
"pm_score": 1,
"selected": false,
"text": "<p>Please try adding this where needed:</p>\n\n<pre><code>WC()->cart->calculate_shipping();\nWC()->cart->calculate_totals();\n</code></pre>\n\n<p>This is how WooCommerce handles it in its own Ajax calls.</p>\n\n<p>I found this in <code>WC_Ajax::update_order_review()</code> (<a href=\"https://github.com/woocommerce/woocommerce/blob/068a2d931dee33ef23556681573a95ff55f8a43b/includes/class-wc-ajax.php#L354-L355\" rel=\"nofollow noreferrer\">class-wc-ajax.php:354</a>).</p>\n"
}
]
| 2018/08/08 | [
"https://wordpress.stackexchange.com/questions/310886",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90442/"
]
| I'm creating a shipping method where the customer can choose a time for the delivery to happen. This choice can be made on product page, cart and checkout. When chosen, it updates a session value with ajax.
The problem however is that I need to re-calculate shipping on cart and checkout if the time is changed, but woocommerce is not calculating shipping unless items are added or removed from the cart.
It wont even recalculate if i refresh the page, I have to manually change the content of the cart for it to fire.
Any suggestions? | I also have the same issue when I created a shipping method and what I did is on my function for the ajax call I add something just to have an update on the cart:
```
global $woocommerce;
$packages = $woocommerce->cart->get_shipping_packages();
foreach( $packages as $package_key => $package ) {
$session_key = 'shipping_for_package_'.$package_key;
$stored_rates = WC()->session->__unset( $session_key );
}
``` |
310,894 | <p>If you create a post whose title has an accent in it and some other unicode character in it, eg <code>à 漢語 title thing</code>, its slug (permalink) will become <code>a-漢語-title-thing</code>... ie, the <code>à</code> was converted into a regular <code>a</code>, but those unicode Chinese characters were left intact.
Why doesn't WordPress leave the accented characters alone?
I created a code snippet to tell WordPress to leave them alone</p>
<pre><code>function mn_sanitize_title($modified_title, $original_title, $context)
{
// the $modified_title may have had accents removed, but not the $original_title
return $original_title;
}
// set this filter to run BEFORE WP already ran the title through `sanitize_title_with_dashes`
add_filter('sanitize_title', 'mn_sanitize_title', 5, 3);
</code></pre>
<p>and it seems to work fine (accented characters are left intact in post slugs) so I'm wondering why WordPress developers removed accented characters from post slugs in the first place?</p>
| [
{
"answer_id": 332944,
"author": "user164084",
"author_id": 164084,
"author_profile": "https://wordpress.stackexchange.com/users/164084",
"pm_score": 2,
"selected": false,
"text": "<p>I also have the same issue when I created a shipping method and what I did is on my function for the ajax call I add something just to have an update on the cart:</p>\n\n<pre><code>global $woocommerce;\n$packages = $woocommerce->cart->get_shipping_packages();\nforeach( $packages as $package_key => $package ) {\n $session_key = 'shipping_for_package_'.$package_key;\n $stored_rates = WC()->session->__unset( $session_key );\n}\n</code></pre>\n"
},
{
"answer_id": 333859,
"author": "djboris",
"author_id": 152412,
"author_profile": "https://wordpress.stackexchange.com/users/152412",
"pm_score": 1,
"selected": false,
"text": "<p>Please try adding this where needed:</p>\n\n<pre><code>WC()->cart->calculate_shipping();\nWC()->cart->calculate_totals();\n</code></pre>\n\n<p>This is how WooCommerce handles it in its own Ajax calls.</p>\n\n<p>I found this in <code>WC_Ajax::update_order_review()</code> (<a href=\"https://github.com/woocommerce/woocommerce/blob/068a2d931dee33ef23556681573a95ff55f8a43b/includes/class-wc-ajax.php#L354-L355\" rel=\"nofollow noreferrer\">class-wc-ajax.php:354</a>).</p>\n"
}
]
| 2018/08/08 | [
"https://wordpress.stackexchange.com/questions/310894",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/52760/"
]
| If you create a post whose title has an accent in it and some other unicode character in it, eg `à 漢語 title thing`, its slug (permalink) will become `a-漢語-title-thing`... ie, the `à` was converted into a regular `a`, but those unicode Chinese characters were left intact.
Why doesn't WordPress leave the accented characters alone?
I created a code snippet to tell WordPress to leave them alone
```
function mn_sanitize_title($modified_title, $original_title, $context)
{
// the $modified_title may have had accents removed, but not the $original_title
return $original_title;
}
// set this filter to run BEFORE WP already ran the title through `sanitize_title_with_dashes`
add_filter('sanitize_title', 'mn_sanitize_title', 5, 3);
```
and it seems to work fine (accented characters are left intact in post slugs) so I'm wondering why WordPress developers removed accented characters from post slugs in the first place? | I also have the same issue when I created a shipping method and what I did is on my function for the ajax call I add something just to have an update on the cart:
```
global $woocommerce;
$packages = $woocommerce->cart->get_shipping_packages();
foreach( $packages as $package_key => $package ) {
$session_key = 'shipping_for_package_'.$package_key;
$stored_rates = WC()->session->__unset( $session_key );
}
``` |
310,943 | <p>I'm looking for a way to open every/any link to a blog post in a lightbox/modal globally and without having to any extra classes or rel attribute to the link element. I know I can access this info from within the page or post itself, but is there a way, through some sort of AJAX call I presume, to get this data before the request for the content is actually made so that when I do retrieve the response content, I can either just display it normally in the same browser tab (in the case of a Page) or trigger a lightbox and populate it with the content instead.</p>
<p>At first I was thinking about using regular expression matching on the link element's href and if it matched something looking like a blog post URL, open the lightbox. that seems pretty hacky tho and is definitely not bulletproof.</p>
<p>This is what I've got so far...</p>
<p><strong>JavaScript:</strong></p>
<pre><code>$('a:not([href^="#"])[href]').click(function(e) {
e.preventDefault();
var $this = $(this);
var lnk = $this.attr('href');
var jqxhr = $.post("/wp-content/themes/mist-child/php/get-post-type.php", {url: lnk});
jqxhr.done(function(data) {
if(data === 'post') {
$.prettyPhoto.open(lnk + '?iframe=true&width=80%&height=80%');
}
});
});
</code></pre>
<p><br><br>
<strong>get-post-type.php</strong> (/wp-content/themes/CHILD_THEME/php/...)</p>
<pre><code><?php
require_once(rtrim($_SERVER['DOCUMENT_ROOT'], '/') . '/wp-load.php');
$url = $_POST['url'];
$postid = url_to_postid($url);
echo(get_post_type($postid));
?>
</code></pre>
<p>The part where Posts get opened in the lightbox is working. It's a little slow - I'm guessing that loading wp-load.php adds quite a bit of overhead. is there any way to add my PHP somewhere in functions.php and call that function (with arguments) via AJAX?</p>
<p>I know it needs some work, but as far as a prototype goes, am I moving in the right direction? Please feel free to shoot this full of as many holes as you can find.</p>
| [
{
"answer_id": 311001,
"author": "Balas",
"author_id": 17849,
"author_profile": "https://wordpress.stackexchange.com/users/17849",
"pm_score": 1,
"selected": false,
"text": "<p>The wordpress way solution is</p>\n\n<pre><code> // put this in header.php\nvar ajax_url =\"<?php echo admin_url('admin-ajax.php');?>\"\n\n// in js file\n$('a:not([href^=\"#\"])[href]').click(function(e) {\n e.preventDefault();\n var $this = $(this);\n var lnk = $this.attr('href');\n\n var jqxhr = $.post(ajax_url, {'action':'list_content', url: lnk});\n jqxhr.done(function(data) {\n if(data === 'post') {\n $.prettyPhoto.open(lnk + '?iframe=true&width=80%&height=80%');\n }\n });\n});\n\n// functions.php\nadd_action('wp_ajax_nopriv_list_content', 'list_content');\nadd_action('wp_ajax_list_content', 'list_content');\n\nfunction list_content() {\n\n $url = $_POST['url'];\n\n $postid = url_to_postid($url);\n echo(get_post_type($postid));\n die();\n}\n</code></pre>\n"
},
{
"answer_id": 311278,
"author": "Daveh0",
"author_id": 118789,
"author_profile": "https://wordpress.stackexchange.com/users/118789",
"pm_score": 1,
"selected": true,
"text": "<p>Going with @milo's suggestion in the comments of the OP, I added a function to functions.php that rewrites URLs output by the API with a specific query string key/value when the <code>post_type</code> is <code>post</code>. This allows me to see this on the front end quite easily and take the appropriate action on the link depending on the absence/presence of said query string data. In this case, the frontend script finds all the elements \"marked\" as linking to <code>post</code>s (and not <code>page</code>s) and simply opens their <code>href</code> in a lightbox. <strong>SO</strong> much simpler than making several AJAX calls when the page is rendered to check the <code>post_type</code> for various links on the page. </p>\n\n<p><br/>\n<strong>functions.php</strong></p>\n\n<pre><code>function append_query_string( $url, $post, $leavename=false ) {\n if ( $post->post_type == 'post' ) {\n $url = add_query_arg( 'blogLnk', '1', $url );\n }\n return $url;\n}\nadd_filter( 'post_link', 'append_query_string', 10, 3 );\n</code></pre>\n\n<p><br />\n<strong>JavaScript</strong></p>\n\n<pre><code>var blogLnks = [\n 'a[hrf*=\"blogLnk=1\"]',\n 'a[rel=\"blogLnk\"]'\n];\nvar $blogLnks = $(blogLnks.join(','));\n$blogLnks.click(function(e) {\n e.preventDefault();\n console.log('click - open me in lightbox');\n var $this = $(this);\n var qs = '?iframe=true&width=80%&height=90%';\n var lnk = $this.attr('href');\n\n $.prettyPhoto.open(lnk + qs);\n});\n</code></pre>\n"
}
]
| 2018/08/09 | [
"https://wordpress.stackexchange.com/questions/310943",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118789/"
]
| I'm looking for a way to open every/any link to a blog post in a lightbox/modal globally and without having to any extra classes or rel attribute to the link element. I know I can access this info from within the page or post itself, but is there a way, through some sort of AJAX call I presume, to get this data before the request for the content is actually made so that when I do retrieve the response content, I can either just display it normally in the same browser tab (in the case of a Page) or trigger a lightbox and populate it with the content instead.
At first I was thinking about using regular expression matching on the link element's href and if it matched something looking like a blog post URL, open the lightbox. that seems pretty hacky tho and is definitely not bulletproof.
This is what I've got so far...
**JavaScript:**
```
$('a:not([href^="#"])[href]').click(function(e) {
e.preventDefault();
var $this = $(this);
var lnk = $this.attr('href');
var jqxhr = $.post("/wp-content/themes/mist-child/php/get-post-type.php", {url: lnk});
jqxhr.done(function(data) {
if(data === 'post') {
$.prettyPhoto.open(lnk + '?iframe=true&width=80%&height=80%');
}
});
});
```
**get-post-type.php** (/wp-content/themes/CHILD\_THEME/php/...)
```
<?php
require_once(rtrim($_SERVER['DOCUMENT_ROOT'], '/') . '/wp-load.php');
$url = $_POST['url'];
$postid = url_to_postid($url);
echo(get_post_type($postid));
?>
```
The part where Posts get opened in the lightbox is working. It's a little slow - I'm guessing that loading wp-load.php adds quite a bit of overhead. is there any way to add my PHP somewhere in functions.php and call that function (with arguments) via AJAX?
I know it needs some work, but as far as a prototype goes, am I moving in the right direction? Please feel free to shoot this full of as many holes as you can find. | Going with @milo's suggestion in the comments of the OP, I added a function to functions.php that rewrites URLs output by the API with a specific query string key/value when the `post_type` is `post`. This allows me to see this on the front end quite easily and take the appropriate action on the link depending on the absence/presence of said query string data. In this case, the frontend script finds all the elements "marked" as linking to `post`s (and not `page`s) and simply opens their `href` in a lightbox. **SO** much simpler than making several AJAX calls when the page is rendered to check the `post_type` for various links on the page.
**functions.php**
```
function append_query_string( $url, $post, $leavename=false ) {
if ( $post->post_type == 'post' ) {
$url = add_query_arg( 'blogLnk', '1', $url );
}
return $url;
}
add_filter( 'post_link', 'append_query_string', 10, 3 );
```
**JavaScript**
```
var blogLnks = [
'a[hrf*="blogLnk=1"]',
'a[rel="blogLnk"]'
];
var $blogLnks = $(blogLnks.join(','));
$blogLnks.click(function(e) {
e.preventDefault();
console.log('click - open me in lightbox');
var $this = $(this);
var qs = '?iframe=true&width=80%&height=90%';
var lnk = $this.attr('href');
$.prettyPhoto.open(lnk + qs);
});
``` |
310,953 | <p>I have successfully forbidden access to any kind of author pages whether trough <code>/author/username/</code> or the <code>?author={#id}</code> query string.</p>
<p>I did this with this added to the beginning of my htaccess file:</p>
<pre><code><IfModule mod_rewrite.c>
RewriteCond %{REQUEST_URI} ^/author/
RewriteRule .* - [F]
RewriteCond %{QUERY_STRING} ^author=([0-9]*)
RewriteRule .* - [F]
</IfModule>
</code></pre>
<p>But the same doesn't work when wordpress is physically in a subdirectory.</p>
<p>The first part works:</p>
<pre><code>RewriteCond %{REQUEST_URI} ^/subdir/author/
RewriteRule .* - [F]
</code></pre>
<p>But no matter how I try to edit the second part, the <code>/subdir/?author=1</code> takes me to the <code>/subdir/usernumber1/</code> and that is forbidden alright, but this defeats the whole purpose of this.</p>
<p>Any ideas?</p>
<p><strong>Edit:</strong></p>
<p>Yes, I was trying to prevent user names from showing.</p>
<p>In the last moment yesterday I was able to come up with a solution:</p>
<pre><code><IfModule mod_rewrite.c>
RewriteCond %{REQUEST_URI} ^/subdir/author/
RewriteRule .* - [F]
RewriteCond %{REQUEST_URI} ^/subdir/
RewriteCond %{QUERY_STRING} ^author=([0-9]*)
RewriteRule .* - [F]
</IfModule>
</code></pre>
<p>I may be able to shorten it based on the answers below(for which I'm very thankful).</p>
<p>And yes this is placed in the subdir.</p>
<p>The first snippet was placed in the root dir, which did not worked(or maybe some of the solutions that I tried along the way actually worked but I had the redirect to the author page already cached, I don't know for sure).</p>
| [
{
"answer_id": 310955,
"author": "Iceable",
"author_id": 136263,
"author_profile": "https://wordpress.stackexchange.com/users/136263",
"pm_score": 1,
"selected": false,
"text": "<p>The question is about doing this with <code>.htaccess</code>, but why not disabling author pages from within WordPress instead?</p>\n\n<p>This would achieve the same result while making the subdirectory concern irrelevant altogether (and also works regardless of permalink structure settings)</p>\n\n<p>Sample code that sets all urls to author pages to a 404 error:</p>\n\n<pre><code>add_action( 'template_redirect',\n function() {\n if ( isset( $_GET['author'] ) || is_author() ) {\n global $wp_query;\n $wp_query->set_404();\n status_header( 404 );\n nocache_headers();\n }\n }, 1 );\nadd_filter( 'author_link', function() { return '#'; }, 99 );\nadd_filter( 'the_author_posts_link', '__return_empty_string', 99 );\n</code></pre>\n\n<p>(code taken from this plugin: <a href=\"https://wordpress.org/plugins/disable-author-archives/\" rel=\"nofollow noreferrer\">Disable Author Archives</a>)</p>\n"
},
{
"answer_id": 310963,
"author": "scytale",
"author_id": 128374,
"author_profile": "https://wordpress.stackexchange.com/users/128374",
"pm_score": 1,
"selected": false,
"text": "<p>I assume you are trying to prevent scanners obtaining your site's user names. And for security I believe in blocking at the first perimeter gate possible i.e. .htaccess not PHP.</p>\n\n<p>No idea why subdirs cause an issue; you could try adding your condition to htaccess files in both root and your WP subdir it certainly won't do any harm. I use a rewrite condition pretty similar to yours and it works for me on sites with WP in subdir or not:</p>\n\n<pre><code>RewriteCond %{QUERY_STRING} author=\n# redirect away from site\nRewriteRule (.*) https://www.fbi.gov/investigate/cyber/%1 [R=302,L]\n</code></pre>\n\n<p>I also use a modified version of <a href=\"https://perishablepress.com/6g/#6g-firewall\" rel=\"nofollow noreferrer\">Jeff Starr's 6G \"firewall\"</a> to additionally check for the <code>WPScan</code> User Agent. This scanner is popular with hackers and also used by some online \"enter a URL\" security scanners to identify admin users, use of vulnerable plugins etc etc. Obviously users can change the UA but legitimate online scanners and script kiddies don't seem to bother:</p>\n\n<pre><code><IfModule mod_setenvif.c>\n # numerous 6G UA Checks (OMITTED)\n #check for WPScan\n SetEnvIfNoCase User-Agent \"WPScan\" bad_bot\n # Apache >= 2.3\n <IfModule mod_authz_core.c>\n <RequireAll>\n Require all Granted\n Require not env bad_bot\n </RequireAll>\n </IfModule>\n</IfModule>\n</code></pre>\n\n<p><strong>re M Kaplun's comment on OP:</strong></p>\n\n<p>I wasn't aware of <a href=\"https://wordpress.org/plugins/prevent-user-name-and-email-leakage/\" rel=\"nofollow noreferrer\">Mark's plugin</a>; and despite my comments on PHP it is obviously a great out of the box one stop solution. I take a different approach (which \"solves\" the problem of username leakage by themes also mentioned by Mark).</p>\n\n<p>Change display name (via WP Dashboard) and author slug (edit \"user_nicename\" in users table; or use <a href=\"https://wordpress.org/plugins/edit-author-slug/\" rel=\"nofollow noreferrer\">Edit Author Slug plugin</a>) to be completely different to username.</p>\n\n<p>So:</p>\n\n<ol>\n<li><p>requests with author querystring (hackers) are redirected (2 lines of htaccess above).</p></li>\n<li><p>author links added to posts by themes still friendly & work. They take you to relevant \"author's page\" - but the author slug no longer identifies username. e.g. on my site the (valid) author link (display name \"AW\") takes you to <code>https://wptest.means.us.com/author/not-for-scanners/</code> for a list of my posts.</p></li>\n</ol>\n\n<p>This is not practical for sites with lots of authors. Maybe ( @Mark Kaplun @mark-kaplun )'s plugin could be extended to automate slug changes (hashing all user_nicename in the DB?)?</p>\n\n<p><strong>Are publicly viewable usernames a risk?</strong></p>\n\n<p>Wordpress.org consensus is that user name \"leakage\" is <a href=\"https://wptavern.com/why-showing-the-wordpress-username-is-not-a-security-risk\" rel=\"nofollow noreferrer\">not a security risk</a> . Yet it provides the potential <strong>for some users to be hacked on first attempt (no brute force needed)</strong>.</p>\n\n<p>You do not need to be a genius to realise that the friendly url slug <code>/author/hclintongmailcom</code> means their is an author with email and (case insensitive) user name of <code>[email protected]</code>.</p>\n\n<p>There are hacker password lists for 1 Billion plus (? from recollection) email addresses (try yours against a small subset <a href=\"https://haveibeenpwned.com/\" rel=\"nofollow noreferrer\">https://haveibeenpwned.com/</a>); and many users use the same never changing password across sites. <strong>So an author with an email username and a password <em>compromised on another site</em> might be \"hacked\" at first attempt on your site.</strong></p>\n"
},
{
"answer_id": 310981,
"author": "MrWhite",
"author_id": 8259,
"author_profile": "https://wordpress.stackexchange.com/users/8259",
"pm_score": 1,
"selected": false,
"text": "<p>This is probably best handled the \"WordPress way\" as @Iceable suggests, rather than using <code>.htaccess</code>, however, to answer your specific queries...</p>\n\n<blockquote>\n <p>But no matter how I try to edit the second part...</p>\n</blockquote>\n\n<p>You don't need to edit the \"second part\". The \"second part\" simply checks the query string, not the URL-path, which does not change when WordPress is installed in a subdirectory.</p>\n\n<p>Also, assuming the <code>.htaccess</code> file is located inside the subdirectory that WordPress is installed in then your directives can be simplified. There is no need to reference the subdirectory:</p>\n\n<pre><code>RewriteRule ^author/ - [F]\nRewriteCond %{QUERY_STRING} ^author=([0-9]*)\nRewriteRule .* - [F]\n</code></pre>\n\n<p>These directives will work regardless of where WP is installed, providing the <code>.htaccess</code> file is located in the root of the WP install.</p>\n\n<p>It is more efficient to check the URL-path using the <code>RewriteRule</code> <em>pattern</em> (when possible), rather than checking against the <code>REQUEST_URI</code> server variable. Also, the <code>RewriteRule</code> <em>pattern</em> matches against the URL-path less the directory-prefix (so this naturally works for any subdirectory without additional work). Whereas the <code>REQUEST_URI</code> server variable contains the entire URL-path, so any subdirectory must be explicitly accounted for.</p>\n\n<p>Also, there is no need for the <code><IfModule mod_rewrite.c></code> container, unless these directives are intended to be optional.</p>\n"
},
{
"answer_id": 371053,
"author": "AJMartel",
"author_id": 191608,
"author_profile": "https://wordpress.stackexchange.com/users/191608",
"pm_score": 0,
"selected": false,
"text": "<p>My site redirects the <strong>?author={#id}</strong> query string to do a Google search for the query string itself.</p>\n<p>I accomplished this by adding the following to my .htaccess file:</p>\n<pre><code># Block User ID Phishing Requests\n<IfModule mod_rewrite.c>\n RewriteCond %{QUERY_STRING} ^author=([0-9]*)\n RewriteRule (.*) https://www.google.com/search?q=?author=%1\n</IfModule>\n</code></pre>\n"
},
{
"answer_id": 371550,
"author": "AJMartel",
"author_id": 192052,
"author_profile": "https://wordpress.stackexchange.com/users/192052",
"pm_score": 0,
"selected": false,
"text": "<pre><code><IfModule mod_rewrite.c>\n RewriteCond %{QUERY_STRING} ^author=([0-9]*)\n RewriteRule (.*) https://www.google.com/search?q=?author=%1 [L,R=301]\n</IfModule>\n</code></pre>\n<p>Sorry, forgot to add part in <strong>[L,R=301]</strong>\nOtherwise you could get unexpected results.</p>\n"
}
]
| 2018/08/09 | [
"https://wordpress.stackexchange.com/questions/310953",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133528/"
]
| I have successfully forbidden access to any kind of author pages whether trough `/author/username/` or the `?author={#id}` query string.
I did this with this added to the beginning of my htaccess file:
```
<IfModule mod_rewrite.c>
RewriteCond %{REQUEST_URI} ^/author/
RewriteRule .* - [F]
RewriteCond %{QUERY_STRING} ^author=([0-9]*)
RewriteRule .* - [F]
</IfModule>
```
But the same doesn't work when wordpress is physically in a subdirectory.
The first part works:
```
RewriteCond %{REQUEST_URI} ^/subdir/author/
RewriteRule .* - [F]
```
But no matter how I try to edit the second part, the `/subdir/?author=1` takes me to the `/subdir/usernumber1/` and that is forbidden alright, but this defeats the whole purpose of this.
Any ideas?
**Edit:**
Yes, I was trying to prevent user names from showing.
In the last moment yesterday I was able to come up with a solution:
```
<IfModule mod_rewrite.c>
RewriteCond %{REQUEST_URI} ^/subdir/author/
RewriteRule .* - [F]
RewriteCond %{REQUEST_URI} ^/subdir/
RewriteCond %{QUERY_STRING} ^author=([0-9]*)
RewriteRule .* - [F]
</IfModule>
```
I may be able to shorten it based on the answers below(for which I'm very thankful).
And yes this is placed in the subdir.
The first snippet was placed in the root dir, which did not worked(or maybe some of the solutions that I tried along the way actually worked but I had the redirect to the author page already cached, I don't know for sure). | The question is about doing this with `.htaccess`, but why not disabling author pages from within WordPress instead?
This would achieve the same result while making the subdirectory concern irrelevant altogether (and also works regardless of permalink structure settings)
Sample code that sets all urls to author pages to a 404 error:
```
add_action( 'template_redirect',
function() {
if ( isset( $_GET['author'] ) || is_author() ) {
global $wp_query;
$wp_query->set_404();
status_header( 404 );
nocache_headers();
}
}, 1 );
add_filter( 'author_link', function() { return '#'; }, 99 );
add_filter( 'the_author_posts_link', '__return_empty_string', 99 );
```
(code taken from this plugin: [Disable Author Archives](https://wordpress.org/plugins/disable-author-archives/)) |
310,957 | <p>i want to ask a simple question that what to do if i have to check whether a pliugin is installed. for example i want to run a code, which says,</p>
<p>if Gutenberg is installed, then run the following code else not.</p>
<p>i have created this code, but not sure will this work or not</p>
<pre><code> if(defined('Gutenberg')) {
}
</code></pre>
<p>is this the right way or is there any other way to that.
thanks in advance</p>
| [
{
"answer_id": 310961,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 4,
"selected": true,
"text": "<p>Checking if a plugin is installed is always a bad idea as plugins might be installed but for whatever reason not function, or function in different way than you might expect. </p>\n\n<p>Specifically for gutenberg as it stands right now for example, post types that are not exposed in the REST API can not be edited by gutenberg.</p>\n\n<p>As always, if you have a functionality that depends on a plugin you should hook to its actions and filters to avoid the need to guess if it is active or not (the fact that the action is \"called\" is the best indication for activity), or ask the plugin author to add the kind of action/filter you might find useful.</p>\n"
},
{
"answer_id": 310966,
"author": "Iceable",
"author_id": 136263,
"author_profile": "https://wordpress.stackexchange.com/users/136263",
"pm_score": 1,
"selected": false,
"text": "<p>One possible way to do this is to check whether a specific class or function that is included in the plugin is defined, with <code>class_exists()</code> or <code>function_exists()</code>, respectively.</p>\n\n<p>For Gutenberg, you could check for <code>register_block_type()</code>:</p>\n\n<pre><code>if ( function_exists( 'register_block_type' ) ) {\n // Gutenberg is available.\n}\n</code></pre>\n\n<p>I would however side with Mark Kaplun to say this is not a good idea in most cases, and it is not even necessary if you follow best practices.</p>\n\n<p>If you are going to interact with a plugin, you should do so via hooks and filters. Whether the plugin is running or not is irrelevant: if the plugin isn't there the hooks simply won't run.</p>\n"
}
]
| 2018/08/09 | [
"https://wordpress.stackexchange.com/questions/310957",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140102/"
]
| i want to ask a simple question that what to do if i have to check whether a pliugin is installed. for example i want to run a code, which says,
if Gutenberg is installed, then run the following code else not.
i have created this code, but not sure will this work or not
```
if(defined('Gutenberg')) {
}
```
is this the right way or is there any other way to that.
thanks in advance | Checking if a plugin is installed is always a bad idea as plugins might be installed but for whatever reason not function, or function in different way than you might expect.
Specifically for gutenberg as it stands right now for example, post types that are not exposed in the REST API can not be edited by gutenberg.
As always, if you have a functionality that depends on a plugin you should hook to its actions and filters to avoid the need to guess if it is active or not (the fact that the action is "called" is the best indication for activity), or ask the plugin author to add the kind of action/filter you might find useful. |
310,969 | <p>I need a wordpress function that search all the posts inside my website and if one or multiple posts have the category ID (example 25) <code>echo "yes"</code>, <code>else echo "no"</code> </p>
<p>I was trying to do: </p>
<pre><code>if ( has_category(25) ) {
echo "OK";
} else {
echo "NO OK";
}
</code></pre>
<p>But dont work</p>
<p>EDIT: My goal is to show comments section only if the category is "25" the other posts has not to show comments section</p>
| [
{
"answer_id": 310961,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 4,
"selected": true,
"text": "<p>Checking if a plugin is installed is always a bad idea as plugins might be installed but for whatever reason not function, or function in different way than you might expect. </p>\n\n<p>Specifically for gutenberg as it stands right now for example, post types that are not exposed in the REST API can not be edited by gutenberg.</p>\n\n<p>As always, if you have a functionality that depends on a plugin you should hook to its actions and filters to avoid the need to guess if it is active or not (the fact that the action is \"called\" is the best indication for activity), or ask the plugin author to add the kind of action/filter you might find useful.</p>\n"
},
{
"answer_id": 310966,
"author": "Iceable",
"author_id": 136263,
"author_profile": "https://wordpress.stackexchange.com/users/136263",
"pm_score": 1,
"selected": false,
"text": "<p>One possible way to do this is to check whether a specific class or function that is included in the plugin is defined, with <code>class_exists()</code> or <code>function_exists()</code>, respectively.</p>\n\n<p>For Gutenberg, you could check for <code>register_block_type()</code>:</p>\n\n<pre><code>if ( function_exists( 'register_block_type' ) ) {\n // Gutenberg is available.\n}\n</code></pre>\n\n<p>I would however side with Mark Kaplun to say this is not a good idea in most cases, and it is not even necessary if you follow best practices.</p>\n\n<p>If you are going to interact with a plugin, you should do so via hooks and filters. Whether the plugin is running or not is irrelevant: if the plugin isn't there the hooks simply won't run.</p>\n"
}
]
| 2018/08/09 | [
"https://wordpress.stackexchange.com/questions/310969",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/135486/"
]
| I need a wordpress function that search all the posts inside my website and if one or multiple posts have the category ID (example 25) `echo "yes"`, `else echo "no"`
I was trying to do:
```
if ( has_category(25) ) {
echo "OK";
} else {
echo "NO OK";
}
```
But dont work
EDIT: My goal is to show comments section only if the category is "25" the other posts has not to show comments section | Checking if a plugin is installed is always a bad idea as plugins might be installed but for whatever reason not function, or function in different way than you might expect.
Specifically for gutenberg as it stands right now for example, post types that are not exposed in the REST API can not be edited by gutenberg.
As always, if you have a functionality that depends on a plugin you should hook to its actions and filters to avoid the need to guess if it is active or not (the fact that the action is "called" is the best indication for activity), or ask the plugin author to add the kind of action/filter you might find useful. |
310,980 | <p>I'm trying to use the <code><?php rewind_posts(); ?></code> feature to use two loops on my homepage template. Does anyone know how to stop the first loop after the latest post? </p>
<p>Here is my Code:</p>
<pre><code><?php
if (have_posts()) : while (have_posts()) : the_post(); ?>
<h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
<?php endwhile; endif; ?>
<?php rewind_posts(); ?>
<?php
if ( have_posts() ) :
if ( is_home() && ! is_front_page() ) :
?>
<header>
<h1 class="page-title screen-reader-text">
<?php single_post_title(); ?>
</h1>
</header>
<?php
endif;
while ( have_posts() ) :
the_post();
get_template_part( 'template-parts/content-home', get_post_type() );
endwhile;
the_posts_navigation();
else :
get_template_part( 'template-parts/content', 'none' );
endif;
?>
</code></pre>
| [
{
"answer_id": 311009,
"author": "Balas",
"author_id": 17849,
"author_profile": "https://wordpress.stackexchange.com/users/17849",
"pm_score": 1,
"selected": true,
"text": "<p>Try like this which fill skip first post:</p>\n\n<pre><code>$i = 0;\nwhile ( have_posts() ) :\n the_post();\n if($i > 0)\n get_template_part( 'template-parts/content-home', get_post_type() );\n else {\n // design your first post as you wish with HTML, CSS\n the_title();\n the_permalink();\n the_post_thumbnail(); \n the_content();\n the_author();\n the_date();\n } \n $i++;\nendwhile;\n</code></pre>\n"
},
{
"answer_id": 311011,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": false,
"text": "<p>You can output the first post outside of a loop, then loop over the remaining posts:</p>\n\n<pre><code>if( have_posts() ){\n\n // first post output\n the_post();\n the_title();\n\n while( have_posts() ){\n // the rest\n the_post();\n the_title();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 413961,
"author": "wittich",
"author_id": 74281,
"author_profile": "https://wordpress.stackexchange.com/users/74281",
"pm_score": 0,
"selected": false,
"text": "<p>I like more the option and syntax of <code>current_post</code>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>// First post inside loop\nif( $wp_query->current_post === 0 ) { \n \n}\n</code></pre>\n<p>See the WordPress Codex for more details: <a href=\"https://codex.wordpress.org/The_Loop#Object_orientation\" rel=\"nofollow noreferrer\">Object orientation of the Loop</a></p>\n"
}
]
| 2018/08/09 | [
"https://wordpress.stackexchange.com/questions/310980",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/148419/"
]
| I'm trying to use the `<?php rewind_posts(); ?>` feature to use two loops on my homepage template. Does anyone know how to stop the first loop after the latest post?
Here is my Code:
```
<?php
if (have_posts()) : while (have_posts()) : the_post(); ?>
<h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
<?php endwhile; endif; ?>
<?php rewind_posts(); ?>
<?php
if ( have_posts() ) :
if ( is_home() && ! is_front_page() ) :
?>
<header>
<h1 class="page-title screen-reader-text">
<?php single_post_title(); ?>
</h1>
</header>
<?php
endif;
while ( have_posts() ) :
the_post();
get_template_part( 'template-parts/content-home', get_post_type() );
endwhile;
the_posts_navigation();
else :
get_template_part( 'template-parts/content', 'none' );
endif;
?>
``` | Try like this which fill skip first post:
```
$i = 0;
while ( have_posts() ) :
the_post();
if($i > 0)
get_template_part( 'template-parts/content-home', get_post_type() );
else {
// design your first post as you wish with HTML, CSS
the_title();
the_permalink();
the_post_thumbnail();
the_content();
the_author();
the_date();
}
$i++;
endwhile;
``` |
311,028 | <p>I'm trying to get the url of an image from a MetaBox (plugin) filed on an archive-page. </p>
<pre><code><?php
if ( rwmb_meta( 'field-id' ) ) {
// Get images
$img_srcset_large = rwmb_meta( 'field-id', array( 'size' => 'image-size', 'limit' => 1 ) );
echo $img_srcset_large['url']
?>
</code></pre>
<p>Unfortunately there is nothing displayed.
Can you give me a hint how this code can work on archive-templates?
Best</p>
| [
{
"answer_id": 311009,
"author": "Balas",
"author_id": 17849,
"author_profile": "https://wordpress.stackexchange.com/users/17849",
"pm_score": 1,
"selected": true,
"text": "<p>Try like this which fill skip first post:</p>\n\n<pre><code>$i = 0;\nwhile ( have_posts() ) :\n the_post();\n if($i > 0)\n get_template_part( 'template-parts/content-home', get_post_type() );\n else {\n // design your first post as you wish with HTML, CSS\n the_title();\n the_permalink();\n the_post_thumbnail(); \n the_content();\n the_author();\n the_date();\n } \n $i++;\nendwhile;\n</code></pre>\n"
},
{
"answer_id": 311011,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": false,
"text": "<p>You can output the first post outside of a loop, then loop over the remaining posts:</p>\n\n<pre><code>if( have_posts() ){\n\n // first post output\n the_post();\n the_title();\n\n while( have_posts() ){\n // the rest\n the_post();\n the_title();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 413961,
"author": "wittich",
"author_id": 74281,
"author_profile": "https://wordpress.stackexchange.com/users/74281",
"pm_score": 0,
"selected": false,
"text": "<p>I like more the option and syntax of <code>current_post</code>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>// First post inside loop\nif( $wp_query->current_post === 0 ) { \n \n}\n</code></pre>\n<p>See the WordPress Codex for more details: <a href=\"https://codex.wordpress.org/The_Loop#Object_orientation\" rel=\"nofollow noreferrer\">Object orientation of the Loop</a></p>\n"
}
]
| 2018/08/10 | [
"https://wordpress.stackexchange.com/questions/311028",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/148458/"
]
| I'm trying to get the url of an image from a MetaBox (plugin) filed on an archive-page.
```
<?php
if ( rwmb_meta( 'field-id' ) ) {
// Get images
$img_srcset_large = rwmb_meta( 'field-id', array( 'size' => 'image-size', 'limit' => 1 ) );
echo $img_srcset_large['url']
?>
```
Unfortunately there is nothing displayed.
Can you give me a hint how this code can work on archive-templates?
Best | Try like this which fill skip first post:
```
$i = 0;
while ( have_posts() ) :
the_post();
if($i > 0)
get_template_part( 'template-parts/content-home', get_post_type() );
else {
// design your first post as you wish with HTML, CSS
the_title();
the_permalink();
the_post_thumbnail();
the_content();
the_author();
the_date();
}
$i++;
endwhile;
``` |
311,035 | <p>He everyone i'm a newbie to wordpress/php and have 1 other problem. I am trying to get the date under the post title and not to display the category tags above the title. I tried it to change thing is the index.php but it would not work. How can I fix this for this page <a href="http://www.quintyvandijk.com/gallery/" rel="nofollow noreferrer">http://www.quintyvandijk.com/gallery/</a>.</p>
<pre><code><?php
$edgt_blog_type = milieu_edge_get_archive_blog_list_layout();
milieu_edge_include_blog_helper_functions( 'lists', $edgt_blog_type );
$edgt_holder_params = milieu_edge_get_holder_params_blog();
get_header();
milieu_edge_get_title();
?>
<div class="<?php echo esc_attr( $edgt_holder_params['holder'] ); ?>">
<?php do_action( 'milieu_edge_action_after_container_open' ); ?>
<div class="<?php echo esc_attr( $edgt_holder_params['inner'] ); ?>">
<?php milieu_edge_get_blog( $edgt_blog_type ); ?>
</div>
<?php do_action( 'milieu_edge_action_before_container_close' ); ?>
</div>
<?php do_action( 'milieu_edge_action_blog_list_additional_tags' ); ?>
<?php get_footer(); ?>
</code></pre>
| [
{
"answer_id": 311009,
"author": "Balas",
"author_id": 17849,
"author_profile": "https://wordpress.stackexchange.com/users/17849",
"pm_score": 1,
"selected": true,
"text": "<p>Try like this which fill skip first post:</p>\n\n<pre><code>$i = 0;\nwhile ( have_posts() ) :\n the_post();\n if($i > 0)\n get_template_part( 'template-parts/content-home', get_post_type() );\n else {\n // design your first post as you wish with HTML, CSS\n the_title();\n the_permalink();\n the_post_thumbnail(); \n the_content();\n the_author();\n the_date();\n } \n $i++;\nendwhile;\n</code></pre>\n"
},
{
"answer_id": 311011,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": false,
"text": "<p>You can output the first post outside of a loop, then loop over the remaining posts:</p>\n\n<pre><code>if( have_posts() ){\n\n // first post output\n the_post();\n the_title();\n\n while( have_posts() ){\n // the rest\n the_post();\n the_title();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 413961,
"author": "wittich",
"author_id": 74281,
"author_profile": "https://wordpress.stackexchange.com/users/74281",
"pm_score": 0,
"selected": false,
"text": "<p>I like more the option and syntax of <code>current_post</code>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>// First post inside loop\nif( $wp_query->current_post === 0 ) { \n \n}\n</code></pre>\n<p>See the WordPress Codex for more details: <a href=\"https://codex.wordpress.org/The_Loop#Object_orientation\" rel=\"nofollow noreferrer\">Object orientation of the Loop</a></p>\n"
}
]
| 2018/08/10 | [
"https://wordpress.stackexchange.com/questions/311035",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/148457/"
]
| He everyone i'm a newbie to wordpress/php and have 1 other problem. I am trying to get the date under the post title and not to display the category tags above the title. I tried it to change thing is the index.php but it would not work. How can I fix this for this page <http://www.quintyvandijk.com/gallery/>.
```
<?php
$edgt_blog_type = milieu_edge_get_archive_blog_list_layout();
milieu_edge_include_blog_helper_functions( 'lists', $edgt_blog_type );
$edgt_holder_params = milieu_edge_get_holder_params_blog();
get_header();
milieu_edge_get_title();
?>
<div class="<?php echo esc_attr( $edgt_holder_params['holder'] ); ?>">
<?php do_action( 'milieu_edge_action_after_container_open' ); ?>
<div class="<?php echo esc_attr( $edgt_holder_params['inner'] ); ?>">
<?php milieu_edge_get_blog( $edgt_blog_type ); ?>
</div>
<?php do_action( 'milieu_edge_action_before_container_close' ); ?>
</div>
<?php do_action( 'milieu_edge_action_blog_list_additional_tags' ); ?>
<?php get_footer(); ?>
``` | Try like this which fill skip first post:
```
$i = 0;
while ( have_posts() ) :
the_post();
if($i > 0)
get_template_part( 'template-parts/content-home', get_post_type() );
else {
// design your first post as you wish with HTML, CSS
the_title();
the_permalink();
the_post_thumbnail();
the_content();
the_author();
the_date();
}
$i++;
endwhile;
``` |
311,044 | <p>I am developing a plugin which will show the caller of all the Hooks & Actions on a Page in Wordpress just like QueryMonitor. I know that global $wp_action & $wp_filter has all the information but it does not provide the Caller Component of the Action or Filter.</p>
<p>Can you please help me out with this.</p>
<p>If you need the Code, Comment down.</p>
<p>Thanks in advance.</p>
<p>Code : - </p>
<pre><code><?php
class MyTracker {
static $hooks;
static function track_hooks( ) {
$filter = current_filter();
if ( ! empty($GLOBALS['wp_filter'][$filter]) ) {
foreach ( $GLOBALS['wp_filter'][$filter] as $priority => $tag_hooks ) {
foreach ( $tag_hooks as $hook ) {
if ( is_array($hook['function']) ) {
if ( is_object($hook['function'][0]) ) {
$func = get_class($hook['function'][0]) . '->' . $hook['function'][1];
} elseif ( is_string($hook['function'][0]) ) {
$func = $hook['function'][0] . '::' . $hook['function'][1];
}
} elseif( $hook['function'] instanceof Closure ) {
$func = 'a closure';
} elseif( is_string($hook['function']) ) {
$func = $hook['function'];
}
self::$hooks[] = 'On hook <b>"' . $filter . '"</b> run <b>'. $func . '</b> at priority ' . $priority;
}
}
}
}
}
add_action( 'all', array('MyTracker', 'track_hooks') );
add_action( 'shutdown', function() {
echo implode( '<br />', MyTracker::$hooks );
}, 9999);
</code></pre>
<p>This displays all the Actions on the Current page, What i Need is that the Execution time by each of these hooks.</p>
| [
{
"answer_id": 311049,
"author": "anmari",
"author_id": 3569,
"author_profile": "https://wordpress.stackexchange.com/users/3569",
"pm_score": 0,
"selected": false,
"text": "<p>Akash, It sounds like you are want to list out all the plugins & themes that have added actions and filters? </p>\n\n<p>IN which case, scan all plugin & theme files in wp-content for 'add_action' and 'add_filter', note the filepath & the function in which they are added. Match the function names with the wp lists and excluded any that didnt actually get added in wp , or maybe not - they might only get added in certain circumstances and not actually be in the wp variables at the time your plugin runs. Might be safer to list the full list? You could note which plugins and themes are not active, which have created their own actions and filters, etc.</p>\n"
},
{
"answer_id": 311240,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 2,
"selected": true,
"text": "<p>As I said in my comment to the question, you can use the PHP internal <a href=\"https://secure.php.net/manual/en/class.reflectionfunction.php\" rel=\"nofollow noreferrer\">ReflectionFunction</a> class to get the filename of the callable. The below code should be a good start to help you. It needs more logic for determining the callbacks and most of that should be abstracted out of the Monitor class anyway. I also didn't write the code that would get the nice name of the theme, plugin, core, or whatever else might have added the hook from the filename. That should be relatively easy to do though once you know the file that added the hook.</p>\n\n<pre><code><?php\n/**\n * Plugin Name: Monitor\n */\n\nnamespace WPSE\\Monitor;\n\nclass Monitor {\n protected $callbacks = [];\n\n protected function addCallback( $callback ) {\n $this->callbacks[] = $callback;\n }\n\n public function shutdown() {\n var_dump( $this->callbacks );\n }\n\n public function monitor() {\n global $wp_filter;\n $name = \\current_filter();\n if( ! isset( $wp_filter[ $name ] ) ) {\n return;\n }\n\n $action = $wp_filter[ $name ];\n\n foreach ( $action->callbacks as $priority => $callbacks ) {\n foreach( $callbacks as $callback ) {\n try {\n if( \\is_array( $callback[ 'function' ] ) ) {\n if( \\is_object( $callback[ 'function' ][ 0 ] ) ) {\n $class = \\get_class( $callback[ 'function' ][ 0 ] );\n $callback[ 'name' ] = $class . '->' . $callback[ 'function' ][ 1 ] . '()';\n $ref = new \\ReflectionMethod( $class, $callback[ 'function' ][ 1 ] );\n }\n elseif( \\is_string( $callback[ 'function' ][ 0 ] ) ) {\n $callback[ 'name' ] = $callback[ 'function' ][ 0 ] . '::' . $callback[ 'function' ][ 1 ];\n $ref = new \\ReflectionMethod( $callback[ 'function' ][ 0 ], $callback[ 'function' ][ 1 ] );\n }\n }\n elseif( $callback[ 'function' ] instanceOf Closure ) {\n $callback[ 'name' ] = 'closure';\n $ref = new \\ReflectionMethod( $callback[ 'function' ] );\n }\n elseif( \\is_string( $callback[ 'function' ] ) ) {\n $callback[ 'name' ] = $callback[ 'function' ] . '()';\n $ref = new \\ReflectionMethod( $callback[ 'name' ] );\n }\n else{\n return;\n }\n\n $callback[ 'filename' ] = $ref->getFileName();\n\n $this->addCallback( $callback );\n\n } catch( \\ReflectionException $e ) {\n $callback['error'] = new \\WP_Error( 'reflection_exception', $e->getMessage() );\n }\n }\n }\n }\n}\nclass MonitorInit {\n\n private static $monitor;\n\n public static function init() {\n self::$monitor = new Monitor();\n \\add_action( 'all', [ self::$monitor, 'monitor' ] );\n \\add_action( 'shutdown', [ self::$monitor, 'shutdown' ] );\n }\n}\n\\add_action( 'plugins_loaded', __NAMESPACE__ . '\\MonitorInit::init', 0 );\n</code></pre>\n\n<p>The <code>plugins_loaded</code> hook is the first that's available to regular plugins. So if you want to catch hooks that are added before this, you'll need to do something tricky.</p>\n"
}
]
| 2018/08/10 | [
"https://wordpress.stackexchange.com/questions/311044",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147912/"
]
| I am developing a plugin which will show the caller of all the Hooks & Actions on a Page in Wordpress just like QueryMonitor. I know that global $wp\_action & $wp\_filter has all the information but it does not provide the Caller Component of the Action or Filter.
Can you please help me out with this.
If you need the Code, Comment down.
Thanks in advance.
Code : -
```
<?php
class MyTracker {
static $hooks;
static function track_hooks( ) {
$filter = current_filter();
if ( ! empty($GLOBALS['wp_filter'][$filter]) ) {
foreach ( $GLOBALS['wp_filter'][$filter] as $priority => $tag_hooks ) {
foreach ( $tag_hooks as $hook ) {
if ( is_array($hook['function']) ) {
if ( is_object($hook['function'][0]) ) {
$func = get_class($hook['function'][0]) . '->' . $hook['function'][1];
} elseif ( is_string($hook['function'][0]) ) {
$func = $hook['function'][0] . '::' . $hook['function'][1];
}
} elseif( $hook['function'] instanceof Closure ) {
$func = 'a closure';
} elseif( is_string($hook['function']) ) {
$func = $hook['function'];
}
self::$hooks[] = 'On hook <b>"' . $filter . '"</b> run <b>'. $func . '</b> at priority ' . $priority;
}
}
}
}
}
add_action( 'all', array('MyTracker', 'track_hooks') );
add_action( 'shutdown', function() {
echo implode( '<br />', MyTracker::$hooks );
}, 9999);
```
This displays all the Actions on the Current page, What i Need is that the Execution time by each of these hooks. | As I said in my comment to the question, you can use the PHP internal [ReflectionFunction](https://secure.php.net/manual/en/class.reflectionfunction.php) class to get the filename of the callable. The below code should be a good start to help you. It needs more logic for determining the callbacks and most of that should be abstracted out of the Monitor class anyway. I also didn't write the code that would get the nice name of the theme, plugin, core, or whatever else might have added the hook from the filename. That should be relatively easy to do though once you know the file that added the hook.
```
<?php
/**
* Plugin Name: Monitor
*/
namespace WPSE\Monitor;
class Monitor {
protected $callbacks = [];
protected function addCallback( $callback ) {
$this->callbacks[] = $callback;
}
public function shutdown() {
var_dump( $this->callbacks );
}
public function monitor() {
global $wp_filter;
$name = \current_filter();
if( ! isset( $wp_filter[ $name ] ) ) {
return;
}
$action = $wp_filter[ $name ];
foreach ( $action->callbacks as $priority => $callbacks ) {
foreach( $callbacks as $callback ) {
try {
if( \is_array( $callback[ 'function' ] ) ) {
if( \is_object( $callback[ 'function' ][ 0 ] ) ) {
$class = \get_class( $callback[ 'function' ][ 0 ] );
$callback[ 'name' ] = $class . '->' . $callback[ 'function' ][ 1 ] . '()';
$ref = new \ReflectionMethod( $class, $callback[ 'function' ][ 1 ] );
}
elseif( \is_string( $callback[ 'function' ][ 0 ] ) ) {
$callback[ 'name' ] = $callback[ 'function' ][ 0 ] . '::' . $callback[ 'function' ][ 1 ];
$ref = new \ReflectionMethod( $callback[ 'function' ][ 0 ], $callback[ 'function' ][ 1 ] );
}
}
elseif( $callback[ 'function' ] instanceOf Closure ) {
$callback[ 'name' ] = 'closure';
$ref = new \ReflectionMethod( $callback[ 'function' ] );
}
elseif( \is_string( $callback[ 'function' ] ) ) {
$callback[ 'name' ] = $callback[ 'function' ] . '()';
$ref = new \ReflectionMethod( $callback[ 'name' ] );
}
else{
return;
}
$callback[ 'filename' ] = $ref->getFileName();
$this->addCallback( $callback );
} catch( \ReflectionException $e ) {
$callback['error'] = new \WP_Error( 'reflection_exception', $e->getMessage() );
}
}
}
}
}
class MonitorInit {
private static $monitor;
public static function init() {
self::$monitor = new Monitor();
\add_action( 'all', [ self::$monitor, 'monitor' ] );
\add_action( 'shutdown', [ self::$monitor, 'shutdown' ] );
}
}
\add_action( 'plugins_loaded', __NAMESPACE__ . '\MonitorInit::init', 0 );
```
The `plugins_loaded` hook is the first that's available to regular plugins. So if you want to catch hooks that are added before this, you'll need to do something tricky. |
311,076 | <p>I initially had a wordpress installation on a free hosting service. After the hosting suffered an attack I got a backup of all files and the database and am recovering the site on my localhost (using wampserver 3.1.0 on windows 10) before I can update it and upload it to my new hosting service.</p>
<p>The thing is, links are not working and some (not all) images are not displaying, not even on edit mode, and not at all (I mean, there is not a square indicating a broken image either). As for settings, I set up my wordpress url and site url (in admin console) to point to my new localhost url (<a href="http://localhost/b17_14344318" rel="nofollow noreferrer">http://localhost/b17_14344318</a>). I also used <code>Search-Replace-DB</code> to replace all instances of my old url with my localhost url (the problems existed before I replaced the url using this script).</p>
<p>An example of images issue is a facebook logo image I had in my old installation. As it wasn't showing up I tried removing it from my post and re-adding, editing it (on wordpress), deleting it and re-uploading it, changing the file name and re-upload to use this "new file", removing the html code and re-writing it... I also disabled my plugins one by one, and checked if the image showed up, but it didn't. This image (as others that have the same problem) did show up when my site was up on its old hosting service, with the same plugins I have now (however, the Wordpress version I'm using now is newer than the one I had on that hosting).</p>
<p>After I add the image through the "add media" button, this is the code it generates:</p>
<pre><code><a href="http://localhost/b17_14344318/2543-2/fb_logo/" rel="attachment wp-att-2549"><img class="alignnone size-full wp-image-2549" src="http://localhost/b17_14344318/wp-content/uploads/2018/08/fb_logo.png" alt="" width="215" height="215" /></a>
</code></pre>
<p>I tried creating a new page, just in case something was corrupt in the old page I recovered from the backup, but the image is still "invisible". This is how it looks after I add the image through "Add media" button:
<a href="https://i.stack.imgur.com/VsmXU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VsmXU.png" alt="edit mode"></a></p>
<p>And this is the html code behind it:
<a href="https://i.stack.imgur.com/362Jh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/362Jh.png" alt="html code"></a></p>
<p>As for links, when clicking on any item (link to a post, a page, a category, etc) I see this un-styled page:
<a href="https://i.stack.imgur.com/e3KCm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e3KCm.png" alt="links"></a></p>
<p>Any ideas on what else I should try?</p>
| [
{
"answer_id": 311049,
"author": "anmari",
"author_id": 3569,
"author_profile": "https://wordpress.stackexchange.com/users/3569",
"pm_score": 0,
"selected": false,
"text": "<p>Akash, It sounds like you are want to list out all the plugins & themes that have added actions and filters? </p>\n\n<p>IN which case, scan all plugin & theme files in wp-content for 'add_action' and 'add_filter', note the filepath & the function in which they are added. Match the function names with the wp lists and excluded any that didnt actually get added in wp , or maybe not - they might only get added in certain circumstances and not actually be in the wp variables at the time your plugin runs. Might be safer to list the full list? You could note which plugins and themes are not active, which have created their own actions and filters, etc.</p>\n"
},
{
"answer_id": 311240,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 2,
"selected": true,
"text": "<p>As I said in my comment to the question, you can use the PHP internal <a href=\"https://secure.php.net/manual/en/class.reflectionfunction.php\" rel=\"nofollow noreferrer\">ReflectionFunction</a> class to get the filename of the callable. The below code should be a good start to help you. It needs more logic for determining the callbacks and most of that should be abstracted out of the Monitor class anyway. I also didn't write the code that would get the nice name of the theme, plugin, core, or whatever else might have added the hook from the filename. That should be relatively easy to do though once you know the file that added the hook.</p>\n\n<pre><code><?php\n/**\n * Plugin Name: Monitor\n */\n\nnamespace WPSE\\Monitor;\n\nclass Monitor {\n protected $callbacks = [];\n\n protected function addCallback( $callback ) {\n $this->callbacks[] = $callback;\n }\n\n public function shutdown() {\n var_dump( $this->callbacks );\n }\n\n public function monitor() {\n global $wp_filter;\n $name = \\current_filter();\n if( ! isset( $wp_filter[ $name ] ) ) {\n return;\n }\n\n $action = $wp_filter[ $name ];\n\n foreach ( $action->callbacks as $priority => $callbacks ) {\n foreach( $callbacks as $callback ) {\n try {\n if( \\is_array( $callback[ 'function' ] ) ) {\n if( \\is_object( $callback[ 'function' ][ 0 ] ) ) {\n $class = \\get_class( $callback[ 'function' ][ 0 ] );\n $callback[ 'name' ] = $class . '->' . $callback[ 'function' ][ 1 ] . '()';\n $ref = new \\ReflectionMethod( $class, $callback[ 'function' ][ 1 ] );\n }\n elseif( \\is_string( $callback[ 'function' ][ 0 ] ) ) {\n $callback[ 'name' ] = $callback[ 'function' ][ 0 ] . '::' . $callback[ 'function' ][ 1 ];\n $ref = new \\ReflectionMethod( $callback[ 'function' ][ 0 ], $callback[ 'function' ][ 1 ] );\n }\n }\n elseif( $callback[ 'function' ] instanceOf Closure ) {\n $callback[ 'name' ] = 'closure';\n $ref = new \\ReflectionMethod( $callback[ 'function' ] );\n }\n elseif( \\is_string( $callback[ 'function' ] ) ) {\n $callback[ 'name' ] = $callback[ 'function' ] . '()';\n $ref = new \\ReflectionMethod( $callback[ 'name' ] );\n }\n else{\n return;\n }\n\n $callback[ 'filename' ] = $ref->getFileName();\n\n $this->addCallback( $callback );\n\n } catch( \\ReflectionException $e ) {\n $callback['error'] = new \\WP_Error( 'reflection_exception', $e->getMessage() );\n }\n }\n }\n }\n}\nclass MonitorInit {\n\n private static $monitor;\n\n public static function init() {\n self::$monitor = new Monitor();\n \\add_action( 'all', [ self::$monitor, 'monitor' ] );\n \\add_action( 'shutdown', [ self::$monitor, 'shutdown' ] );\n }\n}\n\\add_action( 'plugins_loaded', __NAMESPACE__ . '\\MonitorInit::init', 0 );\n</code></pre>\n\n<p>The <code>plugins_loaded</code> hook is the first that's available to regular plugins. So if you want to catch hooks that are added before this, you'll need to do something tricky.</p>\n"
}
]
| 2018/08/10 | [
"https://wordpress.stackexchange.com/questions/311076",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/148485/"
]
| I initially had a wordpress installation on a free hosting service. After the hosting suffered an attack I got a backup of all files and the database and am recovering the site on my localhost (using wampserver 3.1.0 on windows 10) before I can update it and upload it to my new hosting service.
The thing is, links are not working and some (not all) images are not displaying, not even on edit mode, and not at all (I mean, there is not a square indicating a broken image either). As for settings, I set up my wordpress url and site url (in admin console) to point to my new localhost url (<http://localhost/b17_14344318>). I also used `Search-Replace-DB` to replace all instances of my old url with my localhost url (the problems existed before I replaced the url using this script).
An example of images issue is a facebook logo image I had in my old installation. As it wasn't showing up I tried removing it from my post and re-adding, editing it (on wordpress), deleting it and re-uploading it, changing the file name and re-upload to use this "new file", removing the html code and re-writing it... I also disabled my plugins one by one, and checked if the image showed up, but it didn't. This image (as others that have the same problem) did show up when my site was up on its old hosting service, with the same plugins I have now (however, the Wordpress version I'm using now is newer than the one I had on that hosting).
After I add the image through the "add media" button, this is the code it generates:
```
<a href="http://localhost/b17_14344318/2543-2/fb_logo/" rel="attachment wp-att-2549"><img class="alignnone size-full wp-image-2549" src="http://localhost/b17_14344318/wp-content/uploads/2018/08/fb_logo.png" alt="" width="215" height="215" /></a>
```
I tried creating a new page, just in case something was corrupt in the old page I recovered from the backup, but the image is still "invisible". This is how it looks after I add the image through "Add media" button:
[](https://i.stack.imgur.com/VsmXU.png)
And this is the html code behind it:
[](https://i.stack.imgur.com/362Jh.png)
As for links, when clicking on any item (link to a post, a page, a category, etc) I see this un-styled page:
[](https://i.stack.imgur.com/e3KCm.png)
Any ideas on what else I should try? | As I said in my comment to the question, you can use the PHP internal [ReflectionFunction](https://secure.php.net/manual/en/class.reflectionfunction.php) class to get the filename of the callable. The below code should be a good start to help you. It needs more logic for determining the callbacks and most of that should be abstracted out of the Monitor class anyway. I also didn't write the code that would get the nice name of the theme, plugin, core, or whatever else might have added the hook from the filename. That should be relatively easy to do though once you know the file that added the hook.
```
<?php
/**
* Plugin Name: Monitor
*/
namespace WPSE\Monitor;
class Monitor {
protected $callbacks = [];
protected function addCallback( $callback ) {
$this->callbacks[] = $callback;
}
public function shutdown() {
var_dump( $this->callbacks );
}
public function monitor() {
global $wp_filter;
$name = \current_filter();
if( ! isset( $wp_filter[ $name ] ) ) {
return;
}
$action = $wp_filter[ $name ];
foreach ( $action->callbacks as $priority => $callbacks ) {
foreach( $callbacks as $callback ) {
try {
if( \is_array( $callback[ 'function' ] ) ) {
if( \is_object( $callback[ 'function' ][ 0 ] ) ) {
$class = \get_class( $callback[ 'function' ][ 0 ] );
$callback[ 'name' ] = $class . '->' . $callback[ 'function' ][ 1 ] . '()';
$ref = new \ReflectionMethod( $class, $callback[ 'function' ][ 1 ] );
}
elseif( \is_string( $callback[ 'function' ][ 0 ] ) ) {
$callback[ 'name' ] = $callback[ 'function' ][ 0 ] . '::' . $callback[ 'function' ][ 1 ];
$ref = new \ReflectionMethod( $callback[ 'function' ][ 0 ], $callback[ 'function' ][ 1 ] );
}
}
elseif( $callback[ 'function' ] instanceOf Closure ) {
$callback[ 'name' ] = 'closure';
$ref = new \ReflectionMethod( $callback[ 'function' ] );
}
elseif( \is_string( $callback[ 'function' ] ) ) {
$callback[ 'name' ] = $callback[ 'function' ] . '()';
$ref = new \ReflectionMethod( $callback[ 'name' ] );
}
else{
return;
}
$callback[ 'filename' ] = $ref->getFileName();
$this->addCallback( $callback );
} catch( \ReflectionException $e ) {
$callback['error'] = new \WP_Error( 'reflection_exception', $e->getMessage() );
}
}
}
}
}
class MonitorInit {
private static $monitor;
public static function init() {
self::$monitor = new Monitor();
\add_action( 'all', [ self::$monitor, 'monitor' ] );
\add_action( 'shutdown', [ self::$monitor, 'shutdown' ] );
}
}
\add_action( 'plugins_loaded', __NAMESPACE__ . '\MonitorInit::init', 0 );
```
The `plugins_loaded` hook is the first that's available to regular plugins. So if you want to catch hooks that are added before this, you'll need to do something tricky. |
311,100 | <p>I'm trying to create a proper 'tel:' link for phone numbers that are added in an ACF text field. So I'm just trying to strip extraneous characters, but the spaces are causing a problem.</p>
<p><strong>Existing code:</strong></p>
<pre><code>$html .= '<p itemprop="telephone" class="member-phone tel">
<a href="tel:+1'.preg_replace("/[^0-9]/","",esc_url( $member_phone )).'">'.esc_attr( $member_phone ).'</a></p>';
</code></pre>
<p>The result of this is:</p>
<p><strong>Phone number added:</strong> (323) 555-1212</p>
<p><strong>Resulting tel link:</strong> +1323205551212</p>
<p>So I'm guessing the space is interpreted as '%20', then the percentage character is stripped, leaving the extra '20'. </p>
<ul>
<li>How do I modify to strip the space properly (and/or the resulting %20)?</li>
</ul>
| [
{
"answer_id": 311104,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 0,
"selected": false,
"text": "<p>If you're trying to escape a phone number link, just using <code>esc_url()</code> with the <code>tel:</code> included should be sufficient:</p>\n\n<pre><code>esc_url( 'tel:' . $member_phone );\n</code></pre>\n"
},
{
"answer_id": 311107,
"author": "Kenny J",
"author_id": 67697,
"author_profile": "https://wordpress.stackexchange.com/users/67697",
"pm_score": 1,
"selected": false,
"text": "<p>I ended up just changing: <code>esc_url( $member_phone )</code> to <code>esc_attr( $member_phone )</code></p>\n\n<p>Not sure of any drawbacks to this, but it does work as the space is not interpreted as '%20'. </p>\n"
}
]
| 2018/08/10 | [
"https://wordpress.stackexchange.com/questions/311100",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67697/"
]
| I'm trying to create a proper 'tel:' link for phone numbers that are added in an ACF text field. So I'm just trying to strip extraneous characters, but the spaces are causing a problem.
**Existing code:**
```
$html .= '<p itemprop="telephone" class="member-phone tel">
<a href="tel:+1'.preg_replace("/[^0-9]/","",esc_url( $member_phone )).'">'.esc_attr( $member_phone ).'</a></p>';
```
The result of this is:
**Phone number added:** (323) 555-1212
**Resulting tel link:** +1323205551212
So I'm guessing the space is interpreted as '%20', then the percentage character is stripped, leaving the extra '20'.
* How do I modify to strip the space properly (and/or the resulting %20)? | I ended up just changing: `esc_url( $member_phone )` to `esc_attr( $member_phone )`
Not sure of any drawbacks to this, but it does work as the space is not interpreted as '%20'. |
311,116 | <p>i need help. My users register to the website. They type their username <strong>user_login</strong> (see chello) but the Display name (see chello04) is not the same. It has a random two digits at the end.</p>
<p>Is there a way to force Display names to be the same as usernames?</p>
<p><a href="https://i.stack.imgur.com/DiSYE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DiSYE.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/E0bpN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/E0bpN.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 311120,
"author": "Andrea Somovigo",
"author_id": 64435,
"author_profile": "https://wordpress.stackexchange.com/users/64435",
"pm_score": 0,
"selected": false,
"text": "<p>I would do with jQuery:</p>\n\n<pre><code>add_action('admin_footer','myPlugin_fixed_user_name');\n\nfunction myPlugin_fixed_user_name(){\n ob_start();\n ?>\n <script>\n jQuery(document).ready(function($){\n if( pagenow == 'profile' || pagenow == 'user-edit' ){// up to you decide wether to run on edit user ( made by admin ) also or only on personal profile \n var uName=$('#user_login').val();\n $('#display_name option[text=\"'+uName+'\"]').attr('selected','selected');\n $('#display_name').attr('disabled',true);\n }\n })\n </script>\n <?php\n echo ob_get_clean();\n }\n\n//To be 100% safe you can also run a function on user profile update:\n\nadd_action('personal_options_update', 'my_update_extra_profile_fields');\n\nfunction my_update_extra_profile_fields($user_id) {\n if ( current_user_can('edit_user',$user_id) )\n wp_update_user( array( 'ID' => $user_id, 'display_name' => $_POST['user_login'] ) );\n}\n</code></pre>\n"
},
{
"answer_id": 311125,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 3,
"selected": true,
"text": "<p>You can use the <a href=\"https://developer.wordpress.org/reference/hooks/wp_pre_insert_user_data/\" rel=\"nofollow noreferrer\"><code>wp_pre_insert_user_data</code></a> filter.</p>\n\n<pre><code>function wpse_filter_user_data( $data, $update, $id) {\n if( isset( $data[ 'user_login' ] ) ) {\n $data[ 'display_name' ] = $data[ 'user_login' ];\n return $data;\n }\n $user = get_user_by( 'email', $data[ 'user_email' ] );\n $data[ 'display_name' ] = $user->user_login;\n return $data;\n}\nadd_filter( 'wp_pre_insert_user_data', 'wpse_filter_user_data', 10, 3 );\n</code></pre>\n\n<p>You'll probably want to use Javascript and/or CSS to hide the field too for a better user experience.</p>\n\n<pre><code>$( '.user-display-name-wrap' ).remove();\n\n.user-display-name-wrap {\n display:none;\n}\n</code></pre>\n"
}
]
| 2018/08/11 | [
"https://wordpress.stackexchange.com/questions/311116",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87667/"
]
| i need help. My users register to the website. They type their username **user\_login** (see chello) but the Display name (see chello04) is not the same. It has a random two digits at the end.
Is there a way to force Display names to be the same as usernames?
[](https://i.stack.imgur.com/DiSYE.png)
[](https://i.stack.imgur.com/E0bpN.png) | You can use the [`wp_pre_insert_user_data`](https://developer.wordpress.org/reference/hooks/wp_pre_insert_user_data/) filter.
```
function wpse_filter_user_data( $data, $update, $id) {
if( isset( $data[ 'user_login' ] ) ) {
$data[ 'display_name' ] = $data[ 'user_login' ];
return $data;
}
$user = get_user_by( 'email', $data[ 'user_email' ] );
$data[ 'display_name' ] = $user->user_login;
return $data;
}
add_filter( 'wp_pre_insert_user_data', 'wpse_filter_user_data', 10, 3 );
```
You'll probably want to use Javascript and/or CSS to hide the field too for a better user experience.
```
$( '.user-display-name-wrap' ).remove();
.user-display-name-wrap {
display:none;
}
``` |
311,140 | <p>I am using WP-Crontrol and have some CRON jobs running daily to check the age of the posts. If the post is 2 days older, they will be deleted.</p>
<p>This works but for some reason, only some of the three days and older posts get deleted. There are still some that remain published.</p>
<p>It must be because there are a lot of posts on the site around 3000. Is there a way to make my CRON job more efficient?</p>
<p>Here is the current code that I have running:</p>
<pre><code>class EventsWPCron {
public function __construct() {
if ( ! wp_next_scheduled( 'trash_old_events' ) ) {
wp_schedule_event( time(), 'daily', 'trash_old_events' );
}
add_action( 'trash_old_events', array( $this, 'delete_events' ) );
}
public function delete_events() {
$args = array(
'post_type' => 'event',
'post_status' => 'publish',
'posts_per_page' => -1,
'date_query' => array(
array(
'before' => '2 days ago'
)
)
);
$query = new WP_Query( $args );
$posts = $query->get_posts();
foreach( $posts as $post ) {
wp_delete_post( $post->ID, true );
}
}
}
new EventsWPCron();
</code></pre>
| [
{
"answer_id": 311120,
"author": "Andrea Somovigo",
"author_id": 64435,
"author_profile": "https://wordpress.stackexchange.com/users/64435",
"pm_score": 0,
"selected": false,
"text": "<p>I would do with jQuery:</p>\n\n<pre><code>add_action('admin_footer','myPlugin_fixed_user_name');\n\nfunction myPlugin_fixed_user_name(){\n ob_start();\n ?>\n <script>\n jQuery(document).ready(function($){\n if( pagenow == 'profile' || pagenow == 'user-edit' ){// up to you decide wether to run on edit user ( made by admin ) also or only on personal profile \n var uName=$('#user_login').val();\n $('#display_name option[text=\"'+uName+'\"]').attr('selected','selected');\n $('#display_name').attr('disabled',true);\n }\n })\n </script>\n <?php\n echo ob_get_clean();\n }\n\n//To be 100% safe you can also run a function on user profile update:\n\nadd_action('personal_options_update', 'my_update_extra_profile_fields');\n\nfunction my_update_extra_profile_fields($user_id) {\n if ( current_user_can('edit_user',$user_id) )\n wp_update_user( array( 'ID' => $user_id, 'display_name' => $_POST['user_login'] ) );\n}\n</code></pre>\n"
},
{
"answer_id": 311125,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 3,
"selected": true,
"text": "<p>You can use the <a href=\"https://developer.wordpress.org/reference/hooks/wp_pre_insert_user_data/\" rel=\"nofollow noreferrer\"><code>wp_pre_insert_user_data</code></a> filter.</p>\n\n<pre><code>function wpse_filter_user_data( $data, $update, $id) {\n if( isset( $data[ 'user_login' ] ) ) {\n $data[ 'display_name' ] = $data[ 'user_login' ];\n return $data;\n }\n $user = get_user_by( 'email', $data[ 'user_email' ] );\n $data[ 'display_name' ] = $user->user_login;\n return $data;\n}\nadd_filter( 'wp_pre_insert_user_data', 'wpse_filter_user_data', 10, 3 );\n</code></pre>\n\n<p>You'll probably want to use Javascript and/or CSS to hide the field too for a better user experience.</p>\n\n<pre><code>$( '.user-display-name-wrap' ).remove();\n\n.user-display-name-wrap {\n display:none;\n}\n</code></pre>\n"
}
]
| 2018/08/11 | [
"https://wordpress.stackexchange.com/questions/311140",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/139899/"
]
| I am using WP-Crontrol and have some CRON jobs running daily to check the age of the posts. If the post is 2 days older, they will be deleted.
This works but for some reason, only some of the three days and older posts get deleted. There are still some that remain published.
It must be because there are a lot of posts on the site around 3000. Is there a way to make my CRON job more efficient?
Here is the current code that I have running:
```
class EventsWPCron {
public function __construct() {
if ( ! wp_next_scheduled( 'trash_old_events' ) ) {
wp_schedule_event( time(), 'daily', 'trash_old_events' );
}
add_action( 'trash_old_events', array( $this, 'delete_events' ) );
}
public function delete_events() {
$args = array(
'post_type' => 'event',
'post_status' => 'publish',
'posts_per_page' => -1,
'date_query' => array(
array(
'before' => '2 days ago'
)
)
);
$query = new WP_Query( $args );
$posts = $query->get_posts();
foreach( $posts as $post ) {
wp_delete_post( $post->ID, true );
}
}
}
new EventsWPCron();
``` | You can use the [`wp_pre_insert_user_data`](https://developer.wordpress.org/reference/hooks/wp_pre_insert_user_data/) filter.
```
function wpse_filter_user_data( $data, $update, $id) {
if( isset( $data[ 'user_login' ] ) ) {
$data[ 'display_name' ] = $data[ 'user_login' ];
return $data;
}
$user = get_user_by( 'email', $data[ 'user_email' ] );
$data[ 'display_name' ] = $user->user_login;
return $data;
}
add_filter( 'wp_pre_insert_user_data', 'wpse_filter_user_data', 10, 3 );
```
You'll probably want to use Javascript and/or CSS to hide the field too for a better user experience.
```
$( '.user-display-name-wrap' ).remove();
.user-display-name-wrap {
display:none;
}
``` |
311,154 | <p>Hello i have problem. </p>
<p>I can't view /blog/page/2/ i klick "_posts_link" and error 404 shows me</p>
<p>Blog Page -> home.php</p>
<pre><code> <?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array('posts_per_page' => 5, 'paged' => $currentPage);
query_posts($args);
if( have_posts() ): $i = 0;
while( have_posts() ): the_post(); ?>
</code></pre>
<hr>
<pre><code> <?php $i++; endwhile; ?>
<ul class="uk-pagination uk-background-primary uk-light">
<li><?php next_posts_link('<span class="uk-margin-small-right" uk-pagination-previous></span> Stare Posty'); ?></li>
<li class="uk-margin-auto-left"><?php previous_posts_link('Nowe posty <span class="uk-margin-small-left" uk-pagination-next>'); ?></li>
</ul>
<?php endif;
wp_reset_query();
?>
</code></pre>
| [
{
"answer_id": 311187,
"author": "Max",
"author_id": 115933,
"author_profile": "https://wordpress.stackexchange.com/users/115933",
"pm_score": -1,
"selected": false,
"text": "<p>Use this for pagination</p>\n\n<pre><code><?php\n$paged = ( get_query_var( 'page' ) ) ? absint( get_query_var( 'page' ) ) : 1;\n$content_args=array(\n 'post_type' => 'post',\n 'orderby' => 'meta_value_num',\n 'paged' => $paged,\n 'posts_per_page' => '5',\n );\n $wp_query = new WP_Query($content_args);\n while ($wp_query->have_posts()): $wp_query->the_post();?>\n\n //content here\n\n <?php endwhile;?>\n</code></pre>\n\n<p>Pagination</p>\n\n<pre><code><?php\nglobal $wp_query;\n$big = 999999999; // need an unlikely integer\necho paginate_links( array(\n 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) \n),\n 'format' => '?paged=%#%',\n 'current' => max( 1, get_query_var('paged') ),\n 'total' => $wp_query->max_num_pages\n) );?>\n</code></pre>\n"
},
{
"answer_id": 311337,
"author": "WPZA",
"author_id": 146181,
"author_profile": "https://wordpress.stackexchange.com/users/146181",
"pm_score": 0,
"selected": false,
"text": "<p>I guess you don't need to target a taxonomy. You can use the code below:</p>\n\n<pre><code>function query_change_function( $query ) {\n $query->set( 'posts_per_page', 5 );\n}\nadd_action('pre_get_posts', 'query_change_function');\n</code></pre>\n\n<p>You should wrap the <code>$query->set( 'posts_per_page', 5 );</code> around with <code>if ( ! is_admin() && is_home() ) {//the $query->set code}\n</code> to avoid it changing to 5-posts everywhere.</p>\n"
}
]
| 2018/08/11 | [
"https://wordpress.stackexchange.com/questions/311154",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/148538/"
]
| Hello i have problem.
I can't view /blog/page/2/ i klick "\_posts\_link" and error 404 shows me
Blog Page -> home.php
```
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array('posts_per_page' => 5, 'paged' => $currentPage);
query_posts($args);
if( have_posts() ): $i = 0;
while( have_posts() ): the_post(); ?>
```
---
```
<?php $i++; endwhile; ?>
<ul class="uk-pagination uk-background-primary uk-light">
<li><?php next_posts_link('<span class="uk-margin-small-right" uk-pagination-previous></span> Stare Posty'); ?></li>
<li class="uk-margin-auto-left"><?php previous_posts_link('Nowe posty <span class="uk-margin-small-left" uk-pagination-next>'); ?></li>
</ul>
<?php endif;
wp_reset_query();
?>
``` | I guess you don't need to target a taxonomy. You can use the code below:
```
function query_change_function( $query ) {
$query->set( 'posts_per_page', 5 );
}
add_action('pre_get_posts', 'query_change_function');
```
You should wrap the `$query->set( 'posts_per_page', 5 );` around with `if ( ! is_admin() && is_home() ) {//the $query->set code}` to avoid it changing to 5-posts everywhere. |
311,157 | <p>I have serialized post meta values. It looks like this:</p>
<p><a href="https://i.stack.imgur.com/3Aau0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3Aau0.png" alt="enter image description here"></a></p>
<p>In array:</p>
<pre><code>$kisiArray = array(
'option1' => 7,
'option2' => 'bar',
'option3' => 'apple',
'option4' => 'orange'
);
</code></pre>
<p>And I want to make a custom query with <strong>meta_query</strong> args. This is my query args:</p>
<pre><code><?php
$args = array(
'order' => 'DESC',
'meta_query' => array(
array(
'key' => 'themeOps_option1',
'value' => 6,
'compare' => '>=',
)
)
);
?>
</code></pre>
<p>But it doesn't display any result.</p>
| [
{
"answer_id": 311216,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 3,
"selected": true,
"text": "<h2>serialised array in a meta_value for query</h2>\n\n<p>It's not a good idea to save serialised array in a <code>meta_value</code> if you plan to query with any value within that serialized array later. So, the best option is to save meta data as key / value pair.</p>\n\n<h2>Query Serialized array</h2>\n\n<p>Although it's not a good approach, it's still possible to query a serialized array within <code>meta_value</code> using <strong>regular expression</strong>.</p>\n\n<blockquote>\n <p><strong><em>Warning:</em></strong> Performance wise this is not a good idea at all. So if you have any other way to achieve the same thing, better do that. I'm giving the answer only to show that it's possible. So use it <strong>only as a last resort</strong>.</p>\n</blockquote>\n\n<p>Example CODE:</p>\n\n<pre><code>// this array is serialized and saved in meta_value for meta_key 'themeOps'\n$serializedArray = array(\n 'option1' => 7,\n 'option2' => 'bar',\n 'option3' => 'apple',\n 'option4' => 'orange'\n);\n\n// this is the WP_Query argument\n$args = array(\n 'meta_query' => array(\n array(\n 'key' => 'themeOps',\n // this compares if 'option1' >= 6 within the serialized array in meta_value\n 'value' => wpse311157_serialize_num_greater_equals_regex( 'option1', 6 ),\n 'compare' => 'REGEXP',\n )\n )\n);\n</code></pre>\n\n<p>As you can see, I've used <code>'compare' => 'REGEXP'</code> and used the function <code>wpse311157_serialize_num_greater_equals_regex( 'option1', 6 )</code> to generate the proper regular expression (first param is the name of the array <code>key</code> and the second param is the number to compare with <code>>=</code>).</p>\n\n<p>Now, let's implement the <code>wpse311157_serialize_num_greater_equals_regex</code> function. Since <code>meta_value</code> is a serialized array, it'll look something like: <code>a:1:{s:3:\"key\";i:7;}</code>. To match that, our CODE will look like:</p>\n\n<pre><code>function wpse311157_serialize_num_greater_equals_regex( $key, $num ) { \n return 'a\\:[1-9][0-9]*\\:\\{.*' . preg_quote( serialize( $key ) ) . 'i\\:(' . wpse311157_num_greater_equals_regex( $num ) . ');.*\\}';\n}\n</code></pre>\n\n<p>Now we need to implement the <code>wpse311157_num_greater_equals_regex( $num )</code> function by converting <code>>=</code> comparison into regular expression. This is <strong>not very efficient</strong>, but this is the only option we have.</p>\n\n<h2>RegEx algorithm to compare <code>>=</code></h2>\n\n<p>The algorithm is simple:</p>\n\n<p>(A) For any <code>n</code> digit number, any number with <code>(n+1)</code> digits is greater than that number.</p>\n\n<p>(B) Additionally, we need maximum <code>n</code> number of rules to check other <code>n</code> digit numbers that are greater than or equal to this number.</p>\n\n<p>For example, say we want to compare: <code>num >= 12</code></p>\n\n<p>So, RegEx: <code>[1-9][0-9][0-9]+</code> will always satisfy it, as it'll match 3 or more digit numbers.</p>\n\n<p>Now, to match 2 digit numbers that are <code>>=</code> 12, we need 2 rules:</p>\n\n<ol>\n<li><code>1[2-9]</code> => this will match numbers: 12 to 19</li>\n<li><code>[2-9][0-9]</code> => this will match numbers: 20 to 99</li>\n</ol>\n\n<p>So the final RegEx for <code>num >= 12</code> is: <a href=\"https://regex101.com/r/oGgXtP/1\" rel=\"nofollow noreferrer\"><code>1[2-9]|[2-9][0-9]|[1-9][0-9][0-9]+</code></a></p>\n\n<p>With this algorithm, let's create our <code>wpse311157_num_greater_equals_regex( $num )</code> function:</p>\n\n<pre><code>function wpse311157_num_greater_equals_regex( $num ) {\n $digits = wpse311157_num_digits( $num );\n $num_i = $num;\n $regex = ''; \n for( $i = 1; $i <= $digits; $i++ ) { \n $digit = $num_i % 10; \n $num_i = (int) ( $num_i / 10 );\n $regex_i = ''; \n $need_rule = true;\n if( 1 === $i ) { \n if( 9 === $digit ) { \n $regex_i = '9';\n } \n else {\n $regex_i = '[' . $digit . '-9]';\n } \n } \n else {\n // no rule for 9\n if( 9 === $digit ) { \n $need_rule = false;\n }\n else if( 8 === $digit ) {\n $regex_i = '9';\n }\n else {\n $regex_i = '[' . ( $digit + 1 ) . '-9]';\n }\n }\n\n if( $need_rule ) {\n if( $i < $digits ) {\n $regex_i = $num_i . $regex_i;\n }\n\n for( $j = 1; $j < $i; $j++ ) {\n $regex_i = $regex_i . '[0-9]';\n }\n\n if( empty( $regex ) ) {\n $regex = $regex_i;\n }\n else {\n $regex = $regex . '|' . $regex_i;\n }\n }\n }\n\n $regex = $regex . '|[1-9]';\n for( $i = 1; $i < $digits; $i++ ) {\n $regex = $regex . '[0-9]';\n }\n $regex = $regex . '[0-9]+';\n\n return $regex;\n}\n\nfunction wpse311157_num_digits( $num ) { \n // not considering 0 or negative numbers\n if( $num < 1 ) return -1; \n\n return floor( log10( $num ) + 1 );\n}\n</code></pre>\n\n<p>That's all, now you'll be able to compare a value with <code>>=</code> within a serialized array.</p>\n"
},
{
"answer_id": 368243,
"author": "Nic Bug",
"author_id": 144969,
"author_profile": "https://wordpress.stackexchange.com/users/144969",
"pm_score": 0,
"selected": false,
"text": "<p>Outstanding answer from @Fayaz! Thank you!\nI took the Code and changed it to match the size (count) of a serialized array which is at the beginning of the serialized string like \"a:4\" = 4 entries in the array. This is what i came up with:</p>\n\n<pre><code>'meta_query' => array(\n 'user_sets' => array(\n 'key' => 'user_sets',\n 'value' => serialize_num_greater_equals_regex( $_GET['sets'] ),\n 'compare' => 'REGEXP'\n\n )\n)\n</code></pre>\n\n<p>and a simplified function:</p>\n\n<pre><code>function serialize_num_greater_equals_regex( $num ) {\n return 'a\\:(' . num_greater_equals_regex( $num ) . ')\\:\\{s.*';\n}\n</code></pre>\n\n<p>So now you can filter the results by the size of the array! \nBy the way i use the method with \"<strong>users_list_table_query_args</strong>\" hook which is used by <strong>WP_User_Query</strong> class! With the hook you can alter the users.php output.</p>\n"
}
]
| 2018/08/11 | [
"https://wordpress.stackexchange.com/questions/311157",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133897/"
]
| I have serialized post meta values. It looks like this:
[](https://i.stack.imgur.com/3Aau0.png)
In array:
```
$kisiArray = array(
'option1' => 7,
'option2' => 'bar',
'option3' => 'apple',
'option4' => 'orange'
);
```
And I want to make a custom query with **meta\_query** args. This is my query args:
```
<?php
$args = array(
'order' => 'DESC',
'meta_query' => array(
array(
'key' => 'themeOps_option1',
'value' => 6,
'compare' => '>=',
)
)
);
?>
```
But it doesn't display any result. | serialised array in a meta\_value for query
-------------------------------------------
It's not a good idea to save serialised array in a `meta_value` if you plan to query with any value within that serialized array later. So, the best option is to save meta data as key / value pair.
Query Serialized array
----------------------
Although it's not a good approach, it's still possible to query a serialized array within `meta_value` using **regular expression**.
>
> ***Warning:*** Performance wise this is not a good idea at all. So if you have any other way to achieve the same thing, better do that. I'm giving the answer only to show that it's possible. So use it **only as a last resort**.
>
>
>
Example CODE:
```
// this array is serialized and saved in meta_value for meta_key 'themeOps'
$serializedArray = array(
'option1' => 7,
'option2' => 'bar',
'option3' => 'apple',
'option4' => 'orange'
);
// this is the WP_Query argument
$args = array(
'meta_query' => array(
array(
'key' => 'themeOps',
// this compares if 'option1' >= 6 within the serialized array in meta_value
'value' => wpse311157_serialize_num_greater_equals_regex( 'option1', 6 ),
'compare' => 'REGEXP',
)
)
);
```
As you can see, I've used `'compare' => 'REGEXP'` and used the function `wpse311157_serialize_num_greater_equals_regex( 'option1', 6 )` to generate the proper regular expression (first param is the name of the array `key` and the second param is the number to compare with `>=`).
Now, let's implement the `wpse311157_serialize_num_greater_equals_regex` function. Since `meta_value` is a serialized array, it'll look something like: `a:1:{s:3:"key";i:7;}`. To match that, our CODE will look like:
```
function wpse311157_serialize_num_greater_equals_regex( $key, $num ) {
return 'a\:[1-9][0-9]*\:\{.*' . preg_quote( serialize( $key ) ) . 'i\:(' . wpse311157_num_greater_equals_regex( $num ) . ');.*\}';
}
```
Now we need to implement the `wpse311157_num_greater_equals_regex( $num )` function by converting `>=` comparison into regular expression. This is **not very efficient**, but this is the only option we have.
RegEx algorithm to compare `>=`
-------------------------------
The algorithm is simple:
(A) For any `n` digit number, any number with `(n+1)` digits is greater than that number.
(B) Additionally, we need maximum `n` number of rules to check other `n` digit numbers that are greater than or equal to this number.
For example, say we want to compare: `num >= 12`
So, RegEx: `[1-9][0-9][0-9]+` will always satisfy it, as it'll match 3 or more digit numbers.
Now, to match 2 digit numbers that are `>=` 12, we need 2 rules:
1. `1[2-9]` => this will match numbers: 12 to 19
2. `[2-9][0-9]` => this will match numbers: 20 to 99
So the final RegEx for `num >= 12` is: [`1[2-9]|[2-9][0-9]|[1-9][0-9][0-9]+`](https://regex101.com/r/oGgXtP/1)
With this algorithm, let's create our `wpse311157_num_greater_equals_regex( $num )` function:
```
function wpse311157_num_greater_equals_regex( $num ) {
$digits = wpse311157_num_digits( $num );
$num_i = $num;
$regex = '';
for( $i = 1; $i <= $digits; $i++ ) {
$digit = $num_i % 10;
$num_i = (int) ( $num_i / 10 );
$regex_i = '';
$need_rule = true;
if( 1 === $i ) {
if( 9 === $digit ) {
$regex_i = '9';
}
else {
$regex_i = '[' . $digit . '-9]';
}
}
else {
// no rule for 9
if( 9 === $digit ) {
$need_rule = false;
}
else if( 8 === $digit ) {
$regex_i = '9';
}
else {
$regex_i = '[' . ( $digit + 1 ) . '-9]';
}
}
if( $need_rule ) {
if( $i < $digits ) {
$regex_i = $num_i . $regex_i;
}
for( $j = 1; $j < $i; $j++ ) {
$regex_i = $regex_i . '[0-9]';
}
if( empty( $regex ) ) {
$regex = $regex_i;
}
else {
$regex = $regex . '|' . $regex_i;
}
}
}
$regex = $regex . '|[1-9]';
for( $i = 1; $i < $digits; $i++ ) {
$regex = $regex . '[0-9]';
}
$regex = $regex . '[0-9]+';
return $regex;
}
function wpse311157_num_digits( $num ) {
// not considering 0 or negative numbers
if( $num < 1 ) return -1;
return floor( log10( $num ) + 1 );
}
```
That's all, now you'll be able to compare a value with `>=` within a serialized array. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.