qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
sequence | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
340,919 | <p>I am learning wordpress by my own and this is the code of html template.</p>
<pre><code> <div class="collapse navbar-collapse" id="ftco-nav">
<ul class="navbar-nav ml-auto">
<li class="nav-item active"><a href="index.html" class="nav-link">Home</a></li>
<li class="nav-item"><a href="about.html" class="nav-link">Who we are</a></li>
<li class="nav-item"><a href="causes.html" class="nav-link">Causes</a></li>
<li class="nav-item"><a href="blog.html" class="nav-link">Stories</a></li>
<li class="nav-item"><a href="contact.html" class="nav-link">Contact</a></li>
</ul>
</div>
</code></pre>
<p>I want to convert it into wordpress. I converted it into wordpress by adding this code:-</p>
<pre><code><?php wp_nav_menu(array( 'menu' => 'primary', 'container' => 'div', 'container_class' => 'collapse navbar-collapse', 'container_id' => 'ftco-nav', 'menu_class' => 'navbar-nav ml-auto', 'menu_id' => '', ));?>
</code></pre>
<p>but the problem is that how will I apply active class to it? please someone help me in this.</p>
| [
{
"answer_id": 340920,
"author": "MikeNGarrett",
"author_id": 1670,
"author_profile": "https://wordpress.stackexchange.com/users/1670",
"pm_score": 1,
"selected": false,
"text": "<p>Change your active class name in your css. WordPress adds the following active classes, depending on the context of the active state:</p>\n\n<p><code>current-menu-item</code>, <code>current-menu-ancestor</code>, <code>current-menu-parent</code>, and <code>current-page-ancestor</code></p>\n"
},
{
"answer_id": 340932,
"author": "Chetan Vaghela",
"author_id": 169856,
"author_profile": "https://wordpress.stackexchange.com/users/169856",
"pm_score": 0,
"selected": false,
"text": "<p>May be this can helps you. add in functions.php</p>\n\n<pre><code>function add_active_class_to_menu_item($classes, $item) {\n if (in_array('current-menu-item', $classes) ){\n $classes[] = 'active ';\n }\n return $classes;\n}\nadd_filter('nav_menu_css_class' , 'add_active_class_to_menu_item' , 10 , 2);\n</code></pre>\n"
}
] | 2019/06/19 | [
"https://wordpress.stackexchange.com/questions/340919",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/170301/"
] | I am learning wordpress by my own and this is the code of html template.
```
<div class="collapse navbar-collapse" id="ftco-nav">
<ul class="navbar-nav ml-auto">
<li class="nav-item active"><a href="index.html" class="nav-link">Home</a></li>
<li class="nav-item"><a href="about.html" class="nav-link">Who we are</a></li>
<li class="nav-item"><a href="causes.html" class="nav-link">Causes</a></li>
<li class="nav-item"><a href="blog.html" class="nav-link">Stories</a></li>
<li class="nav-item"><a href="contact.html" class="nav-link">Contact</a></li>
</ul>
</div>
```
I want to convert it into wordpress. I converted it into wordpress by adding this code:-
```
<?php wp_nav_menu(array( 'menu' => 'primary', 'container' => 'div', 'container_class' => 'collapse navbar-collapse', 'container_id' => 'ftco-nav', 'menu_class' => 'navbar-nav ml-auto', 'menu_id' => '', ));?>
```
but the problem is that how will I apply active class to it? please someone help me in this. | Change your active class name in your css. WordPress adds the following active classes, depending on the context of the active state:
`current-menu-item`, `current-menu-ancestor`, `current-menu-parent`, and `current-page-ancestor` |
340,969 | <p>I know that this has been frequently asked here, but none of the solutions I find seem to work for me.</p>
<p>The issue is as follows: whenever I post the form, I have a console log with the response which is a full html page rather than a simple message.</p>
<p>Backend script:</p>
<pre><code> add_action( 'admin_ajax_nopriv_email_verification_form', 'verify_and_sanitize_email_form' );
add_action( 'admin_ajax_email_verification_form', 'verify_and_sanitize_email_form' );
// Email verification callback
function verify_and_sanitize_email_form() {
// Check referer
check_ajax_referer( '9pU0Pk7T01', 'security' );
if(empty($_POST) || !isset($_POST['rguroo_email']) || !isset($_POST['rguroo_email_confirmation']) || !isset($_POST['rguroo_desired_action'])) {
echo 'There is one or more empty fields';
wp_die();
}
$sanitized_email = sanitize_email( esc_html($_POST['rguroo_email'] ));
$sanitized_email_confirmation = sanitize_email( esc_html($_POST['rguroo_email_confirmation'] ));
$desired_action = esc_html($_POST['rguroo_desired_action']);
if(!is_email( $sanitized_email ) || !is_email( $sanitized_email_confirmation )) {
echo 'Email is not valid';
wp_die();
}
if($sanitized_email !== $sanitized_email_confirmation) {
echo 'Emails do not match';
wp_die();
}
if($desired_action !== 'purchase' || $desired_action !== 'renewal' || $desired_action !== 'trial') {
echo 'Fatal error with radio buttons';
wp_die();
}
if(!isset($_COOKIE['rguroo_form_type'])) {
echo 'Server error';
wp_die();
}
// student email verification logic
$form_type = $_COOKIE['rguroo_form_type'];
if($form_type === 'student') {
$trail = substr($sanitized_email, -4);
if($trail !== '.edu') {
echo 'Not a valid student email';
wp_die();
}
// Other university specific logic here
}
setcookie('rguroo_form_action',$desired_action, 14 * DAY_IN_SECONDS);
setcookie('rguroo_form_email', $sanitized_email, 14 * DAY_IN_SECONDS);
echo "success";
wp_die();
}
</code></pre>
<p>Frontend javascript:</p>
<pre><code>jQuery(document).ready(function () {
jQuery('form#email-verification').on( 'submit', function () {
var form_data = jQuery(this).serializeArray();
form_data.push( { "name" : "security", "value" : ajax_info.ajax_nonce } );
jQuery.ajax({
url : ajax_info.ajax_url,
type : 'post',
data : form_data,
success : function( response ) {
console.log(response);
if(response !== 'success') {
jQuery('.error').innerHTML = response;
} else {
location.reload();
}
},
fail : function( err ) {
jQuery('.error').innerHTML = "Cannot contact server";
}
});
return false;
});
});
</code></pre>
<p>Form (used in a shortcode):</p>
<pre><code>function output_email_verification() {
return '<form action="'.esc_url( admin_url("admin-ajax.php") ).'" method="post" id="email-verification">
<p class="error">'.$error.'</p>
<input type="radio" label="Purchase 12 months access" value="purchase" name="rguroo_desired_action" checked>Purchase 12 months access</input>
<input type="radio" label="Renew account" name="rguroo_desired_action" value="renewal">Renew account</input>
<input type="radio" label="Create trial account" name="rguroo_desired_action" value="trial">Create trial account</input>
<p class="form-subtext">* indicates required field</p>
<p>Email address*</p>
<input type="text" name="rguroo_email" required>
<p>Re-type email address*</p>
<input type="text" name="rguroo_email_confirmation" required>
<input type="hidden" name="action" value="email_verification_form">
<input type="submit" value="Submit">
</form>';
}
</code></pre>
<p>Things I know: there isn't an issue with jQuery sending the post (or at least making the post request). On submit jQuery sends the post with all of the correct parameters. I also know that I'm not using different nonces. I have tried placing error_logs() all around the callback function, but none of them ever got displayed in debug.log. This leads me to believe that the callback is never actually called, but I don't know why. Also, even if I give the form a test which should fail, jQuery still reads it as a success.</p>
<p>I've wasted all day on this form and feel like an idiot. Could someone with a few more braincells than me please tell me where I'm going wrong?</p>
<p>Thank you so much.</p>
| [
{
"answer_id": 340920,
"author": "MikeNGarrett",
"author_id": 1670,
"author_profile": "https://wordpress.stackexchange.com/users/1670",
"pm_score": 1,
"selected": false,
"text": "<p>Change your active class name in your css. WordPress adds the following active classes, depending on the context of the active state:</p>\n\n<p><code>current-menu-item</code>, <code>current-menu-ancestor</code>, <code>current-menu-parent</code>, and <code>current-page-ancestor</code></p>\n"
},
{
"answer_id": 340932,
"author": "Chetan Vaghela",
"author_id": 169856,
"author_profile": "https://wordpress.stackexchange.com/users/169856",
"pm_score": 0,
"selected": false,
"text": "<p>May be this can helps you. add in functions.php</p>\n\n<pre><code>function add_active_class_to_menu_item($classes, $item) {\n if (in_array('current-menu-item', $classes) ){\n $classes[] = 'active ';\n }\n return $classes;\n}\nadd_filter('nav_menu_css_class' , 'add_active_class_to_menu_item' , 10 , 2);\n</code></pre>\n"
}
] | 2019/06/19 | [
"https://wordpress.stackexchange.com/questions/340969",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/153230/"
] | I know that this has been frequently asked here, but none of the solutions I find seem to work for me.
The issue is as follows: whenever I post the form, I have a console log with the response which is a full html page rather than a simple message.
Backend script:
```
add_action( 'admin_ajax_nopriv_email_verification_form', 'verify_and_sanitize_email_form' );
add_action( 'admin_ajax_email_verification_form', 'verify_and_sanitize_email_form' );
// Email verification callback
function verify_and_sanitize_email_form() {
// Check referer
check_ajax_referer( '9pU0Pk7T01', 'security' );
if(empty($_POST) || !isset($_POST['rguroo_email']) || !isset($_POST['rguroo_email_confirmation']) || !isset($_POST['rguroo_desired_action'])) {
echo 'There is one or more empty fields';
wp_die();
}
$sanitized_email = sanitize_email( esc_html($_POST['rguroo_email'] ));
$sanitized_email_confirmation = sanitize_email( esc_html($_POST['rguroo_email_confirmation'] ));
$desired_action = esc_html($_POST['rguroo_desired_action']);
if(!is_email( $sanitized_email ) || !is_email( $sanitized_email_confirmation )) {
echo 'Email is not valid';
wp_die();
}
if($sanitized_email !== $sanitized_email_confirmation) {
echo 'Emails do not match';
wp_die();
}
if($desired_action !== 'purchase' || $desired_action !== 'renewal' || $desired_action !== 'trial') {
echo 'Fatal error with radio buttons';
wp_die();
}
if(!isset($_COOKIE['rguroo_form_type'])) {
echo 'Server error';
wp_die();
}
// student email verification logic
$form_type = $_COOKIE['rguroo_form_type'];
if($form_type === 'student') {
$trail = substr($sanitized_email, -4);
if($trail !== '.edu') {
echo 'Not a valid student email';
wp_die();
}
// Other university specific logic here
}
setcookie('rguroo_form_action',$desired_action, 14 * DAY_IN_SECONDS);
setcookie('rguroo_form_email', $sanitized_email, 14 * DAY_IN_SECONDS);
echo "success";
wp_die();
}
```
Frontend javascript:
```
jQuery(document).ready(function () {
jQuery('form#email-verification').on( 'submit', function () {
var form_data = jQuery(this).serializeArray();
form_data.push( { "name" : "security", "value" : ajax_info.ajax_nonce } );
jQuery.ajax({
url : ajax_info.ajax_url,
type : 'post',
data : form_data,
success : function( response ) {
console.log(response);
if(response !== 'success') {
jQuery('.error').innerHTML = response;
} else {
location.reload();
}
},
fail : function( err ) {
jQuery('.error').innerHTML = "Cannot contact server";
}
});
return false;
});
});
```
Form (used in a shortcode):
```
function output_email_verification() {
return '<form action="'.esc_url( admin_url("admin-ajax.php") ).'" method="post" id="email-verification">
<p class="error">'.$error.'</p>
<input type="radio" label="Purchase 12 months access" value="purchase" name="rguroo_desired_action" checked>Purchase 12 months access</input>
<input type="radio" label="Renew account" name="rguroo_desired_action" value="renewal">Renew account</input>
<input type="radio" label="Create trial account" name="rguroo_desired_action" value="trial">Create trial account</input>
<p class="form-subtext">* indicates required field</p>
<p>Email address*</p>
<input type="text" name="rguroo_email" required>
<p>Re-type email address*</p>
<input type="text" name="rguroo_email_confirmation" required>
<input type="hidden" name="action" value="email_verification_form">
<input type="submit" value="Submit">
</form>';
}
```
Things I know: there isn't an issue with jQuery sending the post (or at least making the post request). On submit jQuery sends the post with all of the correct parameters. I also know that I'm not using different nonces. I have tried placing error\_logs() all around the callback function, but none of them ever got displayed in debug.log. This leads me to believe that the callback is never actually called, but I don't know why. Also, even if I give the form a test which should fail, jQuery still reads it as a success.
I've wasted all day on this form and feel like an idiot. Could someone with a few more braincells than me please tell me where I'm going wrong?
Thank you so much. | Change your active class name in your css. WordPress adds the following active classes, depending on the context of the active state:
`current-menu-item`, `current-menu-ancestor`, `current-menu-parent`, and `current-page-ancestor` |
340,976 | <p>I'm calling an api with <code>wp_remote_get</code> and I can't seem to parse the results. </p>
<p>Here is how I call the api:</p>
<pre><code> $url = 'https://blah/api/data/';
$args = array(
'headers' => array(
'Authorization' => 'Token ' . $my_token,
),
);
$data = wp_remote_get($url, $args);
$data = json_encode($data);
</code></pre>
<p>The API response looks something like this:</p>
<pre><code>`{
"headers": {},
"body": "[{\"name\":\"bob\",\"email\":\"[email protected]\",\"first_name\":\"Bob\",\"last_name\":\"Bob\"}]"
"response": {
"code": 200,
"message": "OK"
},
"cookies": [],
"filename": null,
"http_response": {
"data": null,
"headers": null,
"status": null
}
}`
</code></pre>
<p>Now, I want loop through the body, which has data I would like to store. When I try this:</p>
<pre><code>foreach($data["body"] as $datapoint){
//blah
}
</code></pre>
<p>I get the following error: <code>PHP Warning: Illegal string offset 'body'</code> and I am unable to loop through the data. I can't' seem to figure it out, shouldn't using json_encode allow me to treat the response as a json object? </p>
<p>Any help is appreciated! Thank you</p>
| [
{
"answer_id": 340920,
"author": "MikeNGarrett",
"author_id": 1670,
"author_profile": "https://wordpress.stackexchange.com/users/1670",
"pm_score": 1,
"selected": false,
"text": "<p>Change your active class name in your css. WordPress adds the following active classes, depending on the context of the active state:</p>\n\n<p><code>current-menu-item</code>, <code>current-menu-ancestor</code>, <code>current-menu-parent</code>, and <code>current-page-ancestor</code></p>\n"
},
{
"answer_id": 340932,
"author": "Chetan Vaghela",
"author_id": 169856,
"author_profile": "https://wordpress.stackexchange.com/users/169856",
"pm_score": 0,
"selected": false,
"text": "<p>May be this can helps you. add in functions.php</p>\n\n<pre><code>function add_active_class_to_menu_item($classes, $item) {\n if (in_array('current-menu-item', $classes) ){\n $classes[] = 'active ';\n }\n return $classes;\n}\nadd_filter('nav_menu_css_class' , 'add_active_class_to_menu_item' , 10 , 2);\n</code></pre>\n"
}
] | 2019/06/20 | [
"https://wordpress.stackexchange.com/questions/340976",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147485/"
] | I'm calling an api with `wp_remote_get` and I can't seem to parse the results.
Here is how I call the api:
```
$url = 'https://blah/api/data/';
$args = array(
'headers' => array(
'Authorization' => 'Token ' . $my_token,
),
);
$data = wp_remote_get($url, $args);
$data = json_encode($data);
```
The API response looks something like this:
```
`{
"headers": {},
"body": "[{\"name\":\"bob\",\"email\":\"[email protected]\",\"first_name\":\"Bob\",\"last_name\":\"Bob\"}]"
"response": {
"code": 200,
"message": "OK"
},
"cookies": [],
"filename": null,
"http_response": {
"data": null,
"headers": null,
"status": null
}
}`
```
Now, I want loop through the body, which has data I would like to store. When I try this:
```
foreach($data["body"] as $datapoint){
//blah
}
```
I get the following error: `PHP Warning: Illegal string offset 'body'` and I am unable to loop through the data. I can't' seem to figure it out, shouldn't using json\_encode allow me to treat the response as a json object?
Any help is appreciated! Thank you | Change your active class name in your css. WordPress adds the following active classes, depending on the context of the active state:
`current-menu-item`, `current-menu-ancestor`, `current-menu-parent`, and `current-page-ancestor` |
341,002 | <p>I have in my code the following variable to call the title of the categories.</p>
<pre><code><?php
$categories = get_the_terms($custom_args->ID, 'veranstaltungen-category');
foreach ($categories as $category) {
$cats .= $category->name . ', ';
echo rtrim($cats, ', ');
}
?>
</code></pre>
<p>The problem is that in the last post of the loop I duplicated the categories and printed them all.
<a href="https://i.stack.imgur.com/2wYQL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2wYQL.png" alt="enter image description here"></a></p>
<p>in fact it is printed by post from less to more.
If I use the following code fragment, I print it well but without commas</p>
<pre><code>foreach ($categories as $category) {
echo '<span>'.$category->name .'</span>';
}
</code></pre>
<p>If someone would be so kind to guide me I would be very grateful, this brings me</p>
| [
{
"answer_id": 341005,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>In this line:</p>\n\n<pre><code>$cats .= $category->name . ', ';\n</code></pre>\n\n<p>You append a name of category to variable called $cats.</p>\n\n<p>But you never reset this variable. So every post appends its categories to the same variable.</p>\n\n<p>So here’s how to fix this:</p>\n\n<pre><code><?php\n $categories = get_the_terms($custom_args->ID, 'veranstaltungen-category');\n $cats = ''; // set empty string as value\n\n foreach ($categories as $category) {\n $cats .= $category->name . ', ';\n echo rtrim($cats, ', ');\n }\n?>\n</code></pre>\n\n<p>Of course you can also add commas to your second code:</p>\n\n<pre><code>foreach ($categories as $i => $category) {\n if ( $i ) echo ', ';\n echo '<span>'.$category->name .'</span>';\n}\n</code></pre>\n"
},
{
"answer_id": 341010,
"author": "Parthavi Patel",
"author_id": 110795,
"author_profile": "https://wordpress.stackexchange.com/users/110795",
"pm_score": 0,
"selected": false,
"text": "<p>You can add comma this way </p>\n\n<pre><code><?php \n$post_cat = get_the_terms( $custom_args->ID, 'veranstaltungen-category' );\n\n$result_pro_cat = \"\";\n\nforeach ( $post_cat as $post_cat_key => $post_cat_value ) {\n $result_pro_cat .= '<a href=\"' . esc_url( get_category_link( $post_cat_value->term_id ) ) . '\">' . $post_cat_value->name . '</a>' . ', '; \n} \necho rtrim( $result_pro_cat, ', ' );\n</code></pre>\n"
},
{
"answer_id": 341015,
"author": "Chetan Vaghela",
"author_id": 169856,
"author_profile": "https://wordpress.stackexchange.com/users/169856",
"pm_score": 0,
"selected": false,
"text": "<p>You have to just define $cats null variable, so every time it reset the cat value null. and echo $cats out side of foreach loop. that's it.</p>\n\n<pre><code> $categories = get_the_terms($custom_args->ID, 'veranstaltungen-category');\n #define blank \n $cats = \"\";\n foreach ($categories as $category) {\n $cats .= $category->name . ', ';\n }\n # echo out of foreach loop\n echo rtrim($cats, ', ');\n</code></pre>\n"
}
] | 2019/06/20 | [
"https://wordpress.stackexchange.com/questions/341002",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/149472/"
] | I have in my code the following variable to call the title of the categories.
```
<?php
$categories = get_the_terms($custom_args->ID, 'veranstaltungen-category');
foreach ($categories as $category) {
$cats .= $category->name . ', ';
echo rtrim($cats, ', ');
}
?>
```
The problem is that in the last post of the loop I duplicated the categories and printed them all.
[](https://i.stack.imgur.com/2wYQL.png)
in fact it is printed by post from less to more.
If I use the following code fragment, I print it well but without commas
```
foreach ($categories as $category) {
echo '<span>'.$category->name .'</span>';
}
```
If someone would be so kind to guide me I would be very grateful, this brings me | In this line:
```
$cats .= $category->name . ', ';
```
You append a name of category to variable called $cats.
But you never reset this variable. So every post appends its categories to the same variable.
So here’s how to fix this:
```
<?php
$categories = get_the_terms($custom_args->ID, 'veranstaltungen-category');
$cats = ''; // set empty string as value
foreach ($categories as $category) {
$cats .= $category->name . ', ';
echo rtrim($cats, ', ');
}
?>
```
Of course you can also add commas to your second code:
```
foreach ($categories as $i => $category) {
if ( $i ) echo ', ';
echo '<span>'.$category->name .'</span>';
}
``` |
341,024 | <p>everybody,</p>
<p>I have created a custom_post_type;</p>
<pre><code>function create_post_type_veranstaltungen()
{
register_post_type('veranstaltungen', array(
'label' => __('Veranstaltungen'),
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_icon' => 'dashicons-admin-site-alt',
'supports' => array('thumbnail', 'title', 'editor', 'author',
'excerpt', 'comments'),
)
);
}
add_action('init', 'create_post_type_veranstaltungen');
</code></pre>
<p>with its own section of taxonomies</p>
<pre><code>function tr_create_my_taxonomy()
{
register_taxonomy(
'veranstaltungen-category',
'veranstaltungen',
array(
'label' => __('Category'),
'rewrite' => array('slug' => 'veranstaltungen-category'),
'hierarchical' => true,
)
);
}
add_action('init', 'tr_create_my_taxonomy');
</code></pre>
<p>Then I created 4 post and I implemented the corresponding loop that works</p>
<pre><code><?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$custom_args = array(
'post_type' => 'veranstaltungen',
'orderby' => 'date',
'order' => 'DESC',
'paged' => $paged,
'posts_per_page' => '10'
);
$wp_query = new WP_Query($custom_args);
if (have_posts()) :
while (have_posts()) : the_post();
?>
<div class="pagination">
<?php
$big = 999999999; // need an unlikely integer
echo paginate_links(array(
base' => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
'format' => '?paged=%#%',
'current' => max(1, get_query_var('paged')),
'total' => $wp_query->max_num_pages
));
?>
</div>
</code></pre>
<p>if income posts_per_page => '-1' works, if I enter posts_per_page => '1' also works, but if I enter posts_per_page => '10' does not show anything at all.</p>
<p>Does anyone have an idea of what may be happening?</p>
<p>Thanks</p>
| [
{
"answer_id": 341027,
"author": "Bhupen",
"author_id": 128529,
"author_profile": "https://wordpress.stackexchange.com/users/128529",
"pm_score": -1,
"selected": false,
"text": "<p>you have missed $wp_query like this $wp_query->have_posts() to add in the loop. \nPlease see the code: </p>\n\n<pre><code>$wp_query = new WP_Query($custom_args); \nif ($wp_query->have_posts()) : while ($wp_query->have_posts()) : $wp_query->the_post();\n</code></pre>\n"
},
{
"answer_id": 341028,
"author": "Chetan Vaghela",
"author_id": 169856,
"author_profile": "https://wordpress.stackexchange.com/users/169856",
"pm_score": -1,
"selected": false,
"text": "<p>Please try below code : </p>\n\n<pre><code>$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;\n $custom_args = array(\n 'post_type' => 'veranstaltungen',\n 'orderby' => 'date',\n 'order' => 'DESC',\n 'paged' => $paged,\n 'posts_per_page' => '10'\n );\n $wp_query = new WP_Query($custom_args);\n\n while ( $wp_query->have_posts() ) {\n $wp_query->the_post();\n\n echo '<lable>Post Name : ' . get_the_title() .'</lable><br/>';\n }\n wp_reset_query();\n ?>\n <div class=\"pagination\">\n <?php\n $big = 999999999; // need an unlikely integer\n\n echo paginate_links(array(\n 'base' => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),\n 'format' => '?paged=%#%',\n 'current' => max(1, get_query_var('paged')),\n 'total' => $wp_query->max_num_pages\n ));\n ?>\n </div>\n</code></pre>\n"
},
{
"answer_id": 341494,
"author": "Dario B.",
"author_id": 149472,
"author_profile": "https://wordpress.stackexchange.com/users/149472",
"pm_score": 0,
"selected": false,
"text": "<p>after days of research, I found that the fault was simply in the pagination.\nBy changing the pagination code, I have made it work.</p>\n\n<pre><code><?php\n\n $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;\n\n $custom_args = array(\n 'post_type' => 'veranstaltungen',\n 'orderby' => 'date',\n 'order' => 'DESC',\n 'paged' => $paged,\n 'posts_per_page' => '10'\n );\n $wp_query = new WP_Query($custom_args);\n\n if ($wp_query->have_posts()) : while ($wp_query->have_posts()) : $wp_query->the_post();\n\n ?>\n\n <div class=\"accordion\">\n <div class=\"columns is-mobile is-flexend \">\n <div class=\"column is-half\">\n <div class=\"columns is-mobile is-vcentered\">\n <div class=\"column is-one-fifth\">\n <i class=\"angle fa fa-angle-down fa-2x\" aria-hidden=\"true\"></i>\n </div>\n <div class=\"column is-four-fifths\">\n <?php\n $categories = get_the_terms($custom_args->ID, 'veranstaltungen-category');\n $cats = ''; // set empty string as value\n\n foreach ($categories as $i => $category) {\n if ($i) echo ', ';\n echo '<span>' . $category->name . '</span>';\n }\n ?>\n\n <div class=\"title\">\n <?php the_title(); ?>\n </div>\n </div>\n </div>\n\n </div>\n <div class=\"column is-half\">\n <div class=\"postdate\">\n <p><?php the_field('tag') ?></p>\n <p><?php the_field('datum') ?></p>\n\n </div>\n </div>\n </div>\n </div>\n <div class=\"thepanel\">\n <div class=\"theimage\">\n <?php the_post_thumbnail(); ?>\n </div>\n <?php the_content(); ?>\n </div>\n <?php endwhile; ?>\n <div class=\"columns is-mobile\">\n <div class=\"column is-3 is-offset-9\">\n <div class=\"pagination\">\n <?php\n $nav = get_the_posts_pagination(array(\n 'mid_size' => 2,\n 'prev_text' => 'Zurück',\n 'next_text' => 'Vor',\n 'screen_reader_text' => 'A'\n ));\n $nav = str_replace('<h2 class=\"screen-reader-text\">A</h2>', '', $nav);\n echo $nav;\n ?>\n </div>\n </div>\n </div>\n <?php endif;\n wp_reset_query();\n ?>\n</code></pre>\n\n<p>Ahora funciona perfectamente. Gracias a todos</p>\n"
}
] | 2019/06/20 | [
"https://wordpress.stackexchange.com/questions/341024",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/149472/"
] | everybody,
I have created a custom\_post\_type;
```
function create_post_type_veranstaltungen()
{
register_post_type('veranstaltungen', array(
'label' => __('Veranstaltungen'),
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_icon' => 'dashicons-admin-site-alt',
'supports' => array('thumbnail', 'title', 'editor', 'author',
'excerpt', 'comments'),
)
);
}
add_action('init', 'create_post_type_veranstaltungen');
```
with its own section of taxonomies
```
function tr_create_my_taxonomy()
{
register_taxonomy(
'veranstaltungen-category',
'veranstaltungen',
array(
'label' => __('Category'),
'rewrite' => array('slug' => 'veranstaltungen-category'),
'hierarchical' => true,
)
);
}
add_action('init', 'tr_create_my_taxonomy');
```
Then I created 4 post and I implemented the corresponding loop that works
```
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$custom_args = array(
'post_type' => 'veranstaltungen',
'orderby' => 'date',
'order' => 'DESC',
'paged' => $paged,
'posts_per_page' => '10'
);
$wp_query = new WP_Query($custom_args);
if (have_posts()) :
while (have_posts()) : the_post();
?>
<div class="pagination">
<?php
$big = 999999999; // need an unlikely integer
echo paginate_links(array(
base' => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
'format' => '?paged=%#%',
'current' => max(1, get_query_var('paged')),
'total' => $wp_query->max_num_pages
));
?>
</div>
```
if income posts\_per\_page => '-1' works, if I enter posts\_per\_page => '1' also works, but if I enter posts\_per\_page => '10' does not show anything at all.
Does anyone have an idea of what may be happening?
Thanks | after days of research, I found that the fault was simply in the pagination.
By changing the pagination code, I have made it work.
```
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$custom_args = array(
'post_type' => 'veranstaltungen',
'orderby' => 'date',
'order' => 'DESC',
'paged' => $paged,
'posts_per_page' => '10'
);
$wp_query = new WP_Query($custom_args);
if ($wp_query->have_posts()) : while ($wp_query->have_posts()) : $wp_query->the_post();
?>
<div class="accordion">
<div class="columns is-mobile is-flexend ">
<div class="column is-half">
<div class="columns is-mobile is-vcentered">
<div class="column is-one-fifth">
<i class="angle fa fa-angle-down fa-2x" aria-hidden="true"></i>
</div>
<div class="column is-four-fifths">
<?php
$categories = get_the_terms($custom_args->ID, 'veranstaltungen-category');
$cats = ''; // set empty string as value
foreach ($categories as $i => $category) {
if ($i) echo ', ';
echo '<span>' . $category->name . '</span>';
}
?>
<div class="title">
<?php the_title(); ?>
</div>
</div>
</div>
</div>
<div class="column is-half">
<div class="postdate">
<p><?php the_field('tag') ?></p>
<p><?php the_field('datum') ?></p>
</div>
</div>
</div>
</div>
<div class="thepanel">
<div class="theimage">
<?php the_post_thumbnail(); ?>
</div>
<?php the_content(); ?>
</div>
<?php endwhile; ?>
<div class="columns is-mobile">
<div class="column is-3 is-offset-9">
<div class="pagination">
<?php
$nav = get_the_posts_pagination(array(
'mid_size' => 2,
'prev_text' => 'Zurück',
'next_text' => 'Vor',
'screen_reader_text' => 'A'
));
$nav = str_replace('<h2 class="screen-reader-text">A</h2>', '', $nav);
echo $nav;
?>
</div>
</div>
</div>
<?php endif;
wp_reset_query();
?>
```
Ahora funciona perfectamente. Gracias a todos |
341,060 | <p>I'm facing an issue where:</p>
<ol>
<li>I've created a custom attribute type</li>
<li>Created an attribute, called it 'test'</li>
<li>Added one term to the attribute, and called this 'Hi'</li>
<li>Go to edit the varations in edit product and I cannot seem to add any terms to it. There's just nothing there to select like normal.</li>
</ol>
<p><a href="https://i.stack.imgur.com/Hl7Wo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Hl7Wo.png" alt=""></a></p>
<p>This is the code I used to add a custom attribute type:</p>
<pre><code>add_filter( 'product_attributes_type_selector', function($array){
$array['test'] = __( 'Test', 'awcs' );
} );
</code></pre>
<p>The code is working, where it adds the type to the dropdown when creating a new attribute, it's just the variants of the attribute not displaying in the edit product page.</p>
| [
{
"answer_id": 359516,
"author": "Kevin Silva",
"author_id": 183388,
"author_profile": "https://wordpress.stackexchange.com/users/183388",
"pm_score": 1,
"selected": false,
"text": "<p>I just had that problem and resolved it alone since i could not find the answer online.\nYou just need to put that code inside an if. Only to run that code on attribute page.</p>\n\n<pre><code>if ($_GET['page']=='product_attributes') {\n add_filter( 'product_attributes_type_selector', function($array){\n $array['test'] = __( 'Test', 'awcs' );\n } );\n}\n</code></pre>\n"
},
{
"answer_id": 365987,
"author": "gregbast1994",
"author_id": 161793,
"author_profile": "https://wordpress.stackexchange.com/users/161793",
"pm_score": 0,
"selected": false,
"text": "<p>It doesn't look like you are returning anything to the filter. <strong>Try this.</strong></p>\n\n<pre><code>add_filter(\"product_attributes_type_selector\" , function( $array ){\n $array['test'] = __( 'Test', 'awcs' );\n return $array ;\n});\n</code></pre>\n"
}
] | 2019/06/20 | [
"https://wordpress.stackexchange.com/questions/341060",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/169069/"
] | I'm facing an issue where:
1. I've created a custom attribute type
2. Created an attribute, called it 'test'
3. Added one term to the attribute, and called this 'Hi'
4. Go to edit the varations in edit product and I cannot seem to add any terms to it. There's just nothing there to select like normal.
[](https://i.stack.imgur.com/Hl7Wo.png)
This is the code I used to add a custom attribute type:
```
add_filter( 'product_attributes_type_selector', function($array){
$array['test'] = __( 'Test', 'awcs' );
} );
```
The code is working, where it adds the type to the dropdown when creating a new attribute, it's just the variants of the attribute not displaying in the edit product page. | I just had that problem and resolved it alone since i could not find the answer online.
You just need to put that code inside an if. Only to run that code on attribute page.
```
if ($_GET['page']=='product_attributes') {
add_filter( 'product_attributes_type_selector', function($array){
$array['test'] = __( 'Test', 'awcs' );
} );
}
``` |
341,087 | <p>My js code:</p>
<pre><code>$('div[aria-label="Asukohad"] input[type="checkbox"]').on("change", function() {
var element = $(this);
if(element.is(":checked")) {
//todo
} else {
uncheckAll();
}
});
function uncheckAll() {
$('div[aria-label="Asukohad"] input[type="checkbox"]').attr('checked', false);
}
</code></pre>
<p>When I select some checkboxes and then unselect one of them, all the checkboxes get unchecked, which is great. But now when I select another checbox all the other checkboxes are also getting checked which where unchekced by jQuery. I got a feeling that I have to sync the checkboxes somehow when I do the unchecking with jQuery.</p>
<p>Checkboxes are located in post/page properties panel. </p>
<p>Video demo:<a href="https://vimeo.com/343601969" rel="nofollow noreferrer">https://vimeo.com/343601969</a></p>
| [
{
"answer_id": 341092,
"author": "Mr.Lister",
"author_id": 118678,
"author_profile": "https://wordpress.stackexchange.com/users/118678",
"pm_score": 1,
"selected": false,
"text": "<p>Can you please clarify your question? Are you attempting to make a checkbox that can clear all checkboxes and also recheck all checkboxes by checking that one checkbox?</p>\n\n<p>Also a checked input would be written like this:</p>\n\n<pre><code><input id=\"editor-post-taxonomies-hierarchical-term-48\" class=\"editor-post-taxonomies__hierarchical-terms-input\" type=\"checkbox\" checked value=\"48\" />\n</code></pre>\n\n<p>You can do this:</p>\n\n<pre><code>$('div[aria-label=\"Asukohad\"] input[type=\"checkbox\"]').on(\"change\", function() {\nvar element = $(this);\n\nif(element.is(\":checked\")) {\n // do nothing.\n} else {\n uncheckAll();\n}\n});\n\nfunction uncheckAll() {\n $('div[aria-label=\"Asukohad\"] input[type=\"checkbox\"]').removeProp('checked');\n}\n</code></pre>\n"
},
{
"answer_id": 403699,
"author": "mrwp.io",
"author_id": 63769,
"author_profile": "https://wordpress.stackexchange.com/users/63769",
"pm_score": 0,
"selected": false,
"text": "<p>I had the same question, so here you go.</p>\n<p>To check all boxes:\n<pre>\njQuery('#select-button').on('click',function(){\n jQuery('.outer-div td label input[type=\"checkbox\"]').prop('checked', true);\n});\n</pre>\n<p>To uncheck all boxes:\n<pre>\njQuery('#select-button').on('click',function(){\n jQuery('.outer-div td label input[type=\"checkbox\"]').removeProp('checked');\n});\n</pre>\n"
}
] | 2019/06/21 | [
"https://wordpress.stackexchange.com/questions/341087",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/170408/"
] | My js code:
```
$('div[aria-label="Asukohad"] input[type="checkbox"]').on("change", function() {
var element = $(this);
if(element.is(":checked")) {
//todo
} else {
uncheckAll();
}
});
function uncheckAll() {
$('div[aria-label="Asukohad"] input[type="checkbox"]').attr('checked', false);
}
```
When I select some checkboxes and then unselect one of them, all the checkboxes get unchecked, which is great. But now when I select another checbox all the other checkboxes are also getting checked which where unchekced by jQuery. I got a feeling that I have to sync the checkboxes somehow when I do the unchecking with jQuery.
Checkboxes are located in post/page properties panel.
Video demo:<https://vimeo.com/343601969> | Can you please clarify your question? Are you attempting to make a checkbox that can clear all checkboxes and also recheck all checkboxes by checking that one checkbox?
Also a checked input would be written like this:
```
<input id="editor-post-taxonomies-hierarchical-term-48" class="editor-post-taxonomies__hierarchical-terms-input" type="checkbox" checked value="48" />
```
You can do this:
```
$('div[aria-label="Asukohad"] input[type="checkbox"]').on("change", function() {
var element = $(this);
if(element.is(":checked")) {
// do nothing.
} else {
uncheckAll();
}
});
function uncheckAll() {
$('div[aria-label="Asukohad"] input[type="checkbox"]').removeProp('checked');
}
``` |
341,111 | <p>I have a website with a lot of </p>
<pre><code>[mybutton]click here[/mybutton]
</code></pre>
<p>or</p>
<pre><code>[mybutton]click there[/mybutton]
</code></pre>
<p>in editor.
I need to add a function to create a href from this shortcodes. Closing of shortcode is a problem for me. How can i do it?</p>
| [
{
"answer_id": 341116,
"author": "Maneza F8",
"author_id": 170430,
"author_profile": "https://wordpress.stackexchange.com/users/170430",
"pm_score": 0,
"selected": false,
"text": "<p>That is a short code not HTML you can put any Attribute there, if you want that function got to your page builder and insert a text editor and to html editor and create a button so you can put any attribute you want in it.</p>\n"
},
{
"answer_id": 341123,
"author": "Nathan Powell",
"author_id": 27196,
"author_profile": "https://wordpress.stackexchange.com/users/27196",
"pm_score": 3,
"selected": true,
"text": "<p>To change the functionality of a shortcode you must first <code>remove_shortcode( 'shortcode_name' );</code> where shortcode name is the name of the shortcode. Add the shortcode back with your NEW function.</p>\n\n<p>A simple example to follow what you might be needing:</p>\n\n<pre><code> remove_shortcode( 'mybutton' );\n add_shortcode( 'mybutton', 'my_shortcode_function' );\n\n my_shortcode_function( $atts, $content = \"\" ) {\n return '<a href=\"http://example.com\">' . $content . '</a>';\n }\n</code></pre>\n"
}
] | 2019/06/21 | [
"https://wordpress.stackexchange.com/questions/341111",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101908/"
] | I have a website with a lot of
```
[mybutton]click here[/mybutton]
```
or
```
[mybutton]click there[/mybutton]
```
in editor.
I need to add a function to create a href from this shortcodes. Closing of shortcode is a problem for me. How can i do it? | To change the functionality of a shortcode you must first `remove_shortcode( 'shortcode_name' );` where shortcode name is the name of the shortcode. Add the shortcode back with your NEW function.
A simple example to follow what you might be needing:
```
remove_shortcode( 'mybutton' );
add_shortcode( 'mybutton', 'my_shortcode_function' );
my_shortcode_function( $atts, $content = "" ) {
return '<a href="http://example.com">' . $content . '</a>';
}
``` |
341,126 | <p>I'm trying to download images from external sites via api (newsapi.org) and use those as thumbnails, using <code>wp_download_url</code>. Although it doesn’t work on so-called dynamically generated images, e.g. </p>
<p><code>https://res.cloudinary.com/demo/image/upload/w_400,h_400,c_crop,g_face,r_max/w_200/lady.jpg</code></p>
<p>Is there a way to make it fetch such images too?</p>
| [
{
"answer_id": 341116,
"author": "Maneza F8",
"author_id": 170430,
"author_profile": "https://wordpress.stackexchange.com/users/170430",
"pm_score": 0,
"selected": false,
"text": "<p>That is a short code not HTML you can put any Attribute there, if you want that function got to your page builder and insert a text editor and to html editor and create a button so you can put any attribute you want in it.</p>\n"
},
{
"answer_id": 341123,
"author": "Nathan Powell",
"author_id": 27196,
"author_profile": "https://wordpress.stackexchange.com/users/27196",
"pm_score": 3,
"selected": true,
"text": "<p>To change the functionality of a shortcode you must first <code>remove_shortcode( 'shortcode_name' );</code> where shortcode name is the name of the shortcode. Add the shortcode back with your NEW function.</p>\n\n<p>A simple example to follow what you might be needing:</p>\n\n<pre><code> remove_shortcode( 'mybutton' );\n add_shortcode( 'mybutton', 'my_shortcode_function' );\n\n my_shortcode_function( $atts, $content = \"\" ) {\n return '<a href=\"http://example.com\">' . $content . '</a>';\n }\n</code></pre>\n"
}
] | 2019/06/21 | [
"https://wordpress.stackexchange.com/questions/341126",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/121208/"
] | I'm trying to download images from external sites via api (newsapi.org) and use those as thumbnails, using `wp_download_url`. Although it doesn’t work on so-called dynamically generated images, e.g.
`https://res.cloudinary.com/demo/image/upload/w_400,h_400,c_crop,g_face,r_max/w_200/lady.jpg`
Is there a way to make it fetch such images too? | To change the functionality of a shortcode you must first `remove_shortcode( 'shortcode_name' );` where shortcode name is the name of the shortcode. Add the shortcode back with your NEW function.
A simple example to follow what you might be needing:
```
remove_shortcode( 'mybutton' );
add_shortcode( 'mybutton', 'my_shortcode_function' );
my_shortcode_function( $atts, $content = "" ) {
return '<a href="http://example.com">' . $content . '</a>';
}
``` |
341,129 | <p>I am using SMTP to send email through WordPress, however this requires using plain text password. What if this password is stored in <code>wp-config.php</code>?
Very <a href="https://wordpress.stackexchange.com/questions/53636/password-in-wp-config-dangerous">similar to this</a>.
Why this topic differs from the linked one: the nature of the password. This password can be used for spam mass mailing, and may require additional protection steps and considerations.</p>
| [
{
"answer_id": 341133,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to make it a bit safer, save the password into the database. Making additional steps necessary to access the SMTP data. You should store sensitive data encrypted, of course. </p>\n\n<p>Besides that, someone malignant having access to your <code>wp-config.php</code>, is pretty much the worst case scenario anyway. So it is of utmost importance to make sure to keep your security up-to-date. So apply all updates for security fixes, WordPress, PHP, simply any software on your server that could be used as attack vector. Furthermore, harden your WordPress and server setup, e.g. file access, access to database and so on. </p>\n\n<p>Generally speaking, to answer your question, if your server is secure, then it's safe to store the SMTP data into the <code>wp-config.php</code>.</p>\n"
},
{
"answer_id": 341134,
"author": "ChristopherJones",
"author_id": 168744,
"author_profile": "https://wordpress.stackexchange.com/users/168744",
"pm_score": 2,
"selected": false,
"text": "<p>I am not sure where you else you would store the SMTP credentials? I am not comfortable storing those credentials in the Database because of the trouble you mentioned you could get into if they got out. Or putting them in a theme file. Like they mentioned in the other thread, if Apache gets screwed up and that files gets processed as plain text. Your credentials get exposed. If your DB is setup to only accept localhost connections or a specific IP, that could save you. But if your SMTP credentials get out, you might not have those luxuries.</p>\n\n<p>If your setup looks like: (And your public website lives inside of public_html)</p>\n\n<pre><code>/home/user/public_html/\n \\__ wp-config.php\n</code></pre>\n\n<p>I would store a file in: (Which is not public facing at all)</p>\n\n<pre><code>/home/user/smtp-connect.php\n</code></pre>\n\n<p>And then include() or require_once() that <code>smtp-connect.php</code> file when you need it. Have your credentials stored in there and your connection script in there as well.</p>\n\n<p>The article you referenced has some good points about locking up your wp-config file. Here is another article that I think could shed some more light on the security of wp-config.php and some work arounds to help secure it if you decide to setup some PHP Constants for your SMTP Credentials:\n<a href=\"https://www.wpwhitesecurity.com/protect-wordpress-wp-config-php-security/\" rel=\"nofollow noreferrer\">https://www.wpwhitesecurity.com/protect-wordpress-wp-config-php-security/</a></p>\n"
}
] | 2019/06/21 | [
"https://wordpress.stackexchange.com/questions/341129",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1210/"
] | I am using SMTP to send email through WordPress, however this requires using plain text password. What if this password is stored in `wp-config.php`?
Very [similar to this](https://wordpress.stackexchange.com/questions/53636/password-in-wp-config-dangerous).
Why this topic differs from the linked one: the nature of the password. This password can be used for spam mass mailing, and may require additional protection steps and considerations. | I am not sure where you else you would store the SMTP credentials? I am not comfortable storing those credentials in the Database because of the trouble you mentioned you could get into if they got out. Or putting them in a theme file. Like they mentioned in the other thread, if Apache gets screwed up and that files gets processed as plain text. Your credentials get exposed. If your DB is setup to only accept localhost connections or a specific IP, that could save you. But if your SMTP credentials get out, you might not have those luxuries.
If your setup looks like: (And your public website lives inside of public\_html)
```
/home/user/public_html/
\__ wp-config.php
```
I would store a file in: (Which is not public facing at all)
```
/home/user/smtp-connect.php
```
And then include() or require\_once() that `smtp-connect.php` file when you need it. Have your credentials stored in there and your connection script in there as well.
The article you referenced has some good points about locking up your wp-config file. Here is another article that I think could shed some more light on the security of wp-config.php and some work arounds to help secure it if you decide to setup some PHP Constants for your SMTP Credentials:
<https://www.wpwhitesecurity.com/protect-wordpress-wp-config-php-security/> |
341,144 | <p>I created a Wordpress REST API custom endpoint to be used as a Webhook URL in WooCommerce in order to convert the received data and then send it to a third party system, but the endpoint apparently is not receiving any data. I tested the code by sending some JSON data to my custom endpoint using Postman and it works only after installing another P;ugin to enable Basic Auth. I wonder if the problem is because probably the webhook needs authentication in order to be able to POST the data to the same domain? If that would be the case I have no idea where to setup basic authentication in the Webhook setting in WooCommerce. </p>
<p>this is my code:</p>
<pre><code> function woocbz_CallAPI($method, $url, $data = false)
{
$curl = curl_init();
switch ($method) {
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data) {
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
break;
case "PUT":
curl_setopt($curl, CURLOPT_PUT, 1);
break;
default:
if ($data) {
$url = sprintf("%s?%s", $url, http_build_query($data));
}
}
// Optional Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "username:password");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
function woocbz_order_created(WP_REST_Request $request)
{
$method = 'POST';
$url = 'https://webhook.site/2e5e23db-68ef-4d03-b9ec-687309d35166';
$data = $request->get_json_params();
$user_data = array(
'order_id' => $data['id'],
'memo' => $data['order_key'],
'status' => $data['status']
);
$resultado = woocbz_CallAPI($method, $url, $user_data);
return $data;
}
add_action(
'rest_api_init',
function () {
register_rest_route(
'woocbz/v1',
'/new-order',
array(
'methods' => 'POST',
'callback' => 'woocbz_order_created',
'permission_callback' => function () {
return true;
}
)
);
}
);
</code></pre>
<p>Any help will be greatly appreciated.</p>
| [
{
"answer_id": 341133,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to make it a bit safer, save the password into the database. Making additional steps necessary to access the SMTP data. You should store sensitive data encrypted, of course. </p>\n\n<p>Besides that, someone malignant having access to your <code>wp-config.php</code>, is pretty much the worst case scenario anyway. So it is of utmost importance to make sure to keep your security up-to-date. So apply all updates for security fixes, WordPress, PHP, simply any software on your server that could be used as attack vector. Furthermore, harden your WordPress and server setup, e.g. file access, access to database and so on. </p>\n\n<p>Generally speaking, to answer your question, if your server is secure, then it's safe to store the SMTP data into the <code>wp-config.php</code>.</p>\n"
},
{
"answer_id": 341134,
"author": "ChristopherJones",
"author_id": 168744,
"author_profile": "https://wordpress.stackexchange.com/users/168744",
"pm_score": 2,
"selected": false,
"text": "<p>I am not sure where you else you would store the SMTP credentials? I am not comfortable storing those credentials in the Database because of the trouble you mentioned you could get into if they got out. Or putting them in a theme file. Like they mentioned in the other thread, if Apache gets screwed up and that files gets processed as plain text. Your credentials get exposed. If your DB is setup to only accept localhost connections or a specific IP, that could save you. But if your SMTP credentials get out, you might not have those luxuries.</p>\n\n<p>If your setup looks like: (And your public website lives inside of public_html)</p>\n\n<pre><code>/home/user/public_html/\n \\__ wp-config.php\n</code></pre>\n\n<p>I would store a file in: (Which is not public facing at all)</p>\n\n<pre><code>/home/user/smtp-connect.php\n</code></pre>\n\n<p>And then include() or require_once() that <code>smtp-connect.php</code> file when you need it. Have your credentials stored in there and your connection script in there as well.</p>\n\n<p>The article you referenced has some good points about locking up your wp-config file. Here is another article that I think could shed some more light on the security of wp-config.php and some work arounds to help secure it if you decide to setup some PHP Constants for your SMTP Credentials:\n<a href=\"https://www.wpwhitesecurity.com/protect-wordpress-wp-config-php-security/\" rel=\"nofollow noreferrer\">https://www.wpwhitesecurity.com/protect-wordpress-wp-config-php-security/</a></p>\n"
}
] | 2019/06/21 | [
"https://wordpress.stackexchange.com/questions/341144",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/170445/"
] | I created a Wordpress REST API custom endpoint to be used as a Webhook URL in WooCommerce in order to convert the received data and then send it to a third party system, but the endpoint apparently is not receiving any data. I tested the code by sending some JSON data to my custom endpoint using Postman and it works only after installing another P;ugin to enable Basic Auth. I wonder if the problem is because probably the webhook needs authentication in order to be able to POST the data to the same domain? If that would be the case I have no idea where to setup basic authentication in the Webhook setting in WooCommerce.
this is my code:
```
function woocbz_CallAPI($method, $url, $data = false)
{
$curl = curl_init();
switch ($method) {
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data) {
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
break;
case "PUT":
curl_setopt($curl, CURLOPT_PUT, 1);
break;
default:
if ($data) {
$url = sprintf("%s?%s", $url, http_build_query($data));
}
}
// Optional Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "username:password");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
function woocbz_order_created(WP_REST_Request $request)
{
$method = 'POST';
$url = 'https://webhook.site/2e5e23db-68ef-4d03-b9ec-687309d35166';
$data = $request->get_json_params();
$user_data = array(
'order_id' => $data['id'],
'memo' => $data['order_key'],
'status' => $data['status']
);
$resultado = woocbz_CallAPI($method, $url, $user_data);
return $data;
}
add_action(
'rest_api_init',
function () {
register_rest_route(
'woocbz/v1',
'/new-order',
array(
'methods' => 'POST',
'callback' => 'woocbz_order_created',
'permission_callback' => function () {
return true;
}
)
);
}
);
```
Any help will be greatly appreciated. | I am not sure where you else you would store the SMTP credentials? I am not comfortable storing those credentials in the Database because of the trouble you mentioned you could get into if they got out. Or putting them in a theme file. Like they mentioned in the other thread, if Apache gets screwed up and that files gets processed as plain text. Your credentials get exposed. If your DB is setup to only accept localhost connections or a specific IP, that could save you. But if your SMTP credentials get out, you might not have those luxuries.
If your setup looks like: (And your public website lives inside of public\_html)
```
/home/user/public_html/
\__ wp-config.php
```
I would store a file in: (Which is not public facing at all)
```
/home/user/smtp-connect.php
```
And then include() or require\_once() that `smtp-connect.php` file when you need it. Have your credentials stored in there and your connection script in there as well.
The article you referenced has some good points about locking up your wp-config file. Here is another article that I think could shed some more light on the security of wp-config.php and some work arounds to help secure it if you decide to setup some PHP Constants for your SMTP Credentials:
<https://www.wpwhitesecurity.com/protect-wordpress-wp-config-php-security/> |
341,148 | <p>I'm very new to the developing world and have been, with the help of Youtube, been learning to design Wordpress themes with HTML, CSS and PHP. I am using MAMP to locally host my wordpress site. When I make an error, like forgetting to close my PHP tag, and I refresh my site, all I see is "the site is experiencing technical difficulties" and I'm not sure where I can check my syntax or other errors. Any suggestions?</p>
| [
{
"answer_id": 341133,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to make it a bit safer, save the password into the database. Making additional steps necessary to access the SMTP data. You should store sensitive data encrypted, of course. </p>\n\n<p>Besides that, someone malignant having access to your <code>wp-config.php</code>, is pretty much the worst case scenario anyway. So it is of utmost importance to make sure to keep your security up-to-date. So apply all updates for security fixes, WordPress, PHP, simply any software on your server that could be used as attack vector. Furthermore, harden your WordPress and server setup, e.g. file access, access to database and so on. </p>\n\n<p>Generally speaking, to answer your question, if your server is secure, then it's safe to store the SMTP data into the <code>wp-config.php</code>.</p>\n"
},
{
"answer_id": 341134,
"author": "ChristopherJones",
"author_id": 168744,
"author_profile": "https://wordpress.stackexchange.com/users/168744",
"pm_score": 2,
"selected": false,
"text": "<p>I am not sure where you else you would store the SMTP credentials? I am not comfortable storing those credentials in the Database because of the trouble you mentioned you could get into if they got out. Or putting them in a theme file. Like they mentioned in the other thread, if Apache gets screwed up and that files gets processed as plain text. Your credentials get exposed. If your DB is setup to only accept localhost connections or a specific IP, that could save you. But if your SMTP credentials get out, you might not have those luxuries.</p>\n\n<p>If your setup looks like: (And your public website lives inside of public_html)</p>\n\n<pre><code>/home/user/public_html/\n \\__ wp-config.php\n</code></pre>\n\n<p>I would store a file in: (Which is not public facing at all)</p>\n\n<pre><code>/home/user/smtp-connect.php\n</code></pre>\n\n<p>And then include() or require_once() that <code>smtp-connect.php</code> file when you need it. Have your credentials stored in there and your connection script in there as well.</p>\n\n<p>The article you referenced has some good points about locking up your wp-config file. Here is another article that I think could shed some more light on the security of wp-config.php and some work arounds to help secure it if you decide to setup some PHP Constants for your SMTP Credentials:\n<a href=\"https://www.wpwhitesecurity.com/protect-wordpress-wp-config-php-security/\" rel=\"nofollow noreferrer\">https://www.wpwhitesecurity.com/protect-wordpress-wp-config-php-security/</a></p>\n"
}
] | 2019/06/21 | [
"https://wordpress.stackexchange.com/questions/341148",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/170494/"
] | I'm very new to the developing world and have been, with the help of Youtube, been learning to design Wordpress themes with HTML, CSS and PHP. I am using MAMP to locally host my wordpress site. When I make an error, like forgetting to close my PHP tag, and I refresh my site, all I see is "the site is experiencing technical difficulties" and I'm not sure where I can check my syntax or other errors. Any suggestions? | I am not sure where you else you would store the SMTP credentials? I am not comfortable storing those credentials in the Database because of the trouble you mentioned you could get into if they got out. Or putting them in a theme file. Like they mentioned in the other thread, if Apache gets screwed up and that files gets processed as plain text. Your credentials get exposed. If your DB is setup to only accept localhost connections or a specific IP, that could save you. But if your SMTP credentials get out, you might not have those luxuries.
If your setup looks like: (And your public website lives inside of public\_html)
```
/home/user/public_html/
\__ wp-config.php
```
I would store a file in: (Which is not public facing at all)
```
/home/user/smtp-connect.php
```
And then include() or require\_once() that `smtp-connect.php` file when you need it. Have your credentials stored in there and your connection script in there as well.
The article you referenced has some good points about locking up your wp-config file. Here is another article that I think could shed some more light on the security of wp-config.php and some work arounds to help secure it if you decide to setup some PHP Constants for your SMTP Credentials:
<https://www.wpwhitesecurity.com/protect-wordpress-wp-config-php-security/> |
341,167 | <p>I have my wordpress multisite setup in LAN network. I also setup dynamic DNS (eg. www.mysite.com) which is directed to my router's public IP (eg. 10.10.10.10). My router will port forward any request to my server's IP (eg. 192.168.0.100). </p>
<p>When I tried to view the wordpress site from another device in my LAN network by typing in my server's IP in the browser, the site showed up nicely. But when I tried to view the site from a device outside of my LAN network by typing in the dynamic DNS name or my router's public IP, the browser showed that there was an error. Sometimes it show timed out error and sometimes it show that a network change has been detected.</p>
<p>The site URL and wordpress URL was set to (<a href="http://192.168.0.100" rel="nofollow noreferrer">http://192.168.0.100</a>) for this example. </p>
<p>Is there any way I could configure so that the site could be viewed from outside the LAN network? Any solution is much appreciated.</p>
| [
{
"answer_id": 341133,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to make it a bit safer, save the password into the database. Making additional steps necessary to access the SMTP data. You should store sensitive data encrypted, of course. </p>\n\n<p>Besides that, someone malignant having access to your <code>wp-config.php</code>, is pretty much the worst case scenario anyway. So it is of utmost importance to make sure to keep your security up-to-date. So apply all updates for security fixes, WordPress, PHP, simply any software on your server that could be used as attack vector. Furthermore, harden your WordPress and server setup, e.g. file access, access to database and so on. </p>\n\n<p>Generally speaking, to answer your question, if your server is secure, then it's safe to store the SMTP data into the <code>wp-config.php</code>.</p>\n"
},
{
"answer_id": 341134,
"author": "ChristopherJones",
"author_id": 168744,
"author_profile": "https://wordpress.stackexchange.com/users/168744",
"pm_score": 2,
"selected": false,
"text": "<p>I am not sure where you else you would store the SMTP credentials? I am not comfortable storing those credentials in the Database because of the trouble you mentioned you could get into if they got out. Or putting them in a theme file. Like they mentioned in the other thread, if Apache gets screwed up and that files gets processed as plain text. Your credentials get exposed. If your DB is setup to only accept localhost connections or a specific IP, that could save you. But if your SMTP credentials get out, you might not have those luxuries.</p>\n\n<p>If your setup looks like: (And your public website lives inside of public_html)</p>\n\n<pre><code>/home/user/public_html/\n \\__ wp-config.php\n</code></pre>\n\n<p>I would store a file in: (Which is not public facing at all)</p>\n\n<pre><code>/home/user/smtp-connect.php\n</code></pre>\n\n<p>And then include() or require_once() that <code>smtp-connect.php</code> file when you need it. Have your credentials stored in there and your connection script in there as well.</p>\n\n<p>The article you referenced has some good points about locking up your wp-config file. Here is another article that I think could shed some more light on the security of wp-config.php and some work arounds to help secure it if you decide to setup some PHP Constants for your SMTP Credentials:\n<a href=\"https://www.wpwhitesecurity.com/protect-wordpress-wp-config-php-security/\" rel=\"nofollow noreferrer\">https://www.wpwhitesecurity.com/protect-wordpress-wp-config-php-security/</a></p>\n"
}
] | 2019/06/22 | [
"https://wordpress.stackexchange.com/questions/341167",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/170461/"
] | I have my wordpress multisite setup in LAN network. I also setup dynamic DNS (eg. www.mysite.com) which is directed to my router's public IP (eg. 10.10.10.10). My router will port forward any request to my server's IP (eg. 192.168.0.100).
When I tried to view the wordpress site from another device in my LAN network by typing in my server's IP in the browser, the site showed up nicely. But when I tried to view the site from a device outside of my LAN network by typing in the dynamic DNS name or my router's public IP, the browser showed that there was an error. Sometimes it show timed out error and sometimes it show that a network change has been detected.
The site URL and wordpress URL was set to (<http://192.168.0.100>) for this example.
Is there any way I could configure so that the site could be viewed from outside the LAN network? Any solution is much appreciated. | I am not sure where you else you would store the SMTP credentials? I am not comfortable storing those credentials in the Database because of the trouble you mentioned you could get into if they got out. Or putting them in a theme file. Like they mentioned in the other thread, if Apache gets screwed up and that files gets processed as plain text. Your credentials get exposed. If your DB is setup to only accept localhost connections or a specific IP, that could save you. But if your SMTP credentials get out, you might not have those luxuries.
If your setup looks like: (And your public website lives inside of public\_html)
```
/home/user/public_html/
\__ wp-config.php
```
I would store a file in: (Which is not public facing at all)
```
/home/user/smtp-connect.php
```
And then include() or require\_once() that `smtp-connect.php` file when you need it. Have your credentials stored in there and your connection script in there as well.
The article you referenced has some good points about locking up your wp-config file. Here is another article that I think could shed some more light on the security of wp-config.php and some work arounds to help secure it if you decide to setup some PHP Constants for your SMTP Credentials:
<https://www.wpwhitesecurity.com/protect-wordpress-wp-config-php-security/> |
341,193 | <p>I have created a custom section with a setting with one control allowing users to choose fonts from a dropdown. However, when I use the get_theme_mod() function, and echo the results to a styles tag in the header, I get nothing. </p>
<p>The debugger tells me that get_theme_mod() is returning 'false', when I expect it to return the value of the selected item. Using get_option() gives me the key of the option, "value3" and not the value.</p>
<p>I would prefer to use get_theme_mod() since that is what the function is for, but if I can't how do I get it to output 'American Typewriter' instead of "value3"?</p>
<p><strong>functions.php</strong></p>
<pre><code>function lettra_customized_css()
{
?>
<style type='text/css'>
.site-title {
<?php
$foo = get_option('title_font'); // "value3"
$bar = get_theme_mod('title_font');// false
?>font-family: <?php echo get_theme_mod('title_font') ?>;
}
</style>
<?php
}
add_action('wp_head', 'lettra_customized_css');
</code></pre>
<p><strong>cutomizer.php</strong></p>
<pre><code>function lettra_customize_register($wp_customize)
{
$wp_customize->add_section(
'font_options',
array(
'title' => __('Font Options', 'lettra'), //Visible title of section
'priority' => 20, //Determines what order this appears in
'capability' => 'edit_theme_options', //Capability needed to tweak
'description' => __('Choose font pairings for your theme here.', 'lettra'), //Descriptive tooltip
)
);
$wp_customize->add_setting('title_font', array(
'default' => 'Roboto Slab',
'capability' => 'edit_theme_options',
'type' => 'option',
'transport' => 'postMessage'
));
$wp_customize->add_control('title_font_control', array(
'label' => __('Title Font', 'lettra'),
'section' => 'font_options',
'settings' => 'title_font',
'type' => 'select',
'choices' => array(
'value1' => 'Roboto Slab',
'value2' => 'Times New Roman',
'value3' => 'American Typewriter',
),
));
}
add_action('customize_register', 'lettra_customize_register');
</code></pre>
| [
{
"answer_id": 341195,
"author": "Aniruddha Gawade",
"author_id": 101818,
"author_profile": "https://wordpress.stackexchange.com/users/101818",
"pm_score": 1,
"selected": false,
"text": "<p>Problem 1: <code>get_option</code> instead of <code>get_theme_mod</code>.</p>\n\n<p>How you store and retrieve value depends on the type you pass to your <code>add_setting</code> function. \nSee <a href=\"https://codex.wordpress.org/Class_Reference/WP_Customize_Manager/add_setting\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Customize_Manager/add_setting</a>.\nIf you want to use <code>get_theme_mod</code>, type should be <code>theme_mod</code>, which is default.</p>\n\n<p>Problem 2: getting value instead of label.</p>\n\n<p>When you are passing choices to <code>add_control</code> function, this is an array with combination of <code>value => label</code>. Hence the value part will be used to store in DB, and to retrieve later on. \nTo use <code>Label</code> to store in DB, you can pass normal array, or use label as value.</p>\n\n<pre><code>'choices' => array(\n 'Roboto Slab' => 'Roboto Slab',\n 'Times New Roman' => 'Times New Roman',\n 'American Typewriter' => 'American Typewriter',\n),\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>'choices' => array(\n 'Roboto Slab',\n 'Times New Roman',\n 'American Typewriter',\n),\n</code></pre>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 341196,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>The debugger tells me that get_theme_mod() is returning 'false', when\n I expect it to return the value of the selected item.</p>\n</blockquote>\n\n<p><code>get_theme_mod()</code> isn't working because when you registered the setting, you set the <code>type</code> to <code>option</code>:</p>\n\n<pre><code>$wp_customize->add_setting('title_font', array(\n 'default' => 'Roboto Slab',\n 'capability' => 'edit_theme_options',\n 'type' => 'option',\n 'transport' => 'postMessage'\n));\n</code></pre>\n\n<p>The possible values for <code>type</code> when adding a setting are <code>'option'</code>, or the default, <code>'theme_mod'</code>. </p>\n\n<p><code>option</code> stores the value independently of the current theme, and is retrieved with <code>get_option()</code>, while <code>theme_mod</code> stores the value only for the current theme, and is retrieved with <code>get_theme_mod()</code>.</p>\n\n<blockquote>\n <p>Using get_option() gives me the key of the option, \"value3\" and not the value.</p>\n</blockquote>\n\n<p>The 'key' <em>is</em> the value. It's what's output into the <code>value=\"\"</code> attribute of the <code><option></code> tag.</p>\n\n<p>If you want to use the label, there's two potential solutions.</p>\n\n<p>First, you could just pass the labels only, then these will also be used as the values:</p>\n\n<pre><code>array(\n 'Roboto Slab',\n 'Times New Roman',\n 'American Typewriter',\n),\n</code></pre>\n\n<p>Or you could store a reference to the labels independently of both places:</p>\n\n<pre><code>function wpse_341193_get_font_options() {\n return array(\n 'value1' => 'Roboto Slab',\n 'value2' => 'Times New Roman',\n 'value3' => 'American Typewriter',\n );\n}\n</code></pre>\n\n<p>Which you can then use as the choices:</p>\n\n<pre><code>'choices' => wpse_341193_get_font_options(),\n</code></pre>\n\n<p>And the output:</p>\n\n<pre><code><?php\n$font_options = wpse_341193_get_font_options();\n$font_family = get_theme_mod('title_font');// false\n?>font-family: <?php echo $font_options[$font_family] ?>;\n</code></pre>\n"
}
] | 2019/06/22 | [
"https://wordpress.stackexchange.com/questions/341193",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/153787/"
] | I have created a custom section with a setting with one control allowing users to choose fonts from a dropdown. However, when I use the get\_theme\_mod() function, and echo the results to a styles tag in the header, I get nothing.
The debugger tells me that get\_theme\_mod() is returning 'false', when I expect it to return the value of the selected item. Using get\_option() gives me the key of the option, "value3" and not the value.
I would prefer to use get\_theme\_mod() since that is what the function is for, but if I can't how do I get it to output 'American Typewriter' instead of "value3"?
**functions.php**
```
function lettra_customized_css()
{
?>
<style type='text/css'>
.site-title {
<?php
$foo = get_option('title_font'); // "value3"
$bar = get_theme_mod('title_font');// false
?>font-family: <?php echo get_theme_mod('title_font') ?>;
}
</style>
<?php
}
add_action('wp_head', 'lettra_customized_css');
```
**cutomizer.php**
```
function lettra_customize_register($wp_customize)
{
$wp_customize->add_section(
'font_options',
array(
'title' => __('Font Options', 'lettra'), //Visible title of section
'priority' => 20, //Determines what order this appears in
'capability' => 'edit_theme_options', //Capability needed to tweak
'description' => __('Choose font pairings for your theme here.', 'lettra'), //Descriptive tooltip
)
);
$wp_customize->add_setting('title_font', array(
'default' => 'Roboto Slab',
'capability' => 'edit_theme_options',
'type' => 'option',
'transport' => 'postMessage'
));
$wp_customize->add_control('title_font_control', array(
'label' => __('Title Font', 'lettra'),
'section' => 'font_options',
'settings' => 'title_font',
'type' => 'select',
'choices' => array(
'value1' => 'Roboto Slab',
'value2' => 'Times New Roman',
'value3' => 'American Typewriter',
),
));
}
add_action('customize_register', 'lettra_customize_register');
``` | >
> The debugger tells me that get\_theme\_mod() is returning 'false', when
> I expect it to return the value of the selected item.
>
>
>
`get_theme_mod()` isn't working because when you registered the setting, you set the `type` to `option`:
```
$wp_customize->add_setting('title_font', array(
'default' => 'Roboto Slab',
'capability' => 'edit_theme_options',
'type' => 'option',
'transport' => 'postMessage'
));
```
The possible values for `type` when adding a setting are `'option'`, or the default, `'theme_mod'`.
`option` stores the value independently of the current theme, and is retrieved with `get_option()`, while `theme_mod` stores the value only for the current theme, and is retrieved with `get_theme_mod()`.
>
> Using get\_option() gives me the key of the option, "value3" and not the value.
>
>
>
The 'key' *is* the value. It's what's output into the `value=""` attribute of the `<option>` tag.
If you want to use the label, there's two potential solutions.
First, you could just pass the labels only, then these will also be used as the values:
```
array(
'Roboto Slab',
'Times New Roman',
'American Typewriter',
),
```
Or you could store a reference to the labels independently of both places:
```
function wpse_341193_get_font_options() {
return array(
'value1' => 'Roboto Slab',
'value2' => 'Times New Roman',
'value3' => 'American Typewriter',
);
}
```
Which you can then use as the choices:
```
'choices' => wpse_341193_get_font_options(),
```
And the output:
```
<?php
$font_options = wpse_341193_get_font_options();
$font_family = get_theme_mod('title_font');// false
?>font-family: <?php echo $font_options[$font_family] ?>;
``` |
341,200 | <p>I've cast a pretty wide net to find an answer but nothing seems to quite hit the mark.</p>
<p>Process:: I Login to my site/dashboard and I decide I need to edit a portion of my theme through the customiser, so I do, pretty straight forward...</p>
<p>In the mean time, I've built up my child theme and it seems to work pretty well for a novice and have generally figured out how to duplicate and edit particular .php files such as the footer, header etc... and, change (template to stylesheet) to load child theme images; however!</p>
<p>I wanted to change the social media links in my footer and had to scratch my head for a fews before figuring out how the customiser works and where the .php files are stored so I could change and add new fab fa.icons icon.</p>
<p>Problem:: my child theme function.php is doing what it needs to be doing, likewise with my pages, and is safeguarded form theme updates, however! not my new "customeriser" changes, so I have to go back in and change them time over...</p>
<p>I have found the location of the directory for the customiser, hence the ability to edit it, but to safeguard it from being changed is another thing. </p>
<p>The customiser files are duplicated to the child directory, then I load (along with tried variations of include, stylesheet, url)</p>
<pre><code>require get_template_directory() . '/inc/business-prime-customizer.php';
</code></pre>
<p>it crashes my site...</p>
<p>So how do I point my child function.php at that new customiser address/files?</p>
<p>Many thanks and greatly appreciated</p>
<p>John</p>
| [
{
"answer_id": 341202,
"author": "Mobeen Abdullah",
"author_id": 170482,
"author_profile": "https://wordpress.stackexchange.com/users/170482",
"pm_score": -1,
"selected": false,
"text": "<p>This should load the file from the child theme.</p>\n\n<pre><code>require get_stylesheet_directory() . '/inc/business-prime-customizer.php';\n</code></pre>\n\n<p>you should also set <code>WP_DEBUG</code> variable to <code>true</code> in <code>wp-config.php</code> file</p>\n\n<p>if you want to load any file from the parent theme then you will use</p>\n\n<pre><code>require get_template_directory() . '/path_to_the_file.php';\nor\nrequire get_template_directory_uri() . '/path_to_the_css_file.css';\n</code></pre>\n\n<p>if you want to load file from the current child theme or active theme.</p>\n\n<pre><code>require get_stylesheet_directory() . '/path_to_the_file.php';\nor\nrequire get_stylesheet_directory_uri() . '/path_to_the_css_file.css';\n</code></pre>\n"
},
{
"answer_id": 341203,
"author": "Chetan Vaghela",
"author_id": 169856,
"author_profile": "https://wordpress.stackexchange.com/users/169856",
"pm_score": 1,
"selected": true,
"text": "<p>First remove action of customizer then add your action with new function name.</p>\n\n<p><strong>in your child-theme functions.php</strong></p>\n\n<pre><code>add_action( 'init', 'remove_my_action');\nfunction remove_my_action() {\n remove_action('customize_register', 'business_prime_settings_control',10);\n}\nrequire_once dirname( __FILE__ ) . '/inc/business-prime-customizer.php';\n</code></pre>\n\n<p><strong>in your child-theme/inc/business-prime-customizer.php</strong>\n<strong>change name of function and callback</strong></p>\n\n<pre><code>function business_prime_settings_control_child($wp_customize) {\n # here your all customizer settings code\n}\nadd_action('customize_register', 'business_prime_settings_control_child');\n</code></pre>\n\n<p>Remove other extra actions and declared functions. otherwise you will get : Cannot redeclare Fatal error.</p>\n"
},
{
"answer_id": 341244,
"author": "Shadow Crown",
"author_id": 170479,
"author_profile": "https://wordpress.stackexchange.com/users/170479",
"pm_score": 0,
"selected": false,
"text": "<p>Just wanted to say thank you for your feedback it has, and without a boubt, been very helpful. Otherwise, one answer and its results have been better than the other. </p>\n\n<p>Just a little feedback of my own explorations...</p>\n\n<p>After exploring the net, there does seem to be a slight gap in undersatanding these things, more so referring to us novices/amatures and our questions, equally so, when the answers can be somewhat long and not to the point, so thanks for your patience there.</p>\n\n<p>Child theme creations seem to be quite the moot subject and, based on the parent theme, difficult to ensure they work properly. Therefore, based on your patience and obvious abilities, need to keep working at it, as such I'll keep exploring.</p>\n\n<p>I'm kind of thinking that the answers are within the development process of creating the parent themes itselves, if I choose to invest that much time and money into it, or commission someone. So what worked and yielded a greater result:</p>\n\n<p>As expected and to reduce the impact on the parent files, I duplicated the required parent files into the child theme, then as per advice added the following with a few tweaks.</p>\n\n<p>Child functions.php::</p>\n\n<pre><code> add_action( 'init', 'remove_my_customizer');\n function remove_my_customizer() {\n remove_action('customize_register', 'business_prime_settings_control',100);\n }\n require_once dirname( __FILE__ ) . '/inc/business-prime-customizer.php';\n\n add_action( 'business_prime_settings_control_child', 'business_prime_child_customizer',10);\n</code></pre>\n\n<p>Based on other opinions, my parent theme, and to increase stability, I added the additional add action as a forced loop element. Then I replaced the necessary elements in the new child copy of the customizer::</p>\n\n<pre><code> function business_prime_settings_control_child($wp_customize) {\n # child.php customizer settings code\n }\n add_action('customize_register', 'business_prime_settings_control_child');\n</code></pre>\n\n<p>This approach yielded the better result as none of my customizer tabs, coding or functions, where lost and it removed particular parent theme marketing banners.</p>\n\n<p>This approach also worked for inc/functions.php file too::</p>\n\n<pre><code> add_action( 'init', 'remove_my_functions');\n function remove_my_functions() {\n remove_action('functions_register', 'business_prime_functions',100);\n}\n require_once dirname( __FILE__ ) . '/inc/business-prime-functions.php';\n\n add_action( 'business_prime_functions_child', 'business_prime_child_functions',10);\n</code></pre>\n\n<p>However, the aspect I was talking about being a \"95% resolve\" was surrounding the parent main functions.php file::</p>\n\n<pre><code> #require get_template_directory() . '/inc/business-prime-customizer.php';\n #require get_template_directory() . '/inc/business-prime-functions.php';\n require get_template_directory() . '/inc/business-prime-sanitize-cb.php';\n</code></pre>\n\n<p>Because the child theme functions is not overriding the hierarchy of the parent theme, out of the nine inc/parent.php files in the directory, I had to manually block out the two necessary ones to force the code to work; which I guess I will have to do again on the next update.</p>\n\n<p>Once again, thank you for time and you've been a great helping hand, keep up the good work.</p>\n\n<p>Kind Regards,\nJohn</p>\n"
}
] | 2019/06/22 | [
"https://wordpress.stackexchange.com/questions/341200",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/170479/"
] | I've cast a pretty wide net to find an answer but nothing seems to quite hit the mark.
Process:: I Login to my site/dashboard and I decide I need to edit a portion of my theme through the customiser, so I do, pretty straight forward...
In the mean time, I've built up my child theme and it seems to work pretty well for a novice and have generally figured out how to duplicate and edit particular .php files such as the footer, header etc... and, change (template to stylesheet) to load child theme images; however!
I wanted to change the social media links in my footer and had to scratch my head for a fews before figuring out how the customiser works and where the .php files are stored so I could change and add new fab fa.icons icon.
Problem:: my child theme function.php is doing what it needs to be doing, likewise with my pages, and is safeguarded form theme updates, however! not my new "customeriser" changes, so I have to go back in and change them time over...
I have found the location of the directory for the customiser, hence the ability to edit it, but to safeguard it from being changed is another thing.
The customiser files are duplicated to the child directory, then I load (along with tried variations of include, stylesheet, url)
```
require get_template_directory() . '/inc/business-prime-customizer.php';
```
it crashes my site...
So how do I point my child function.php at that new customiser address/files?
Many thanks and greatly appreciated
John | First remove action of customizer then add your action with new function name.
**in your child-theme functions.php**
```
add_action( 'init', 'remove_my_action');
function remove_my_action() {
remove_action('customize_register', 'business_prime_settings_control',10);
}
require_once dirname( __FILE__ ) . '/inc/business-prime-customizer.php';
```
**in your child-theme/inc/business-prime-customizer.php**
**change name of function and callback**
```
function business_prime_settings_control_child($wp_customize) {
# here your all customizer settings code
}
add_action('customize_register', 'business_prime_settings_control_child');
```
Remove other extra actions and declared functions. otherwise you will get : Cannot redeclare Fatal error. |
341,220 | <p>WordPress generates several thumbnail sizes and adding custom image sizes in a theme is great, but is there a way to view all URLs for a given image in WP, ideally right in the media library popup?</p>
<p>Currently if I want the "large" thumbnail URL of an image, I have to edit/add a Page/Post, add the image to the page, view the text editor and copy the URL out of the inserted <code><img src="goal_url.jpg" /></code>. Not very convenient!</p>
<p>For example, I'd use this to share a specific image crop on social media or to paste the correct URL in a theme/ plugin that doesn't use the media library correctly.</p>
<p>WP gives the full url src in the media popup, I'm looking for the thumbnail sizes as well.</p>
| [
{
"answer_id": 341202,
"author": "Mobeen Abdullah",
"author_id": 170482,
"author_profile": "https://wordpress.stackexchange.com/users/170482",
"pm_score": -1,
"selected": false,
"text": "<p>This should load the file from the child theme.</p>\n\n<pre><code>require get_stylesheet_directory() . '/inc/business-prime-customizer.php';\n</code></pre>\n\n<p>you should also set <code>WP_DEBUG</code> variable to <code>true</code> in <code>wp-config.php</code> file</p>\n\n<p>if you want to load any file from the parent theme then you will use</p>\n\n<pre><code>require get_template_directory() . '/path_to_the_file.php';\nor\nrequire get_template_directory_uri() . '/path_to_the_css_file.css';\n</code></pre>\n\n<p>if you want to load file from the current child theme or active theme.</p>\n\n<pre><code>require get_stylesheet_directory() . '/path_to_the_file.php';\nor\nrequire get_stylesheet_directory_uri() . '/path_to_the_css_file.css';\n</code></pre>\n"
},
{
"answer_id": 341203,
"author": "Chetan Vaghela",
"author_id": 169856,
"author_profile": "https://wordpress.stackexchange.com/users/169856",
"pm_score": 1,
"selected": true,
"text": "<p>First remove action of customizer then add your action with new function name.</p>\n\n<p><strong>in your child-theme functions.php</strong></p>\n\n<pre><code>add_action( 'init', 'remove_my_action');\nfunction remove_my_action() {\n remove_action('customize_register', 'business_prime_settings_control',10);\n}\nrequire_once dirname( __FILE__ ) . '/inc/business-prime-customizer.php';\n</code></pre>\n\n<p><strong>in your child-theme/inc/business-prime-customizer.php</strong>\n<strong>change name of function and callback</strong></p>\n\n<pre><code>function business_prime_settings_control_child($wp_customize) {\n # here your all customizer settings code\n}\nadd_action('customize_register', 'business_prime_settings_control_child');\n</code></pre>\n\n<p>Remove other extra actions and declared functions. otherwise you will get : Cannot redeclare Fatal error.</p>\n"
},
{
"answer_id": 341244,
"author": "Shadow Crown",
"author_id": 170479,
"author_profile": "https://wordpress.stackexchange.com/users/170479",
"pm_score": 0,
"selected": false,
"text": "<p>Just wanted to say thank you for your feedback it has, and without a boubt, been very helpful. Otherwise, one answer and its results have been better than the other. </p>\n\n<p>Just a little feedback of my own explorations...</p>\n\n<p>After exploring the net, there does seem to be a slight gap in undersatanding these things, more so referring to us novices/amatures and our questions, equally so, when the answers can be somewhat long and not to the point, so thanks for your patience there.</p>\n\n<p>Child theme creations seem to be quite the moot subject and, based on the parent theme, difficult to ensure they work properly. Therefore, based on your patience and obvious abilities, need to keep working at it, as such I'll keep exploring.</p>\n\n<p>I'm kind of thinking that the answers are within the development process of creating the parent themes itselves, if I choose to invest that much time and money into it, or commission someone. So what worked and yielded a greater result:</p>\n\n<p>As expected and to reduce the impact on the parent files, I duplicated the required parent files into the child theme, then as per advice added the following with a few tweaks.</p>\n\n<p>Child functions.php::</p>\n\n<pre><code> add_action( 'init', 'remove_my_customizer');\n function remove_my_customizer() {\n remove_action('customize_register', 'business_prime_settings_control',100);\n }\n require_once dirname( __FILE__ ) . '/inc/business-prime-customizer.php';\n\n add_action( 'business_prime_settings_control_child', 'business_prime_child_customizer',10);\n</code></pre>\n\n<p>Based on other opinions, my parent theme, and to increase stability, I added the additional add action as a forced loop element. Then I replaced the necessary elements in the new child copy of the customizer::</p>\n\n<pre><code> function business_prime_settings_control_child($wp_customize) {\n # child.php customizer settings code\n }\n add_action('customize_register', 'business_prime_settings_control_child');\n</code></pre>\n\n<p>This approach yielded the better result as none of my customizer tabs, coding or functions, where lost and it removed particular parent theme marketing banners.</p>\n\n<p>This approach also worked for inc/functions.php file too::</p>\n\n<pre><code> add_action( 'init', 'remove_my_functions');\n function remove_my_functions() {\n remove_action('functions_register', 'business_prime_functions',100);\n}\n require_once dirname( __FILE__ ) . '/inc/business-prime-functions.php';\n\n add_action( 'business_prime_functions_child', 'business_prime_child_functions',10);\n</code></pre>\n\n<p>However, the aspect I was talking about being a \"95% resolve\" was surrounding the parent main functions.php file::</p>\n\n<pre><code> #require get_template_directory() . '/inc/business-prime-customizer.php';\n #require get_template_directory() . '/inc/business-prime-functions.php';\n require get_template_directory() . '/inc/business-prime-sanitize-cb.php';\n</code></pre>\n\n<p>Because the child theme functions is not overriding the hierarchy of the parent theme, out of the nine inc/parent.php files in the directory, I had to manually block out the two necessary ones to force the code to work; which I guess I will have to do again on the next update.</p>\n\n<p>Once again, thank you for time and you've been a great helping hand, keep up the good work.</p>\n\n<p>Kind Regards,\nJohn</p>\n"
}
] | 2019/06/22 | [
"https://wordpress.stackexchange.com/questions/341220",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/31367/"
] | WordPress generates several thumbnail sizes and adding custom image sizes in a theme is great, but is there a way to view all URLs for a given image in WP, ideally right in the media library popup?
Currently if I want the "large" thumbnail URL of an image, I have to edit/add a Page/Post, add the image to the page, view the text editor and copy the URL out of the inserted `<img src="goal_url.jpg" />`. Not very convenient!
For example, I'd use this to share a specific image crop on social media or to paste the correct URL in a theme/ plugin that doesn't use the media library correctly.
WP gives the full url src in the media popup, I'm looking for the thumbnail sizes as well. | First remove action of customizer then add your action with new function name.
**in your child-theme functions.php**
```
add_action( 'init', 'remove_my_action');
function remove_my_action() {
remove_action('customize_register', 'business_prime_settings_control',10);
}
require_once dirname( __FILE__ ) . '/inc/business-prime-customizer.php';
```
**in your child-theme/inc/business-prime-customizer.php**
**change name of function and callback**
```
function business_prime_settings_control_child($wp_customize) {
# here your all customizer settings code
}
add_action('customize_register', 'business_prime_settings_control_child');
```
Remove other extra actions and declared functions. otherwise you will get : Cannot redeclare Fatal error. |
341,237 | <p>I have created a page for plugin. For that page i have added a checkbox meta field. The field is working fine.
By default, the checkbox field is unchecked. I mean at first to active the plugin, the checkbox field is unchecked.
But I need to make it check by default. I have tried a condition but not working at all. My code is :</p>
<pre><code>function ins_street_address_shortcode_callback(){
$val = get_option('ins_street_address_shortcode');
$checkval = "";
if ($val == 'on'){
$checkval = "checked";
}
printf("<input type='checkbox' name='ins_street_address_shortcode' %s />", $checkval);
}
</code></pre>
| [
{
"answer_id": 341239,
"author": "Camille V.",
"author_id": 140435,
"author_profile": "https://wordpress.stackexchange.com/users/140435",
"pm_score": 2,
"selected": false,
"text": "<p>Actually, your code is working, as long as <code>$val == 'on'</code>.</p>\n\n<p>Did you try debugging by doing <code>echo $val</code> ?</p>\n\n<p>If it's still not working, try <em>hard refreshing</em> (Ctrl + F5) your webpage, checkboxes tend to keep their state on normal refresh (F5).</p>\n\n<p>Also, please put your code directly on this forum, so the code is always accessible for future viewers ;)</p>\n"
},
{
"answer_id": 341258,
"author": "Roirraw",
"author_id": 170487,
"author_profile": "https://wordpress.stackexchange.com/users/170487",
"pm_score": 1,
"selected": false,
"text": "<p>If you want a HTML checkbox to be checked by default just add \"checked\" attribute:</p>\n\n<p><code>printf(\"<input type='checkbox' name='ins_street_address_shortcode' %s /> checked\", $checkval);</code></p>\n"
}
] | 2019/06/23 | [
"https://wordpress.stackexchange.com/questions/341237",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/170505/"
] | I have created a page for plugin. For that page i have added a checkbox meta field. The field is working fine.
By default, the checkbox field is unchecked. I mean at first to active the plugin, the checkbox field is unchecked.
But I need to make it check by default. I have tried a condition but not working at all. My code is :
```
function ins_street_address_shortcode_callback(){
$val = get_option('ins_street_address_shortcode');
$checkval = "";
if ($val == 'on'){
$checkval = "checked";
}
printf("<input type='checkbox' name='ins_street_address_shortcode' %s />", $checkval);
}
``` | Actually, your code is working, as long as `$val == 'on'`.
Did you try debugging by doing `echo $val` ?
If it's still not working, try *hard refreshing* (Ctrl + F5) your webpage, checkboxes tend to keep their state on normal refresh (F5).
Also, please put your code directly on this forum, so the code is always accessible for future viewers ;) |
341,299 | <p>When I try to upload a theme in my Wordpress website I need to fill in FTP credentials. </p>
<p>I've installed vsftpd on my Ubuntu 18.04 server. When I connect with the credentials in my FTP client (ex. Cyberduck on mac) I see the following:</p>
<p><a href="https://i.stack.imgur.com/7Ps5B.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7Ps5B.png" alt="enter image description here"></a></p>
<p>The problem is when I try this in Wordpress I get the error <code>FTP + Unable to locate WordPress content directory (wp-content).</code>. What could be the problem here?</p>
| [
{
"answer_id": 341305,
"author": "Owais Alam",
"author_id": 91939,
"author_profile": "https://wordpress.stackexchange.com/users/91939",
"pm_score": 3,
"selected": true,
"text": "<ul>\n<li>All files should be owned by the actual user's account, not the user account used for the httpd process.</li>\n<li>Group ownership is irrelevant unless there are specific group requirements for the web-server process permissions checking. This is not usually the case.</li>\n<li>All directories should be 755 or 750.</li>\n<li>All files should be 644 or 640. Exception: wp-config.php should be 440 or 400 to prevent other users on the server from reading it.</li>\n<li>No directories should ever be given 777, even upload directories. Since the PHP process is running as the owner of the files, it gets the owners permissions and - - can write to even a 755 directory.</li>\n</ul>\n\n<p>You can use</p>\n\n<pre><code>chown www-data:www-data -R * \nfind . -type d -exec chmod 755 {} \\; \nfind . -type f -exec chmod 644 {} \\;\n</code></pre>\n\n<p>you can also trying the following</p>\n\n<pre><code>add_filter('filesystem_method', create_function('$a', 'return \"direct\";' ));\ndefine( 'FS_CHMOD_DIR', 0751 );\ndefine('WP_TEMP_DIR', ABSPATH . 'wp-content/tmp');\n</code></pre>\n\n<p>The <code>tmp</code> folder wasn't having the permission and that caused the website plugins from updating.</p>\n"
},
{
"answer_id": 341306,
"author": "Ciprian",
"author_id": 7349,
"author_profile": "https://wordpress.stackexchange.com/users/7349",
"pm_score": 0,
"selected": false,
"text": "<p>You might be on one of those servers which move the <code>/wp-content/</code> directory one level up for security purposes.</p>\n\n<p>Did you ask the hosting provider for these details? Where are you hosted?</p>\n\n<p><strong>UPDATE:</strong> Check your <code>wp-config.php</code> file for these details:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>define( 'WP_CONTENT_DIR', dirname( __FILE__ ) . '/../wp-content' );\ndefine( 'WP_CONTENT_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wp-content' );\n</code></pre>\n"
}
] | 2019/06/24 | [
"https://wordpress.stackexchange.com/questions/341299",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/65180/"
] | When I try to upload a theme in my Wordpress website I need to fill in FTP credentials.
I've installed vsftpd on my Ubuntu 18.04 server. When I connect with the credentials in my FTP client (ex. Cyberduck on mac) I see the following:
[](https://i.stack.imgur.com/7Ps5B.png)
The problem is when I try this in Wordpress I get the error `FTP + Unable to locate WordPress content directory (wp-content).`. What could be the problem here? | * All files should be owned by the actual user's account, not the user account used for the httpd process.
* Group ownership is irrelevant unless there are specific group requirements for the web-server process permissions checking. This is not usually the case.
* All directories should be 755 or 750.
* All files should be 644 or 640. Exception: wp-config.php should be 440 or 400 to prevent other users on the server from reading it.
* No directories should ever be given 777, even upload directories. Since the PHP process is running as the owner of the files, it gets the owners permissions and - - can write to even a 755 directory.
You can use
```
chown www-data:www-data -R *
find . -type d -exec chmod 755 {} \;
find . -type f -exec chmod 644 {} \;
```
you can also trying the following
```
add_filter('filesystem_method', create_function('$a', 'return "direct";' ));
define( 'FS_CHMOD_DIR', 0751 );
define('WP_TEMP_DIR', ABSPATH . 'wp-content/tmp');
```
The `tmp` folder wasn't having the permission and that caused the website plugins from updating. |
341,328 | <p>I'm working on a setup where user logins <em>have to</em> follow this format : </p>
<blockquote>
<p>login : [email protected]</p>
</blockquote>
<p>Even though Wordpress has no problem creating such accounts, it seems they don't play well with the "Forgotten password" form :</p>
<p><a href="https://i.stack.imgur.com/mpJ9E.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mpJ9E.png" alt="enter image description here"></a></p>
<p>The culprit is in <code>wp-login.php</code> : </p>
<pre><code>function retrieve_password() {
$errors = new WP_Error();
if ( empty( $_POST['user_login'] ) || ! is_string( $_POST['user_login'] ) ) {
$errors->add( 'empty_username', __( '<strong>ERROR</strong>: Enter a username or email address.' ) );
} elseif ( strpos( $_POST['user_login'], '@' ) ) {
$user_data = get_user_by( 'email', trim( wp_unslash( $_POST['user_login'] ) ) );
if ( empty( $user_data ) ) {
$errors->add( 'invalid_email', __( '<strong>ERROR</strong>: There is no account with that username or email address.' ) );
}
} else {
$login = trim( $_POST['user_login'] );
$user_data = get_user_by( 'login', $login );
}
</code></pre>
<p>Specifically this line : </p>
<pre><code>} elseif ( strpos( $_POST['user_login'], '@' ) ) {
</code></pre>
<p>When Wordpress finds a @ in the login, it thinks that it's actually the email.</p>
<p>Is there a way to get around this without having to modifiy this core file ?</p>
<p>The two constraints I have is I cannot change the login format and the user has to submit his login (password reset calling the email field is not allowed, for reasons irrelevant to this tread)</p>
| [
{
"answer_id": 341582,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 0,
"selected": false,
"text": "<p>Usernames typically should not contain any special characters, only letters, numbers and the underline ( _ ) should be allowed. If a login contains @, then it should be interpreted as an email.</p>\n\n<p>I'm not sure what you meant by this:</p>\n\n<blockquote>\n <p>When Wordpress finds a @ in the login, it thinks that it's actually\n the email.</p>\n</blockquote>\n\n<p>If you are trying to implement custom login logics, you can create a page, assign a template to it and use your own code to reset password inside that page. After you are finished, you can use the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/lostpassword_url\" rel=\"nofollow noreferrer\"><code>lostpassword_url</code></a> filter to redirect users to this page to reset their passwords.</p>\n"
},
{
"answer_id": 341591,
"author": "Bhupen",
"author_id": 128529,
"author_profile": "https://wordpress.stackexchange.com/users/128529",
"pm_score": 2,
"selected": false,
"text": "<p>Create a custom template for forgot password and add forgot password page link to WordPress login page using theme functions.php. Please see the code given below and modify conditions as per your need.</p>\n\n<pre><code> <?php \n/*\n* Template Name: Forgot Password\n*/\n\nglobal $wpdb;\n\n$error = '';\n$success = '';\n\n// check if we're in reset form\nif( isset( $_POST['action'] ) && 'reset' == $_POST['action'] ) \n{\n $user_info = trim($_POST['user_login']);\n\n $user_by_email = get_user_by( 'email', $user_info ); \n $user_by_username = get_user_by( 'login', $user_info ); \n\n if( !empty( $user_by_email ) || !empty( $user_by_username ) ) {\n $valid_user = true;\n } else {\n $valid_user = false;\n }\n\n if( !$valid_user ) {\n $error = 'There is no user registered with that username or email address.';\n } else {\n\n $random_password = wp_generate_password( 12, false );\n $user = get_user_by( 'email', $email );\n\n $update_user = wp_update_user( array (\n 'ID' => $user->ID, \n 'user_pass' => $random_password\n )\n );\n\n // if update user return true then lets send user an email containing the new password\n if( $update_user ) {\n $to = $email;\n $subject = 'Your new password';\n $sender = get_option('name');\n\n $message = 'Your new password is: '.$random_password;\n\n $headers[] = 'MIME-Version: 1.0' . \"\\r\\n\";\n $headers[] = 'Content-type: text/html; charset=iso-8859-1' . \"\\r\\n\";\n $headers[] = \"X-Mailer: PHP \\r\\n\";\n $headers[] = 'From: '.$sender.' < '.$email.'>' . \"\\r\\n\";\n\n $mail = wp_mail( $to, $subject, $message, $headers );\n if( $mail )\n $success = 'Check your email address for you new password.';\n\n } else {\n $error = 'Oops something went wrong updaing your account.';\n }\n\n }\n\n if( ! empty( $error ) )\n echo '<div class=\"message\"><p class=\"error\"><strong>ERROR:</strong> '. $error .'</p></div>';\n\n if( ! empty( $success ) )\n echo '<div class=\"error_login\"><p class=\"success\">'. $success .'</p></div>';\n}\n?>\n\n\n<form method=\"post\">\n <fieldset>\n <p>Please enter your username or email address. You will receive a link to create a new password via email.</p>\n <p><label for=\"user_login\">Username or E-mail:</label>\n <?php $user_login = isset( $_POST['user_login'] ) ? $_POST['user_login'] : ''; ?>\n <input type=\"text\" name=\"user_login\" id=\"user_login\" value=\"<?php echo $user_login; ?>\" /></p>\n <p>\n <input type=\"hidden\" name=\"action\" value=\"reset\" />\n <input type=\"submit\" value=\"Get New Password\" class=\"button\" id=\"submit\" />\n </p>\n </fieldset> \n</form> \n</code></pre>\n\n<p>And add the code given below to change forgot password page link.</p>\n\n<pre><code>add_filter( 'lostpassword_url', 'my_lost_password_page', 10, 2 );\nfunction my_lost_password_page( $lostpassword_url, $redirect ) {\n return 'your custom page link';\n}\n</code></pre>\n"
},
{
"answer_id": 341616,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<p>I would not recommend using the email address as username, for post authors, as this could expose the emails to the public.</p>\n\n<p>If <code>[email protected]</code> has written any posts, the author archive will be accessible with:</p>\n\n<pre><code>https://example.com/author/user-johnexample-com/\n</code></pre>\n\n<p>or from the redirection of e.g.:</p>\n\n<pre><code>https://example.com/?author=123\n</code></pre>\n\n<p>The REST API users endpoint also outputs similar information for post authors.</p>\n\n<p>Modifying an important part like the login flow, could also introduce technical dept to ensure the security and exposure is intact after each core/theme/plugin update.</p>\n"
}
] | 2019/06/24 | [
"https://wordpress.stackexchange.com/questions/341328",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1381/"
] | I'm working on a setup where user logins *have to* follow this format :
>
> login : [email protected]
>
>
>
Even though Wordpress has no problem creating such accounts, it seems they don't play well with the "Forgotten password" form :
[](https://i.stack.imgur.com/mpJ9E.png)
The culprit is in `wp-login.php` :
```
function retrieve_password() {
$errors = new WP_Error();
if ( empty( $_POST['user_login'] ) || ! is_string( $_POST['user_login'] ) ) {
$errors->add( 'empty_username', __( '<strong>ERROR</strong>: Enter a username or email address.' ) );
} elseif ( strpos( $_POST['user_login'], '@' ) ) {
$user_data = get_user_by( 'email', trim( wp_unslash( $_POST['user_login'] ) ) );
if ( empty( $user_data ) ) {
$errors->add( 'invalid_email', __( '<strong>ERROR</strong>: There is no account with that username or email address.' ) );
}
} else {
$login = trim( $_POST['user_login'] );
$user_data = get_user_by( 'login', $login );
}
```
Specifically this line :
```
} elseif ( strpos( $_POST['user_login'], '@' ) ) {
```
When Wordpress finds a @ in the login, it thinks that it's actually the email.
Is there a way to get around this without having to modifiy this core file ?
The two constraints I have is I cannot change the login format and the user has to submit his login (password reset calling the email field is not allowed, for reasons irrelevant to this tread) | Create a custom template for forgot password and add forgot password page link to WordPress login page using theme functions.php. Please see the code given below and modify conditions as per your need.
```
<?php
/*
* Template Name: Forgot Password
*/
global $wpdb;
$error = '';
$success = '';
// check if we're in reset form
if( isset( $_POST['action'] ) && 'reset' == $_POST['action'] )
{
$user_info = trim($_POST['user_login']);
$user_by_email = get_user_by( 'email', $user_info );
$user_by_username = get_user_by( 'login', $user_info );
if( !empty( $user_by_email ) || !empty( $user_by_username ) ) {
$valid_user = true;
} else {
$valid_user = false;
}
if( !$valid_user ) {
$error = 'There is no user registered with that username or email address.';
} else {
$random_password = wp_generate_password( 12, false );
$user = get_user_by( 'email', $email );
$update_user = wp_update_user( array (
'ID' => $user->ID,
'user_pass' => $random_password
)
);
// if update user return true then lets send user an email containing the new password
if( $update_user ) {
$to = $email;
$subject = 'Your new password';
$sender = get_option('name');
$message = 'Your new password is: '.$random_password;
$headers[] = 'MIME-Version: 1.0' . "\r\n";
$headers[] = 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers[] = "X-Mailer: PHP \r\n";
$headers[] = 'From: '.$sender.' < '.$email.'>' . "\r\n";
$mail = wp_mail( $to, $subject, $message, $headers );
if( $mail )
$success = 'Check your email address for you new password.';
} else {
$error = 'Oops something went wrong updaing your account.';
}
}
if( ! empty( $error ) )
echo '<div class="message"><p class="error"><strong>ERROR:</strong> '. $error .'</p></div>';
if( ! empty( $success ) )
echo '<div class="error_login"><p class="success">'. $success .'</p></div>';
}
?>
<form method="post">
<fieldset>
<p>Please enter your username or email address. You will receive a link to create a new password via email.</p>
<p><label for="user_login">Username or E-mail:</label>
<?php $user_login = isset( $_POST['user_login'] ) ? $_POST['user_login'] : ''; ?>
<input type="text" name="user_login" id="user_login" value="<?php echo $user_login; ?>" /></p>
<p>
<input type="hidden" name="action" value="reset" />
<input type="submit" value="Get New Password" class="button" id="submit" />
</p>
</fieldset>
</form>
```
And add the code given below to change forgot password page link.
```
add_filter( 'lostpassword_url', 'my_lost_password_page', 10, 2 );
function my_lost_password_page( $lostpassword_url, $redirect ) {
return 'your custom page link';
}
``` |
341,339 | <p>How I can Activate and deactivate plugin automatically?
For example,
I want the "Yoast Seo" plugin to be active only on Monday, Wednesday, Friday, Saturday and the other days deactivated.
How can I do it?
Thanks..</p>
| [
{
"answer_id": 341341,
"author": "Liam Stewart",
"author_id": 121955,
"author_profile": "https://wordpress.stackexchange.com/users/121955",
"pm_score": 0,
"selected": false,
"text": "<p>You can mange this by adding the following to your <code>functions.php</code> file.</p>\n\n<p>Checking todays timestamp for the days you want the plugin active - on the off days the plugin is disabled.</p>\n\n<pre><code>$timestamp = time(); // Timestamp\n$day = date( 'D', $timestamp ); // Get day from timestamp\n$active = array( 'Mon', 'Wed', 'Fri', 'Sat' ); // Days plugin to be active\nif ( in_array( $day, $active, true ) ) { // Yoast SEO is active\n activate_plugin( '/wordpress-seo/wp-seo.php' );\n} else { // Yoast SEO is deactivated\n deactivate_plugins( '/wordpress-seo/wp-seo.php' );\n}\n</code></pre>\n\n<p>It uses <code>activate_plugin()</code> to activate and <code>deactivate_plugins()</code> to deactivate the plugin.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/activate_plugin/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/activate_plugin/</a>\n<a href=\"https://developer.wordpress.org/reference/functions/deactivate_plugins/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/deactivate_plugins/</a></p>\n"
},
{
"answer_id": 341346,
"author": "ChristopherJones",
"author_id": 168744,
"author_profile": "https://wordpress.stackexchange.com/users/168744",
"pm_score": 1,
"selected": false,
"text": "<p>I like the idea of running this through a schedule event in WordPress, <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<p>Here is a snippet that hopefully will get you there:</p>\n<pre><code><?php\n \n if(!wp_next_scheduled('daily_plugin_check')){\n wp_schedule_event( time(), 'daily', 'daily_plugin_check' );\n }\n\n add_action( 'daily_plugin_check', 'toggle_plugins' );\n\n function toggle_plugins() {\n switch(date('D')){\n case 'Mon' :\n case 'Wed' :\n case 'Fri' :\n // Could be an array or a single string\n $plugin_to_activate = 'akismet/akismet.php';\n $plugin_to_deactivate = 'akismet/akismet.php';\n break;\n // Continue with each day you'd like to activate / deactive them\n }\n\n if(!function_exists('activate_plugin')){\n require_once ABSPATH . 'wp-admin/includes/plugin.php';\n }\n\n if(!empty($plugin_to_activate){\n // If $plugin_to_activate is an array, then you can foreach of it\n if(!is_plugin_active($plugin_to_activate)){\n activate_plugin($plugin_to_activate);\n }\n }\n\n if(!empty($plugin_to_deactivate){\n // If $plugin_to_activate is an array, then you can foreach of it\n if(is_plugin_active($plugin_to_deactivate)){\n deactivate_plugins($plugin_to_deactivate);\n }\n }\n\n }\n\n</code></pre>\n<p>Hope that helps!</p>\n"
}
] | 2019/06/24 | [
"https://wordpress.stackexchange.com/questions/341339",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/135643/"
] | How I can Activate and deactivate plugin automatically?
For example,
I want the "Yoast Seo" plugin to be active only on Monday, Wednesday, Friday, Saturday and the other days deactivated.
How can I do it?
Thanks.. | I like the idea of running this through a schedule event in WordPress, <https://codex.wordpress.org/Function_Reference/wp_schedule_event>
Here is a snippet that hopefully will get you there:
```
<?php
if(!wp_next_scheduled('daily_plugin_check')){
wp_schedule_event( time(), 'daily', 'daily_plugin_check' );
}
add_action( 'daily_plugin_check', 'toggle_plugins' );
function toggle_plugins() {
switch(date('D')){
case 'Mon' :
case 'Wed' :
case 'Fri' :
// Could be an array or a single string
$plugin_to_activate = 'akismet/akismet.php';
$plugin_to_deactivate = 'akismet/akismet.php';
break;
// Continue with each day you'd like to activate / deactive them
}
if(!function_exists('activate_plugin')){
require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
if(!empty($plugin_to_activate){
// If $plugin_to_activate is an array, then you can foreach of it
if(!is_plugin_active($plugin_to_activate)){
activate_plugin($plugin_to_activate);
}
}
if(!empty($plugin_to_deactivate){
// If $plugin_to_activate is an array, then you can foreach of it
if(is_plugin_active($plugin_to_deactivate)){
deactivate_plugins($plugin_to_deactivate);
}
}
}
```
Hope that helps! |
341,347 | <p>I've been working on a project and I just cant pull the data from this API.
I'm developing a plugin that's supposed to pull data from an API and then use that data.
I developed this project offline and after it was working I started developing inside the WordPress plugin space.</p>
<p>but for some reason i'm not getting any data.</p>
<hr>
<p>Following is my request.</p>
<pre><code>add_action( 'wp_loaded', 'precious_metals' );
function precious_metals ( ) {
$content = file_get_contents("A WORKING API"); //Doing this for a client so hiding the API to be safe ;)
$result = json_decode($content);
}
</code></pre>
<hr>
<p>Following is my display(which is working offline).
The table headings do display but no data
is being pulled from the API.</p>
<pre><code><H4>New data fetched</H4>
<table border = solid 1px>
<tr>
<td><b>Type</b></td>
<td><b>$value</b></td>
</tr>
<?php foreach($result as $key=>$value): ?>
<tr>
<td><?php echo $key; ?></td>
<td><?php echo $value; ?></td>
</tr>
<?php endforeach; ?>
</table>
</code></pre>
| [
{
"answer_id": 341341,
"author": "Liam Stewart",
"author_id": 121955,
"author_profile": "https://wordpress.stackexchange.com/users/121955",
"pm_score": 0,
"selected": false,
"text": "<p>You can mange this by adding the following to your <code>functions.php</code> file.</p>\n\n<p>Checking todays timestamp for the days you want the plugin active - on the off days the plugin is disabled.</p>\n\n<pre><code>$timestamp = time(); // Timestamp\n$day = date( 'D', $timestamp ); // Get day from timestamp\n$active = array( 'Mon', 'Wed', 'Fri', 'Sat' ); // Days plugin to be active\nif ( in_array( $day, $active, true ) ) { // Yoast SEO is active\n activate_plugin( '/wordpress-seo/wp-seo.php' );\n} else { // Yoast SEO is deactivated\n deactivate_plugins( '/wordpress-seo/wp-seo.php' );\n}\n</code></pre>\n\n<p>It uses <code>activate_plugin()</code> to activate and <code>deactivate_plugins()</code> to deactivate the plugin.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/activate_plugin/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/activate_plugin/</a>\n<a href=\"https://developer.wordpress.org/reference/functions/deactivate_plugins/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/deactivate_plugins/</a></p>\n"
},
{
"answer_id": 341346,
"author": "ChristopherJones",
"author_id": 168744,
"author_profile": "https://wordpress.stackexchange.com/users/168744",
"pm_score": 1,
"selected": false,
"text": "<p>I like the idea of running this through a schedule event in WordPress, <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<p>Here is a snippet that hopefully will get you there:</p>\n<pre><code><?php\n \n if(!wp_next_scheduled('daily_plugin_check')){\n wp_schedule_event( time(), 'daily', 'daily_plugin_check' );\n }\n\n add_action( 'daily_plugin_check', 'toggle_plugins' );\n\n function toggle_plugins() {\n switch(date('D')){\n case 'Mon' :\n case 'Wed' :\n case 'Fri' :\n // Could be an array or a single string\n $plugin_to_activate = 'akismet/akismet.php';\n $plugin_to_deactivate = 'akismet/akismet.php';\n break;\n // Continue with each day you'd like to activate / deactive them\n }\n\n if(!function_exists('activate_plugin')){\n require_once ABSPATH . 'wp-admin/includes/plugin.php';\n }\n\n if(!empty($plugin_to_activate){\n // If $plugin_to_activate is an array, then you can foreach of it\n if(!is_plugin_active($plugin_to_activate)){\n activate_plugin($plugin_to_activate);\n }\n }\n\n if(!empty($plugin_to_deactivate){\n // If $plugin_to_activate is an array, then you can foreach of it\n if(is_plugin_active($plugin_to_deactivate)){\n deactivate_plugins($plugin_to_deactivate);\n }\n }\n\n }\n\n</code></pre>\n<p>Hope that helps!</p>\n"
}
] | 2019/06/24 | [
"https://wordpress.stackexchange.com/questions/341347",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/170591/"
] | I've been working on a project and I just cant pull the data from this API.
I'm developing a plugin that's supposed to pull data from an API and then use that data.
I developed this project offline and after it was working I started developing inside the WordPress plugin space.
but for some reason i'm not getting any data.
---
Following is my request.
```
add_action( 'wp_loaded', 'precious_metals' );
function precious_metals ( ) {
$content = file_get_contents("A WORKING API"); //Doing this for a client so hiding the API to be safe ;)
$result = json_decode($content);
}
```
---
Following is my display(which is working offline).
The table headings do display but no data
is being pulled from the API.
```
<H4>New data fetched</H4>
<table border = solid 1px>
<tr>
<td><b>Type</b></td>
<td><b>$value</b></td>
</tr>
<?php foreach($result as $key=>$value): ?>
<tr>
<td><?php echo $key; ?></td>
<td><?php echo $value; ?></td>
</tr>
<?php endforeach; ?>
</table>
``` | I like the idea of running this through a schedule event in WordPress, <https://codex.wordpress.org/Function_Reference/wp_schedule_event>
Here is a snippet that hopefully will get you there:
```
<?php
if(!wp_next_scheduled('daily_plugin_check')){
wp_schedule_event( time(), 'daily', 'daily_plugin_check' );
}
add_action( 'daily_plugin_check', 'toggle_plugins' );
function toggle_plugins() {
switch(date('D')){
case 'Mon' :
case 'Wed' :
case 'Fri' :
// Could be an array or a single string
$plugin_to_activate = 'akismet/akismet.php';
$plugin_to_deactivate = 'akismet/akismet.php';
break;
// Continue with each day you'd like to activate / deactive them
}
if(!function_exists('activate_plugin')){
require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
if(!empty($plugin_to_activate){
// If $plugin_to_activate is an array, then you can foreach of it
if(!is_plugin_active($plugin_to_activate)){
activate_plugin($plugin_to_activate);
}
}
if(!empty($plugin_to_deactivate){
// If $plugin_to_activate is an array, then you can foreach of it
if(is_plugin_active($plugin_to_deactivate)){
deactivate_plugins($plugin_to_deactivate);
}
}
}
```
Hope that helps! |
341,407 | <p>Since Wordpress 5.2 can not display errors on the site.
The constants "<em>WP_DEBUG</em>" et "<em>WP_DEBUG_DISPLAY</em>" doesn't work.
The following message is always displayed : "The site is experiencing technical difficulties. Please check your site admin email inbox for instructions."</p>
<p>Have you solution?</p>
| [
{
"answer_id": 341414,
"author": "ChristopherJones",
"author_id": 168744,
"author_profile": "https://wordpress.stackexchange.com/users/168744",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe I am wrong here, but <code>define( 'WP_DEBUG', true );</code> is still available and works in installs 5.2 and after.</p>\n\n<p>According to WordPress docs: <a href=\"https://codex.wordpress.org/WP_DEBUG\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/WP_DEBUG</a></p>\n\n<blockquote>\n <p>Starting with WordPress version 2.5, setting WP_DEBUG to true also raises the error reporting level to E_ALL and activates warnings when deprecated functions or files are used; otherwise, WordPress sets the error reporting level to E_ALL ^ E_NOTICE ^ E_USER_NOTICE.</p>\n</blockquote>\n\n<p>Edit: Here is how things play out in the back end. <a href=\"https://core.trac.wordpress.org/browser/tags/5.2/src/wp-includes/load.php#L321\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/browser/tags/5.2/src/wp-includes/load.php#L321</a></p>\n\n<p>There is nothing in there that says it is deprecated or being removed. And that error reporting level are set correctly.</p>\n\n<p>I just tested it in my environment by setting <strong>WP_DEBUG</strong> to true inside of the wp-config.php file. And it gave the same <em>The site is experiencing technical difficulties. Please check your site admin email inbox for instructions</em> message, but also gave me the syntax error I put into my site to test and break it. I am running PHP 7.2</p>\n"
},
{
"answer_id": 341415,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>You can disable this behaviour by setting <code>WP_DISABLE_FATAL_ERROR_HANDLER</code> to <code>true</code>:</p>\n\n<pre><code>define( 'WP_DISABLE_FATAL_ERROR_HANDLER', true );\n</code></pre>\n\n<p>This will stop the \"The site is experiencing technical difficulties\" message from appearing, so errors will appear as they did prior to this feature being added.</p>\n"
},
{
"answer_id": 341434,
"author": "Orange Publishers",
"author_id": 170662,
"author_profile": "https://wordpress.stackexchange.com/users/170662",
"pm_score": 0,
"selected": false,
"text": "<p>I have checked this code on WordPress 5.2 <code>define( 'WP_DEBUG', true );</code>\nand it is perfectly working. I think you should reinstall the WordPress.</p>\n"
}
] | 2019/06/25 | [
"https://wordpress.stackexchange.com/questions/341407",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/170642/"
] | Since Wordpress 5.2 can not display errors on the site.
The constants "*WP\_DEBUG*" et "*WP\_DEBUG\_DISPLAY*" doesn't work.
The following message is always displayed : "The site is experiencing technical difficulties. Please check your site admin email inbox for instructions."
Have you solution? | You can disable this behaviour by setting `WP_DISABLE_FATAL_ERROR_HANDLER` to `true`:
```
define( 'WP_DISABLE_FATAL_ERROR_HANDLER', true );
```
This will stop the "The site is experiencing technical difficulties" message from appearing, so errors will appear as they did prior to this feature being added. |
341,408 | <p>I am tring to implement custom filter for The Event Calendar. I have used this code</p>
<pre><code>$args = array(
'post_type' => 'tribe_events',
'meta_key' => '_EventStartDate',
'meta_query' => array(
array(
'key' => '_EventStartDate',
'value' => array( $start_date, $end_date ),
'compare' => 'BETWEEN',
'type' => 'DATE'
)
),
'category__in' => array( 2, 6 )
);
$query = new WP_Query($args);
</code></pre>
<p>It will return blank post</p>
| [
{
"answer_id": 341414,
"author": "ChristopherJones",
"author_id": 168744,
"author_profile": "https://wordpress.stackexchange.com/users/168744",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe I am wrong here, but <code>define( 'WP_DEBUG', true );</code> is still available and works in installs 5.2 and after.</p>\n\n<p>According to WordPress docs: <a href=\"https://codex.wordpress.org/WP_DEBUG\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/WP_DEBUG</a></p>\n\n<blockquote>\n <p>Starting with WordPress version 2.5, setting WP_DEBUG to true also raises the error reporting level to E_ALL and activates warnings when deprecated functions or files are used; otherwise, WordPress sets the error reporting level to E_ALL ^ E_NOTICE ^ E_USER_NOTICE.</p>\n</blockquote>\n\n<p>Edit: Here is how things play out in the back end. <a href=\"https://core.trac.wordpress.org/browser/tags/5.2/src/wp-includes/load.php#L321\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/browser/tags/5.2/src/wp-includes/load.php#L321</a></p>\n\n<p>There is nothing in there that says it is deprecated or being removed. And that error reporting level are set correctly.</p>\n\n<p>I just tested it in my environment by setting <strong>WP_DEBUG</strong> to true inside of the wp-config.php file. And it gave the same <em>The site is experiencing technical difficulties. Please check your site admin email inbox for instructions</em> message, but also gave me the syntax error I put into my site to test and break it. I am running PHP 7.2</p>\n"
},
{
"answer_id": 341415,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>You can disable this behaviour by setting <code>WP_DISABLE_FATAL_ERROR_HANDLER</code> to <code>true</code>:</p>\n\n<pre><code>define( 'WP_DISABLE_FATAL_ERROR_HANDLER', true );\n</code></pre>\n\n<p>This will stop the \"The site is experiencing technical difficulties\" message from appearing, so errors will appear as they did prior to this feature being added.</p>\n"
},
{
"answer_id": 341434,
"author": "Orange Publishers",
"author_id": 170662,
"author_profile": "https://wordpress.stackexchange.com/users/170662",
"pm_score": 0,
"selected": false,
"text": "<p>I have checked this code on WordPress 5.2 <code>define( 'WP_DEBUG', true );</code>\nand it is perfectly working. I think you should reinstall the WordPress.</p>\n"
}
] | 2019/06/25 | [
"https://wordpress.stackexchange.com/questions/341408",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115907/"
] | I am tring to implement custom filter for The Event Calendar. I have used this code
```
$args = array(
'post_type' => 'tribe_events',
'meta_key' => '_EventStartDate',
'meta_query' => array(
array(
'key' => '_EventStartDate',
'value' => array( $start_date, $end_date ),
'compare' => 'BETWEEN',
'type' => 'DATE'
)
),
'category__in' => array( 2, 6 )
);
$query = new WP_Query($args);
```
It will return blank post | You can disable this behaviour by setting `WP_DISABLE_FATAL_ERROR_HANDLER` to `true`:
```
define( 'WP_DISABLE_FATAL_ERROR_HANDLER', true );
```
This will stop the "The site is experiencing technical difficulties" message from appearing, so errors will appear as they did prior to this feature being added. |
341,419 | <pre><code><div class="row">
<?php
$taxonomyName = "product_tag";
if($taxonomyname = "latest-product"){
//This gets top layer terms only. This is done by setting parent to 0.
$parent_terms = get_terms($taxonomyName, array('parent' => 0, 'orderby' => 'term_id', 'hide_empty' => true, 'order' => 'ASC'));
foreach ($parent_terms as $pterm) { ?>
<div class="col-xs-3 col-md-3 padding_fix">
<a href="<?php echo get_term_link($pterm->name, $taxonomyName); ?>">
<?php
$thumbnail_id = get_woocommerce_term_meta($pterm->term_id, 'thumbnail_id', true);
// get the image URL for parent category
$image = wp_get_attachment_url($thumbnail_id);
echo '<img src="'.$image.'" alt="" width="762" height="365" />'; ?>
<h3 class="text-center" style="color: #fff;"><?php echo $pterm->name; ?></h3>
</a>
</div>
<?php } ?>
<?php } ?>
</code></pre>
<p>this is my above code where i want to display product with latest-product tag name.</p>
<p>I am not able to display product by latest-product tag.</p>
| [
{
"answer_id": 341414,
"author": "ChristopherJones",
"author_id": 168744,
"author_profile": "https://wordpress.stackexchange.com/users/168744",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe I am wrong here, but <code>define( 'WP_DEBUG', true );</code> is still available and works in installs 5.2 and after.</p>\n\n<p>According to WordPress docs: <a href=\"https://codex.wordpress.org/WP_DEBUG\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/WP_DEBUG</a></p>\n\n<blockquote>\n <p>Starting with WordPress version 2.5, setting WP_DEBUG to true also raises the error reporting level to E_ALL and activates warnings when deprecated functions or files are used; otherwise, WordPress sets the error reporting level to E_ALL ^ E_NOTICE ^ E_USER_NOTICE.</p>\n</blockquote>\n\n<p>Edit: Here is how things play out in the back end. <a href=\"https://core.trac.wordpress.org/browser/tags/5.2/src/wp-includes/load.php#L321\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/browser/tags/5.2/src/wp-includes/load.php#L321</a></p>\n\n<p>There is nothing in there that says it is deprecated or being removed. And that error reporting level are set correctly.</p>\n\n<p>I just tested it in my environment by setting <strong>WP_DEBUG</strong> to true inside of the wp-config.php file. And it gave the same <em>The site is experiencing technical difficulties. Please check your site admin email inbox for instructions</em> message, but also gave me the syntax error I put into my site to test and break it. I am running PHP 7.2</p>\n"
},
{
"answer_id": 341415,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>You can disable this behaviour by setting <code>WP_DISABLE_FATAL_ERROR_HANDLER</code> to <code>true</code>:</p>\n\n<pre><code>define( 'WP_DISABLE_FATAL_ERROR_HANDLER', true );\n</code></pre>\n\n<p>This will stop the \"The site is experiencing technical difficulties\" message from appearing, so errors will appear as they did prior to this feature being added.</p>\n"
},
{
"answer_id": 341434,
"author": "Orange Publishers",
"author_id": 170662,
"author_profile": "https://wordpress.stackexchange.com/users/170662",
"pm_score": 0,
"selected": false,
"text": "<p>I have checked this code on WordPress 5.2 <code>define( 'WP_DEBUG', true );</code>\nand it is perfectly working. I think you should reinstall the WordPress.</p>\n"
}
] | 2019/06/25 | [
"https://wordpress.stackexchange.com/questions/341419",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/134743/"
] | ```
<div class="row">
<?php
$taxonomyName = "product_tag";
if($taxonomyname = "latest-product"){
//This gets top layer terms only. This is done by setting parent to 0.
$parent_terms = get_terms($taxonomyName, array('parent' => 0, 'orderby' => 'term_id', 'hide_empty' => true, 'order' => 'ASC'));
foreach ($parent_terms as $pterm) { ?>
<div class="col-xs-3 col-md-3 padding_fix">
<a href="<?php echo get_term_link($pterm->name, $taxonomyName); ?>">
<?php
$thumbnail_id = get_woocommerce_term_meta($pterm->term_id, 'thumbnail_id', true);
// get the image URL for parent category
$image = wp_get_attachment_url($thumbnail_id);
echo '<img src="'.$image.'" alt="" width="762" height="365" />'; ?>
<h3 class="text-center" style="color: #fff;"><?php echo $pterm->name; ?></h3>
</a>
</div>
<?php } ?>
<?php } ?>
```
this is my above code where i want to display product with latest-product tag name.
I am not able to display product by latest-product tag. | You can disable this behaviour by setting `WP_DISABLE_FATAL_ERROR_HANDLER` to `true`:
```
define( 'WP_DISABLE_FATAL_ERROR_HANDLER', true );
```
This will stop the "The site is experiencing technical difficulties" message from appearing, so errors will appear as they did prior to this feature being added. |
341,428 | <p>So I'm trying to connect to an external db in order to access/update information located on a different non-wordpress database (oracle).</p>
<p>I tried constructing a new wpdb object (as suggested by many other posts on stack exchange) like so:</p>
<pre><code>function initialize_rgr_db() {
global $rgr_db;
$rgr_db = new wpdb('usr', 'pw', 'sid', 'host');
}
</code></pre>
<p>However, I kept getting the "error connecting to database" when vardumping the $rgr_db object</p>
<p>debug.log displayed the following:</p>
<pre><code>PHP Warning: mysqli_real_connect(): (HY000/2003): Can't connect to MySQL server on 'host' (111) in /home/dowxx543z3a1/public_html/wp-includes/wp-db.php on line 1612
</code></pre>
<p>Alternatively, I tried using oci_connect like so:</p>
<pre><code>$conn = oci_connect('usr', 'pw', '(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(Host=host)(Port=1521)))(CONNECT_DATA=(SID=sid)))');
if(!$conn) {
error_log('DB CONNECTION ERROR NOOO');
die();
}
...
</code></pre>
<p>But then I got call to undefined function.</p>
<p>Based on what I found, it seems like oci8 is not installed in wordpress. Online I found instructions on how to install oci8 on things like xampp or local environments, but nothing related to wordpress and frankly I'm afraid to mess something up.</p>
<p>So, here's my question. If someone could tell me what I'm doing wrong with wpdb, I'd love to find out. My guess is maybe that the oracle sid != the dbname that wpdb requires as the third argument.</p>
<p>Otherwise, could someone offer some guidance as to how to install oci8 (through cpanel)?</p>
<p>Thank you so much.</p>
| [
{
"answer_id": 341433,
"author": "ChristopherJones",
"author_id": 168744,
"author_profile": "https://wordpress.stackexchange.com/users/168744",
"pm_score": 1,
"selected": false,
"text": "<p>Have you tried the PDO Class yet?</p>\n\n<pre><code>$db = new PDO(\"sqlsrv:Server=YouAddress;Database=YourDatabase\", \"Username\", \"Password\");\n</code></pre>\n\n<p>If that fails, I think you might need specific drivers setup on your WordPress hosting environment to talk to that Oracle DB. (At least to get the PDO class working) <a href=\"https://www.php.net/manual/en/ref.pdo-oci.php\" rel=\"nofollow noreferrer\">https://www.php.net/manual/en/ref.pdo-oci.php</a></p>\n"
},
{
"answer_id": 341435,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p><strong>You can't use <code>WPDB</code> to connect to databases that aren't MySQL/MariaDB based.</strong></p>\n\n<p>There are no WordPress APIs or WP based solutions that will do this. Instead you will need to use a general PHP solution inside your plugin, and should look at general PHP resources and communities, not WP ones.</p>\n\n<p>I can also guarantee, that this will require additional PHP extensions to be installed, not just PHP code. Doing this will require root access to the server, and will require your host to get involved.</p>\n\n<p>You should consult with stack overflow on how to use that PHP extension, and Serverfault for how to install it, either way you have left the realm of WordPress expertise and knowledge.</p>\n\n<p>As an aside, have you considered setting up a REST API at the other end you can talk to?</p>\n"
}
] | 2019/06/25 | [
"https://wordpress.stackexchange.com/questions/341428",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/153230/"
] | So I'm trying to connect to an external db in order to access/update information located on a different non-wordpress database (oracle).
I tried constructing a new wpdb object (as suggested by many other posts on stack exchange) like so:
```
function initialize_rgr_db() {
global $rgr_db;
$rgr_db = new wpdb('usr', 'pw', 'sid', 'host');
}
```
However, I kept getting the "error connecting to database" when vardumping the $rgr\_db object
debug.log displayed the following:
```
PHP Warning: mysqli_real_connect(): (HY000/2003): Can't connect to MySQL server on 'host' (111) in /home/dowxx543z3a1/public_html/wp-includes/wp-db.php on line 1612
```
Alternatively, I tried using oci\_connect like so:
```
$conn = oci_connect('usr', 'pw', '(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(Host=host)(Port=1521)))(CONNECT_DATA=(SID=sid)))');
if(!$conn) {
error_log('DB CONNECTION ERROR NOOO');
die();
}
...
```
But then I got call to undefined function.
Based on what I found, it seems like oci8 is not installed in wordpress. Online I found instructions on how to install oci8 on things like xampp or local environments, but nothing related to wordpress and frankly I'm afraid to mess something up.
So, here's my question. If someone could tell me what I'm doing wrong with wpdb, I'd love to find out. My guess is maybe that the oracle sid != the dbname that wpdb requires as the third argument.
Otherwise, could someone offer some guidance as to how to install oci8 (through cpanel)?
Thank you so much. | **You can't use `WPDB` to connect to databases that aren't MySQL/MariaDB based.**
There are no WordPress APIs or WP based solutions that will do this. Instead you will need to use a general PHP solution inside your plugin, and should look at general PHP resources and communities, not WP ones.
I can also guarantee, that this will require additional PHP extensions to be installed, not just PHP code. Doing this will require root access to the server, and will require your host to get involved.
You should consult with stack overflow on how to use that PHP extension, and Serverfault for how to install it, either way you have left the realm of WordPress expertise and knowledge.
As an aside, have you considered setting up a REST API at the other end you can talk to? |
341,460 | <p>I want to run a script before any Wordpress stuff kicks in.</p>
<p>I know it's wrong but currently I have my function in the <code>index.php</code> file before the below code:</p>
<pre><code>{{{MY FUNCTION IS HERE}}}
require 'vendor/autoload.php';
use GeoIp2\Database\Reader;
session_start();
if (!isset($_SESSION['country'])) {
$reader = new Reader('db/GeoLite2-Country.mmdb');
$record = $reader->country($_SERVER['REMOTE_ADDR']);
$_SESSION['country'] = $record->country->isoCode;
}
{{{MY FUNCTION ENDS HERE}}}
/**
* Front to the WordPress application. This file doesn't do anything, but loads
* wp-blog-header.php which does and tells WordPress to load the theme.
*
* @package WordPress
*/
/**
* Tells WordPress to load the WordPress theme and output it.
*
* @var bool
*/
define( 'WP_USE_THEMES', true );
/** Loads the WordPress Environment and Template */
require( dirname( __FILE__ ) . '/wp-blog-header.php' );
</code></pre>
<p>This obviously gets overidden whenever Wordpress updates so how can I include my function safely and correctly please?</p>
<p>I've tried with the following in my themes <code>functions.php</code> file:</p>
<pre><code>add_action( 'init', 'my_script' );
function my_script() {
// my script here
}
</code></pre>
<p>But that's not soon enough, unless I'm making a mistake?</p>
<p>Can anyone help please?</p>
<p>Many thanks</p>
| [
{
"answer_id": 341461,
"author": "ChristopherJones",
"author_id": 168744,
"author_profile": "https://wordpress.stackexchange.com/users/168744",
"pm_score": 1,
"selected": false,
"text": "<p><code>init</code> is not the first action to run on a WordPress install. Here is a basic rundown of a typical stack order.</p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference</a></p>\n\n<p>Try hooking into `muplugins_loaded'. I don't believe it is conditional, so it should run every time.</p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/muplugins_loaded\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference/muplugins_loaded</a></p>\n\n<pre><code><?php\n add_action( 'muplugins_loaded', 'my_script' );\n\n function my_script() {\n // my script here\n }\n</code></pre>\n"
},
{
"answer_id": 341470,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 0,
"selected": false,
"text": "<p>The first PHP file that WordPress loads and doesn't overwrite on update is <code>wp-config.php</code>. At this point, WordPress is not loaded. So you can put your functions at the beginning of that file.</p>\n"
},
{
"answer_id": 341529,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 0,
"selected": false,
"text": "<p>You can simply place your code in any file (with a <code>.php</code> extension that is) in <code>/wp-content/mu-plugins/</code></p>\n\n<p>All PHP files in that directory (but not subdirectories) will automatically be run before any hooks are fired (yes even before <code>muplugins_loaded</code>.)</p>\n\n<p>This is arguably a better place for sitewide customizations than a theme <code>functions.php</code> anyway so they will persist if you change themes.</p>\n"
}
] | 2019/06/25 | [
"https://wordpress.stackexchange.com/questions/341460",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159870/"
] | I want to run a script before any Wordpress stuff kicks in.
I know it's wrong but currently I have my function in the `index.php` file before the below code:
```
{{{MY FUNCTION IS HERE}}}
require 'vendor/autoload.php';
use GeoIp2\Database\Reader;
session_start();
if (!isset($_SESSION['country'])) {
$reader = new Reader('db/GeoLite2-Country.mmdb');
$record = $reader->country($_SERVER['REMOTE_ADDR']);
$_SESSION['country'] = $record->country->isoCode;
}
{{{MY FUNCTION ENDS HERE}}}
/**
* Front to the WordPress application. This file doesn't do anything, but loads
* wp-blog-header.php which does and tells WordPress to load the theme.
*
* @package WordPress
*/
/**
* Tells WordPress to load the WordPress theme and output it.
*
* @var bool
*/
define( 'WP_USE_THEMES', true );
/** Loads the WordPress Environment and Template */
require( dirname( __FILE__ ) . '/wp-blog-header.php' );
```
This obviously gets overidden whenever Wordpress updates so how can I include my function safely and correctly please?
I've tried with the following in my themes `functions.php` file:
```
add_action( 'init', 'my_script' );
function my_script() {
// my script here
}
```
But that's not soon enough, unless I'm making a mistake?
Can anyone help please?
Many thanks | `init` is not the first action to run on a WordPress install. Here is a basic rundown of a typical stack order.
<https://codex.wordpress.org/Plugin_API/Action_Reference>
Try hooking into `muplugins\_loaded'. I don't believe it is conditional, so it should run every time.
<https://codex.wordpress.org/Plugin_API/Action_Reference/muplugins_loaded>
```
<?php
add_action( 'muplugins_loaded', 'my_script' );
function my_script() {
// my script here
}
``` |
341,471 | <p>I'm trying to create a nav menu with a clickable dropdown function but minimize scripting at the same time, so I found out a way to achieve this with an invisible input box and CSS. My only problem is I have no experience with PHP and getting the menu to load the right HTML is very frustrating (it took me forever just to get the custom walker to show up in the first place). This is the effect I want to achieve - the same default WordPress menu, but the menu items with children are slightly different:</p>
<pre><code><ul>
<li>A menu item</li>
<li>A menu item</li>
<li>
<input id="check-(item-id)" type="checkbox" />
<label for="check-(item-id)">A menu item with children</label>
<ul>
<li>Child one</li>
<li>Child two</li>
</li>
<li>A menu item</li>
</ul>
</code></pre>
<p>In my functions.php file, I have this:</p>
<pre><code><?php
/*---- Custom Menu Settings ----*/
function custom_menus() {
$locations = array(
"top-menu" => __( "Top Menu" ),
"side-menu" => __( "Side Menu" ),
);
register_nav_menus( $locations );
}
add_action( "init", "custom_menus" );
class Clickable_Dropdown_Walker extends Walker_Nav_Menu {
// The code isn't even worth showing because I've tried at least a dozen combinations and nothing's worked
}
?>
</code></pre>
<p>And finally, in my sidebar.php I have this:</p>
<pre><code><?php
if ( has_nav_menu( "side-menu" ) ) {
wp_nav_menu( array(
"theme_location" => "side-menu",
"container_class" => "side-menu",
"walker" => new Clickable_Dropdown_Walker() ) );
}
?>
</code></pre>
<p>Any help would be appreciated, thanks!</p>
| [
{
"answer_id": 341481,
"author": "Joy Reynolds",
"author_id": 43242,
"author_profile": "https://wordpress.stackexchange.com/users/43242",
"pm_score": 1,
"selected": false,
"text": "<p>I did this in my theme, so you can look at the whole code here: <a href=\"https://wordpress.org/themes/twenty8teen\" rel=\"nofollow noreferrer\">https://wordpress.org/themes/twenty8teen</a></p>\n\n<p>I used the standard walker and added a filter for 'walker_nav_menu_start_el'. Of course, I also wanted it to work for the fallback Page menu, so I cloned the standard walker and added the call to <code>apply_filters</code> with a slightly different filter.</p>\n\n<pre><code>/**\n * For custom menu, adding an input and label for submenus.\n */\nfunction twenty8teen_nav_menu_start_el( $item_output, $item, $depth, $args ) {\n $classes = empty( $item->classes ) ? array() : (array) $item->classes;\n if ( $classes && in_array( 'menu-item-has-children', $classes ) ||\n in_array( 'page_item_has_children', $classes) ) {\n $item_output .= '<input type=\"checkbox\" id=\"sub' . $item->ID\n . '\"><label for=\"sub' . $item->ID . '\"></label>';\n }\n return $item_output;\n}\n\n/**\n * For page menu, adding an input and label for submenus.\n */\nfunction twenty8teen_page_menu_start_el( $item_output, $page, $depth, $args ) {\n if ( isset( $args['pages_with_children'][ $page->ID ] ) ) {\n $item_output .= '<input type=\"checkbox\" id=\"sub' . $page->ID\n . '\"><label for=\"sub' . $page->ID . '\"></label>';\n }\n return $item_output;\n}\nadd_filter( 'walker_page_menu_start_el', 'twenty8teen_page_menu_start_el', 9, 4);\n</code></pre>\n"
},
{
"answer_id": 341525,
"author": "mira-fraiyo",
"author_id": 170670,
"author_profile": "https://wordpress.stackexchange.com/users/170670",
"pm_score": 0,
"selected": false,
"text": "<p>I managed to use what you did and other resources to come up with my own solution! The code is short and sweet:</p>\n\n<pre><code>class Clickable_Dropdown_Walker extends Walker_Nav_Menu {\n function start_el( &$output, $item, $item_output, $depth = 0, $args = array() ) {\n if( in_array( 'menu-item-has-children', $item->classes ) ){\n $output .= '<li class=\"menu-item-has-children\"><input id=\"check-' . $item->ID . '\" type=\"checkbox\" />'\n . '<label for=\"check-' . $item->ID . '\">' . $item->title . '</label>';\n }\n\n else {\n $output .= '<li><a href=\"' . $item->url . '\">' . $item->title . '</a>';\n }\n }\n }\n</code></pre>\n\n<p>I had to make sure the walker was enabled in my custom menu and the menu in the WP Admin was assigned to \"Side Menu.\"</p>\n\n<p>Thanks for your help!!</p>\n"
}
] | 2019/06/25 | [
"https://wordpress.stackexchange.com/questions/341471",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/170670/"
] | I'm trying to create a nav menu with a clickable dropdown function but minimize scripting at the same time, so I found out a way to achieve this with an invisible input box and CSS. My only problem is I have no experience with PHP and getting the menu to load the right HTML is very frustrating (it took me forever just to get the custom walker to show up in the first place). This is the effect I want to achieve - the same default WordPress menu, but the menu items with children are slightly different:
```
<ul>
<li>A menu item</li>
<li>A menu item</li>
<li>
<input id="check-(item-id)" type="checkbox" />
<label for="check-(item-id)">A menu item with children</label>
<ul>
<li>Child one</li>
<li>Child two</li>
</li>
<li>A menu item</li>
</ul>
```
In my functions.php file, I have this:
```
<?php
/*---- Custom Menu Settings ----*/
function custom_menus() {
$locations = array(
"top-menu" => __( "Top Menu" ),
"side-menu" => __( "Side Menu" ),
);
register_nav_menus( $locations );
}
add_action( "init", "custom_menus" );
class Clickable_Dropdown_Walker extends Walker_Nav_Menu {
// The code isn't even worth showing because I've tried at least a dozen combinations and nothing's worked
}
?>
```
And finally, in my sidebar.php I have this:
```
<?php
if ( has_nav_menu( "side-menu" ) ) {
wp_nav_menu( array(
"theme_location" => "side-menu",
"container_class" => "side-menu",
"walker" => new Clickable_Dropdown_Walker() ) );
}
?>
```
Any help would be appreciated, thanks! | I did this in my theme, so you can look at the whole code here: <https://wordpress.org/themes/twenty8teen>
I used the standard walker and added a filter for 'walker\_nav\_menu\_start\_el'. Of course, I also wanted it to work for the fallback Page menu, so I cloned the standard walker and added the call to `apply_filters` with a slightly different filter.
```
/**
* For custom menu, adding an input and label for submenus.
*/
function twenty8teen_nav_menu_start_el( $item_output, $item, $depth, $args ) {
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
if ( $classes && in_array( 'menu-item-has-children', $classes ) ||
in_array( 'page_item_has_children', $classes) ) {
$item_output .= '<input type="checkbox" id="sub' . $item->ID
. '"><label for="sub' . $item->ID . '"></label>';
}
return $item_output;
}
/**
* For page menu, adding an input and label for submenus.
*/
function twenty8teen_page_menu_start_el( $item_output, $page, $depth, $args ) {
if ( isset( $args['pages_with_children'][ $page->ID ] ) ) {
$item_output .= '<input type="checkbox" id="sub' . $page->ID
. '"><label for="sub' . $page->ID . '"></label>';
}
return $item_output;
}
add_filter( 'walker_page_menu_start_el', 'twenty8teen_page_menu_start_el', 9, 4);
``` |
341,474 | <p>I'm not so good at coding but managed to write a little piece of code to have a shortcode to display a co-authors (co-authors plus plugin) bio/description in posts.</p>
<p>The code I came up with is</p>
<pre><code><?php function torque_hello_world_shortcode() { ?>
<?php if ( function_exists( 'get_coauthors' ) ) ?>
<?php $coauthors = get_coauthors(); ?>
<?php foreach ( $coauthors as $coauthor ) { ?>
<div><span class="authorboxsinglename"><?php echo ( $coauthor->display_name ); ?></span></div>
<div><span class="authorboxsinglebio"><?php echo ( $coauthor->description ); ?></span></div>
<?php } ?>
<?php } ?>
</code></pre>
<p>It works, except: the content appears at the very top of the post, not where I put the shortcode. Somewhere I've read it might be because I used <em>echo</em> instead of <em>return</em>.</p>
<p>Since I'm not good at coding I have no clue how to change my code to <em>return</em>. Could anyone do that for me? It would be really appreciated.</p>
<p>Kind regards,
Cédric</p>
| [
{
"answer_id": 341481,
"author": "Joy Reynolds",
"author_id": 43242,
"author_profile": "https://wordpress.stackexchange.com/users/43242",
"pm_score": 1,
"selected": false,
"text": "<p>I did this in my theme, so you can look at the whole code here: <a href=\"https://wordpress.org/themes/twenty8teen\" rel=\"nofollow noreferrer\">https://wordpress.org/themes/twenty8teen</a></p>\n\n<p>I used the standard walker and added a filter for 'walker_nav_menu_start_el'. Of course, I also wanted it to work for the fallback Page menu, so I cloned the standard walker and added the call to <code>apply_filters</code> with a slightly different filter.</p>\n\n<pre><code>/**\n * For custom menu, adding an input and label for submenus.\n */\nfunction twenty8teen_nav_menu_start_el( $item_output, $item, $depth, $args ) {\n $classes = empty( $item->classes ) ? array() : (array) $item->classes;\n if ( $classes && in_array( 'menu-item-has-children', $classes ) ||\n in_array( 'page_item_has_children', $classes) ) {\n $item_output .= '<input type=\"checkbox\" id=\"sub' . $item->ID\n . '\"><label for=\"sub' . $item->ID . '\"></label>';\n }\n return $item_output;\n}\n\n/**\n * For page menu, adding an input and label for submenus.\n */\nfunction twenty8teen_page_menu_start_el( $item_output, $page, $depth, $args ) {\n if ( isset( $args['pages_with_children'][ $page->ID ] ) ) {\n $item_output .= '<input type=\"checkbox\" id=\"sub' . $page->ID\n . '\"><label for=\"sub' . $page->ID . '\"></label>';\n }\n return $item_output;\n}\nadd_filter( 'walker_page_menu_start_el', 'twenty8teen_page_menu_start_el', 9, 4);\n</code></pre>\n"
},
{
"answer_id": 341525,
"author": "mira-fraiyo",
"author_id": 170670,
"author_profile": "https://wordpress.stackexchange.com/users/170670",
"pm_score": 0,
"selected": false,
"text": "<p>I managed to use what you did and other resources to come up with my own solution! The code is short and sweet:</p>\n\n<pre><code>class Clickable_Dropdown_Walker extends Walker_Nav_Menu {\n function start_el( &$output, $item, $item_output, $depth = 0, $args = array() ) {\n if( in_array( 'menu-item-has-children', $item->classes ) ){\n $output .= '<li class=\"menu-item-has-children\"><input id=\"check-' . $item->ID . '\" type=\"checkbox\" />'\n . '<label for=\"check-' . $item->ID . '\">' . $item->title . '</label>';\n }\n\n else {\n $output .= '<li><a href=\"' . $item->url . '\">' . $item->title . '</a>';\n }\n }\n }\n</code></pre>\n\n<p>I had to make sure the walker was enabled in my custom menu and the menu in the WP Admin was assigned to \"Side Menu.\"</p>\n\n<p>Thanks for your help!!</p>\n"
}
] | 2019/06/26 | [
"https://wordpress.stackexchange.com/questions/341474",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/170688/"
] | I'm not so good at coding but managed to write a little piece of code to have a shortcode to display a co-authors (co-authors plus plugin) bio/description in posts.
The code I came up with is
```
<?php function torque_hello_world_shortcode() { ?>
<?php if ( function_exists( 'get_coauthors' ) ) ?>
<?php $coauthors = get_coauthors(); ?>
<?php foreach ( $coauthors as $coauthor ) { ?>
<div><span class="authorboxsinglename"><?php echo ( $coauthor->display_name ); ?></span></div>
<div><span class="authorboxsinglebio"><?php echo ( $coauthor->description ); ?></span></div>
<?php } ?>
<?php } ?>
```
It works, except: the content appears at the very top of the post, not where I put the shortcode. Somewhere I've read it might be because I used *echo* instead of *return*.
Since I'm not good at coding I have no clue how to change my code to *return*. Could anyone do that for me? It would be really appreciated.
Kind regards,
Cédric | I did this in my theme, so you can look at the whole code here: <https://wordpress.org/themes/twenty8teen>
I used the standard walker and added a filter for 'walker\_nav\_menu\_start\_el'. Of course, I also wanted it to work for the fallback Page menu, so I cloned the standard walker and added the call to `apply_filters` with a slightly different filter.
```
/**
* For custom menu, adding an input and label for submenus.
*/
function twenty8teen_nav_menu_start_el( $item_output, $item, $depth, $args ) {
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
if ( $classes && in_array( 'menu-item-has-children', $classes ) ||
in_array( 'page_item_has_children', $classes) ) {
$item_output .= '<input type="checkbox" id="sub' . $item->ID
. '"><label for="sub' . $item->ID . '"></label>';
}
return $item_output;
}
/**
* For page menu, adding an input and label for submenus.
*/
function twenty8teen_page_menu_start_el( $item_output, $page, $depth, $args ) {
if ( isset( $args['pages_with_children'][ $page->ID ] ) ) {
$item_output .= '<input type="checkbox" id="sub' . $page->ID
. '"><label for="sub' . $page->ID . '"></label>';
}
return $item_output;
}
add_filter( 'walker_page_menu_start_el', 'twenty8teen_page_menu_start_el', 9, 4);
``` |
341,482 | <p>My plugin is throwing the error "Cannot use object of type WP_Error as array". The line in question is...</p>
<pre><code>$http = new WP_Http();
$response = $http->request( $url, array('timeout' => 20));
if( $response['response']['code'] != 200 ) { // THIS IS THE LINE
return false;
}
$upload = wp_upload_bits( basename($url), null, $response['body'] );
</code></pre>
<p>So the problem is $response only has one result, so it's not an array? How do I fix this?</p>
| [
{
"answer_id": 341487,
"author": "ngearing",
"author_id": 50184,
"author_profile": "https://wordpress.stackexchange.com/users/50184",
"pm_score": 2,
"selected": false,
"text": "<p>Your logic for your updated if statement is wrong.</p>\n\n<p><code>if( !is_wp_error($response) && $response['response']['code'] != 200 )</code></p>\n\n<p>Here you are saying; if NOT wp_error AND response code NOT 200 return false. So your not actually catching the WP_Error</p>\n\n<p>I believe what you are after is something like:</p>\n\n<p><code>if ( is_wp_error($response) || $response['response']['code'] != 200 ) return false;</code></p>\n\n<p>IS wp_error OR code NOT 200</p>\n"
},
{
"answer_id": 341488,
"author": "Bryan",
"author_id": 110183,
"author_profile": "https://wordpress.stackexchange.com/users/110183",
"pm_score": 0,
"selected": false,
"text": "<p>OK, I think may have fixed it by doing this...</p>\n\n<pre><code>$http = new WP_Http();\n$response = $http->request( $url, array('timeout' => 20));\n\n$response = is_array($response) ? $response : array($response);\n\nif( is_wp_error($response) && isset($response) && $response['response']['code'] != 200 ) {\n return false;\n}\n</code></pre>\n"
}
] | 2019/06/26 | [
"https://wordpress.stackexchange.com/questions/341482",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110183/"
] | My plugin is throwing the error "Cannot use object of type WP\_Error as array". The line in question is...
```
$http = new WP_Http();
$response = $http->request( $url, array('timeout' => 20));
if( $response['response']['code'] != 200 ) { // THIS IS THE LINE
return false;
}
$upload = wp_upload_bits( basename($url), null, $response['body'] );
```
So the problem is $response only has one result, so it's not an array? How do I fix this? | Your logic for your updated if statement is wrong.
`if( !is_wp_error($response) && $response['response']['code'] != 200 )`
Here you are saying; if NOT wp\_error AND response code NOT 200 return false. So your not actually catching the WP\_Error
I believe what you are after is something like:
`if ( is_wp_error($response) || $response['response']['code'] != 200 ) return false;`
IS wp\_error OR code NOT 200 |
341,485 | <p>My wordpress page URL is like this </p>
<p>https:www.com/thanks-page/?origin_name=Sydney&origin_iata=SYD&destination_name=Ahmedabad&destination_iata=AMD</p>
<p>I need to display SYD and AMD in to the page content like this..</p>
<p>Flights from SYD to AMD... </p>
<p>How can I display those two Param query sting in to the actual wordpress page. </p>
<p>Thanks in advance. </p>
| [
{
"answer_id": 341486,
"author": "Nam Duong",
"author_id": 167566,
"author_profile": "https://wordpress.stackexchange.com/users/167566",
"pm_score": 0,
"selected": false,
"text": "<p>You just use <code>$_GET[\"origin_iata\"]</code> and <code>$_GET[\"destination_iata\"]</code> to get those two Params you need</p>\n"
},
{
"answer_id": 341489,
"author": "Chetan Vaghela",
"author_id": 169856,
"author_profile": "https://wordpress.stackexchange.com/users/169856",
"pm_score": -1,
"selected": true,
"text": "<p>Simple, you can use $_GET method.</p>\n\n<pre><code>if(isset($_GET[\"origin_iata\"]) && !empty($_GET[\"origin_iata\"]) && isset($_GET[\"destination_iata\"]) && !empty($_GET[\"destination_iata\"]))\n{\n echo \"Flights from \".$_GET[\"origin_iata\"].\" to \".$_GET[\"destination_iata\"].\"...\";\n}\n</code></pre>\n"
}
] | 2019/06/26 | [
"https://wordpress.stackexchange.com/questions/341485",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/170697/"
] | My wordpress page URL is like this
https:www.com/thanks-page/?origin\_name=Sydney&origin\_iata=SYD&destination\_name=Ahmedabad&destination\_iata=AMD
I need to display SYD and AMD in to the page content like this..
Flights from SYD to AMD...
How can I display those two Param query sting in to the actual wordpress page.
Thanks in advance. | Simple, you can use $\_GET method.
```
if(isset($_GET["origin_iata"]) && !empty($_GET["origin_iata"]) && isset($_GET["destination_iata"]) && !empty($_GET["destination_iata"]))
{
echo "Flights from ".$_GET["origin_iata"]." to ".$_GET["destination_iata"]."...";
}
``` |
341,496 | <p>My wordpress site sits behind Akamai, which is a cacheing service similar to Cloudflare. </p>
<p>I make the following API call: </p>
<pre><code>GET /wp-json/mytheme/v1/get-posts?post_type=videos
</code></pre>
<p>This is done using apiFetch from '@wordpress/api-fetch';</p>
<p>And it automatically includes this in the request header</p>
<pre><code>X-WP-Nonce: 12323423
</code></pre>
<p>This works fine until 24 hours later, when the nonce expires.
The cache still continues to use the expired Nonce resulting in a 403 forbidden and a broken page.</p>
<p>If I make the same request without Nonce header, it works perfectly fine. </p>
<p>Is there a way in Wordpress to disable or remove the Nonce for GET requests only?</p>
<p>Or even strip out the X-WP-Nonce header by intercepting the Request? </p>
<p>This my code for making the request which is being made from the wordpress frontend. </p>
<pre><code>apiFetch({
path: '/wp-json/mytheme/v1/get-posts?post_type=videos',
parse: false,
});
</code></pre>
| [
{
"answer_id": 341640,
"author": "thomas_jones",
"author_id": 170751,
"author_profile": "https://wordpress.stackexchange.com/users/170751",
"pm_score": 3,
"selected": true,
"text": "<p>Based on the authentication documentation <a href=\"https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/\" rel=\"nofollow noreferrer\">here</a> - a nonce key needs to be passed with each request. </p>\n\n<p>So if the nonce key is being cached on the frontend beyond its lifespan, you will need to hook into the API request before the authentication step and replace the cached nonce key with a valid one.</p>\n\n<p>WordPress provides a <code>rest_send_nocache_headers</code> filter for us to hook into (<a href=\"https://developer.wordpress.org/reference/hooks/rest_send_nocache_headers/\" rel=\"nofollow noreferrer\">See here</a>). This lets us perform an action before the authentication.</p>\n\n<pre><code>$send_no_cache_headers = apply_filters('rest_send_nocache_headers', is_user_logged_in());\nif (!$send_no_cache_headers && !is_admin() && $_SERVER['REQUEST_METHOD'] == 'GET') {\n $nonce = wp_create_nonce('wp_rest');\n $_SERVER['HTTP_X_WP_NONCE'] = $nonce;\n}\n</code></pre>\n\n<p>In the above example, we hook into the filter passing the <code>is_user_logged_in()</code> function as the parameter. This will return true or false.</p>\n\n<p>Then in our query, if the user is not logged in, they are not in the admin and, this is a <code>GET</code> request we proceed with switching the invalid nonce key with a valid one.</p>\n"
},
{
"answer_id": 379171,
"author": "Andy Keith",
"author_id": 157236,
"author_profile": "https://wordpress.stackexchange.com/users/157236",
"pm_score": 2,
"selected": false,
"text": "<p>Just to add to the accepted answer, I found a similar solution but instead hooked into <code>rest_authentication_errors</code> prior to <code>rest_cookie_check_errors</code> running.</p>\n<p>Since the underlying issue is nonce expiration, it's possible you could have this problem when the user is logged in (i.e. when no cache headers <em>are</em> sent) as well as when logged out. I also put some checks in to ensure we're dealing with just our REST request - I checked the 'rest_route' query var but there may be a better way of doing this.</p>\n<pre><code>add_filter( 'rest_authentication_errors', function( $errors ) {\n // Bail if rest_route isn't defined (shouldn't happen!)\n if ( empty( $GLOBALS['wp']->query_vars['rest_route'] ) ) {\n return $errors;\n }\n\n $route = ltrim( $GLOBALS['wp']->query_vars['rest_route'], '/' );\n\n // Ensure we're dealing with our REST requst.\n if ( 0 !== strpos( $route, 'my-awesome-namespace/v1' ) ) {\n return $errors;\n }\n\n if ( ! empty( $_SERVER['HTTP_X_WP_NONCE'] ) ) {\n $nonce = $_SERVER['HTTP_X_WP_NONCE'];\n\n if ( ! wp_verify_nonce( $nonce, 'wp_rest' ) ) {\n // Nonce check failed, so create a new one.\n $_SERVER['HTTP_X_WP_NONCE'] = wp_create_nonce( 'wp_rest' );\n }\n }\n\n return $errors;\n }, 10 );\n</code></pre>\n"
}
] | 2019/06/26 | [
"https://wordpress.stackexchange.com/questions/341496",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/162117/"
] | My wordpress site sits behind Akamai, which is a cacheing service similar to Cloudflare.
I make the following API call:
```
GET /wp-json/mytheme/v1/get-posts?post_type=videos
```
This is done using apiFetch from '@wordpress/api-fetch';
And it automatically includes this in the request header
```
X-WP-Nonce: 12323423
```
This works fine until 24 hours later, when the nonce expires.
The cache still continues to use the expired Nonce resulting in a 403 forbidden and a broken page.
If I make the same request without Nonce header, it works perfectly fine.
Is there a way in Wordpress to disable or remove the Nonce for GET requests only?
Or even strip out the X-WP-Nonce header by intercepting the Request?
This my code for making the request which is being made from the wordpress frontend.
```
apiFetch({
path: '/wp-json/mytheme/v1/get-posts?post_type=videos',
parse: false,
});
``` | Based on the authentication documentation [here](https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/) - a nonce key needs to be passed with each request.
So if the nonce key is being cached on the frontend beyond its lifespan, you will need to hook into the API request before the authentication step and replace the cached nonce key with a valid one.
WordPress provides a `rest_send_nocache_headers` filter for us to hook into ([See here](https://developer.wordpress.org/reference/hooks/rest_send_nocache_headers/)). This lets us perform an action before the authentication.
```
$send_no_cache_headers = apply_filters('rest_send_nocache_headers', is_user_logged_in());
if (!$send_no_cache_headers && !is_admin() && $_SERVER['REQUEST_METHOD'] == 'GET') {
$nonce = wp_create_nonce('wp_rest');
$_SERVER['HTTP_X_WP_NONCE'] = $nonce;
}
```
In the above example, we hook into the filter passing the `is_user_logged_in()` function as the parameter. This will return true or false.
Then in our query, if the user is not logged in, they are not in the admin and, this is a `GET` request we proceed with switching the invalid nonce key with a valid one. |
341,500 | <p>I'm working on small, vue based SPA. I'm using axios to get data from api that I'm interested about. The problem is that parameters are not working in any way, the same happens in Postman (I tried Postman because I thought that there is an error in my code, but there is not). Let's say I want to get posts from category 12 and order them ascending. So what I would try is something like this:</p>
<pre><code>http://api-address.com/wp-json/wp/v2/posts/?categories=12&order=asc
</code></pre>
<p>Call presented above returns posts <strong>in wrong order</strong>. I'm struggling with this and can't make it work - so frustrating that official documentation lacks real usage examples...</p>
| [
{
"answer_id": 341683,
"author": "thomas_jones",
"author_id": 170751,
"author_profile": "https://wordpress.stackexchange.com/users/170751",
"pm_score": 1,
"selected": false,
"text": "<p>If results should be ordered by a method other than the default <code>asc</code> or <code>desc</code>, you should also pass the <code>orderby</code> parameter. This gives you the ability to order by title, date, parent, type and many more that can be seen <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>For example, a request ordering the results a-z by title would be:</p>\n\n<pre><code>http://api-address.com/wp-json/wp/v2/posts/?categories=12&order=asc&orderby=title\n</code></pre>\n"
},
{
"answer_id": 341713,
"author": "Ronak J Vanpariya",
"author_id": 170878,
"author_profile": "https://wordpress.stackexchange.com/users/170878",
"pm_score": 0,
"selected": false,
"text": "<p>@thomas answer is right\nSometimes is parameter don't recognised by the API then it will be give the default response.</p>\n\n<p>You need to provide some default argument to the API.</p>\n\n<p>You can use your own custom rest route to the your site.</p>\n\n<p>Sometimes you need authentication from the word wordpress like WP nouns and anothers. For POST request.</p>\n\n<p>Wordpress rest API 2 support delete get post put.</p>\n\n<p>In WordPress Codex you might get stuck.</p>\n"
}
] | 2019/06/26 | [
"https://wordpress.stackexchange.com/questions/341500",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/170710/"
] | I'm working on small, vue based SPA. I'm using axios to get data from api that I'm interested about. The problem is that parameters are not working in any way, the same happens in Postman (I tried Postman because I thought that there is an error in my code, but there is not). Let's say I want to get posts from category 12 and order them ascending. So what I would try is something like this:
```
http://api-address.com/wp-json/wp/v2/posts/?categories=12&order=asc
```
Call presented above returns posts **in wrong order**. I'm struggling with this and can't make it work - so frustrating that official documentation lacks real usage examples... | If results should be ordered by a method other than the default `asc` or `desc`, you should also pass the `orderby` parameter. This gives you the ability to order by title, date, parent, type and many more that can be seen [here](https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters).
For example, a request ordering the results a-z by title would be:
```
http://api-address.com/wp-json/wp/v2/posts/?categories=12&order=asc&orderby=title
``` |
341,516 | <p>I am Creating New Wordpress Plugin and splitting my code into different files for code management.
Here is code of my main Plugin file which <code>my-best-plugin.php</code>with following code:</p>
<pre><code><?php
if ( ! defined('ABSPATH') ){
die;
}
if(!defined('MY_PLUGIN_PATH')) {
define( 'MY_PLUGIN_PATH', plugin_dir_path(__FILE__) );
}
if( ! class_exists('MyBestPlugin') ){
class MyBestPlugin {
function mbp_activate(){
require_once MY_PLUGIN_PATH .'inc/mbp-plugin-activate.php';
MBPActivate::activate();
}
}
$pluginInstance = new MyBestPlugin();
// activation
register_activation_hook( __FILE__ , array( $pluginInstance, 'mbp_activate' ) );
}
</code></pre>
<p>Now in my second file which is for activation is located in <code>inc/mbp-plugin-activate.php</code> and code is below:</p>
<pre><code><?php
class MBPActivate {
public static function activate(){
// I want to do more here by calling functions
// cpt();
// dont know how to call function cpt()
// also not sure is it running properly or not :P
add_action('init', array( 'MBPActivate','cpt' ));
flush_rewrite_rules();
}
public static function cpt(){
register_post_type('book', ['public'=>true, 'label'=>'Books']);
}
}
</code></pre>
<p>first Im not sure my plugin activate file is running or not but giving No error, also when I call my own functions it gives fatal error OR headers already sent error.
Please tell me how to call my functions during activation from activate plugin file.
Thanks in advance :) </p>
| [
{
"answer_id": 341683,
"author": "thomas_jones",
"author_id": 170751,
"author_profile": "https://wordpress.stackexchange.com/users/170751",
"pm_score": 1,
"selected": false,
"text": "<p>If results should be ordered by a method other than the default <code>asc</code> or <code>desc</code>, you should also pass the <code>orderby</code> parameter. This gives you the ability to order by title, date, parent, type and many more that can be seen <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>For example, a request ordering the results a-z by title would be:</p>\n\n<pre><code>http://api-address.com/wp-json/wp/v2/posts/?categories=12&order=asc&orderby=title\n</code></pre>\n"
},
{
"answer_id": 341713,
"author": "Ronak J Vanpariya",
"author_id": 170878,
"author_profile": "https://wordpress.stackexchange.com/users/170878",
"pm_score": 0,
"selected": false,
"text": "<p>@thomas answer is right\nSometimes is parameter don't recognised by the API then it will be give the default response.</p>\n\n<p>You need to provide some default argument to the API.</p>\n\n<p>You can use your own custom rest route to the your site.</p>\n\n<p>Sometimes you need authentication from the word wordpress like WP nouns and anothers. For POST request.</p>\n\n<p>Wordpress rest API 2 support delete get post put.</p>\n\n<p>In WordPress Codex you might get stuck.</p>\n"
}
] | 2019/06/26 | [
"https://wordpress.stackexchange.com/questions/341516",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/170724/"
] | I am Creating New Wordpress Plugin and splitting my code into different files for code management.
Here is code of my main Plugin file which `my-best-plugin.php`with following code:
```
<?php
if ( ! defined('ABSPATH') ){
die;
}
if(!defined('MY_PLUGIN_PATH')) {
define( 'MY_PLUGIN_PATH', plugin_dir_path(__FILE__) );
}
if( ! class_exists('MyBestPlugin') ){
class MyBestPlugin {
function mbp_activate(){
require_once MY_PLUGIN_PATH .'inc/mbp-plugin-activate.php';
MBPActivate::activate();
}
}
$pluginInstance = new MyBestPlugin();
// activation
register_activation_hook( __FILE__ , array( $pluginInstance, 'mbp_activate' ) );
}
```
Now in my second file which is for activation is located in `inc/mbp-plugin-activate.php` and code is below:
```
<?php
class MBPActivate {
public static function activate(){
// I want to do more here by calling functions
// cpt();
// dont know how to call function cpt()
// also not sure is it running properly or not :P
add_action('init', array( 'MBPActivate','cpt' ));
flush_rewrite_rules();
}
public static function cpt(){
register_post_type('book', ['public'=>true, 'label'=>'Books']);
}
}
```
first Im not sure my plugin activate file is running or not but giving No error, also when I call my own functions it gives fatal error OR headers already sent error.
Please tell me how to call my functions during activation from activate plugin file.
Thanks in advance :) | If results should be ordered by a method other than the default `asc` or `desc`, you should also pass the `orderby` parameter. This gives you the ability to order by title, date, parent, type and many more that can be seen [here](https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters).
For example, a request ordering the results a-z by title would be:
```
http://api-address.com/wp-json/wp/v2/posts/?categories=12&order=asc&orderby=title
``` |
341,532 | <p>I am trying to modify a portfolio plugin with filter function. The current code for listing to post items is: </p>
<pre><code><?php
class FullwidthPortfolioGallery extends ET_Builder_Module {
public $slug = 'fullwidth_portfolio_gallery';
public $vb_support = 'on';
protected $module_credits = array(
'module_uri' => '',
'author' => '',
'author_uri' => '',
);
public function init() {
$this->name = esc_html__('Portfolio Gallery', 'divi-modules');
$this->fullwidth = true;
$this->advanced_fields = [
'background' => false,
'fonts' => false,
'max_width' => false,
'link_options' => false,
];
}
public function get_fields() {
return [];
}
public function render($attrs, $content = null, $render_slug) {
global $post;
$portfolio = [];
$post_args = [
'posts_per_page' => -1,
'orderby' => 'date',
'order' => 'DESC',
'post_type' => 'portfolio',
];
foreach (get_posts($post_args) as $post) {
$new = new \stdClass;
$images = get_post_meta($post->ID, 'portfolio_photos', true);
$new->images = [];
if (empty($images)) {
continue;
} else {
foreach($images as $k => $img) {
$i = wp_get_attachment_image_src($k, 'portfolio_gallery_size');
$new->images[] = (object) [
'src' => $i[0],
'w' => $i[1],
'h' => $i[2],
];
}
}
$billboard_image = array_rand($images, 1);
$new->billboard = new \stdClass;
$new->billboard->mobile = wp_get_attachment_image_src($billboard_image, 'portfolio_billboard_mobile')[0];
$new->billboard->desktop = wp_get_attachment_image_src($billboard_image, 'portfolio_billboard_desktop')[0];
$new->title = $post->post_title;
$new->category = wp_get_post_terms($post->ID, 'portfolio_category')[0]->name;
$new->category_slug = wp_get_post_terms($post->ID, 'portfolio_category')[0]->slug;
$new->lightbox = 'lightbox-' . $post->ID;
$new->id = $post->ID;
$portfolio[] = $new;
unset($new);
unset($images);
}
if (empty($portfolio)) {
return;
}
add_action('wp_footer', function() {
include plugin_dir_path( dirname( __FILE__ ) ) . '../template/photoswipe.html';
});
wp_register_script('isotope', 'https://unpkg.com/isotope-layout@3/dist/isotope.pkgd.min.js', ['jquery'], false, true);
wp_register_script('portfolio_scripts', plugins_url( 'FullwidthPortfolioGallery.js', __FILE__), ['isotope', 'jquery'], false, true);
$portfolio_items = [];
foreach ($portfolio as $p) {
$portfolio_items[$p->id] = $p;
}
wp_localize_script('portfolio_scripts', 'portfolio_items', $portfolio_items);
wp_enqueue_script('isotope');
wp_enqueue_script('portfolio_scripts');
$categories = get_terms( [
'taxonomy' => 'portfolio_category',
'hide_empty' => true,
] );
$html = '<div class="portfolio-categories"><div class="portfolio-categories-wrap"><div class="portfolio-categories-list container">';
$html .= '<button class="toggle"><span class="dashicons dashicons-no"></span><span class="dashicons dashicons-filter"></span></button>';
$html .= '<button class="filter active" data-filter="*">Vis alle</button>';
foreach ($categories as $cat) {
$html .= '<button data-filter=".filter-'.$cat->slug.'" class="filter">'.$cat->name.'</button>';
}
$html .= '</div></div></div>';
$html .= '<div class="portfolio-list"><div class="portfolio-list-wrap">';
foreach ($portfolio as $p) {
$html .= '<div class="portfolio filter-'.$p->category_slug.'" data-id="'.$p->id.'"><div class="portfolio-wrap">';
$html .= '<div class="spinner-wrapper"><div class="spinner-wrap"><div class="spinner"></div></div></div>';
$html .= '<div class="billboard"><img class="lazy mobile" data-src="'.$p->billboard->mobile.'" alt="'.$p->title.'" /><img class="lazy desktop" data-src="'.$p->billboard->desktop.'" alt="'.$p->title.'" /><div class="overlay"><span class="dashicons dashicons-images-alt"></span></div></div>';
$html .= '<div class="info"><p class="cat">'.$p->category.'</p><h2>'.$p->title.'</h2></div>';
$html .= '</div></div>';
}
$html .= '</div></div>';
return '<div class="fullwidth-portfolio-gallery">'.$html.'</div>';
}
}
new FullwidthPortfolioGallery;
</code></pre>
<p>Currently each item get only one class "filter-TERMSLUG", but I would like to have classes listed for all the categories the item is in.</p>
<p>Can anyone help me with that?</p>
<p>Best regards</p>
| [
{
"answer_id": 341683,
"author": "thomas_jones",
"author_id": 170751,
"author_profile": "https://wordpress.stackexchange.com/users/170751",
"pm_score": 1,
"selected": false,
"text": "<p>If results should be ordered by a method other than the default <code>asc</code> or <code>desc</code>, you should also pass the <code>orderby</code> parameter. This gives you the ability to order by title, date, parent, type and many more that can be seen <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>For example, a request ordering the results a-z by title would be:</p>\n\n<pre><code>http://api-address.com/wp-json/wp/v2/posts/?categories=12&order=asc&orderby=title\n</code></pre>\n"
},
{
"answer_id": 341713,
"author": "Ronak J Vanpariya",
"author_id": 170878,
"author_profile": "https://wordpress.stackexchange.com/users/170878",
"pm_score": 0,
"selected": false,
"text": "<p>@thomas answer is right\nSometimes is parameter don't recognised by the API then it will be give the default response.</p>\n\n<p>You need to provide some default argument to the API.</p>\n\n<p>You can use your own custom rest route to the your site.</p>\n\n<p>Sometimes you need authentication from the word wordpress like WP nouns and anothers. For POST request.</p>\n\n<p>Wordpress rest API 2 support delete get post put.</p>\n\n<p>In WordPress Codex you might get stuck.</p>\n"
}
] | 2019/06/26 | [
"https://wordpress.stackexchange.com/questions/341532",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/170731/"
] | I am trying to modify a portfolio plugin with filter function. The current code for listing to post items is:
```
<?php
class FullwidthPortfolioGallery extends ET_Builder_Module {
public $slug = 'fullwidth_portfolio_gallery';
public $vb_support = 'on';
protected $module_credits = array(
'module_uri' => '',
'author' => '',
'author_uri' => '',
);
public function init() {
$this->name = esc_html__('Portfolio Gallery', 'divi-modules');
$this->fullwidth = true;
$this->advanced_fields = [
'background' => false,
'fonts' => false,
'max_width' => false,
'link_options' => false,
];
}
public function get_fields() {
return [];
}
public function render($attrs, $content = null, $render_slug) {
global $post;
$portfolio = [];
$post_args = [
'posts_per_page' => -1,
'orderby' => 'date',
'order' => 'DESC',
'post_type' => 'portfolio',
];
foreach (get_posts($post_args) as $post) {
$new = new \stdClass;
$images = get_post_meta($post->ID, 'portfolio_photos', true);
$new->images = [];
if (empty($images)) {
continue;
} else {
foreach($images as $k => $img) {
$i = wp_get_attachment_image_src($k, 'portfolio_gallery_size');
$new->images[] = (object) [
'src' => $i[0],
'w' => $i[1],
'h' => $i[2],
];
}
}
$billboard_image = array_rand($images, 1);
$new->billboard = new \stdClass;
$new->billboard->mobile = wp_get_attachment_image_src($billboard_image, 'portfolio_billboard_mobile')[0];
$new->billboard->desktop = wp_get_attachment_image_src($billboard_image, 'portfolio_billboard_desktop')[0];
$new->title = $post->post_title;
$new->category = wp_get_post_terms($post->ID, 'portfolio_category')[0]->name;
$new->category_slug = wp_get_post_terms($post->ID, 'portfolio_category')[0]->slug;
$new->lightbox = 'lightbox-' . $post->ID;
$new->id = $post->ID;
$portfolio[] = $new;
unset($new);
unset($images);
}
if (empty($portfolio)) {
return;
}
add_action('wp_footer', function() {
include plugin_dir_path( dirname( __FILE__ ) ) . '../template/photoswipe.html';
});
wp_register_script('isotope', 'https://unpkg.com/isotope-layout@3/dist/isotope.pkgd.min.js', ['jquery'], false, true);
wp_register_script('portfolio_scripts', plugins_url( 'FullwidthPortfolioGallery.js', __FILE__), ['isotope', 'jquery'], false, true);
$portfolio_items = [];
foreach ($portfolio as $p) {
$portfolio_items[$p->id] = $p;
}
wp_localize_script('portfolio_scripts', 'portfolio_items', $portfolio_items);
wp_enqueue_script('isotope');
wp_enqueue_script('portfolio_scripts');
$categories = get_terms( [
'taxonomy' => 'portfolio_category',
'hide_empty' => true,
] );
$html = '<div class="portfolio-categories"><div class="portfolio-categories-wrap"><div class="portfolio-categories-list container">';
$html .= '<button class="toggle"><span class="dashicons dashicons-no"></span><span class="dashicons dashicons-filter"></span></button>';
$html .= '<button class="filter active" data-filter="*">Vis alle</button>';
foreach ($categories as $cat) {
$html .= '<button data-filter=".filter-'.$cat->slug.'" class="filter">'.$cat->name.'</button>';
}
$html .= '</div></div></div>';
$html .= '<div class="portfolio-list"><div class="portfolio-list-wrap">';
foreach ($portfolio as $p) {
$html .= '<div class="portfolio filter-'.$p->category_slug.'" data-id="'.$p->id.'"><div class="portfolio-wrap">';
$html .= '<div class="spinner-wrapper"><div class="spinner-wrap"><div class="spinner"></div></div></div>';
$html .= '<div class="billboard"><img class="lazy mobile" data-src="'.$p->billboard->mobile.'" alt="'.$p->title.'" /><img class="lazy desktop" data-src="'.$p->billboard->desktop.'" alt="'.$p->title.'" /><div class="overlay"><span class="dashicons dashicons-images-alt"></span></div></div>';
$html .= '<div class="info"><p class="cat">'.$p->category.'</p><h2>'.$p->title.'</h2></div>';
$html .= '</div></div>';
}
$html .= '</div></div>';
return '<div class="fullwidth-portfolio-gallery">'.$html.'</div>';
}
}
new FullwidthPortfolioGallery;
```
Currently each item get only one class "filter-TERMSLUG", but I would like to have classes listed for all the categories the item is in.
Can anyone help me with that?
Best regards | If results should be ordered by a method other than the default `asc` or `desc`, you should also pass the `orderby` parameter. This gives you the ability to order by title, date, parent, type and many more that can be seen [here](https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters).
For example, a request ordering the results a-z by title would be:
```
http://api-address.com/wp-json/wp/v2/posts/?categories=12&order=asc&orderby=title
``` |
341,550 | <p>I'd like to exclude a path that matches a rule from booting WordPress. The normal way I'd approach this is using the last flag <code>[L]</code> in a rule before all the others.</p>
<p>To keep things simple in this example, I'll just pretend I want to match a simple path <code>/foo/</code>.</p>
<pre><code><IfModule mod_rewrite.c>
RewriteEngine On
</code></pre>
<pre><code>RewriteRule ^foo/?$ - [L]
</code></pre>
<pre><code>RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
</code></pre>
<p>However, this does not work.
A few other options are suggested in this older <a href="https://stackoverflow.com/questions/2322559/htaccess-wordpress-exclude-folder-from-rewriterule/2350305">Stack Overflow post</a>, but none of them work (neither for myself nor anyone in the comments of that post).</p>
<p>I did try this rewrite condition instead of the rule: </p>
<pre><code>RewriteCond %{REQUEST_URI} ^/?(foo/.*)$
</code></pre>
<p>As well as adding <code>ErrorDocument 401 default</code> to the end of the <code>.htaccess</code> document.</p>
| [
{
"answer_id": 342001,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 2,
"selected": false,
"text": "<p>You should use <code>RewriteCond</code> instead of <code>RewriteRule</code>. Use this:</p>\n\n<pre><code>RewriteCond %{REQUEST_URI} !/foo/\n</code></pre>\n\n<p>So, for example, the full code could be like this:</p>\n\n<pre><code># BEGIN WordPress\n<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_URI} !/foo/\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n</IfModule>\n# END WordPress\n</code></pre>\n"
},
{
"answer_id": 342003,
"author": "ChristopherJones",
"author_id": 168744,
"author_profile": "https://wordpress.stackexchange.com/users/168744",
"pm_score": 3,
"selected": true,
"text": "<p>One small hiccup is that you'll need to update <code>RewriteRule ./</code> in that second to last line. Here is an updated (and tested) snippet for you:</p>\n\n<pre><code># BEGIN WordPress\n<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_URI} !^/foo/.*$\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule ./ /index.php [L]\n</IfModule>\n\n# END WordPress\n</code></pre>\n\n<p>I tested both:</p>\n\n<ul>\n<li><a href=\"https://www.domain.com/foo/\" rel=\"nofollow noreferrer\">https://www.domain.com/foo/</a></li>\n<li><a href=\"https://www.domain.com/foo/bar/\" rel=\"nofollow noreferrer\">https://www.domain.com/foo/bar/</a></li>\n</ul>\n\n<p>Hope that helps!!</p>\n"
},
{
"answer_id": 342010,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 1,
"selected": false,
"text": "<p>The following rule works for me</p>\n\n<pre><code>RewriteRule ^(foo)($|/) - [L]\n</code></pre>\n\n<p>meaning, any path beginning with <em>foo</em> like <em>/foo/</em>, <em>/foo/bar/</em> or whatever, leads to the Apache 404 instead of the themes 404; under the assumption that there is no actual directory with that path.</p>\n\n<p>The rule has to be before the last standard line of the WordPress block:</p>\n\n<pre><code>RewriteRule . /index.php [L]\n</code></pre>\n\n<p>And it doesn't really matter, if it is after <code>RewriteBase /</code>, it can be before it; it was previously just hastily and sloppily worded on my part. </p>\n\n<p>Which would give you the chance to leave the block between <code># BEGIN WordPress</code> and <code># END WordPress</code> untouched, if you'd like to do so. By putting</p>\n\n<pre><code><IfModule mod_rewrite.c>\nRewriteRule ^(foo)($|/) - [L]\n</IfModule>\n</code></pre>\n\n<p>in front of <code># BEGIN WordPress</code>.</p>\n\n<p>You might want to prevent the path <em>/foo/</em> from being created in WordPress, this came to mind:</p>\n\n<pre><code>add_filter( 'wp_unique_post_slug', 'no_more_foo_wp_unique_post_slug', 2, 6 );\nfunction no_more_foo_wp_unique_post_slug( \n $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug \n) {\n if ( $post_parent === 0 ) {\n $pattern = '/^foo$/';\n $replace = 'bar';\n $slug = preg_replace( $pattern, $replace, $slug );\n }\n return $slug;\n}\n</code></pre>\n"
}
] | 2019/06/26 | [
"https://wordpress.stackexchange.com/questions/341550",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/18228/"
] | I'd like to exclude a path that matches a rule from booting WordPress. The normal way I'd approach this is using the last flag `[L]` in a rule before all the others.
To keep things simple in this example, I'll just pretend I want to match a simple path `/foo/`.
```
<IfModule mod_rewrite.c>
RewriteEngine On
```
```
RewriteRule ^foo/?$ - [L]
```
```
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
```
However, this does not work.
A few other options are suggested in this older [Stack Overflow post](https://stackoverflow.com/questions/2322559/htaccess-wordpress-exclude-folder-from-rewriterule/2350305), but none of them work (neither for myself nor anyone in the comments of that post).
I did try this rewrite condition instead of the rule:
```
RewriteCond %{REQUEST_URI} ^/?(foo/.*)$
```
As well as adding `ErrorDocument 401 default` to the end of the `.htaccess` document. | One small hiccup is that you'll need to update `RewriteRule ./` in that second to last line. Here is an updated (and tested) snippet for you:
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_URI} !^/foo/.*$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ./ /index.php [L]
</IfModule>
# END WordPress
```
I tested both:
* <https://www.domain.com/foo/>
* <https://www.domain.com/foo/bar/>
Hope that helps!! |
341,557 | <p>I'm working on a very simple theme. I have tried adding next and previous links and cannot get them to work.</p>
<p>After trying a few different things, I ended up with this <code>index.php</code> (mostly based on answers on SO).</p>
<pre><code><?php get_header(); ?>
<!-- html stuff -->
<?php
if ( have_posts() ) {
while ( have_posts() ) : the_post();
// ... post layout stuff
endwhile;
}
?>
<!-- Other html bits -->
<?php
$prev_link = get_previous_posts_link(__('&laquo; Older Entries'));
$next_link = get_next_posts_link(__('Newer Entries &raquo;'));
if ($prev_link || $next_link) {
echo '<nav><ul class="pager">';
if ($prev_link){
echo '<li>'.$prev_link .'</li>';
}
if ($next_link){
echo '<li>'.$next_link .'</li>';
}
echo '</ul></nav>';
}
?>
<!-- html stuff -->
<?php get_footer(); ?>
</code></pre>
<p>There are two blog posts on the development install I am working with. But neither of them display with the navigational links.</p>
| [
{
"answer_id": 341558,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>Put the code block with all the prev/next links code inside the loop.</p>\n\n<p>The <code>get_previous_posts_link()</code> function relies on the current post ID, and outside of the loop that post ID is not available.</p>\n"
},
{
"answer_id": 341559,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": true,
"text": "<p>As suggested by the default link labels, \"Older Entries\" and \"Newer Entries\", <code>get_next_posts_link()</code> and <code>get_next_posts_link()</code> are for outputting links between pages of posts. If you only have 2 posts, and your posts per page setting is set to anything higher than 1, then you're not going to have more than one page of any archive or your blog, so the links won't appear.</p>\n\n<p>If you want links between single posts, then the correct functions are <a href=\"https://developer.wordpress.org/reference/functions/get_next_post_link/\" rel=\"nofollow noreferrer\"><code>get_next_post_link()</code></a> and <a href=\"https://developer.wordpress.org/reference/functions/get_previous_post_link/\" rel=\"nofollow noreferrer\"><code>get_previous_post_link()</code></a>. Those functions <em>do</em> need to be in the loop.</p>\n\n<p>While it's technically possible to use <code>index.php</code> for single posts and archives/the blog, you can avoid some confusion by starting with at least <code>index.php</code> for your lists of posts, and <code>singular.php</code> for single posts and pages. Use <code>get_next_posts_link()</code> and <code>get_next_posts_link()</code> for links between pages in <code>index.php</code>, outside the loop, but use <code>get_next_post_link()</code> and <code>get_previous_post_link()</code> for links between single posts in <code>singular.php</code>, inside the loop.</p>\n"
}
] | 2019/06/27 | [
"https://wordpress.stackexchange.com/questions/341557",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109240/"
] | I'm working on a very simple theme. I have tried adding next and previous links and cannot get them to work.
After trying a few different things, I ended up with this `index.php` (mostly based on answers on SO).
```
<?php get_header(); ?>
<!-- html stuff -->
<?php
if ( have_posts() ) {
while ( have_posts() ) : the_post();
// ... post layout stuff
endwhile;
}
?>
<!-- Other html bits -->
<?php
$prev_link = get_previous_posts_link(__('« Older Entries'));
$next_link = get_next_posts_link(__('Newer Entries »'));
if ($prev_link || $next_link) {
echo '<nav><ul class="pager">';
if ($prev_link){
echo '<li>'.$prev_link .'</li>';
}
if ($next_link){
echo '<li>'.$next_link .'</li>';
}
echo '</ul></nav>';
}
?>
<!-- html stuff -->
<?php get_footer(); ?>
```
There are two blog posts on the development install I am working with. But neither of them display with the navigational links. | As suggested by the default link labels, "Older Entries" and "Newer Entries", `get_next_posts_link()` and `get_next_posts_link()` are for outputting links between pages of posts. If you only have 2 posts, and your posts per page setting is set to anything higher than 1, then you're not going to have more than one page of any archive or your blog, so the links won't appear.
If you want links between single posts, then the correct functions are [`get_next_post_link()`](https://developer.wordpress.org/reference/functions/get_next_post_link/) and [`get_previous_post_link()`](https://developer.wordpress.org/reference/functions/get_previous_post_link/). Those functions *do* need to be in the loop.
While it's technically possible to use `index.php` for single posts and archives/the blog, you can avoid some confusion by starting with at least `index.php` for your lists of posts, and `singular.php` for single posts and pages. Use `get_next_posts_link()` and `get_next_posts_link()` for links between pages in `index.php`, outside the loop, but use `get_next_post_link()` and `get_previous_post_link()` for links between single posts in `singular.php`, inside the loop. |
341,608 | <p>I have created a custom post type and I got it to show in the REST API.
I have also registered a custom field using the following code :</p>
<pre><code>function slug_get_post_meta_cb( $object, $field_name, $request ) {
return get_post_meta( $object[ 'id' ], $field_name );
}
function slug_update_post_meta_cb( $value, $object, $field_name ) {
return update_post_meta( $object[ 'id' ], $field_name, $value );
}
add_action( 'rest_api_init', function() {
register_rest_field( 'custom_type',
'myfield',
array(
'get_callback' => 'slug_get_post_meta_cb',
'update_callback' => 'slug_update_post_meta_cb',
'schema' => array(
'type' => 'string',
'context' => array( 'view', 'edit' )
),
)
);
</code></pre>
<p>I'm using jQuery to create an ajax POST request in order to create a new custom post with the following javascript code :</p>
<pre><code>jQuery.ajax( {
url: requete.api,
method: 'POST',
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', questionnaireScript.nonce );
},
data:{
title : myData.title,
content: myData.content,
status: "publish",
myfield: "Stop flying"
}
} ).done( function ( response ) {
console.log( response );
} );
</code></pre>
<p>The posts are created all right, by without the custom field <code>myfield</code> . It does show up as part of the custom post object in the response to a GET request, but as an empty array. I also tried to set it as <code>myfield : ["Stop flying"]</code>, and as <code>meta : {myfield: "Stop flying"}</code>, to no avail.
I am aware of the other WP function to register a meta field (<code>register_meta</code>). However since the documentation reads that it cannot be applied to a custom post type only I chose to use register_rest_field instead.
Any idea what I'm doing wrong ?</p>
| [
{
"answer_id": 341612,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 3,
"selected": true,
"text": "<p>I haven't tested your code, but here the <code>$object</code> is an object and not array:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>// Here, $object is a WP_Post object.\nfunction slug_update_post_meta_cb( $value, $object, $field_name ) {\n return update_post_meta( $object->ID, $field_name, $value );\n}\n</code></pre>\n\n<p>And you can actually use <a href=\"https://developer.wordpress.org/reference/functions/register_meta/\" rel=\"nofollow noreferrer\"><code>register_meta()</code></a> with a custom post type:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>register_meta( 'post', 'myfield', [\n 'object_subtype' => 'custom_type', // Limit to a post type.\n 'type' => 'string',\n 'description' => 'My Field',\n 'single' => true,\n 'show_in_rest' => true,\n] );\n</code></pre>\n\n<p>Check my answer <a href=\"https://wordpress.stackexchange.com/a/331834\">here</a> for more details.</p>\n"
},
{
"answer_id": 341613,
"author": "ChristopherJones",
"author_id": 168744,
"author_profile": "https://wordpress.stackexchange.com/users/168744",
"pm_score": 0,
"selected": false,
"text": "<p>Try and JSON.stringify() your data as you pass it over, and send it over as that type:</p>\n\n<pre><code>// Data to pass over\nobj_to_pass = {\n title : myData.title,\n content: myData.content,\n status: \"publish\",\n myfield: \"Stop flying\"\n};\n</code></pre>\n\n<pre><code>// Updated AJAX call\njQuery.ajax( {\n url: requete.api,\n method: 'POST',\n beforeSend: function ( xhr ) {\n xhr.setRequestHeader( 'X-WP-Nonce', questionnaireScript.nonce );\n },\n dataType : 'json',\n data: JSON.stringify(obj_to_pass)\n} ).done( function ( response ) {\n console.log( response );\n} );\n</code></pre>\n\n<p>I felt like I have had issues with it in the past. I don't have a good testing environment to test it in, so fingers crossed!</p>\n"
}
] | 2019/06/27 | [
"https://wordpress.stackexchange.com/questions/341608",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/130265/"
] | I have created a custom post type and I got it to show in the REST API.
I have also registered a custom field using the following code :
```
function slug_get_post_meta_cb( $object, $field_name, $request ) {
return get_post_meta( $object[ 'id' ], $field_name );
}
function slug_update_post_meta_cb( $value, $object, $field_name ) {
return update_post_meta( $object[ 'id' ], $field_name, $value );
}
add_action( 'rest_api_init', function() {
register_rest_field( 'custom_type',
'myfield',
array(
'get_callback' => 'slug_get_post_meta_cb',
'update_callback' => 'slug_update_post_meta_cb',
'schema' => array(
'type' => 'string',
'context' => array( 'view', 'edit' )
),
)
);
```
I'm using jQuery to create an ajax POST request in order to create a new custom post with the following javascript code :
```
jQuery.ajax( {
url: requete.api,
method: 'POST',
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', questionnaireScript.nonce );
},
data:{
title : myData.title,
content: myData.content,
status: "publish",
myfield: "Stop flying"
}
} ).done( function ( response ) {
console.log( response );
} );
```
The posts are created all right, by without the custom field `myfield` . It does show up as part of the custom post object in the response to a GET request, but as an empty array. I also tried to set it as `myfield : ["Stop flying"]`, and as `meta : {myfield: "Stop flying"}`, to no avail.
I am aware of the other WP function to register a meta field (`register_meta`). However since the documentation reads that it cannot be applied to a custom post type only I chose to use register\_rest\_field instead.
Any idea what I'm doing wrong ? | I haven't tested your code, but here the `$object` is an object and not array:
```php
// Here, $object is a WP_Post object.
function slug_update_post_meta_cb( $value, $object, $field_name ) {
return update_post_meta( $object->ID, $field_name, $value );
}
```
And you can actually use [`register_meta()`](https://developer.wordpress.org/reference/functions/register_meta/) with a custom post type:
```php
register_meta( 'post', 'myfield', [
'object_subtype' => 'custom_type', // Limit to a post type.
'type' => 'string',
'description' => 'My Field',
'single' => true,
'show_in_rest' => true,
] );
```
Check my answer [here](https://wordpress.stackexchange.com/a/331834) for more details. |
341,641 | <p>Will <code>current_theme_supports()</code> return TRUE with a nonstandard <code>add_theme_support()</code> string?</p>
<p>If I do this in my theme:</p>
<pre><code>add_theme_support( 'my_funky_new_thing' );
</code></pre>
<p>Can someone else writing a plugin do this?</p>
<pre><code>if( current_theme_supports( 'my_funky_new_thing' ) ){
// ...
}
</code></pre>
| [
{
"answer_id": 341644,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>Yes. You can take advantage of this to enable or disable features in your plugin if a theme does or does not declare support for a feature. WooCommmerce is an example of a plugin that does this. </p>\n"
},
{
"answer_id": 341663,
"author": "Antti Koskinen",
"author_id": 144392,
"author_profile": "https://wordpress.stackexchange.com/users/144392",
"pm_score": 2,
"selected": false,
"text": "<p>As a side note for those interested, you can also pass parameters with your custom theme support.</p>\n\n<pre><code>// theme functions.php\nadd_theme_support( 'some_feature', array(\n 'arg_foo',\n 'arg_bar'\n) );\n\n// plugin.php\n$feature_args = get_theme_support( 'some_feature' );\nvar_dump( $feature_args );\n// array(\n// array(\n// 'arg_foo',\n// 'arg_bar'\n// )\n// );\n</code></pre>\n"
}
] | 2019/06/27 | [
"https://wordpress.stackexchange.com/questions/341641",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109240/"
] | Will `current_theme_supports()` return TRUE with a nonstandard `add_theme_support()` string?
If I do this in my theme:
```
add_theme_support( 'my_funky_new_thing' );
```
Can someone else writing a plugin do this?
```
if( current_theme_supports( 'my_funky_new_thing' ) ){
// ...
}
``` | Yes. You can take advantage of this to enable or disable features in your plugin if a theme does or does not declare support for a feature. WooCommmerce is an example of a plugin that does this. |
341,675 | <p>Hey there WordPress community,</p>
<p>Google page speed is moaning about dashicons.min.css being on our site. However, we need it for the Mega menu.</p>
<p>I wanted to know if it's possible to move it to the footer.</p>
<p>I have tried this code already:</p>
<pre><code>add_action( 'wp_print_styles', 'my_deregister_styles' );
function my_deregister_styles() {
wp_deregister_style( 'dashicons' );
wp_enqueue_style( 'dashicons', array(), false, true );
}
</code></pre>
<p>I have also tried a few other samples, however, nothing seems to work here.</p>
<p>Any ideas?</p>
<p>Thanks</p>
| [
{
"answer_id": 341681,
"author": "Milan Hirpara",
"author_id": 168898,
"author_profile": "https://wordpress.stackexchange.com/users/168898",
"pm_score": 1,
"selected": true,
"text": "<p>Please try below code :</p>\n\n<pre><code>add_action( 'wp_print_styles', 'my_deregister_styles' );\nfunction my_deregister_styles() { \n wp_deregister_style( 'dashicons' ); \n}\n</code></pre>\n\n<p>Replace your css path \"PATH_OF_CSS\" :</p>\n\n<pre><code>add_action( 'wp_footer', 'register_wp_footer', 11 );\nfunction register_wp_footer() { \n wp_enqueue_style( 'dashicons', 'PATH_OF_CSS' ,array(), false, true );\n}\n</code></pre>\n"
},
{
"answer_id": 341698,
"author": "Chris",
"author_id": 161219,
"author_profile": "https://wordpress.stackexchange.com/users/161219",
"pm_score": 1,
"selected": false,
"text": "<p>Final working solution was:</p>\n\n<pre><code>add_action( 'wp_print_styles', 'my_deregister_styles' );\nfunction my_deregister_styles() { \n wp_deregister_style( 'dashicons' ); \n}\n\nadd_action( 'wp_footer', 'register_wp_footer' );\nfunction register_wp_footer() { \n wp_enqueue_style( 'dashicons', '/wp-includes/css/dashicons.min.css');\n}\n</code></pre>\n"
}
] | 2019/06/28 | [
"https://wordpress.stackexchange.com/questions/341675",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/161219/"
] | Hey there WordPress community,
Google page speed is moaning about dashicons.min.css being on our site. However, we need it for the Mega menu.
I wanted to know if it's possible to move it to the footer.
I have tried this code already:
```
add_action( 'wp_print_styles', 'my_deregister_styles' );
function my_deregister_styles() {
wp_deregister_style( 'dashicons' );
wp_enqueue_style( 'dashicons', array(), false, true );
}
```
I have also tried a few other samples, however, nothing seems to work here.
Any ideas?
Thanks | Please try below code :
```
add_action( 'wp_print_styles', 'my_deregister_styles' );
function my_deregister_styles() {
wp_deregister_style( 'dashicons' );
}
```
Replace your css path "PATH\_OF\_CSS" :
```
add_action( 'wp_footer', 'register_wp_footer', 11 );
function register_wp_footer() {
wp_enqueue_style( 'dashicons', 'PATH_OF_CSS' ,array(), false, true );
}
``` |
341,685 | <p>This code goes into an infinite loop! What am i doing wrong? There is only one post called “hello there”. The only way to stop it is use <code>break;</code> in while.</p>
<p>Any help appreciated</p>
<pre><code> $gotop="hello there";
$args = array(
's' => $gotop,
'post_type' => 'post'
);
$wp_query = new WP_Query($args);
if ( $wp_query->have_posts() ) : ?>
<?php
while ( $wp_query->have_posts() ) {
$wp_query->the_post();
}
else:
echo "nothing found.";
endif;
?>
</code></pre>
| [
{
"answer_id": 341687,
"author": "Chetan Vaghela",
"author_id": 169856,
"author_profile": "https://wordpress.stackexchange.com/users/169856",
"pm_score": 1,
"selected": false,
"text": "<p>add wp_reset_query(); after while loop. </p>\n\n<pre><code>$gotop=\"hello there\";\n\n$args = array(\n\n 's' => $gotop,\n 'post_type' => 'post'\n\n);\n\n$my_query = new WP_Query($args);\n\nif ( $my_query->have_posts() ) : \n\n while ( $my_query->have_posts() ) {\n $my_query->the_post();\n }\n wp_reset_query();\n\nelse:\n echo \"nothing found.\";\nendif;\n</code></pre>\n\n<p>let me know if this works for you!</p>\n"
},
{
"answer_id": 341693,
"author": "dragos.nicolae",
"author_id": 170794,
"author_profile": "https://wordpress.stackexchange.com/users/170794",
"pm_score": -1,
"selected": false,
"text": "<p>According to WP codex, have_posts() will return True on success, false on failure.\nCalling this function within the loop will cause an infinite loop. So you need to use <strong>endwhile</strong>;</p>\n\n<pre><code> $gotop=\"hello there\";\n\n$args = array(\n\n 's' => $gotop,\n 'post_type' => 'post'\n\n);\n\n$wp_query = new WP_Query($args);\n\nif ( $wp_query->have_posts() ) : ?>\n\n <?php\n\n while ( $wp_query->have_posts() ) {\n $wp_query->the_post();\n endwhile;\n}\n\nelse:\n echo \"nothing found.\";\nendif;\n?>\n</code></pre>\n"
},
{
"answer_id": 341694,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>I'm not certain why it would cause an infinite loop, but make sure not to use <code>$wp_query</code> as the variable name for your custom query. It's a <a href=\"https://codex.wordpress.org/Global_Variables\" rel=\"nofollow noreferrer\">reserved global variable</a> for the main query. Use a different name for the variable. I'd also suggest using <code>wp_reset_postdata()</code> after the loop:</p>\n\n<pre><code>$my_query = new WP_Query( $args );\n\nif ( $my_query->have_posts() ) :\n while ( $my_query->have_posts() ) {\n $my_query->the_post();\n }\nelse:\n echo \"nothing found.\";\nendif;\n\nwp_reset_postdata();\n</code></pre>\n"
}
] | 2019/06/28 | [
"https://wordpress.stackexchange.com/questions/341685",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/170446/"
] | This code goes into an infinite loop! What am i doing wrong? There is only one post called “hello there”. The only way to stop it is use `break;` in while.
Any help appreciated
```
$gotop="hello there";
$args = array(
's' => $gotop,
'post_type' => 'post'
);
$wp_query = new WP_Query($args);
if ( $wp_query->have_posts() ) : ?>
<?php
while ( $wp_query->have_posts() ) {
$wp_query->the_post();
}
else:
echo "nothing found.";
endif;
?>
``` | I'm not certain why it would cause an infinite loop, but make sure not to use `$wp_query` as the variable name for your custom query. It's a [reserved global variable](https://codex.wordpress.org/Global_Variables) for the main query. Use a different name for the variable. I'd also suggest using `wp_reset_postdata()` after the loop:
```
$my_query = new WP_Query( $args );
if ( $my_query->have_posts() ) :
while ( $my_query->have_posts() ) {
$my_query->the_post();
}
else:
echo "nothing found.";
endif;
wp_reset_postdata();
``` |
341,726 | <p>I'm rewording this because, as it's correctly been pointed out, the original post was "woefully inadequate." I made a plugin which has tabbed views for the various settings. It's based on this <a href="https://github.com/hlashbrooke/WordPress-Plugin-Template" rel="nofollow noreferrer">Wordpress Plugin Template</a>. The template uses the WP Settings API to construct the settings page and display the tabs. The form uses the default <code>_wpnonce</code> for the submit/save settings button.</p>
<p>The tabs are link elements that alter the page URL query string, e.g., from <code>/wp-admin/options-general.php?page=my_plugin_settings&amp;tab=tab_1</code> to <code>/wp-admin/options-general.php?page=my_plugin_settings&amp;tab=tab_2</code>.</p>
<p>The question is now: how to create a nonce for the tabs and check it when the page loads or the user selects one of the tabs. </p>
<p><strong>class-my-plugin.php</strong>. Code example is simplified for clarity. </p>
<pre><code>class My_Plugin {
private static $_instance = null;
public $admin = null;
public $settings = null;
public $_token;
public function __construct( $file = '', $version = '1.0.0' ) {
$this->_version = $version;
$this->_token = 'my_plugin';
}
}
</code></pre>
<p><strong>class-my-plugin-settings.php</strong>. Code example is simplified for clarity.</p>
<pre><code>class My_Plugin_Settings {
private static $_instance = null;
public $parent = null;
public $base = '';
public $settings = array();
public function __construct( $parent ) {
$this->parent = $parent;
$this->base = 'wpt_';
add_action( 'init', array( $this, 'init_settings' ), 11 );
add_action( 'admin_init', array( $this, 'register_settings' ) );
add_action( 'admin_menu', array( $this, 'add_menu_item' ) );
add_filter( $this->base . 'menu_settings', array( $this, 'configure_settings' ) );
}
/**
* Initialise settings
*/
public function init_settings() {
$this->settings = $this->settings_fields();
}
/**
* Add settings page to admin menu
*/
public function add_menu_item() {
// Code omitted for brevity.
}
/**
* Prepare default settings page arguments
*/
private function menu_settings() {
// Code omitted for brevity.
}
/**
* Container for settings page arguments
*/
public function configure_settings( $settings = array() ) {
return $settings;
}
/**
* Build settings fields
*/
private function settings_fields() {
$settings['tab_1'] = array(
'title' => __( 'Tab 1', 'my_plugin' ),
'description' => __( 'The first settings screen.', 'my_plugin' ),
'fields' => array(
// Form fields etc. here
),
);
$settings['tab_2'] = array(
'title' => __( 'Tab 2', 'my_plugin' ),
'description' => __( 'The second settings screen.', 'my_plugin' ),
'fields' => array(
// Form fields etc. here
),
);
$settings = apply_filters( $this->parent->_token . '_settings_fields', $settings );
return $settings;
}
/**
* Register plugin settings
*/
public function register_settings() {
if ( is_array( $this->settings ) ) {
// Check posted/selected tab.
$current_section = '';
if ( isset( $_POST['tab'] ) && $_POST['tab'] ) { // NONCE warning
$current_section = $_POST['tab']; // NONCE warning
} else {
if ( isset( $_GET['tab'] ) && $_GET['tab'] ) { // NONCE warning
$current_section = $_GET['tab']; // Nonce warning
}
}
foreach ( $this->settings as $section => $data ) {
if ( $current_section && $current_section !== $section ) {
continue;
}
// Add section to page.
add_settings_section( $section, $data['title'], array( $this, 'settings_section' ), $this->parent->_token . '_settings' );
foreach ( $data['fields'] as $field ) {
// Validation callback for field.
$validation = '';
if ( isset( $field['callback'] ) ) {
$validation = $field['callback'];
}
// Register field.
$option_name = $this->base . $field['id'];
register_setting( $this->parent->_token . '_settings', $option_name, $validation );
// Add field to page.
add_settings_field(
$field['id'],
$field['label'],
array( $this->parent->admin, 'display_field' ),
$this->parent->_token . '_settings',
$section,
array(
'field' => $field,
'prefix' => $this->base,
)
);
}
if ( ! $current_section ) {
break;
}
}
}
}
/**
* Settings section.
*
* @param array $section Array of section ids.
* @return void
*/
public function settings_section( $section ) {
$html = '<p> ' . $this->settings[ $section['id'] ]['description'] . '</p>' . "\n";
echo $html;
}
/**
* Load settings page content.
*
* @return void
*/
public function settings_page() {
// Build page HTML.
$html = '<div class="wrap" id="' . $this->parent->_token . '_settings">' . "\n";
$html .= '<h2>' . __( 'Plugin Settings', 'my_plugin' ) . '</h2>' . "\n";
$tab = '';
//phpcs:disable
if ( isset( $_GET['tab'] ) && $_GET['tab'] ) {
$tab .= $_GET['tab'];
}
//phpcs:enable
// Show page tabs.
if ( is_array( $this->settings ) && 1 < count( $this->settings ) ) {
$html .= '<h2 class="nav-tab-wrapper">' . "\n";
$c = 0;
foreach ( $this->settings as $section => $data ) {
// Set tab class.
$class = 'nav-tab';
if ( ! isset( $_GET['tab'] ) ) { // NONCE warning
if ( 0 === $c ) {
$class .= ' nav-tab-active';
}
} else {
if ( isset( $_GET['tab'] ) && $section == $_GET['tab'] ) { // Nonce warning
$class .= ' nav-tab-active';
}
}
// Set tab link.
$tab_link = add_query_arg( array( 'tab' => $section ) );
if ( isset( $_GET['settings-updated'] ) ) { // NONCE warning
$tab_link = remove_query_arg( 'settings-updated', $tab_link );
}
// Output tab.
$html .= '<a href="' . $tab_link . '" class="' . esc_attr( $class ) . '">' . esc_html( $data['title'] ) . '</a>' . "\n";
++$c;
}
$html .= '</h2>' . "\n";
}
$html .= '<form method="post" action="options.php" enctype="multipart/form-data">' . "\n";
// Get settings fields.
ob_start();
settings_fields( $this->parent->_token . '_settings' );
do_settings_sections( $this->parent->_token . '_settings' );
$html .= ob_get_clean();
$html .= '<p class="submit">' . "\n";
$html .= '<input type="hidden" name="tab" value="' . esc_attr( $tab ) . '" />' . "\n";
$html .= '<input name="Submit" type="submit" class="button-primary" value="' . esc_attr( __( 'Save Settings', 'my_plugin' ) ) . '" />' . "\n";
$html .= '</p>' . "\n";
$html .= '</form>' . "\n";
$html .= '</div>' . "\n";
echo $html;
}
/**
* Main My_Plugin_Settings Instance
*
* Ensures only one instance of My_Plugin_Settings is loaded or can be loaded.
*
* @since 1.0.0
* @static
* @see My_Plugin()
* @param object $parent Object instance.
* @return object My_Plugin_Settings instance
*/
public static function instance( $parent ) {
if ( is_null( self::$_instance ) ) {
self::$_instance = new self( $parent );
}
return self::$_instance;
} // End instance()
}
</code></pre>
<p><strong>Form output</strong>. Changes depending on which tab is selected.</p>
<pre><code><div class="wrap">
<h2>Heading</h2>
<p>Plugin description.</p>
<h2 class="nav-tab-wrapper">
<a href="/wp-admin/options-general.php?page=my_plugin_settings&amp;tab=tab_1" class="nav-tab nav-tab-active">Tab 1</a>
<a href="/wp-admin/options-general.php?page=my_plugin_settings&amp;tab=tab_2" class="nav-tab">Tab 2</a>
</h2>
<form method="post" action="options.php" enctype="multipart/form-data">
<input type="hidden" name="option_page" value="my_plugin_settings"><input type="hidden" name="action" value="update"><input type="hidden" id="_wpnonce" name="_wpnonce" value="$integer"><input type="hidden" name="_wp_http_referer" value="/wp-admin/options-general.php?page=my_plugin_settings&amp;tab=tab_1">
<h2>Tab 1</h2>
<p>
Description for Tab 1 screen.</p>
<table class="form-table">
<!-- Form table contents -->
</table>
<p class="submit">
<input type="hidden" name="tab" value="upload">
<input name="Submit" type="submit" class="button-primary" value="Save Settings">
</p>
</form>
</div>
</code></pre>
<p>ORIGINAL POST: I'm using PHPCS with Wordpress<strike>-Extra</strike> coding standards to check my plugin code. I'm getting this warning:</p>
<blockquote>
<p>WARNING | Processing form data without nonce verification.</p>
</blockquote>
<p>The code in question displays tabbed navigation in the settings page:</p>
<pre><code>class Example_Class {
public function settings_page() {
$tab = '';
if ( isset( $_GET['tab'] ) && $_GET['tab'] ) { // WARNING
$tab .= $_GET['tab']; // WARNING
}
if ( isset( $_GET['tab'] ) && $_GET['tab'] ) { // WARNING
$tab .= $_GET['tab']; // WARNING
}
// Show page tabs
if ( is_array( $this->settings ) && 1 < count( $this->settings ) ) {
$html .= '<h2 class="nav-tab-wrapper">' . chr( 0x0D ) . chr( 0x0A );
$c = 0;
foreach ( $this->settings as $section => $data ) {
// Set tab class
$class = 'nav-tab';
if ( ! isset( $_GET['tab'] ) ) { // WARNING
if ( 0 === $c ) {
$class .= ' nav-tab-active';
}
} else {
if ( isset( $_GET['tab'] ) && $section === $_GET['tab'] ) { // WARNING
$class .= ' nav-tab-active';
}
}
// Set tab link
$tab_link = add_query_arg( array( 'tab' => $section ) );
if ( isset( $_GET['settings-updated'] ) ) { // WARNING
$tab_link = remove_query_arg( 'settings-updated', $tab_link );
}
// Output tab
$html .= '<a href="' . $tab_link . '" class="' . esc_attr( $class ) . '">' . esc_html( $data['title'] ) . '</a>' . chr( 0x0D ) . chr( 0x0A );
++$c;
}
$html .= '</h2>' . chr( 0x0D ) . chr( 0x0A );
}
}
public function register_settings() {
if ( is_array( $this->settings ) ) {
// Check posted/selected tab
$current_section = '';
if ( isset( $_POST['tab'] ) && $_POST['tab'] ) { // WARNING
$current_section = $_POST['tab'];
} else {
if ( isset( $_GET['tab'] ) && $_GET['tab'] ) { // WARNING
$current_section = $_GET['tab']; // WARNING
}
}
// Unrelated code omitted
}
}
}
</code></pre>
<p>I thought the API handled nonces automagically? Should I be concerned? Or is the code OK as it is? If not, how should I fix this?</p>
<p>EDIT: In light of the answers, the API provides a default nonce <code><input type="hidden" id="_wpnonce" name="_wpnonce" value="$int"></code> & the associated hidden field <code><input type="hidden" name="_wp_http_referer" value="/wp-admin/options-general.php?page=_settings"></code>. How do I verify? I've tried, unsuccessfully:</p>
<pre><code>if ( isset( $_POST['tab'] ) && $_POST['tab'] ) {
if ( ! wp_verify_nonce( '_wpnonce' ) ) {
wp_die( 'Go away!' );
} else {
$current_section = sanitize_text_field( wp_unslash( $_POST['tab'] ) );
}
} else {
if ( isset( $_GET['tab'] ) && $_GET['tab'] ) {
if ( ! wp_verify_nonce( '_wpnonce' ) ) {
wp_die( 'Go away!' );
} else {
$current_section = sanitize_text_field( wp_unslash( $_GET['tab'] ) );
}
}
}
</code></pre>
| [
{
"answer_id": 341687,
"author": "Chetan Vaghela",
"author_id": 169856,
"author_profile": "https://wordpress.stackexchange.com/users/169856",
"pm_score": 1,
"selected": false,
"text": "<p>add wp_reset_query(); after while loop. </p>\n\n<pre><code>$gotop=\"hello there\";\n\n$args = array(\n\n 's' => $gotop,\n 'post_type' => 'post'\n\n);\n\n$my_query = new WP_Query($args);\n\nif ( $my_query->have_posts() ) : \n\n while ( $my_query->have_posts() ) {\n $my_query->the_post();\n }\n wp_reset_query();\n\nelse:\n echo \"nothing found.\";\nendif;\n</code></pre>\n\n<p>let me know if this works for you!</p>\n"
},
{
"answer_id": 341693,
"author": "dragos.nicolae",
"author_id": 170794,
"author_profile": "https://wordpress.stackexchange.com/users/170794",
"pm_score": -1,
"selected": false,
"text": "<p>According to WP codex, have_posts() will return True on success, false on failure.\nCalling this function within the loop will cause an infinite loop. So you need to use <strong>endwhile</strong>;</p>\n\n<pre><code> $gotop=\"hello there\";\n\n$args = array(\n\n 's' => $gotop,\n 'post_type' => 'post'\n\n);\n\n$wp_query = new WP_Query($args);\n\nif ( $wp_query->have_posts() ) : ?>\n\n <?php\n\n while ( $wp_query->have_posts() ) {\n $wp_query->the_post();\n endwhile;\n}\n\nelse:\n echo \"nothing found.\";\nendif;\n?>\n</code></pre>\n"
},
{
"answer_id": 341694,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>I'm not certain why it would cause an infinite loop, but make sure not to use <code>$wp_query</code> as the variable name for your custom query. It's a <a href=\"https://codex.wordpress.org/Global_Variables\" rel=\"nofollow noreferrer\">reserved global variable</a> for the main query. Use a different name for the variable. I'd also suggest using <code>wp_reset_postdata()</code> after the loop:</p>\n\n<pre><code>$my_query = new WP_Query( $args );\n\nif ( $my_query->have_posts() ) :\n while ( $my_query->have_posts() ) {\n $my_query->the_post();\n }\nelse:\n echo \"nothing found.\";\nendif;\n\nwp_reset_postdata();\n</code></pre>\n"
}
] | 2019/06/28 | [
"https://wordpress.stackexchange.com/questions/341726",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/119814/"
] | I'm rewording this because, as it's correctly been pointed out, the original post was "woefully inadequate." I made a plugin which has tabbed views for the various settings. It's based on this [Wordpress Plugin Template](https://github.com/hlashbrooke/WordPress-Plugin-Template). The template uses the WP Settings API to construct the settings page and display the tabs. The form uses the default `_wpnonce` for the submit/save settings button.
The tabs are link elements that alter the page URL query string, e.g., from `/wp-admin/options-general.php?page=my_plugin_settings&tab=tab_1` to `/wp-admin/options-general.php?page=my_plugin_settings&tab=tab_2`.
The question is now: how to create a nonce for the tabs and check it when the page loads or the user selects one of the tabs.
**class-my-plugin.php**. Code example is simplified for clarity.
```
class My_Plugin {
private static $_instance = null;
public $admin = null;
public $settings = null;
public $_token;
public function __construct( $file = '', $version = '1.0.0' ) {
$this->_version = $version;
$this->_token = 'my_plugin';
}
}
```
**class-my-plugin-settings.php**. Code example is simplified for clarity.
```
class My_Plugin_Settings {
private static $_instance = null;
public $parent = null;
public $base = '';
public $settings = array();
public function __construct( $parent ) {
$this->parent = $parent;
$this->base = 'wpt_';
add_action( 'init', array( $this, 'init_settings' ), 11 );
add_action( 'admin_init', array( $this, 'register_settings' ) );
add_action( 'admin_menu', array( $this, 'add_menu_item' ) );
add_filter( $this->base . 'menu_settings', array( $this, 'configure_settings' ) );
}
/**
* Initialise settings
*/
public function init_settings() {
$this->settings = $this->settings_fields();
}
/**
* Add settings page to admin menu
*/
public function add_menu_item() {
// Code omitted for brevity.
}
/**
* Prepare default settings page arguments
*/
private function menu_settings() {
// Code omitted for brevity.
}
/**
* Container for settings page arguments
*/
public function configure_settings( $settings = array() ) {
return $settings;
}
/**
* Build settings fields
*/
private function settings_fields() {
$settings['tab_1'] = array(
'title' => __( 'Tab 1', 'my_plugin' ),
'description' => __( 'The first settings screen.', 'my_plugin' ),
'fields' => array(
// Form fields etc. here
),
);
$settings['tab_2'] = array(
'title' => __( 'Tab 2', 'my_plugin' ),
'description' => __( 'The second settings screen.', 'my_plugin' ),
'fields' => array(
// Form fields etc. here
),
);
$settings = apply_filters( $this->parent->_token . '_settings_fields', $settings );
return $settings;
}
/**
* Register plugin settings
*/
public function register_settings() {
if ( is_array( $this->settings ) ) {
// Check posted/selected tab.
$current_section = '';
if ( isset( $_POST['tab'] ) && $_POST['tab'] ) { // NONCE warning
$current_section = $_POST['tab']; // NONCE warning
} else {
if ( isset( $_GET['tab'] ) && $_GET['tab'] ) { // NONCE warning
$current_section = $_GET['tab']; // Nonce warning
}
}
foreach ( $this->settings as $section => $data ) {
if ( $current_section && $current_section !== $section ) {
continue;
}
// Add section to page.
add_settings_section( $section, $data['title'], array( $this, 'settings_section' ), $this->parent->_token . '_settings' );
foreach ( $data['fields'] as $field ) {
// Validation callback for field.
$validation = '';
if ( isset( $field['callback'] ) ) {
$validation = $field['callback'];
}
// Register field.
$option_name = $this->base . $field['id'];
register_setting( $this->parent->_token . '_settings', $option_name, $validation );
// Add field to page.
add_settings_field(
$field['id'],
$field['label'],
array( $this->parent->admin, 'display_field' ),
$this->parent->_token . '_settings',
$section,
array(
'field' => $field,
'prefix' => $this->base,
)
);
}
if ( ! $current_section ) {
break;
}
}
}
}
/**
* Settings section.
*
* @param array $section Array of section ids.
* @return void
*/
public function settings_section( $section ) {
$html = '<p> ' . $this->settings[ $section['id'] ]['description'] . '</p>' . "\n";
echo $html;
}
/**
* Load settings page content.
*
* @return void
*/
public function settings_page() {
// Build page HTML.
$html = '<div class="wrap" id="' . $this->parent->_token . '_settings">' . "\n";
$html .= '<h2>' . __( 'Plugin Settings', 'my_plugin' ) . '</h2>' . "\n";
$tab = '';
//phpcs:disable
if ( isset( $_GET['tab'] ) && $_GET['tab'] ) {
$tab .= $_GET['tab'];
}
//phpcs:enable
// Show page tabs.
if ( is_array( $this->settings ) && 1 < count( $this->settings ) ) {
$html .= '<h2 class="nav-tab-wrapper">' . "\n";
$c = 0;
foreach ( $this->settings as $section => $data ) {
// Set tab class.
$class = 'nav-tab';
if ( ! isset( $_GET['tab'] ) ) { // NONCE warning
if ( 0 === $c ) {
$class .= ' nav-tab-active';
}
} else {
if ( isset( $_GET['tab'] ) && $section == $_GET['tab'] ) { // Nonce warning
$class .= ' nav-tab-active';
}
}
// Set tab link.
$tab_link = add_query_arg( array( 'tab' => $section ) );
if ( isset( $_GET['settings-updated'] ) ) { // NONCE warning
$tab_link = remove_query_arg( 'settings-updated', $tab_link );
}
// Output tab.
$html .= '<a href="' . $tab_link . '" class="' . esc_attr( $class ) . '">' . esc_html( $data['title'] ) . '</a>' . "\n";
++$c;
}
$html .= '</h2>' . "\n";
}
$html .= '<form method="post" action="options.php" enctype="multipart/form-data">' . "\n";
// Get settings fields.
ob_start();
settings_fields( $this->parent->_token . '_settings' );
do_settings_sections( $this->parent->_token . '_settings' );
$html .= ob_get_clean();
$html .= '<p class="submit">' . "\n";
$html .= '<input type="hidden" name="tab" value="' . esc_attr( $tab ) . '" />' . "\n";
$html .= '<input name="Submit" type="submit" class="button-primary" value="' . esc_attr( __( 'Save Settings', 'my_plugin' ) ) . '" />' . "\n";
$html .= '</p>' . "\n";
$html .= '</form>' . "\n";
$html .= '</div>' . "\n";
echo $html;
}
/**
* Main My_Plugin_Settings Instance
*
* Ensures only one instance of My_Plugin_Settings is loaded or can be loaded.
*
* @since 1.0.0
* @static
* @see My_Plugin()
* @param object $parent Object instance.
* @return object My_Plugin_Settings instance
*/
public static function instance( $parent ) {
if ( is_null( self::$_instance ) ) {
self::$_instance = new self( $parent );
}
return self::$_instance;
} // End instance()
}
```
**Form output**. Changes depending on which tab is selected.
```
<div class="wrap">
<h2>Heading</h2>
<p>Plugin description.</p>
<h2 class="nav-tab-wrapper">
<a href="/wp-admin/options-general.php?page=my_plugin_settings&tab=tab_1" class="nav-tab nav-tab-active">Tab 1</a>
<a href="/wp-admin/options-general.php?page=my_plugin_settings&tab=tab_2" class="nav-tab">Tab 2</a>
</h2>
<form method="post" action="options.php" enctype="multipart/form-data">
<input type="hidden" name="option_page" value="my_plugin_settings"><input type="hidden" name="action" value="update"><input type="hidden" id="_wpnonce" name="_wpnonce" value="$integer"><input type="hidden" name="_wp_http_referer" value="/wp-admin/options-general.php?page=my_plugin_settings&tab=tab_1">
<h2>Tab 1</h2>
<p>
Description for Tab 1 screen.</p>
<table class="form-table">
<!-- Form table contents -->
</table>
<p class="submit">
<input type="hidden" name="tab" value="upload">
<input name="Submit" type="submit" class="button-primary" value="Save Settings">
</p>
</form>
</div>
```
ORIGINAL POST: I'm using PHPCS with Wordpress-Extra coding standards to check my plugin code. I'm getting this warning:
>
> WARNING | Processing form data without nonce verification.
>
>
>
The code in question displays tabbed navigation in the settings page:
```
class Example_Class {
public function settings_page() {
$tab = '';
if ( isset( $_GET['tab'] ) && $_GET['tab'] ) { // WARNING
$tab .= $_GET['tab']; // WARNING
}
if ( isset( $_GET['tab'] ) && $_GET['tab'] ) { // WARNING
$tab .= $_GET['tab']; // WARNING
}
// Show page tabs
if ( is_array( $this->settings ) && 1 < count( $this->settings ) ) {
$html .= '<h2 class="nav-tab-wrapper">' . chr( 0x0D ) . chr( 0x0A );
$c = 0;
foreach ( $this->settings as $section => $data ) {
// Set tab class
$class = 'nav-tab';
if ( ! isset( $_GET['tab'] ) ) { // WARNING
if ( 0 === $c ) {
$class .= ' nav-tab-active';
}
} else {
if ( isset( $_GET['tab'] ) && $section === $_GET['tab'] ) { // WARNING
$class .= ' nav-tab-active';
}
}
// Set tab link
$tab_link = add_query_arg( array( 'tab' => $section ) );
if ( isset( $_GET['settings-updated'] ) ) { // WARNING
$tab_link = remove_query_arg( 'settings-updated', $tab_link );
}
// Output tab
$html .= '<a href="' . $tab_link . '" class="' . esc_attr( $class ) . '">' . esc_html( $data['title'] ) . '</a>' . chr( 0x0D ) . chr( 0x0A );
++$c;
}
$html .= '</h2>' . chr( 0x0D ) . chr( 0x0A );
}
}
public function register_settings() {
if ( is_array( $this->settings ) ) {
// Check posted/selected tab
$current_section = '';
if ( isset( $_POST['tab'] ) && $_POST['tab'] ) { // WARNING
$current_section = $_POST['tab'];
} else {
if ( isset( $_GET['tab'] ) && $_GET['tab'] ) { // WARNING
$current_section = $_GET['tab']; // WARNING
}
}
// Unrelated code omitted
}
}
}
```
I thought the API handled nonces automagically? Should I be concerned? Or is the code OK as it is? If not, how should I fix this?
EDIT: In light of the answers, the API provides a default nonce `<input type="hidden" id="_wpnonce" name="_wpnonce" value="$int">` & the associated hidden field `<input type="hidden" name="_wp_http_referer" value="/wp-admin/options-general.php?page=_settings">`. How do I verify? I've tried, unsuccessfully:
```
if ( isset( $_POST['tab'] ) && $_POST['tab'] ) {
if ( ! wp_verify_nonce( '_wpnonce' ) ) {
wp_die( 'Go away!' );
} else {
$current_section = sanitize_text_field( wp_unslash( $_POST['tab'] ) );
}
} else {
if ( isset( $_GET['tab'] ) && $_GET['tab'] ) {
if ( ! wp_verify_nonce( '_wpnonce' ) ) {
wp_die( 'Go away!' );
} else {
$current_section = sanitize_text_field( wp_unslash( $_GET['tab'] ) );
}
}
}
``` | I'm not certain why it would cause an infinite loop, but make sure not to use `$wp_query` as the variable name for your custom query. It's a [reserved global variable](https://codex.wordpress.org/Global_Variables) for the main query. Use a different name for the variable. I'd also suggest using `wp_reset_postdata()` after the loop:
```
$my_query = new WP_Query( $args );
if ( $my_query->have_posts() ) :
while ( $my_query->have_posts() ) {
$my_query->the_post();
}
else:
echo "nothing found.";
endif;
wp_reset_postdata();
``` |
341,742 | <p>I have an activation hook to create 2 new database tables that don't exist, only the second table is created from this code:</p>
<pre><code> public function add_tables() {
// Global $wpdb
global $wpdb;
$wpdb->hide_errors();
// Require upgrade
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
// Set charset
$collate = '';
if ( $wpdb->has_cap( 'collation' ) ) {
$collate = $wpdb->get_charset_collate();
}
// SQL query
$sql = "
CREATE TABLE IF NOT EXISTS " . $wpdb->prefix . "test1 (
test_id bigint(20) NOT NULL AUTO_INCREMENT,
test_key char(64) NOT NULL,
) $collate;
CREATE TABLE IF NOT EXISTS " . $wpdb->prefix . "test2 (
test_id bigint(20) NOT NULL AUTO_INCREMENT,
test_key char(64) NOT NULL,
) $collate;
";
// Do SQL
dbDelta( $sql );
}
</code></pre>
<p>Why only the second? If I print out the <code>$sql</code> variable I get the SQL statement and if I run that in phpMyAdmin it creates the 2 tables.</p>
<p>I looked at how plugins like WooCommerce do it (<a href="https://github.com/woocommerce/woocommerce/blob/c04f7b79f972ee854e5f5d726eb78ac04a726b32/includes/class-wc-install.php#L687" rel="nofollow noreferrer">https://github.com/woocommerce/woocommerce/blob/c04f7b79f972ee854e5f5d726eb78ac04a726b32/includes/class-wc-install.php#L687</a>) and it appears I am doing the same as they are.</p>
| [
{
"answer_id": 341755,
"author": "Faham Shaikh",
"author_id": 147414,
"author_profile": "https://wordpress.stackexchange.com/users/147414",
"pm_score": 2,
"selected": false,
"text": "<p>One way to get it to work would be to do it like this:</p>\n\n<pre><code>global $wpdb;\n$wpdb->hide_errors();\n// Require upgrade\n// Set charset\n$collate = '';\nif ( $wpdb->has_cap( 'collation' ) ) {\n $collate = $wpdb->get_charset_collate();\n}\nrequire_once( ABSPATH . 'wp-admin/includes/upgrade.php' );\n$queries = array();\narray_push($queries, \"\nCREATE TABLE IF NOT EXISTS {$wpdb->prefix}test1 (\n `test_id1` bigint(20) NOT NULL AUTO_INCREMENT,\n `test_key1` char(64) NOT NULL,\n `test_key21` char(64) NULL, PRIMARY KEY (`test_id1`)\n ) {$collate}\");\narray_push($queries, \"CREATE TABLE IF NOT EXISTS {$wpdb->prefix}test2 (\n `test_id2` bigint(20) NOT NULL AUTO_INCREMENT,\n `test_key2` char(64) NOT NULL,\n `test_key12` char(64) NULL, PRIMARY KEY (`test_id2`)\n ) {$collate}\");\nforeach ($queries as $key => $sql) {\n dbDelta( $sql );\n}\n</code></pre>\n\n<p>I agree that this doesn't actually explains why the supported format for <code>dbdelta</code> is not working but this seems to work at the very least.</p>\n"
},
{
"answer_id": 341783,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>Why only the second?</p>\n</blockquote>\n\n<p>Because <code>dbDelta()</code> supports <code>CREATE TABLE table_name</code> format only. I.e. Exactly \"CREATE TABLE\" followed by (one space and) the table name.</p>\n\n<p>More specifically, <code>dbDelta()</code> uses this regular expression pattern: <code>CREATE TABLE ([^ ]*)</code> when parsing the queries into an array indexed by the table name; i.e. <code>array( 'table_1' => 'query', 'table_2' => 'query', ... )</code>.</p>\n\n<p>Here's the relevant <a href=\"https://core.trac.wordpress.org/browser/tags/5.2/src/wp-admin/includes/upgrade.php#L2547\" rel=\"nofollow noreferrer\">code</a>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$cqueries = array(); // Creation Queries\n...\n\n// Create a tablename index for an array ($cqueries) of queries\nforeach ( $queries as $qry ) {\n if ( preg_match( '|CREATE TABLE ([^ ]*)|', $qry, $matches ) ) {\n $cqueries[ trim( $matches[1], '`' ) ] = $qry;\n $for_update[ $matches[1] ] = 'Created table ' . $matches[1];\n }\n ...\n}\n</code></pre>\n\n<p>So in the case of <code>CREATE TABLE IF NOT EXISTS table_name</code>, the table name is (seen as) <code>IF</code> and not <code>table_name</code> due to the regular expression pattern:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>preg_match( '|CREATE TABLE ([^ ]*)|', 'CREATE TABLE IF NOT EXISTS table_name', $matches );\nvar_dump( $matches );\n/* Output:\narray(2) {\n [0]=>\n string(15) \"CREATE TABLE IF\"\n [1]=>\n string(2) \"IF\"\n}\n*/\n\npreg_match( '|CREATE TABLE ([^ ]*)|', 'CREATE TABLE table_name', $matches );\nvar_dump( $matches );\n/* Output:\narray(2) {\n [0]=>\n string(23) \"CREATE TABLE table_name\"\n [1]=>\n string(10) \"table_name\"\n}\n*/\n</code></pre>\n\n<p>And in your case, both queries do match that pattern, but since the table names are both (seen as) <code>IF</code>, the first/previous array item (<code>$queries['IF']</code>) is then overridden. Hence only the second table (the one in the final value of <code>$queries['IF']</code>) gets created.</p>\n\n<p>And WooCommerce actually do <strong>not</strong> have <code>CREATE TABLE IF NOT EXISTS</code> in their code:</p>\n\n<p><a href=\"https://github.com/woocommerce/woocommerce/blob/c04f7b79f972ee854e5f5d726eb78ac04a726b32/includes/class-wc-install.php#L687\" rel=\"nofollow noreferrer\">https://github.com/woocommerce/woocommerce/blob/c04f7b79f972ee854e5f5d726eb78ac04a726b32/includes/class-wc-install.php#L687</a></p>\n\n<p><strong>Possible Solution when using the <code>CREATE TABLE IF NOT EXISTS table_name</code> format</strong></p>\n\n<p>Call <code>dbDelta()</code> for each of the queries, as in @FahamShaikh's answer:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$queries = [ // array of queries\n \"CREATE TABLE IF NOT EXISTS \" . $wpdb->prefix . \"test1 ...\",\n \"CREATE TABLE IF NOT EXISTS \" . $wpdb->prefix . \"test2 ...\",\n];\n\nforeach ( $queries as $sql ) {\n dbDelta( $sql );\n}\n</code></pre>\n\n<p>Or:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>dbDelta( \"CREATE TABLE IF NOT EXISTS \" . $wpdb->prefix . \"test1 ...\" );\n\ndbDelta( \"CREATE TABLE IF NOT EXISTS \" . $wpdb->prefix . \"test2 ...\" );\n</code></pre>\n"
},
{
"answer_id": 401992,
"author": "lonelioness",
"author_id": 172357,
"author_profile": "https://wordpress.stackexchange.com/users/172357",
"pm_score": 0,
"selected": false,
"text": "<p>Here's another way that worked for me which I found <a href=\"https://wordpress.org/support/topic/how-to-create-multiple-wpdb-tables-during-plugin-installation/\" rel=\"nofollow noreferrer\">here</a>:</p>\n<pre><code>require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );\n\n$sql = 'CREATE TABLE table1...';\ndbDelta ($sql);\n\n$sql = 'CREATE TABLE table2...';\ndbDelta ($sql);\n\n$sql = 'CREATE TABLE table3...';\ndbDelta ($sql);\n</code></pre>\n<p>Here's how I used it in a plugin:</p>\n<pre><code>/**\n * register_activation_hook implementation\n */\nif (!function_exists('custom_install')) {\n function custom_install()\n {\n global $wpdb;\n global $custom_db_version;\n\n $table_name = $wpdb->prefix . 'customers';\n\n $table_name2 = $wpdb->prefix . 'favorite';\n\n // sql to create your table\n $sql = "CREATE TABLE " . $table_name . " (\n id int(11) NOT NULL AUTO_INCREMENT,\n name VARCHAR(255) NOT NULL,\n email VARCHAR(255) NOT NULL,\n subject VARCHAR(255) NOT NULL,\n message text,\n amount VARCHAR(255),\n status VARCHAR(10),\n PRIMARY KEY (id)\n );";\n\n $sql2 = "CREATE TABLE " . $table_name2 . " (\n `color` bigint(12) NOT NULL,\n `size` varchar(20) NOT NULL,\n ) ENGINE=InnoDB DEFAULT CHARSET=latin1";\n\n require_once(ABSPATH . 'wp-admin/includes/upgrade.php');\n dbDelta($sql);\n dbDelta($sql2);\n\n // save current database version \n add_option('custom_db_version', $custom_db_version);\n }\n\n register_activation_hook(__FILE__, 'custom_install');\n}\n</code></pre>\n"
}
] | 2019/06/29 | [
"https://wordpress.stackexchange.com/questions/341742",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75779/"
] | I have an activation hook to create 2 new database tables that don't exist, only the second table is created from this code:
```
public function add_tables() {
// Global $wpdb
global $wpdb;
$wpdb->hide_errors();
// Require upgrade
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
// Set charset
$collate = '';
if ( $wpdb->has_cap( 'collation' ) ) {
$collate = $wpdb->get_charset_collate();
}
// SQL query
$sql = "
CREATE TABLE IF NOT EXISTS " . $wpdb->prefix . "test1 (
test_id bigint(20) NOT NULL AUTO_INCREMENT,
test_key char(64) NOT NULL,
) $collate;
CREATE TABLE IF NOT EXISTS " . $wpdb->prefix . "test2 (
test_id bigint(20) NOT NULL AUTO_INCREMENT,
test_key char(64) NOT NULL,
) $collate;
";
// Do SQL
dbDelta( $sql );
}
```
Why only the second? If I print out the `$sql` variable I get the SQL statement and if I run that in phpMyAdmin it creates the 2 tables.
I looked at how plugins like WooCommerce do it (<https://github.com/woocommerce/woocommerce/blob/c04f7b79f972ee854e5f5d726eb78ac04a726b32/includes/class-wc-install.php#L687>) and it appears I am doing the same as they are. | >
> Why only the second?
>
>
>
Because `dbDelta()` supports `CREATE TABLE table_name` format only. I.e. Exactly "CREATE TABLE" followed by (one space and) the table name.
More specifically, `dbDelta()` uses this regular expression pattern: `CREATE TABLE ([^ ]*)` when parsing the queries into an array indexed by the table name; i.e. `array( 'table_1' => 'query', 'table_2' => 'query', ... )`.
Here's the relevant [code](https://core.trac.wordpress.org/browser/tags/5.2/src/wp-admin/includes/upgrade.php#L2547):
```php
$cqueries = array(); // Creation Queries
...
// Create a tablename index for an array ($cqueries) of queries
foreach ( $queries as $qry ) {
if ( preg_match( '|CREATE TABLE ([^ ]*)|', $qry, $matches ) ) {
$cqueries[ trim( $matches[1], '`' ) ] = $qry;
$for_update[ $matches[1] ] = 'Created table ' . $matches[1];
}
...
}
```
So in the case of `CREATE TABLE IF NOT EXISTS table_name`, the table name is (seen as) `IF` and not `table_name` due to the regular expression pattern:
```php
preg_match( '|CREATE TABLE ([^ ]*)|', 'CREATE TABLE IF NOT EXISTS table_name', $matches );
var_dump( $matches );
/* Output:
array(2) {
[0]=>
string(15) "CREATE TABLE IF"
[1]=>
string(2) "IF"
}
*/
preg_match( '|CREATE TABLE ([^ ]*)|', 'CREATE TABLE table_name', $matches );
var_dump( $matches );
/* Output:
array(2) {
[0]=>
string(23) "CREATE TABLE table_name"
[1]=>
string(10) "table_name"
}
*/
```
And in your case, both queries do match that pattern, but since the table names are both (seen as) `IF`, the first/previous array item (`$queries['IF']`) is then overridden. Hence only the second table (the one in the final value of `$queries['IF']`) gets created.
And WooCommerce actually do **not** have `CREATE TABLE IF NOT EXISTS` in their code:
<https://github.com/woocommerce/woocommerce/blob/c04f7b79f972ee854e5f5d726eb78ac04a726b32/includes/class-wc-install.php#L687>
**Possible Solution when using the `CREATE TABLE IF NOT EXISTS table_name` format**
Call `dbDelta()` for each of the queries, as in @FahamShaikh's answer:
```php
$queries = [ // array of queries
"CREATE TABLE IF NOT EXISTS " . $wpdb->prefix . "test1 ...",
"CREATE TABLE IF NOT EXISTS " . $wpdb->prefix . "test2 ...",
];
foreach ( $queries as $sql ) {
dbDelta( $sql );
}
```
Or:
```php
dbDelta( "CREATE TABLE IF NOT EXISTS " . $wpdb->prefix . "test1 ..." );
dbDelta( "CREATE TABLE IF NOT EXISTS " . $wpdb->prefix . "test2 ..." );
``` |
341,744 | <p>Where i must put hooks in overridable functions for better child themes? Inside if statement or outside?</p>
<pre><code>if( !function_exists( ovveridable_function() ) {
function overridable_function() {
echo 'Test';
}
add_action( 'init', 'overridable_function' );
}
</code></pre>
<p><strong>OR</strong></p>
<pre><code>if( !function_exists( ovveridable_function() ) {
function overridable_function() {
echo 'Test';
}
}
add_action( 'init', 'overridable_function' );
</code></pre>
| [
{
"answer_id": 341750,
"author": "Deepak Gupta",
"author_id": 170346,
"author_profile": "https://wordpress.stackexchange.com/users/170346",
"pm_score": -1,
"selected": false,
"text": "<p>Try with outside if </p>\n\n<pre><code>function overridable_function() {\n echo 'Test';\n}\nadd_action( 'init', 'overridable_function' );\n</code></pre>\n"
},
{
"answer_id": 341752,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>Neither. Hooked functions don’t need to be pluggable because child themes can already unhook and replace them with <code>remove_action()</code>.</p>\n\n<p>The main functions that you’d want to make pluggable are functions that are used in templates i.e. template tags, and those functions aren’t usually hooked, so the placement of <code>add_action()</code> isn’t relevant. Even then you probably only need to make them pluggable if they’re used in multiple templates, because otherwise the child theme could just replace the template file.</p>\n"
}
] | 2019/06/29 | [
"https://wordpress.stackexchange.com/questions/341744",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133897/"
] | Where i must put hooks in overridable functions for better child themes? Inside if statement or outside?
```
if( !function_exists( ovveridable_function() ) {
function overridable_function() {
echo 'Test';
}
add_action( 'init', 'overridable_function' );
}
```
**OR**
```
if( !function_exists( ovveridable_function() ) {
function overridable_function() {
echo 'Test';
}
}
add_action( 'init', 'overridable_function' );
``` | Neither. Hooked functions don’t need to be pluggable because child themes can already unhook and replace them with `remove_action()`.
The main functions that you’d want to make pluggable are functions that are used in templates i.e. template tags, and those functions aren’t usually hooked, so the placement of `add_action()` isn’t relevant. Even then you probably only need to make them pluggable if they’re used in multiple templates, because otherwise the child theme could just replace the template file. |
341,757 | <p>I have just started learning WP coding . So , I am trying to delete all custom posts on uninstall of my plugin . I have created uninstall.php in my plugin root and have the following : </p>
<pre><code><?php
if(!defined(WP_UNINSTALL_PLUGIN)){
die();
}
// Delete Database
$books= get_posts(['post_type'=>'book','numberposts'=>-1]);// all posts
foreach($books as $book){
wp_delete_post($book->ID,true);
}
</code></pre>
<p>On uninstall I get an error 'Deletion Failed'. Could somebody tell me whats going wrong ? Also , how do you debug this sort of issues in WP ? I enabled in my wp-config the following </p>
<pre><code>define('WP_DEBUG', true);
define( 'WP_DEBUG_LOG', true );
</code></pre>
<p>but I do not see any helpful debug message other than "Deletion Failed' in the plugin screen nor a debug.log file in my wp-content after enabling the above two .</p>
<p>I also tried deleting using SQL like below :</p>
<pre><code>global $wpdb;
$wpdb->query("DELETE FROM wp_posts WHERE post_type='book'");
$wpdb->query("DELETE from wp_postmeta WHERE post_id NOT IN( SELECT id FROM wp_posts");
</code></pre>
<p>Even this gives me Deletion Failed Error . After , deactivation I see the custom posts with the post_type in my database and I have no clue why this is not working . </p>
| [
{
"answer_id": 341750,
"author": "Deepak Gupta",
"author_id": 170346,
"author_profile": "https://wordpress.stackexchange.com/users/170346",
"pm_score": -1,
"selected": false,
"text": "<p>Try with outside if </p>\n\n<pre><code>function overridable_function() {\n echo 'Test';\n}\nadd_action( 'init', 'overridable_function' );\n</code></pre>\n"
},
{
"answer_id": 341752,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>Neither. Hooked functions don’t need to be pluggable because child themes can already unhook and replace them with <code>remove_action()</code>.</p>\n\n<p>The main functions that you’d want to make pluggable are functions that are used in templates i.e. template tags, and those functions aren’t usually hooked, so the placement of <code>add_action()</code> isn’t relevant. Even then you probably only need to make them pluggable if they’re used in multiple templates, because otherwise the child theme could just replace the template file.</p>\n"
}
] | 2019/06/29 | [
"https://wordpress.stackexchange.com/questions/341757",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/170935/"
] | I have just started learning WP coding . So , I am trying to delete all custom posts on uninstall of my plugin . I have created uninstall.php in my plugin root and have the following :
```
<?php
if(!defined(WP_UNINSTALL_PLUGIN)){
die();
}
// Delete Database
$books= get_posts(['post_type'=>'book','numberposts'=>-1]);// all posts
foreach($books as $book){
wp_delete_post($book->ID,true);
}
```
On uninstall I get an error 'Deletion Failed'. Could somebody tell me whats going wrong ? Also , how do you debug this sort of issues in WP ? I enabled in my wp-config the following
```
define('WP_DEBUG', true);
define( 'WP_DEBUG_LOG', true );
```
but I do not see any helpful debug message other than "Deletion Failed' in the plugin screen nor a debug.log file in my wp-content after enabling the above two .
I also tried deleting using SQL like below :
```
global $wpdb;
$wpdb->query("DELETE FROM wp_posts WHERE post_type='book'");
$wpdb->query("DELETE from wp_postmeta WHERE post_id NOT IN( SELECT id FROM wp_posts");
```
Even this gives me Deletion Failed Error . After , deactivation I see the custom posts with the post\_type in my database and I have no clue why this is not working . | Neither. Hooked functions don’t need to be pluggable because child themes can already unhook and replace them with `remove_action()`.
The main functions that you’d want to make pluggable are functions that are used in templates i.e. template tags, and those functions aren’t usually hooked, so the placement of `add_action()` isn’t relevant. Even then you probably only need to make them pluggable if they’re used in multiple templates, because otherwise the child theme could just replace the template file. |
341,769 | <p>Having looked at <a href="https://wordpress.stackexchange.com/questions/36570/show-twentyeleven-header-image-only-on-home-page">Show TwentyEleven header image only on home page</a>, <a href="https://wordpress.stackexchange.com/questions/331138/replace-home-with-image-link-inside-custom-header-menu">Replace Home with image link inside custom header menu</a> and more, I don't see what I am trying to do.</p>
<p><strong>We want to replace the header only on the home page, with a much taller image.</strong> FYI I am not the designer and we had an intern using a lot of plugins to modify sidebars and build pages, so that's not me LOL. I prefer code-based solutions, not plugins.</p>
<p><strong>QUESTION IS:</strong> I have this code in the Genesis child theme (Outreach Pro, also beyond my control) front-page.php:</p>
<pre><code>/** added by jim 6/28/19 per https://wpsites.net/web-design/remove-header/
remove header on front page (this file) from */
remove_action( 'genesis_header', 'genesis_header_markup_open', 5 );
remove_action( 'genesis_header', 'genesis_do_header' );
remove_action( 'genesis_header', 'genesis_header_markup_close', 15 );
</code></pre>
<p>This successfully suppressed the header, but now it seems like I can't use after_header type code to place my image. Instead I am trying to use a <code>::before</code> on the nav menu in css like this:</p>
<pre><code>/** jim's customizations July 2019 for tall Bob Gray image replacing header on home page only */
.nav-primary:before {
content:url(/images/robert-c-gray-banner-maskbob-sharpen.jpg);
padding−right:6px;
}
</code></pre>
<p>But it's not showing up and the Inspector doesn't show it either.</p>
<p>Is the <code>::before</code> on the <code>nav-primary</code> selector a good approach? (<a href="https://organicweb.com.au/wordpress/css-before-pseudo/" rel="nofollow noreferrer">I got the idea here</a>.) FWIW I will need to float some text over this image as well.</p>
<p>Thanks for any guidance. Here's <a href="http://railroad.social/virginia5" rel="nofollow noreferrer">the page I am working on (test page)</a> and here's <a href="http://train.team/schedule7" rel="nofollow noreferrer">what another page looks like with the header</a>. Any suggestions to improve the question are quite welcome!</p>
| [
{
"answer_id": 341750,
"author": "Deepak Gupta",
"author_id": 170346,
"author_profile": "https://wordpress.stackexchange.com/users/170346",
"pm_score": -1,
"selected": false,
"text": "<p>Try with outside if </p>\n\n<pre><code>function overridable_function() {\n echo 'Test';\n}\nadd_action( 'init', 'overridable_function' );\n</code></pre>\n"
},
{
"answer_id": 341752,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>Neither. Hooked functions don’t need to be pluggable because child themes can already unhook and replace them with <code>remove_action()</code>.</p>\n\n<p>The main functions that you’d want to make pluggable are functions that are used in templates i.e. template tags, and those functions aren’t usually hooked, so the placement of <code>add_action()</code> isn’t relevant. Even then you probably only need to make them pluggable if they’re used in multiple templates, because otherwise the child theme could just replace the template file.</p>\n"
}
] | 2019/06/29 | [
"https://wordpress.stackexchange.com/questions/341769",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118869/"
] | Having looked at [Show TwentyEleven header image only on home page](https://wordpress.stackexchange.com/questions/36570/show-twentyeleven-header-image-only-on-home-page), [Replace Home with image link inside custom header menu](https://wordpress.stackexchange.com/questions/331138/replace-home-with-image-link-inside-custom-header-menu) and more, I don't see what I am trying to do.
**We want to replace the header only on the home page, with a much taller image.** FYI I am not the designer and we had an intern using a lot of plugins to modify sidebars and build pages, so that's not me LOL. I prefer code-based solutions, not plugins.
**QUESTION IS:** I have this code in the Genesis child theme (Outreach Pro, also beyond my control) front-page.php:
```
/** added by jim 6/28/19 per https://wpsites.net/web-design/remove-header/
remove header on front page (this file) from */
remove_action( 'genesis_header', 'genesis_header_markup_open', 5 );
remove_action( 'genesis_header', 'genesis_do_header' );
remove_action( 'genesis_header', 'genesis_header_markup_close', 15 );
```
This successfully suppressed the header, but now it seems like I can't use after\_header type code to place my image. Instead I am trying to use a `::before` on the nav menu in css like this:
```
/** jim's customizations July 2019 for tall Bob Gray image replacing header on home page only */
.nav-primary:before {
content:url(/images/robert-c-gray-banner-maskbob-sharpen.jpg);
padding−right:6px;
}
```
But it's not showing up and the Inspector doesn't show it either.
Is the `::before` on the `nav-primary` selector a good approach? ([I got the idea here](https://organicweb.com.au/wordpress/css-before-pseudo/).) FWIW I will need to float some text over this image as well.
Thanks for any guidance. Here's [the page I am working on (test page)](http://railroad.social/virginia5) and here's [what another page looks like with the header](http://train.team/schedule7). Any suggestions to improve the question are quite welcome! | Neither. Hooked functions don’t need to be pluggable because child themes can already unhook and replace them with `remove_action()`.
The main functions that you’d want to make pluggable are functions that are used in templates i.e. template tags, and those functions aren’t usually hooked, so the placement of `add_action()` isn’t relevant. Even then you probably only need to make them pluggable if they’re used in multiple templates, because otherwise the child theme could just replace the template file. |
341,803 | <p>Iam trying get selected variation from order.</p>
<pre><code>global $order;
$items = $order->get_items();
foreach( $items as $item ) {
$product_id = $item->get_product_id();
$product = wc_get_product( $product_id );
if( $product->is_type( 'variable' ) ) {
$variationName = $product->get_attribute( 'pa_my-custom-variation' );
}
}
</code></pre>
<p>But this gets all variation values. I want to get only selected.</p>
| [
{
"answer_id": 341822,
"author": "Maciej Rogosz",
"author_id": 123145,
"author_profile": "https://wordpress.stackexchange.com/users/123145",
"pm_score": 0,
"selected": false,
"text": "<p>Why <strong>get_attribute()</strong>? Maybe you're looking for <strong>get_title()</strong>? This would retrieve the variation's name.</p>\n"
},
{
"answer_id": 378739,
"author": "Ale",
"author_id": 48811,
"author_profile": "https://wordpress.stackexchange.com/users/48811",
"pm_score": 0,
"selected": false,
"text": "<p>What you need I think is the following code:</p>\n<pre class=\"lang-php prettyprint-override\"><code> $get_order = wc_get_order( $order_id );\n $items = $get_order->get_items();\n\n foreach ( $items as $item ) {\n $product = $item->get_product();\n //check if this is a variation using is_type\n if ( 'variation' === $product->get_type() ) {\n $variation_id = $item->get_variation_id();\n $variation = new WC_Product_Variation( $variation_id );\n $attributes = $variation->get_attributes();\n foreach ( $attributes as $key => $value ) {\n if ( 'pa_my-custom-variation' === $key ) {\n // whatever you want to do next\n }\n }\n }\n }\n</code></pre>\n<p>What it does it to look into each item from the order and check if it is actually a variable one. If it is, then it will get its variation ID and from there it will get the variation attributes and you can loop through each of them to find the one you need.</p>\n<p>Here is also another way to check if the an item is variable. This way you are getting the variation ID if there is one.</p>\n<pre class=\"lang-php prettyprint-override\"><code>$variation_id = $item->get_variation_id();\nif(! empty($variation_id) {\n// item is variable and we can check its variation\n}\n</code></pre>\n<p>I know this is an old question but hope this might be useful for anybody who drops here.</p>\n"
},
{
"answer_id": 380680,
"author": "HK89",
"author_id": 179278,
"author_profile": "https://wordpress.stackexchange.com/users/179278",
"pm_score": 3,
"selected": true,
"text": "<p>Following below code according your need</p>\n<blockquote>\n<p>To get the selected variation attributes using\nget_variation_attributes( ) method.</p>\n</blockquote>\n<pre><code>// Get an instance of the WC_Order object from an Order ID\n $order = wc_get_order( $order_id ); \n\n// Loop though order "line items"\nforeach( $order->get_items() as $item_id => $item ){\n $product_id = $item->get_product_id(); //Get the product ID\n $quantity = $item->get_quantity(); //Get the product QTY\n $product_name = $item->get_name(); //Get the product NAME\n\n // Get an instance of the WC_Product object (can be a product variation too)\n $product = $item->get_product();\n\n // Get the product description (works for product variation too)\n $description = $product->get_description();\n\n // Only for product variation\n if( $product->is_type('variation') ){\n // Get the variation attributes\n $variation_attributes = $product->get_variation_attributes();\n // Loop through each selected attributes\n foreach($variation_attributes as $attribute_taxonomy => $term_slug ){\n // Get product attribute name or taxonomy\n $taxonomy = str_replace('attribute_', '', $attribute_taxonomy );\n // The label name from the product attribute\n $attribute_name = wc_attribute_label( $taxonomy, $product );\n // The term name (or value) from this attribute\n if( taxonomy_exists($taxonomy) ) {\n $attribute_value = get_term_by( 'slug', $term_slug, $taxonomy )->name;\n } else {\n $attribute_value = \n $term_slug; // For custom product attributes\n }\n }\n }\n }\n</code></pre>\n"
}
] | 2019/06/30 | [
"https://wordpress.stackexchange.com/questions/341803",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133897/"
] | Iam trying get selected variation from order.
```
global $order;
$items = $order->get_items();
foreach( $items as $item ) {
$product_id = $item->get_product_id();
$product = wc_get_product( $product_id );
if( $product->is_type( 'variable' ) ) {
$variationName = $product->get_attribute( 'pa_my-custom-variation' );
}
}
```
But this gets all variation values. I want to get only selected. | Following below code according your need
>
> To get the selected variation attributes using
> get\_variation\_attributes( ) method.
>
>
>
```
// Get an instance of the WC_Order object from an Order ID
$order = wc_get_order( $order_id );
// Loop though order "line items"
foreach( $order->get_items() as $item_id => $item ){
$product_id = $item->get_product_id(); //Get the product ID
$quantity = $item->get_quantity(); //Get the product QTY
$product_name = $item->get_name(); //Get the product NAME
// Get an instance of the WC_Product object (can be a product variation too)
$product = $item->get_product();
// Get the product description (works for product variation too)
$description = $product->get_description();
// Only for product variation
if( $product->is_type('variation') ){
// Get the variation attributes
$variation_attributes = $product->get_variation_attributes();
// Loop through each selected attributes
foreach($variation_attributes as $attribute_taxonomy => $term_slug ){
// Get product attribute name or taxonomy
$taxonomy = str_replace('attribute_', '', $attribute_taxonomy );
// The label name from the product attribute
$attribute_name = wc_attribute_label( $taxonomy, $product );
// The term name (or value) from this attribute
if( taxonomy_exists($taxonomy) ) {
$attribute_value = get_term_by( 'slug', $term_slug, $taxonomy )->name;
} else {
$attribute_value =
$term_slug; // For custom product attributes
}
}
}
}
``` |
341,929 | <p>in a class I have a function for save_post action. In this function I send an email. All this works except for querying the categories for that post:</p>
<pre><code>class _new_notifications
{
public function __construct()
{
add_action( 'save_post', array( $this, 'send_new_post_notifications' ) );
}
public function send_new_post_notifications( $post_id ){
$send_notify = get_field('send_notifications', 'option');
if ( !$send_notify || wp_is_post_revision( $post_id ) ) {
return;
}
$categorie = get_the_category( $post_id );
$cat = $categorie[0]->name;
//doing other stuff...
</code></pre>
<p>I already tried everything possible (several hours :)
but I just do not get the category for that post ID.</p>
<p>Maybe someone can. help?
Many Thanks!!</p>
| [
{
"answer_id": 341822,
"author": "Maciej Rogosz",
"author_id": 123145,
"author_profile": "https://wordpress.stackexchange.com/users/123145",
"pm_score": 0,
"selected": false,
"text": "<p>Why <strong>get_attribute()</strong>? Maybe you're looking for <strong>get_title()</strong>? This would retrieve the variation's name.</p>\n"
},
{
"answer_id": 378739,
"author": "Ale",
"author_id": 48811,
"author_profile": "https://wordpress.stackexchange.com/users/48811",
"pm_score": 0,
"selected": false,
"text": "<p>What you need I think is the following code:</p>\n<pre class=\"lang-php prettyprint-override\"><code> $get_order = wc_get_order( $order_id );\n $items = $get_order->get_items();\n\n foreach ( $items as $item ) {\n $product = $item->get_product();\n //check if this is a variation using is_type\n if ( 'variation' === $product->get_type() ) {\n $variation_id = $item->get_variation_id();\n $variation = new WC_Product_Variation( $variation_id );\n $attributes = $variation->get_attributes();\n foreach ( $attributes as $key => $value ) {\n if ( 'pa_my-custom-variation' === $key ) {\n // whatever you want to do next\n }\n }\n }\n }\n</code></pre>\n<p>What it does it to look into each item from the order and check if it is actually a variable one. If it is, then it will get its variation ID and from there it will get the variation attributes and you can loop through each of them to find the one you need.</p>\n<p>Here is also another way to check if the an item is variable. This way you are getting the variation ID if there is one.</p>\n<pre class=\"lang-php prettyprint-override\"><code>$variation_id = $item->get_variation_id();\nif(! empty($variation_id) {\n// item is variable and we can check its variation\n}\n</code></pre>\n<p>I know this is an old question but hope this might be useful for anybody who drops here.</p>\n"
},
{
"answer_id": 380680,
"author": "HK89",
"author_id": 179278,
"author_profile": "https://wordpress.stackexchange.com/users/179278",
"pm_score": 3,
"selected": true,
"text": "<p>Following below code according your need</p>\n<blockquote>\n<p>To get the selected variation attributes using\nget_variation_attributes( ) method.</p>\n</blockquote>\n<pre><code>// Get an instance of the WC_Order object from an Order ID\n $order = wc_get_order( $order_id ); \n\n// Loop though order "line items"\nforeach( $order->get_items() as $item_id => $item ){\n $product_id = $item->get_product_id(); //Get the product ID\n $quantity = $item->get_quantity(); //Get the product QTY\n $product_name = $item->get_name(); //Get the product NAME\n\n // Get an instance of the WC_Product object (can be a product variation too)\n $product = $item->get_product();\n\n // Get the product description (works for product variation too)\n $description = $product->get_description();\n\n // Only for product variation\n if( $product->is_type('variation') ){\n // Get the variation attributes\n $variation_attributes = $product->get_variation_attributes();\n // Loop through each selected attributes\n foreach($variation_attributes as $attribute_taxonomy => $term_slug ){\n // Get product attribute name or taxonomy\n $taxonomy = str_replace('attribute_', '', $attribute_taxonomy );\n // The label name from the product attribute\n $attribute_name = wc_attribute_label( $taxonomy, $product );\n // The term name (or value) from this attribute\n if( taxonomy_exists($taxonomy) ) {\n $attribute_value = get_term_by( 'slug', $term_slug, $taxonomy )->name;\n } else {\n $attribute_value = \n $term_slug; // For custom product attributes\n }\n }\n }\n }\n</code></pre>\n"
}
] | 2019/07/01 | [
"https://wordpress.stackexchange.com/questions/341929",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/130709/"
] | in a class I have a function for save\_post action. In this function I send an email. All this works except for querying the categories for that post:
```
class _new_notifications
{
public function __construct()
{
add_action( 'save_post', array( $this, 'send_new_post_notifications' ) );
}
public function send_new_post_notifications( $post_id ){
$send_notify = get_field('send_notifications', 'option');
if ( !$send_notify || wp_is_post_revision( $post_id ) ) {
return;
}
$categorie = get_the_category( $post_id );
$cat = $categorie[0]->name;
//doing other stuff...
```
I already tried everything possible (several hours :)
but I just do not get the category for that post ID.
Maybe someone can. help?
Many Thanks!! | Following below code according your need
>
> To get the selected variation attributes using
> get\_variation\_attributes( ) method.
>
>
>
```
// Get an instance of the WC_Order object from an Order ID
$order = wc_get_order( $order_id );
// Loop though order "line items"
foreach( $order->get_items() as $item_id => $item ){
$product_id = $item->get_product_id(); //Get the product ID
$quantity = $item->get_quantity(); //Get the product QTY
$product_name = $item->get_name(); //Get the product NAME
// Get an instance of the WC_Product object (can be a product variation too)
$product = $item->get_product();
// Get the product description (works for product variation too)
$description = $product->get_description();
// Only for product variation
if( $product->is_type('variation') ){
// Get the variation attributes
$variation_attributes = $product->get_variation_attributes();
// Loop through each selected attributes
foreach($variation_attributes as $attribute_taxonomy => $term_slug ){
// Get product attribute name or taxonomy
$taxonomy = str_replace('attribute_', '', $attribute_taxonomy );
// The label name from the product attribute
$attribute_name = wc_attribute_label( $taxonomy, $product );
// The term name (or value) from this attribute
if( taxonomy_exists($taxonomy) ) {
$attribute_value = get_term_by( 'slug', $term_slug, $taxonomy )->name;
} else {
$attribute_value =
$term_slug; // For custom product attributes
}
}
}
}
``` |
341,933 | <p>I am attempting to submit an Ajax call transfer the source URL of a selected image from a WordPress Media Library to PHP in my plugin settings page. Upon clicking save I'm constantly met with "error, bad request". Status 400 when attempting to call my AJAX URL. </p>
<p>My AJAX URL is currently domain/wp-admin/admin-ajax.php which does indeed exist. I have tried setting multiple data types that the AJAX call should expect but I'm met with the same error. </p>
<p>If I remove the URL portion of the AJAX call in the javascript, it does lead to the success function, but the parameter for success, "response" consists of the HTML for the page and not the data I wish to transfer.</p>
<p>The HTML</p>
<pre><code><form method='post'>
<div class='image-preview-wrapper'>
<img id='image-preview' src='<?php echo wp_get_attachment_url( get_option( 'media_selector_attachment_id' ) ); ?>' height='100'>
</div>
<input id="upload_image_button" type="button" class="button" value="<?php _e( 'Upload image' ); ?>" />
<input type='hidden' name='image_attachment_id' id='image_attachment_id' value='<?php echo get_option( 'media_selector_attachment_id' ); ?>'>
<input type="submit" name="submit_image_selector" value="Save" id="saveMediaButton" class="button-primary">
</form>
</code></pre>
<p>Loading in the Javascript through enques</p>
<pre><code>function enqueue_my_scripts() {
wp_enqueue_script( 'media-library', plugins_url( '/media-library.js', __FILE__ ), array(), '1.0.0', true );
wp_localize_script( 'media-library', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'admin_enqueue_scripts', 'enqueue_my_scripts' );
</code></pre>
<p>The JavaScript that is called upon the button click ID'ed submitMediaButton</p>
<pre><code>$('#saveMediaButton').click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
dataType: "html",
url: my_ajax_object.ajax_url,
data: {
image_attachment_id: document.getElementById("image-preview").getAttribute('src')
},
success: function(response) {
var jsonData = response;
console.log(response);
console.log(document.getElementById("image-preview").getAttribute('src'));
},
error: function(jqxhr, textStatus, errorThrown) {
console.log(my_ajax_object.ajax_url);
console.log(jqxhr);
console.log(textStatus);
console.log(errorThrown);
}
});
});
</code></pre>
| [
{
"answer_id": 341945,
"author": "Milan Hirpara",
"author_id": 168898,
"author_profile": "https://wordpress.stackexchange.com/users/168898",
"pm_score": 1,
"selected": true,
"text": "<p>Hi please try below code </p>\n\n<p>jquery :</p>\n\n<pre><code>$('#saveMediaButton').click(function(e) {\n e.preventDefault();\n\n $.ajax({\n url : my_ajax_object.ajax_url,\n type : 'post',\n data : {\n action : 'action_upload_img',\n image_attachment_id : document.getElementById(\"image-preview\").getAttribute('src')\n },\n dataType : 'html',\n success : function( response ) {\n\n var jsonData = response;\n console.log(response);\n console.log(document.getElementById(\"image-preview\").getAttribute('src'));\n\n },\n error : function(jqxhr, textStatus, errorThrown) {\n console.log(my_ajax_object.ajax_url);\n console.log(jqxhr);\n console.log(textStatus);\n console.log(errorThrown);\n },\n });\n\n});\n</code></pre>\n\n<p>PHP Code :</p>\n\n<pre><code>add_action( 'wp_ajax_action_upload_img', 'action_upload_img' );\nadd_action( 'wp_ajax_nopriv_action_upload_img', 'action_upload_img' );\nfunction action_upload_img(){\n\n $response = [];\n $response['data'] = $_POST;\n\n //Your code\n update_option( 'media_selector_attachment_id', $_POST[\"image_attachment_id\"] ); \n\n wp_send_json( $response );\n wp_die();\n}\n</code></pre>\n"
},
{
"answer_id": 341946,
"author": "Chetan Vaghela",
"author_id": 169856,
"author_profile": "https://wordpress.stackexchange.com/users/169856",
"pm_score": -1,
"selected": false,
"text": "<p>Please try this :</p>\n\n<p>add action parameter in data. </p>\n\n<pre><code>data: {\n action:\"this_ajax_action\",image_attachment_id: document.getElementById(\"image-preview\").getAttribute('src')\n },\n</code></pre>\n\n<p>add in <strong>functions.php</strong></p>\n\n<pre><code>add_action( 'wp_ajax_this_ajax_action', 'this_ajax_action_callback' );\nadd_filter( 'wp_ajax_nopriv_this_ajax_action', 'this_ajax_action_callback');\nfunction this_ajax_action_callback()\n{\n if(isset($_POST[\"image_attachment_id\"]) && !empty($_POST[\"image_attachment_id\"]));\n\n # here what you want to do with attachment id\n $data = \"\";\n\n echo $data;\n die();\n}\n</code></pre>\n"
}
] | 2019/07/02 | [
"https://wordpress.stackexchange.com/questions/341933",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/146727/"
] | I am attempting to submit an Ajax call transfer the source URL of a selected image from a WordPress Media Library to PHP in my plugin settings page. Upon clicking save I'm constantly met with "error, bad request". Status 400 when attempting to call my AJAX URL.
My AJAX URL is currently domain/wp-admin/admin-ajax.php which does indeed exist. I have tried setting multiple data types that the AJAX call should expect but I'm met with the same error.
If I remove the URL portion of the AJAX call in the javascript, it does lead to the success function, but the parameter for success, "response" consists of the HTML for the page and not the data I wish to transfer.
The HTML
```
<form method='post'>
<div class='image-preview-wrapper'>
<img id='image-preview' src='<?php echo wp_get_attachment_url( get_option( 'media_selector_attachment_id' ) ); ?>' height='100'>
</div>
<input id="upload_image_button" type="button" class="button" value="<?php _e( 'Upload image' ); ?>" />
<input type='hidden' name='image_attachment_id' id='image_attachment_id' value='<?php echo get_option( 'media_selector_attachment_id' ); ?>'>
<input type="submit" name="submit_image_selector" value="Save" id="saveMediaButton" class="button-primary">
</form>
```
Loading in the Javascript through enques
```
function enqueue_my_scripts() {
wp_enqueue_script( 'media-library', plugins_url( '/media-library.js', __FILE__ ), array(), '1.0.0', true );
wp_localize_script( 'media-library', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'admin_enqueue_scripts', 'enqueue_my_scripts' );
```
The JavaScript that is called upon the button click ID'ed submitMediaButton
```
$('#saveMediaButton').click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
dataType: "html",
url: my_ajax_object.ajax_url,
data: {
image_attachment_id: document.getElementById("image-preview").getAttribute('src')
},
success: function(response) {
var jsonData = response;
console.log(response);
console.log(document.getElementById("image-preview").getAttribute('src'));
},
error: function(jqxhr, textStatus, errorThrown) {
console.log(my_ajax_object.ajax_url);
console.log(jqxhr);
console.log(textStatus);
console.log(errorThrown);
}
});
});
``` | Hi please try below code
jquery :
```
$('#saveMediaButton').click(function(e) {
e.preventDefault();
$.ajax({
url : my_ajax_object.ajax_url,
type : 'post',
data : {
action : 'action_upload_img',
image_attachment_id : document.getElementById("image-preview").getAttribute('src')
},
dataType : 'html',
success : function( response ) {
var jsonData = response;
console.log(response);
console.log(document.getElementById("image-preview").getAttribute('src'));
},
error : function(jqxhr, textStatus, errorThrown) {
console.log(my_ajax_object.ajax_url);
console.log(jqxhr);
console.log(textStatus);
console.log(errorThrown);
},
});
});
```
PHP Code :
```
add_action( 'wp_ajax_action_upload_img', 'action_upload_img' );
add_action( 'wp_ajax_nopriv_action_upload_img', 'action_upload_img' );
function action_upload_img(){
$response = [];
$response['data'] = $_POST;
//Your code
update_option( 'media_selector_attachment_id', $_POST["image_attachment_id"] );
wp_send_json( $response );
wp_die();
}
``` |
341,957 | <p>I have the following code in my <code>functions.php</code>. It works great: when a booking is made, it emails me. Simple. </p>
<p><em>However</em>, I'd like it to send me the post ID for that booking rather than just a 'Hello World!' message. Help?</p>
<pre><code>function add_to_system() {
// get post meta
// $email = get_post_meta('',$post_id)
// $post_id = get_queried_object_id();
mail('[email protected]', $post_id.' Hello', 'World!');
}
add_action('booked_new_appointment_created', 'add_to_system', 99);
</code></pre>
<p>Thanks for any guidance.</p>
| [
{
"answer_id": 341959,
"author": "Chetan Vaghela",
"author_id": 169856,
"author_profile": "https://wordpress.stackexchange.com/users/169856",
"pm_score": -1,
"selected": false,
"text": "<p>try with this :</p>\n\n<pre><code>function add_to_system($appointment_id) {\n mail(\"[email protected]\",\"My subject\",$appointment_id);\n}\nadd_action('booked_new_appointment_created', 'add_to_system', 99,1);\n</code></pre>\n\n<p>let me know if it works for you!</p>\n"
},
{
"answer_id": 341964,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": true,
"text": "<p>Only posting an alternative answer despite the question being about a 3rd-party plugin, whose source code isn't even freely available, because I don't believe the accepted answer is likely to be a good solution.</p>\n\n<p>It's not documented on their website, but a <a href=\"https://codecanyon.net/item/booked-appointments-appointment-booking-for-wordpress/9466968/comments?page=50&filter=all#comment_12081430\" rel=\"nofollow noreferrer\">comment from the developer</a> states:</p>\n\n<blockquote>\n <p>These would all be considered custom requests, which our free support\n doesn’t handle. What’d you want to do is probably hook into the\n “booked_new_appointment_created” action which comes with the\n Appointment ID (which you can use to pull down meta fields, etc.) —\n That’s all the direction I can really offer you regarding these custom\n coding questions.</p>\n</blockquote>\n\n<p>Which implies that callback functions for the <code>booked_new_appointment_created</code> hook receive the appointment ID as an argument:</p>\n\n<pre><code>function add_to_system( $appointment_id ) {\n mail( '[email protected]', 'My subject', $appointment_id );\n}\nadd_action( 'booked_new_appointment_created', 'add_to_system', 99, 1 );\n</code></pre>\n\n<p>Doing it this way is far more reliable, as you can be certain that the ID of the appointment you're using is the ID of the appointment that triggered the action, and not some other post or page that might be the 'current' post in the global state.</p>\n\n<p>This is a good rule of thumb for all hooks: Use the arguments passed to callbacks wherever possible instead of global variables.</p>\n"
},
{
"answer_id": 341972,
"author": "Michelle ",
"author_id": 110232,
"author_profile": "https://wordpress.stackexchange.com/users/110232",
"pm_score": 0,
"selected": false,
"text": "<p>Use <a href=\"https://developer.wordpress.org/reference/functions/get_the_id/\" rel=\"nofollow noreferrer\">get_the_id</a> rather than global $post;</p>\n\n<pre><code>get_the_ID()\n</code></pre>\n\n<p>Update Like this</p>\n\n<pre><code>function add_to_system() {\n mail(\"[email protected]\",\"My subject\",get_the_ID());\n}\nadd_action('booked_new_appointment_created', 'add_to_system', 99);\n</code></pre>\n"
}
] | 2019/07/02 | [
"https://wordpress.stackexchange.com/questions/341957",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/171109/"
] | I have the following code in my `functions.php`. It works great: when a booking is made, it emails me. Simple.
*However*, I'd like it to send me the post ID for that booking rather than just a 'Hello World!' message. Help?
```
function add_to_system() {
// get post meta
// $email = get_post_meta('',$post_id)
// $post_id = get_queried_object_id();
mail('[email protected]', $post_id.' Hello', 'World!');
}
add_action('booked_new_appointment_created', 'add_to_system', 99);
```
Thanks for any guidance. | Only posting an alternative answer despite the question being about a 3rd-party plugin, whose source code isn't even freely available, because I don't believe the accepted answer is likely to be a good solution.
It's not documented on their website, but a [comment from the developer](https://codecanyon.net/item/booked-appointments-appointment-booking-for-wordpress/9466968/comments?page=50&filter=all#comment_12081430) states:
>
> These would all be considered custom requests, which our free support
> doesn’t handle. What’d you want to do is probably hook into the
> “booked\_new\_appointment\_created” action which comes with the
> Appointment ID (which you can use to pull down meta fields, etc.) —
> That’s all the direction I can really offer you regarding these custom
> coding questions.
>
>
>
Which implies that callback functions for the `booked_new_appointment_created` hook receive the appointment ID as an argument:
```
function add_to_system( $appointment_id ) {
mail( '[email protected]', 'My subject', $appointment_id );
}
add_action( 'booked_new_appointment_created', 'add_to_system', 99, 1 );
```
Doing it this way is far more reliable, as you can be certain that the ID of the appointment you're using is the ID of the appointment that triggered the action, and not some other post or page that might be the 'current' post in the global state.
This is a good rule of thumb for all hooks: Use the arguments passed to callbacks wherever possible instead of global variables. |
341,965 | <p>Is it possible to call a function from functions.php in custom page or blog post? </p>
<p>I put simple function in functions.php:</p>
<pre><code>function testTest()
{
echo "Test";
}
</code></pre>
<p>And called it from the page:</p>
<pre><code><?php testTest();?>
</code></pre>
<p>But it doesn't work. Do I need to make a plugin to use simple function like that inside one chosen custom page?</p>
<p>Thanks for your answer,
Mary</p>
| [
{
"answer_id": 341969,
"author": "Michelle ",
"author_id": 110232,
"author_profile": "https://wordpress.stackexchange.com/users/110232",
"pm_score": 3,
"selected": true,
"text": "<p>You could use <a href=\"https://codex.wordpress.org/Function_Reference/add_shortcode\" rel=\"nofollow noreferrer\">add_shortcode</a> if you want to use it within the editor.</p>\n\n<pre><code>function footag_func() {\n return \"Test\";\n}\nadd_shortcode( 'footag', 'footag_func' );\n</code></pre>\n\n<p>And then use [footag] in your editor.</p>\n\n<p>Or</p>\n\n<p>Use code like this in functions.php and add a conditional tag</p>\n\n<pre><code>add_action( 'loop_start', 'your_function' );\nfunction your_function() {\nif ( is_singular('post') ) {\n echo 'Test';\n }\n}\n</code></pre>\n\n<p>or</p>\n\n<p>Create a function in functions.php</p>\n\n<pre><code>function your_function() {\nreturn 'Test';\n\n}\n</code></pre>\n\n<p>And then use this in your template</p>\n\n<pre><code>echo your_function();\n</code></pre>\n"
},
{
"answer_id": 341970,
"author": "Cornel Raiu",
"author_id": 62221,
"author_profile": "https://wordpress.stackexchange.com/users/62221",
"pm_score": 1,
"selected": false,
"text": "<p>You can quickly create a quick shortcode for doing that.</p>\n\n<p><code>add_shortcode( 'test_shortcode', 'my_test_callback' );</code></p>\n\n<p>Then, in the callback function you do this:</p>\n\n<pre><code>function my_test_callback() {\n //start adding the echoed content to the output buffer\n ob_start();\n\n //run your code here - in this case your testTest() function\n testTest();\n\n //return the output buffer\n //NOTE: directly echoing the content will give unexpected results\n return ob_get_clean();\n}\n</code></pre>\n\n<p>Then, in your content pages you just add <code>[test_shortcode]</code> and it will run your PHP function.</p>\n\n<p>For a better view on shortcodes here are some useful links:</p>\n\n<p><a href=\"https://codex.wordpress.org/Shortcode_API\" rel=\"nofollow noreferrer\">Official Shortcode API</a></p>\n\n<p><a href=\"https://generatewp.com/shortcodes/\" rel=\"nofollow noreferrer\">A nice tool for creating shortcodes</a></p>\n\n<p><a href=\"https://www.cornelraiu.com/how-to-create-a-wordpress-shortcode/\" rel=\"nofollow noreferrer\">An article I wrote on how to build shortcodes</a></p>\n"
}
] | 2019/07/02 | [
"https://wordpress.stackexchange.com/questions/341965",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90955/"
] | Is it possible to call a function from functions.php in custom page or blog post?
I put simple function in functions.php:
```
function testTest()
{
echo "Test";
}
```
And called it from the page:
```
<?php testTest();?>
```
But it doesn't work. Do I need to make a plugin to use simple function like that inside one chosen custom page?
Thanks for your answer,
Mary | You could use [add\_shortcode](https://codex.wordpress.org/Function_Reference/add_shortcode) if you want to use it within the editor.
```
function footag_func() {
return "Test";
}
add_shortcode( 'footag', 'footag_func' );
```
And then use [footag] in your editor.
Or
Use code like this in functions.php and add a conditional tag
```
add_action( 'loop_start', 'your_function' );
function your_function() {
if ( is_singular('post') ) {
echo 'Test';
}
}
```
or
Create a function in functions.php
```
function your_function() {
return 'Test';
}
```
And then use this in your template
```
echo your_function();
``` |
341,967 | <p>For example: </p>
<pre><code> $args = array(
'type' => 'string',
'description' => '',
'sanitize_callback' => null,
'show_in_rest' => true
);
//Job Board Settings Info
register_setting( 'jobboard-settings', 'company_name', $args );
</code></pre>
<p>I have trouble figuring out which route these are exposed to.</p>
| [
{
"answer_id": 341968,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>Settings are accessible through the <a href=\"https://developer.wordpress.org/rest-api/reference/settings/\" rel=\"nofollow noreferrer\">Settings endpoint</a>:</p>\n\n<pre><code>/wp-json/wp/v2/settings\n</code></pre>\n"
},
{
"answer_id": 359470,
"author": "Kuuak",
"author_id": 86838,
"author_profile": "https://wordpress.stackexchange.com/users/86838",
"pm_score": 0,
"selected": false,
"text": "<p>You have to <code>register_setting()</code> in both <code>admin_init</code> & <code>rest_api_init</code> hooks in order to get your setting through <code>wp/v2/settings</code> REST API endpoint.</p>\n\n<p>Had the same issue and found the solution <a href=\"https://coreysalzano.com/wordpress/using-register_setting-and-the-rest-api/\" rel=\"nofollow noreferrer\">in this blog post</a> to save me </p>\n"
}
] | 2019/07/02 | [
"https://wordpress.stackexchange.com/questions/341967",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/166650/"
] | For example:
```
$args = array(
'type' => 'string',
'description' => '',
'sanitize_callback' => null,
'show_in_rest' => true
);
//Job Board Settings Info
register_setting( 'jobboard-settings', 'company_name', $args );
```
I have trouble figuring out which route these are exposed to. | Settings are accessible through the [Settings endpoint](https://developer.wordpress.org/rest-api/reference/settings/):
```
/wp-json/wp/v2/settings
``` |
342,148 | <p>Where could I find an exhaustive list of javascript events defined by WooCommerce. ( Events like "woocommerce_variation_has_changed" )</p>
| [
{
"answer_id": 352171,
"author": "jgangso",
"author_id": 104184,
"author_profile": "https://wordpress.stackexchange.com/users/104184",
"pm_score": 8,
"selected": true,
"text": "<p>On a hunt for the same I took a little dive into the JS source files.</p>\n<h1>Woocommerce Javascript events</h1>\n<h2>Woocommerce Checkout JS events</h2>\n<pre><code>$( document.body ).trigger( 'init_checkout' );\n$( document.body ).trigger( 'payment_method_selected' );\n$( document.body ).trigger( 'update_checkout' );\n$( document.body ).trigger( 'updated_checkout' );\n$( document.body ).trigger( 'checkout_error' );\n$( document.body ).trigger( 'applied_coupon_in_checkout' );\n$( document.body ).trigger( 'removed_coupon_in_checkout' );\n</code></pre>\n<h2>Woocommerce cart page JS events</h2>\n<pre><code>$( document.body ).trigger( 'wc_cart_emptied' );\n$( document.body ).trigger( 'update_checkout' );\n$( document.body ).trigger( 'updated_wc_div' );\n$( document.body ).trigger( 'updated_cart_totals' );\n$( document.body ).trigger( 'country_to_state_changed' );\n$( document.body ).trigger( 'updated_shipping_method' );\n$( document.body ).trigger( 'applied_coupon', [ coupon_code ] );\n$( document.body ).trigger( 'removed_coupon', [ coupon ] );\n</code></pre>\n<h2>Woocommerce Single product page JS events</h2>\n<pre><code>$( '.wc-tabs-wrapper, .woocommerce-tabs, #rating' ).trigger( 'init' );\n</code></pre>\n<h2>Woocommerce Variable product page JS events</h2>\n<pre><code>$( document.body ).trigger( 'found_variation', [variation] );\n</code></pre>\n<h2>Woocommerce Add to cart JS events</h2>\n<pre><code>$( document.body ).trigger( 'adding_to_cart', [ $thisbutton, data ] );\n$( document.body ).trigger( 'added_to_cart', [ response.fragments, response.cart_hash, $thisbutton ] );\n$( document.body ).trigger( 'removed_from_cart', [ response.fragments, response.cart_hash, $thisbutton ] );\n$( document.body ).trigger( 'wc_cart_button_updated', [ $button ] );\n$( document.body ).trigger( 'cart_page_refreshed' );\n$( document.body ).trigger( 'cart_totals_refreshed' );\n$( document.body ).trigger( 'wc_fragments_loaded' );\n</code></pre>\n<h2>Woocommerce Add payment method JS events</h2>\n<pre><code>$( document.body ).trigger( 'init_add_payment_method' );\n</code></pre>\n<h2>To bind listener to these events, use:</h2>\n<pre><code>jQuery('<event_target>').on('<event_name>', function(){\n console.log('<event_name> triggered');\n});\n</code></pre>\n<p><strong>F. ex.</strong></p>\n<pre><code>jQuery('body').on('init_checkout', function(){\n console.log('init_checkout triggered');\n // now.do.whatever();\n});\n</code></pre>\n"
},
{
"answer_id": 385043,
"author": "Vincenzo Di Gaetano",
"author_id": 200545,
"author_profile": "https://wordpress.stackexchange.com/users/200545",
"pm_score": 4,
"selected": false,
"text": "<blockquote>\n<p><strong>To find a complete list of all events</strong> <em>(and stay updated on any new\nones added)</em> you can consult the .js files in the directory: <code>/wp-content/plugins/woocommerce/assets/js/frontend</code></p>\n</blockquote>\n<p>Below I report other events <em>(in addition to @jgangso's answer)</em>:</p>\n<h3>VARIATIONS</h3>\n<ul>\n<li><code>hide_variation</code> triggered when displayed variation data is reset</li>\n<li><code>show_variation</code> triggered when a variation has been found which matches all attributes</li>\n<li><code>woocommerce_variation_select_change</code> triggered when an attribute field changes</li>\n<li><code>woocommerce_variation_has_changed</code> triggered when variation selection has been changed</li>\n<li><code>check_variations</code> triggered:\n<ul>\n<li>when an attribute field changes</li>\n<li>when reload variation data from the DOM</li>\n</ul>\n</li>\n<li><code>woocommerce_update_variation_values</code> triggered when variations have been updated</li>\n<li><code>woocommerce_gallery_reset_slide_position</code> reset the slide position if the variation has a different image than the current one</li>\n<li><code>woocommerce_gallery_init_zoom</code> sets product images for the chosen variation</li>\n</ul>\n<h3>CART FRAGMENTS</h3>\n<ul>\n<li><code>wc_fragments_refreshed</code> triggered when refreshing of cart fragments via Ajax was successful</li>\n<li><code>wc_fragments_ajax_error</code> triggered when refreshing of cart fragments via Ajax has failed</li>\n<li><code>wc_fragment_refresh</code> refresh when page is shown after back button (safari)</li>\n<li><code>wc_fragments_loaded</code> triggered after the cart fragments have been loaded</li>\n</ul>\n<h3>COUNTRY SELECT (CHECKOUT)</h3>\n<ul>\n<li><code>country_to_state_changed</code> triggered when the country changes from the select field</li>\n<li><code>country_to_state_changing</code> and <code>wc_address_i18n_ready</code> handle locale</li>\n</ul>\n<h3>SINGLE PRODUCT</h3>\n<ul>\n<li><code>wc-product-gallery-before-init</code> triggered before initializing all the galleries on the page</li>\n<li><code>wc-product-gallery-after-init</code> triggered after initializing all the galleries on the page</li>\n</ul>\n<h3>PRICE SLIDER</h3>\n<ul>\n<li><code>price_slider_updated</code> triggered after price slider updated</li>\n<li><code>price_slider_create</code> triggered after price slider create</li>\n<li><code>price_slider_slide</code> triggered after price slider slide</li>\n<li><code>price_slider_change</code> triggered after price slider change</li>\n</ul>\n<p>Related answers:</p>\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/66626942/where-to-find-a-complete-list-of-javascript-jquery-events-that-fire-on-the-woo\">Where to find a complete list of Javascript (JQuery) events that fire on the WooCommerce admin page?</a></li>\n</ul>\n"
},
{
"answer_id": 409055,
"author": "David Wolf",
"author_id": 218274,
"author_profile": "https://wordpress.stackexchange.com/users/218274",
"pm_score": 3,
"selected": false,
"text": "<p>In addition to the full list references, you can go the interactive way and paste the below into your JS console and do the actions on the store, which you want to target, watch the console to see the effected events getting logged.</p>\n<pre class=\"lang-js prettyprint-override\"><code>jQuery(document.body).on(\n "init_checkout payment_method_selected update_checkout updated_checkout checkout_error applied_coupon_in_checkout removed_coupon_in_checkout adding_to_cart added_to_cart removed_from_cart wc_cart_button_updated cart_page_refreshed cart_totals_refreshed wc_fragments_loaded init_add_payment_method wc_cart_emptied updated_wc_div updated_cart_totals country_to_state_changed updated_shipping_method applied_coupon removed_coupon",\n function (e) {\n console.log(e.type)\n }\n)\n</code></pre>\n"
}
] | 2019/07/04 | [
"https://wordpress.stackexchange.com/questions/342148",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82323/"
] | Where could I find an exhaustive list of javascript events defined by WooCommerce. ( Events like "woocommerce\_variation\_has\_changed" ) | On a hunt for the same I took a little dive into the JS source files.
Woocommerce Javascript events
=============================
Woocommerce Checkout JS events
------------------------------
```
$( document.body ).trigger( 'init_checkout' );
$( document.body ).trigger( 'payment_method_selected' );
$( document.body ).trigger( 'update_checkout' );
$( document.body ).trigger( 'updated_checkout' );
$( document.body ).trigger( 'checkout_error' );
$( document.body ).trigger( 'applied_coupon_in_checkout' );
$( document.body ).trigger( 'removed_coupon_in_checkout' );
```
Woocommerce cart page JS events
-------------------------------
```
$( document.body ).trigger( 'wc_cart_emptied' );
$( document.body ).trigger( 'update_checkout' );
$( document.body ).trigger( 'updated_wc_div' );
$( document.body ).trigger( 'updated_cart_totals' );
$( document.body ).trigger( 'country_to_state_changed' );
$( document.body ).trigger( 'updated_shipping_method' );
$( document.body ).trigger( 'applied_coupon', [ coupon_code ] );
$( document.body ).trigger( 'removed_coupon', [ coupon ] );
```
Woocommerce Single product page JS events
-----------------------------------------
```
$( '.wc-tabs-wrapper, .woocommerce-tabs, #rating' ).trigger( 'init' );
```
Woocommerce Variable product page JS events
-------------------------------------------
```
$( document.body ).trigger( 'found_variation', [variation] );
```
Woocommerce Add to cart JS events
---------------------------------
```
$( document.body ).trigger( 'adding_to_cart', [ $thisbutton, data ] );
$( document.body ).trigger( 'added_to_cart', [ response.fragments, response.cart_hash, $thisbutton ] );
$( document.body ).trigger( 'removed_from_cart', [ response.fragments, response.cart_hash, $thisbutton ] );
$( document.body ).trigger( 'wc_cart_button_updated', [ $button ] );
$( document.body ).trigger( 'cart_page_refreshed' );
$( document.body ).trigger( 'cart_totals_refreshed' );
$( document.body ).trigger( 'wc_fragments_loaded' );
```
Woocommerce Add payment method JS events
----------------------------------------
```
$( document.body ).trigger( 'init_add_payment_method' );
```
To bind listener to these events, use:
--------------------------------------
```
jQuery('<event_target>').on('<event_name>', function(){
console.log('<event_name> triggered');
});
```
**F. ex.**
```
jQuery('body').on('init_checkout', function(){
console.log('init_checkout triggered');
// now.do.whatever();
});
``` |
342,168 | <p>I use the latest version of wordpress under php7, I use a theme that uses itself the plugin WPBakery Page Builder (based on visual composer).</p>
<p>I create a post that contains this:</p>
<pre><code>[vc_row el_id="bloc-doc-a-telecharger"]
[vc_column]
[vc_basic_grid post_type="post" max_items="-1" style="pagination" items_per_page="4" element_width="3" arrows_design="vc_arrow-icon-arrow_09_left" arrows_position="outside" arrows_color="white" paging_color="white" item="1234" taxonomies="123"]
[/vc_column]
[/vc_row]
</code></pre>
<p>Shortcode so. Most of the time I can copy this kind of code and integrate it in php with <code>do_shortcode('[my_short_code'])</code> but it does not work here, it shows me the message "nothing_found". This is the <code>style="pagination"</code> that causes the error.</p>
<p>I specify that I try to integrate it in the file <code>category.php</code> and that if I integrate exactly the same code in <code>page.php</code> there it works.</p>
| [
{
"answer_id": 342171,
"author": "Oscprofessionals",
"author_id": 171102,
"author_profile": "https://wordpress.stackexchange.com/users/171102",
"pm_score": -1,
"selected": false,
"text": "<p>use shortcode inside single quotes as:</p>\n\n<pre><code> do_shortcode('[my_short_code]');\n</code></pre>\n"
},
{
"answer_id": 342235,
"author": "Entretoize",
"author_id": 166674,
"author_profile": "https://wordpress.stackexchange.com/users/166674",
"pm_score": 0,
"selected": false,
"text": "<p>I finally found the problem, in fact when you add pagination to visual composer post-grid shortcode, it will use ajax to load the things. But to communicate to the ajax php script it uses the post id. \nThe problem is that the shortcode will have no post id if you create it live, or another post id if you use an external post as a model.</p>\n\n<p>Then to make it works, I first create a page with the short code I want, then in my other page I get it contents like that :</p>\n\n<pre><code>$post = get_posts(array( 'name' => 'my-page-slug','post_type' => 'page'))[0];\nprint do_shortcode($post->post_content);\n</code></pre>\n\n<p>Notice the <code>$post</code> that is a global variable used by visual composer and that now have the correct post ID.</p>\n"
}
] | 2019/07/04 | [
"https://wordpress.stackexchange.com/questions/342168",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/166674/"
] | I use the latest version of wordpress under php7, I use a theme that uses itself the plugin WPBakery Page Builder (based on visual composer).
I create a post that contains this:
```
[vc_row el_id="bloc-doc-a-telecharger"]
[vc_column]
[vc_basic_grid post_type="post" max_items="-1" style="pagination" items_per_page="4" element_width="3" arrows_design="vc_arrow-icon-arrow_09_left" arrows_position="outside" arrows_color="white" paging_color="white" item="1234" taxonomies="123"]
[/vc_column]
[/vc_row]
```
Shortcode so. Most of the time I can copy this kind of code and integrate it in php with `do_shortcode('[my_short_code'])` but it does not work here, it shows me the message "nothing\_found". This is the `style="pagination"` that causes the error.
I specify that I try to integrate it in the file `category.php` and that if I integrate exactly the same code in `page.php` there it works. | I finally found the problem, in fact when you add pagination to visual composer post-grid shortcode, it will use ajax to load the things. But to communicate to the ajax php script it uses the post id.
The problem is that the shortcode will have no post id if you create it live, or another post id if you use an external post as a model.
Then to make it works, I first create a page with the short code I want, then in my other page I get it contents like that :
```
$post = get_posts(array( 'name' => 'my-page-slug','post_type' => 'page'))[0];
print do_shortcode($post->post_content);
```
Notice the `$post` that is a global variable used by visual composer and that now have the correct post ID. |
342,259 | <p>I want to have various development (say <code>dev.example.com</code>) and staging environments of a WordPress multisite (<code>example.com</code>). For this it would be great if WordPress wouldn't redirect to what it considers the canonical domain name.</p>
<p>I'm running into trouble with this in my <code>wp-config.php</code>:</p>
<pre><code>define('DOMAIN_CURRENT_SITE', gethostname());
</code></pre>
<p>It redirects to <code>example.com</code> or gives me database errors.</p>
<p>This is after <code>wp search-replace example.com dev.example.com</code>.</p>
<p>Is it possible to turn off this redirection? If so, how?</p>
| [
{
"answer_id": 343504,
"author": "Haqa",
"author_id": 167099,
"author_profile": "https://wordpress.stackexchange.com/users/167099",
"pm_score": 0,
"selected": false,
"text": "<p>From: <a href=\"http://www.velvetblues.com/web-development-blog/turn-off-wordpress-homepage-url-redirection/\" rel=\"nofollow noreferrer\">Velvet Blues</a></p>\n\n<p>To turn off Canonical URL Redirection, you can add the following code to your theme’s functions.php file.</p>\n\n<pre><code>remove_filter('template_redirect','redirect_canonical'); \n</code></pre>\n\n<p>or use the plugin: <a href=\"http://txfx.net/files/wordpress/disable-canonical-redirects.phps\" rel=\"nofollow noreferrer\">Disable Canonical Redirects Plugin</a></p>\n"
},
{
"answer_id": 343806,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 2,
"selected": true,
"text": "<p>In addition to modification of <code>wp-config</code> you might need to check <code>.htaccess</code> too, if there are any pointers to subfolder.</p>\n\n<p>After that, you might need to replace the values in DB tables <code>wp_site</code> and <code>wp_blogs</code>. </p>\n"
}
] | 2019/07/05 | [
"https://wordpress.stackexchange.com/questions/342259",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/44793/"
] | I want to have various development (say `dev.example.com`) and staging environments of a WordPress multisite (`example.com`). For this it would be great if WordPress wouldn't redirect to what it considers the canonical domain name.
I'm running into trouble with this in my `wp-config.php`:
```
define('DOMAIN_CURRENT_SITE', gethostname());
```
It redirects to `example.com` or gives me database errors.
This is after `wp search-replace example.com dev.example.com`.
Is it possible to turn off this redirection? If so, how? | In addition to modification of `wp-config` you might need to check `.htaccess` too, if there are any pointers to subfolder.
After that, you might need to replace the values in DB tables `wp_site` and `wp_blogs`. |
342,271 | <p>I have been working on a project where I will have to call a method(that accepts user id as an input) from a click of a submit button(Accept button).</p>
<p>I have been trying all the ways but the real challenge I am facing is how to get the user id in the front end and pass it to the method.</p>
<p>My method updates the user meta of that particular user.</p>
<p><strong>Html code:</strong></p>
<pre><code><div id="modal">
<div class="modalconent">
<h3 align=center>GDPR</h3>
<p>This is a GDPR Pop Up</p><br><br><br>
<form>
<input name="accept" type="checkbox" value="Gdpr" required/>I accept the GDPR
<input type="submit" id="accept-button" value="Accept">
</form>
</div>
</div>
<script>
window.onload = function () {
document.getElementById('accept-button').onclick = function () {
document.getElementById('modal').style.display = "none"
};
};
</script>
</code></pre>
<p>At present, my Accept button when clicked is only displaying none. I want to call the method along with display:none;</p>
<p><strong>My PHP code:</strong></p>
<pre><code>function updateHasReadFlag($user) {
// I added support for using this function either with user ID or user object
if ( $user && is_int( $user ) ) {
$user_id = $user;
} else if ( ! empty( $user->ID ) ) {
$user_id = $user->ID;
} else {
return;
}
return update_user_meta( $user_id, 'META_KEY', true );
}
</code></pre>
<p><strong>The form code generated :</strong> </p>
<pre><code><form method="post" action="<?php echo esc_url( home_url() ); ?>">
<input name="accept" type="checkbox" value="Gdpr" required=""> I accept the GDPR
<input type="submit" id="accept-button" value="Accept">
<!--?php wp_nonce_field( 'accept-gdpr', 'accept_gdpr_nonce' ); ?-->
</form>
</code></pre>
<p>I do not understand why nonce field is commented. This is exactly what the code got generated, I have not edited anything in the code.</p>
| [
{
"answer_id": 342311,
"author": "LebCit",
"author_id": 102912,
"author_profile": "https://wordpress.stackexchange.com/users/102912",
"pm_score": 0,
"selected": false,
"text": "<p>You will need to use <a href=\"https://codex.wordpress.org/Function_Reference/wp_localize_script\" rel=\"nofollow noreferrer\">wp_localize_script()</a> also available <a href=\"https://developer.wordpress.org/reference/functions/wp_localize_script/\" rel=\"nofollow noreferrer\">here</a>.<br />\nShort story : it's the WordPress way to call <code>PHP</code> in <code>JS</code><br />\nSo you could do something like the following.<br />\n<strong>FIRST</strong> create a <code>js</code> folder at the root of your theme, same level as style.css, if you do not have one yet, then in this <code>js</code> folder create a file <code>call-php.js</code>. You can name it what ever you want, the important thing is that it has to be a <code>.js</code> file<br />\nIn your <strong>functions.php</strong> <strong>after</strong> your <code>function updateHasReadFlag($user)</code> add :</p>\n<pre><code>/**\n * Hooking in JS code.\n */\nfunction call_php_in_js() {\n wp_enqueue_script( 'call-php-in-js', get_template_directory_uri() . '/js/call-php.js', array( 'jquery' ), filemtime( get_theme_file_path( '/js/call-php.js' ) ), true );\n $php_to_js = array(\n 'my_php_function' => updateHasReadFlag( $user ),\n );\n wp_localize_script( 'call-php-in-js', 'object_name', $php_to_js );\n}\nadd_action( 'wp_enqueue_scripts', 'call_php_in_js' );\n</code></pre>\n<p><strong>SECOND</strong>, in the <code>call-php.js</code> file add :</p>\n<pre><code>( function( $ ) {\n $( "#accept-button" ).click( function( e ) {\n e.preventDefault();\n $( "#modal" ).hide();\n object_name.my_php_function;\n });\n} )( jQuery );\n</code></pre>\n<p>Hope this will solve your issue.<br />\nI didn't test it but it should work.<br />\nLet me know after testing it.</p>\n"
},
{
"answer_id": 342453,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": true,
"text": "<p>You could use AJAX if you don't want to reload the current page — i.e. upon clicking the \"Accept\" button, make an AJAX request to update the user metadata, all without leaving the current page.</p>\n\n<p>However, the solution I'm proposing is <em>not</em> using AJAX; instead, we simply submit the form (set its <code>action</code> attribute value) to the homepage and then we use the <code>template_redirect</code> hook to update the metadata (and redirect back to the previous or referring page).</p>\n\n<h2>The Steps</h2>\n\n<ol>\n<li><p>Change the <code>form</code> tag to:</p>\n\n<pre><code><form method=\"post\" action=\"<?php echo esc_url( home_url() ); ?>\">\n</code></pre>\n\n<p>and add this <a href=\"https://codex.wordpress.org/WordPress_Nonces\" rel=\"nofollow noreferrer\">nonce</a> field:</p>\n\n<pre><code><?php wp_nonce_field( 'accept-gdpr', 'accept_gdpr_nonce' ); ?>\n</code></pre>\n\n<p>so your <code>form</code> now looks like:</p>\n\n<pre><code><form method=\"post\" action=\"<?php echo esc_url( home_url() ); ?>\">\n <input name=\"accept\" type=\"checkbox\" value=\"Gdpr\" required /> I accept the GDPR\n <input type=\"submit\" id=\"accept-button\" value=\"Accept\" />\n <?php wp_nonce_field( 'accept-gdpr', 'accept_gdpr_nonce' ); ?>\n</form>\n</code></pre></li>\n<li><p>Add this to the theme <code>functions.php</code> file:</p>\n\n<pre><code>function accept_gdpr() {\n // Check if the user is authenticated.\n if ( ! is_user_logged_in() ) {\n return;\n }\n\n // Check if we have all necessary data.\n if ( empty( $_POST['accept_gdpr_nonce'] ) || empty( $_POST['accept'] ) ||\n 'Gdpr' !== $_POST['accept'] ) {\n return;\n }\n\n // Verify the nonce.\n if ( ! wp_verify_nonce( $_POST['accept_gdpr_nonce'], 'accept-gdpr' ) ) {\n return;\n }\n\n // Update the meta.\n update_user_meta( get_current_user_id(), 'META_KEY', '1' );\n\n // Redirect back to the previous page.\n wp_safe_redirect( wp_get_referer() );\n exit;\n}\nadd_action( 'template_redirect', 'accept_gdpr' );\n</code></pre>\n\n<p><strong>Notes:</strong></p>\n\n<ol>\n<li><p>The <code>Gdpr</code> as in <code>'Gdpr' !== $_POST['accept']</code> is the same as in the <code><input name=\"accept\" type=\"checkbox\" value=\"Gdpr\" required /></code> above.</p></li>\n<li><p><em>Be sure to replace the <code>META_KEY</code> with the actual meta key.</em></p></li>\n<li><p>I believe that the GDPR acceptance is aimed at logged-in users only, so that's why I used <code>is_user_logged_in()</code> and <code>get_current_user_id()</code> in the above code/function.</p></li>\n</ol></li>\n</ol>\n\n<h2>UPDATE</h2>\n\n<p><code>wp_safe_redirect()</code> didn't work for the OP, so he used <code>wp_redirect()</code>.</p>\n"
}
] | 2019/07/06 | [
"https://wordpress.stackexchange.com/questions/342271",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/168253/"
] | I have been working on a project where I will have to call a method(that accepts user id as an input) from a click of a submit button(Accept button).
I have been trying all the ways but the real challenge I am facing is how to get the user id in the front end and pass it to the method.
My method updates the user meta of that particular user.
**Html code:**
```
<div id="modal">
<div class="modalconent">
<h3 align=center>GDPR</h3>
<p>This is a GDPR Pop Up</p><br><br><br>
<form>
<input name="accept" type="checkbox" value="Gdpr" required/>I accept the GDPR
<input type="submit" id="accept-button" value="Accept">
</form>
</div>
</div>
<script>
window.onload = function () {
document.getElementById('accept-button').onclick = function () {
document.getElementById('modal').style.display = "none"
};
};
</script>
```
At present, my Accept button when clicked is only displaying none. I want to call the method along with display:none;
**My PHP code:**
```
function updateHasReadFlag($user) {
// I added support for using this function either with user ID or user object
if ( $user && is_int( $user ) ) {
$user_id = $user;
} else if ( ! empty( $user->ID ) ) {
$user_id = $user->ID;
} else {
return;
}
return update_user_meta( $user_id, 'META_KEY', true );
}
```
**The form code generated :**
```
<form method="post" action="<?php echo esc_url( home_url() ); ?>">
<input name="accept" type="checkbox" value="Gdpr" required=""> I accept the GDPR
<input type="submit" id="accept-button" value="Accept">
<!--?php wp_nonce_field( 'accept-gdpr', 'accept_gdpr_nonce' ); ?-->
</form>
```
I do not understand why nonce field is commented. This is exactly what the code got generated, I have not edited anything in the code. | You could use AJAX if you don't want to reload the current page — i.e. upon clicking the "Accept" button, make an AJAX request to update the user metadata, all without leaving the current page.
However, the solution I'm proposing is *not* using AJAX; instead, we simply submit the form (set its `action` attribute value) to the homepage and then we use the `template_redirect` hook to update the metadata (and redirect back to the previous or referring page).
The Steps
---------
1. Change the `form` tag to:
```
<form method="post" action="<?php echo esc_url( home_url() ); ?>">
```
and add this [nonce](https://codex.wordpress.org/WordPress_Nonces) field:
```
<?php wp_nonce_field( 'accept-gdpr', 'accept_gdpr_nonce' ); ?>
```
so your `form` now looks like:
```
<form method="post" action="<?php echo esc_url( home_url() ); ?>">
<input name="accept" type="checkbox" value="Gdpr" required /> I accept the GDPR
<input type="submit" id="accept-button" value="Accept" />
<?php wp_nonce_field( 'accept-gdpr', 'accept_gdpr_nonce' ); ?>
</form>
```
2. Add this to the theme `functions.php` file:
```
function accept_gdpr() {
// Check if the user is authenticated.
if ( ! is_user_logged_in() ) {
return;
}
// Check if we have all necessary data.
if ( empty( $_POST['accept_gdpr_nonce'] ) || empty( $_POST['accept'] ) ||
'Gdpr' !== $_POST['accept'] ) {
return;
}
// Verify the nonce.
if ( ! wp_verify_nonce( $_POST['accept_gdpr_nonce'], 'accept-gdpr' ) ) {
return;
}
// Update the meta.
update_user_meta( get_current_user_id(), 'META_KEY', '1' );
// Redirect back to the previous page.
wp_safe_redirect( wp_get_referer() );
exit;
}
add_action( 'template_redirect', 'accept_gdpr' );
```
**Notes:**
1. The `Gdpr` as in `'Gdpr' !== $_POST['accept']` is the same as in the `<input name="accept" type="checkbox" value="Gdpr" required />` above.
2. *Be sure to replace the `META_KEY` with the actual meta key.*
3. I believe that the GDPR acceptance is aimed at logged-in users only, so that's why I used `is_user_logged_in()` and `get_current_user_id()` in the above code/function.
UPDATE
------
`wp_safe_redirect()` didn't work for the OP, so he used `wp_redirect()`. |
342,290 | <p>I have added some code in header.php but it is not showing in shop page. It is showing all other pages.</p>
<pre><code> if( is_home() || ! $ed_section || ! ( is_front_page() || is_page_template( 'template-home.php' ) ) ){
echo '<div class = "container"><div id="content" class="site-content">
<div class="tab1">
<a class="cat_button" href="https://packnchew.com/product-category/appetizers-snacks/">Appetizers & Snacks</a>
<a class="cat_button" href="https://packnchew.com/product-category/fillers-international/">Fillers International</a>
<a class="cat_button" href="https://packnchew.com/product-category/meals-more/">Meals and More</a>
<a class="cat_button" href="https://packnchew.com/product-category/mains-indian/">Mains Indian</a>
<a class="cat_button" href="https://packnchew.com/product-category/mains-oriental/">Mains Oriental</a>
<a class="cat_button" href="https://packnchew.com/product-category/mains-international/">Mains International</a>
<a class="cat_button" href="https://packnchew.com/product-category/desserts-drinks/">Desserts And Drinks</a>
</div>
<div class = "row">';
} ?>
</code></pre>
<p>This is my code and I added the lines <code><div class="tab1">
<a class="cat_button" href="https://packnchew.com/product-category/appetizers-snacks/">Appetizers & Snacks</a>
<a class="cat_button" href="https://packnchew.com/product-category/fillers-international/">Fillers International</a>
<a class="cat_button" href="https://packnchew.com/product-category/meals-more/">Meals and More</a>
<a class="cat_button" href="https://packnchew.com/product-category/mains-indian/">Mains Indian</a>
<a class="cat_button" href="https://packnchew.com/product-category/mains-oriental/">Mains Oriental</a>
<a class="cat_button" href="https://packnchew.com/product-category/mains-international/">Mains International</a>
<a class="cat_button" href="https://packnchew.com/product-category/desserts-drinks/">Desserts And Drinks</a>
</div></code></p>
<p>This tab class is showing in all pages excepts shop page, category page, product page.</p>
| [
{
"answer_id": 342311,
"author": "LebCit",
"author_id": 102912,
"author_profile": "https://wordpress.stackexchange.com/users/102912",
"pm_score": 0,
"selected": false,
"text": "<p>You will need to use <a href=\"https://codex.wordpress.org/Function_Reference/wp_localize_script\" rel=\"nofollow noreferrer\">wp_localize_script()</a> also available <a href=\"https://developer.wordpress.org/reference/functions/wp_localize_script/\" rel=\"nofollow noreferrer\">here</a>.<br />\nShort story : it's the WordPress way to call <code>PHP</code> in <code>JS</code><br />\nSo you could do something like the following.<br />\n<strong>FIRST</strong> create a <code>js</code> folder at the root of your theme, same level as style.css, if you do not have one yet, then in this <code>js</code> folder create a file <code>call-php.js</code>. You can name it what ever you want, the important thing is that it has to be a <code>.js</code> file<br />\nIn your <strong>functions.php</strong> <strong>after</strong> your <code>function updateHasReadFlag($user)</code> add :</p>\n<pre><code>/**\n * Hooking in JS code.\n */\nfunction call_php_in_js() {\n wp_enqueue_script( 'call-php-in-js', get_template_directory_uri() . '/js/call-php.js', array( 'jquery' ), filemtime( get_theme_file_path( '/js/call-php.js' ) ), true );\n $php_to_js = array(\n 'my_php_function' => updateHasReadFlag( $user ),\n );\n wp_localize_script( 'call-php-in-js', 'object_name', $php_to_js );\n}\nadd_action( 'wp_enqueue_scripts', 'call_php_in_js' );\n</code></pre>\n<p><strong>SECOND</strong>, in the <code>call-php.js</code> file add :</p>\n<pre><code>( function( $ ) {\n $( "#accept-button" ).click( function( e ) {\n e.preventDefault();\n $( "#modal" ).hide();\n object_name.my_php_function;\n });\n} )( jQuery );\n</code></pre>\n<p>Hope this will solve your issue.<br />\nI didn't test it but it should work.<br />\nLet me know after testing it.</p>\n"
},
{
"answer_id": 342453,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": true,
"text": "<p>You could use AJAX if you don't want to reload the current page — i.e. upon clicking the \"Accept\" button, make an AJAX request to update the user metadata, all without leaving the current page.</p>\n\n<p>However, the solution I'm proposing is <em>not</em> using AJAX; instead, we simply submit the form (set its <code>action</code> attribute value) to the homepage and then we use the <code>template_redirect</code> hook to update the metadata (and redirect back to the previous or referring page).</p>\n\n<h2>The Steps</h2>\n\n<ol>\n<li><p>Change the <code>form</code> tag to:</p>\n\n<pre><code><form method=\"post\" action=\"<?php echo esc_url( home_url() ); ?>\">\n</code></pre>\n\n<p>and add this <a href=\"https://codex.wordpress.org/WordPress_Nonces\" rel=\"nofollow noreferrer\">nonce</a> field:</p>\n\n<pre><code><?php wp_nonce_field( 'accept-gdpr', 'accept_gdpr_nonce' ); ?>\n</code></pre>\n\n<p>so your <code>form</code> now looks like:</p>\n\n<pre><code><form method=\"post\" action=\"<?php echo esc_url( home_url() ); ?>\">\n <input name=\"accept\" type=\"checkbox\" value=\"Gdpr\" required /> I accept the GDPR\n <input type=\"submit\" id=\"accept-button\" value=\"Accept\" />\n <?php wp_nonce_field( 'accept-gdpr', 'accept_gdpr_nonce' ); ?>\n</form>\n</code></pre></li>\n<li><p>Add this to the theme <code>functions.php</code> file:</p>\n\n<pre><code>function accept_gdpr() {\n // Check if the user is authenticated.\n if ( ! is_user_logged_in() ) {\n return;\n }\n\n // Check if we have all necessary data.\n if ( empty( $_POST['accept_gdpr_nonce'] ) || empty( $_POST['accept'] ) ||\n 'Gdpr' !== $_POST['accept'] ) {\n return;\n }\n\n // Verify the nonce.\n if ( ! wp_verify_nonce( $_POST['accept_gdpr_nonce'], 'accept-gdpr' ) ) {\n return;\n }\n\n // Update the meta.\n update_user_meta( get_current_user_id(), 'META_KEY', '1' );\n\n // Redirect back to the previous page.\n wp_safe_redirect( wp_get_referer() );\n exit;\n}\nadd_action( 'template_redirect', 'accept_gdpr' );\n</code></pre>\n\n<p><strong>Notes:</strong></p>\n\n<ol>\n<li><p>The <code>Gdpr</code> as in <code>'Gdpr' !== $_POST['accept']</code> is the same as in the <code><input name=\"accept\" type=\"checkbox\" value=\"Gdpr\" required /></code> above.</p></li>\n<li><p><em>Be sure to replace the <code>META_KEY</code> with the actual meta key.</em></p></li>\n<li><p>I believe that the GDPR acceptance is aimed at logged-in users only, so that's why I used <code>is_user_logged_in()</code> and <code>get_current_user_id()</code> in the above code/function.</p></li>\n</ol></li>\n</ol>\n\n<h2>UPDATE</h2>\n\n<p><code>wp_safe_redirect()</code> didn't work for the OP, so he used <code>wp_redirect()</code>.</p>\n"
}
] | 2019/07/06 | [
"https://wordpress.stackexchange.com/questions/342290",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/170624/"
] | I have added some code in header.php but it is not showing in shop page. It is showing all other pages.
```
if( is_home() || ! $ed_section || ! ( is_front_page() || is_page_template( 'template-home.php' ) ) ){
echo '<div class = "container"><div id="content" class="site-content">
<div class="tab1">
<a class="cat_button" href="https://packnchew.com/product-category/appetizers-snacks/">Appetizers & Snacks</a>
<a class="cat_button" href="https://packnchew.com/product-category/fillers-international/">Fillers International</a>
<a class="cat_button" href="https://packnchew.com/product-category/meals-more/">Meals and More</a>
<a class="cat_button" href="https://packnchew.com/product-category/mains-indian/">Mains Indian</a>
<a class="cat_button" href="https://packnchew.com/product-category/mains-oriental/">Mains Oriental</a>
<a class="cat_button" href="https://packnchew.com/product-category/mains-international/">Mains International</a>
<a class="cat_button" href="https://packnchew.com/product-category/desserts-drinks/">Desserts And Drinks</a>
</div>
<div class = "row">';
} ?>
```
This is my code and I added the lines `<div class="tab1">
<a class="cat_button" href="https://packnchew.com/product-category/appetizers-snacks/">Appetizers & Snacks</a>
<a class="cat_button" href="https://packnchew.com/product-category/fillers-international/">Fillers International</a>
<a class="cat_button" href="https://packnchew.com/product-category/meals-more/">Meals and More</a>
<a class="cat_button" href="https://packnchew.com/product-category/mains-indian/">Mains Indian</a>
<a class="cat_button" href="https://packnchew.com/product-category/mains-oriental/">Mains Oriental</a>
<a class="cat_button" href="https://packnchew.com/product-category/mains-international/">Mains International</a>
<a class="cat_button" href="https://packnchew.com/product-category/desserts-drinks/">Desserts And Drinks</a>
</div>`
This tab class is showing in all pages excepts shop page, category page, product page. | You could use AJAX if you don't want to reload the current page — i.e. upon clicking the "Accept" button, make an AJAX request to update the user metadata, all without leaving the current page.
However, the solution I'm proposing is *not* using AJAX; instead, we simply submit the form (set its `action` attribute value) to the homepage and then we use the `template_redirect` hook to update the metadata (and redirect back to the previous or referring page).
The Steps
---------
1. Change the `form` tag to:
```
<form method="post" action="<?php echo esc_url( home_url() ); ?>">
```
and add this [nonce](https://codex.wordpress.org/WordPress_Nonces) field:
```
<?php wp_nonce_field( 'accept-gdpr', 'accept_gdpr_nonce' ); ?>
```
so your `form` now looks like:
```
<form method="post" action="<?php echo esc_url( home_url() ); ?>">
<input name="accept" type="checkbox" value="Gdpr" required /> I accept the GDPR
<input type="submit" id="accept-button" value="Accept" />
<?php wp_nonce_field( 'accept-gdpr', 'accept_gdpr_nonce' ); ?>
</form>
```
2. Add this to the theme `functions.php` file:
```
function accept_gdpr() {
// Check if the user is authenticated.
if ( ! is_user_logged_in() ) {
return;
}
// Check if we have all necessary data.
if ( empty( $_POST['accept_gdpr_nonce'] ) || empty( $_POST['accept'] ) ||
'Gdpr' !== $_POST['accept'] ) {
return;
}
// Verify the nonce.
if ( ! wp_verify_nonce( $_POST['accept_gdpr_nonce'], 'accept-gdpr' ) ) {
return;
}
// Update the meta.
update_user_meta( get_current_user_id(), 'META_KEY', '1' );
// Redirect back to the previous page.
wp_safe_redirect( wp_get_referer() );
exit;
}
add_action( 'template_redirect', 'accept_gdpr' );
```
**Notes:**
1. The `Gdpr` as in `'Gdpr' !== $_POST['accept']` is the same as in the `<input name="accept" type="checkbox" value="Gdpr" required />` above.
2. *Be sure to replace the `META_KEY` with the actual meta key.*
3. I believe that the GDPR acceptance is aimed at logged-in users only, so that's why I used `is_user_logged_in()` and `get_current_user_id()` in the above code/function.
UPDATE
------
`wp_safe_redirect()` didn't work for the OP, so he used `wp_redirect()`. |
342,309 | <p>I have a custom post type of Hotel. Hotels can be can be categorised with the taxonomy Resort. </p>
<p>On my search page I need to be able to list hotels <strong>and</strong> taxonomy terms in the results, as separate results. eg:</p>
<pre><code>Resort Name
Hotel Name
Hotel Name
Hotel Name
</code></pre>
<p>Resorts should come first, followed by hotels and anything else. As far as I know taxonomy terms are not shown by default in WordPress search. </p>
<p>In my functions.php I'm currently limiting the search to specific post types:</p>
<pre><code>function filter_search($query) {
// Don't run in admin area
if(!is_admin()) {
// Limit search to posts
if($query->is_main_query() && $query->is_search()) {
$query->set('post_type', array('hotel', 'post', 'activities', 'page'));
}
// Return query
return $query;
}
}
add_filter('pre_get_posts', 'filter_search');
</code></pre>
<p>Then in my search.php I am grouping the results by post type: </p>
<pre><code><?php $types = array('hotel', 'post', 'activities', 'page');
foreach( $types as $type ){
echo '<div class="results"> '; ?>
<?php while( have_posts() ){
the_post();
if( $type == get_post_type() ){ ?>
<div class="result">
<div class="result-inner">
<h2>
<?php if ( $type == "hotel" ) { ?>
Hotel:
<?php } elseif ( $type == "activities" ) { ?>
Activity:
<?php } elseif ( $type == "post" ) { ?>
Blog Post:
<?php } elseif ( $type == "page" ) { ?>
Page:
<?php } else { ?>
Page:
<?php } ?>
<a href="<?php the_permalink() ?>"><?php the_title(); ?></a>
</h2>
<p class="blog-more"><a href="<?php the_permalink() ?>" class="button">View Page</a></p>
</div>
</div>
<?php }
}
rewind_posts();
echo '</div> ';
} ?>
</code></pre>
<p>What I'm struggling with is how to tell WordPress to show the taxonomy term (Resort) in the results as it's own result. Can anybody help?</p>
<p>UPDATE: I'm happy to preserve the default WordPress search order. The results don't have to be <em>grouped</em> by taxonomy term. I just need to be able to spit out the term <em>as a result itself</em>, with a link to the term (and be counted in the search count query). So if a search matches a taxonomy term that should come first, followed by the other results in whatever order. </p>
| [
{
"answer_id": 343204,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": false,
"text": "<p>If you mean to have a display like this:</p>\n\n<pre><code>Hotels: Resort 1 <- \"Resort 1\" is a term in the \"resort\" taxonomy\n Sample Hotel\n Sample Hotel 2\n Sample Hotel 4 <- This post is assigned to both \"Resort 1\" and \"Resort 2\"\n\nHotels: Resort 2 <- \"Resort 2\" is a term in the \"resort\" taxonomy\n Sample Hotel 3\n Sample Hotel 4 <- This post is assigned to both \"Resort 1\" and \"Resort 2\"\n\nBlog Posts\n Sample Post\n Sample Post 2\n\nActivities\n Sample Activity\n Sample Activity 2\n\nPages\n Sample Page\n</code></pre>\n\n<p>Then this can give you that, where we first group the posts by their post type or by the \"resort\" term name for \"hotel\" posts: (this is inside <code>search.php</code>)</p>\n\n<pre class=\"lang-php prettyprint-override\"><code><?php if ( have_posts() ) : ?>\n\n <div class=\"results\">\n\n <?php\n $_posts = $wp_query->posts;\n $posts_arr = [];\n $resorts = [];\n\n foreach ( $_posts as $i => $p ) {\n // Group \"hotel\" posts by the \"resort\" term name.\n if ( 'hotel' === $p->post_type ) {\n $terms = get_the_terms( $p, 'resort' );\n if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) {\n foreach ( $terms as $term ) {\n if ( ! isset( $resorts[ $term->name ] ) ) {\n $resorts[ $term->name ] = [];\n }\n $resorts[ $term->name ][] =& $_posts[ $i ];\n }\n }\n // Group other posts by their type.\n } else {\n if ( ! isset( $posts_arr[ $p->post_type ] ) ) {\n $posts_arr[ $p->post_type ] = [];\n }\n $posts_arr[ $p->post_type ][] =& $_posts[ $i ];\n }\n }\n $posts_arr['hotel'] = ! empty( $resorts );\n\n // List of post_type => Heading.\n $types = [\n 'hotel' => 'Hotels',\n 'post' => 'Blog Posts',\n 'activities' => 'Activities',\n 'page' => 'Pages',\n ];\n\n foreach ( $types as $type => $heading ) {\n if ( ! isset( $posts_arr[ $type ] ) ) {\n continue;\n }\n\n // Display \"hotel\" posts.\n if ( 'hotel' === $type ) {\n foreach ( $resorts as $name => $ps ) {\n echo '<h2>Hotels: ' . $name . '</h2>';\n foreach ( $ps as $post ) {\n setup_postdata( $post );\n get_template_part( 'template-parts/content', 'search' );\n }\n }\n // Display posts in other post types.\n } else {\n echo '<h2>' . $heading . '</h2>';\n foreach ( $posts_arr[ $type ] as $post ) {\n setup_postdata( $post );\n get_template_part( 'template-parts/content', 'search' );\n }\n }\n }\n\n unset( $_posts, $posts_arr, $resorts );\n ?>\n\n </div><!-- .results -->\n\n<?php endif; // end have_posts() ?>\n</code></pre>\n\n<p>And the template part (<code>content-search.php</code> inside <code>wp-content/themes/your-theme/template-parts</code>):</p>\n\n<pre class=\"lang-php prettyprint-override\"><code><div <?php post_class( 'result' ); ?>>\n <div class=\"result-inner\">\n <h4><a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a></h4>\n <p class=\"blog-more\"><a href=\"<?php the_permalink(); ?>\" class=\"button\">View Page</a></p>\n </div>\n</div>\n</code></pre>\n"
},
{
"answer_id": 343210,
"author": "HU is Sebastian",
"author_id": 56587,
"author_profile": "https://wordpress.stackexchange.com/users/56587",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to group your search results by a custom taxonomy, you can either group your posts AFTER the query like Sally CJ proposed, but this would only work correctly if you have all of your search results on one page.</p>\n\n<p>To order search results AND use pagination, you have to alter your MySQL Query, so that's what we're going to do.</p>\n\n<p>Step 1:\nAdd a filter to \"posts_clauses\" within the pre_get_posts action to change the generated Query:</p>\n\n<pre><code>add_action('pre_get_posts','setup_my_query_interception');\n\nfunction setup_my_query_interception($query){\n if(!is_admin() && $query->is_search() && $query->is_main_query()){\n add_filter( 'posts_clauses', 'order_by_taxonomy_intercept_query_clauses', 20, 1 );\n }\n}\n</code></pre>\n\n<p>Step 2: In the order_by_taxonomy_intercept_query_clauses function, you enhance the Query:</p>\n\n<pre><code>function order_by_taxonomy_intercept_query_clauses($pieces){\n global $wpdb;\n //First we add the taxonomy and term tables to our joins...\n $pieces['join'].=\" LEFT JOIN $wpdb->term_relationships trt ON ($wpdb->posts.ID = trt.object_id) LEFT JOIN $wpdb->term_taxonomy ttt ON (trt.term_taxonomy_id = ttt.term_taxonomy_id) INNER JOIN $wpdb->terms termts ON (termts.term_id = ttt.term_id)\";\n //Now we add a WHERE condition that we only want Resort Terms\n $pieces['where'].=\" AND ttt.taxonomy = 'resort'\"; //change this, if your taxonomy type is named different\n //At last, we tell the orderby to FIRST order by the term title, after that use the wanted orderby\n $pieces['orderby']=\"termts.name ASC, \".$pieces['orderby'];\n //Remove the filter so it only runs once in our main query\n remove_filter('posts_clauses', 'order_by_taxonomy_intercept_query_clauses');\n return $pieces;\n}\n</code></pre>\n\n<p>Step 3: Your search results will now be ordered by resorts first. If you want to echo the Resort name BEFORE the results, you will have to do something like this in your search.php or index.php:</p>\n\n<p>before the loop:</p>\n\n<pre><code>if(is_search()){\n global $activetax;\n $activetax = \"\";\n echo '<div class=\"mywrapper\">\n}\n</code></pre>\n\n<p>in the loop:</p>\n\n<pre><code>if(is_search()){\n$resorts = get_the_terms(get_the_ID(),'resort');\nif(is_array($resorts)){\n if(!($activetax==$resorts[0]->name)){\n $activetax = $resorts[0]->name;\n ?>\n </div>\n <h2 id=\"tax_id_<?php echo $resorts[0]->term_id; ?>\" class=\"resort-header\"><?php echo $activetax; ?></h2>\n <div class=\"mywrapper\">\n <?php\n }\n}\n}\nget_template_part('content'); \n</code></pre>\n\n<p>after the loop:</p>\n\n<pre><code>if(is_search()){\n echo \"</div>\";\n}\n</code></pre>\n\n<p>Did not test it, but it should work.</p>\n\n<p>Happy Coding!</p>\n"
},
{
"answer_id": 343253,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>I just need to be able to spit out the term as a <em>result itself</em>, with\n a link to the term (and be counted in the search count query). So if a\n search matches a taxonomy term that should come first, followed by the\n other results in whatever order.</p>\n</blockquote>\n\n<p><code>WP_Query::$posts</code> are <code>WP_Post</code> objects and can't include (or be mixed with) term/<code>WP_Term</code> objects.</p>\n\n<p>However, there's a way to achieve what you want — use <code>get_terms()</code> to search for the taxonomy terms and modify the <code>WP_Query</code>'s <code>posts_per_page</code> and <code>offset</code> parameters to make the matched terms <em>as if</em> they're part of the actual search results (which are posts).</p>\n\n<p>Note though, for now, <code>get_terms()</code>/<code>WP_Term_Query</code> supports single search keywords only — i.e. <code>foo, bar</code> is treated as one keyword — in <code>WP_Query</code>, that would be two keywords (<code>foo</code> and <code>bar</code>).</p>\n\n<h2>The Code/Steps</h2>\n\n<h3>In <code>functions.php</code>:</h3>\n\n<p>Add this:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function wpse342309_search_terms( $query, $taxonomy ) {\n $per_page = absint( $query->get( 'posts_per_page' ) );\n if ( ! $per_page ) {\n $per_page = max( 10, get_option( 'posts_per_page' ) );\n }\n\n $paged = max( 1, $query->get( 'paged' ) );\n $offset = absint( ( $paged - 1 ) * $per_page );\n $args = [\n 'taxonomy' => $taxonomy,\n// 'hide_empty' => '0',\n 'search' => $query->get( 's' ),\n 'number' => $per_page,\n 'offset' => $offset,\n ];\n\n $query->terms = [];\n $terms = get_terms( $args );\n if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) {\n $query->terms = $terms;\n }\n\n $args['offset'] = 0; // always 0\n $args['fields'] = 'count';\n $query->found_terms = get_terms( $args );\n\n $query->term_count = count( $query->terms );\n $query->terms_per_page = $per_page; // for WP_Query::$max_num_pages\n $query->is_all_terms = ( (int) $per_page === $query->term_count );\n\n $query->set( 'posts_per_page', max( 1, $per_page - $query->term_count ) );\n $query->set( 'offset', $query->term_count ? 0 :\n max( 0, $offset - $query->found_terms ) );\n}\n</code></pre>\n\n<p>In the <code>filter_search()</code>, add <code>wpse342309_search_terms( $query, 'resort' );</code> after this line:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$query->set( 'post_type', array( 'hotel', 'post', 'activities', 'page' ) );\n</code></pre>\n\n<h3>In <code>search.php</code>, for the main WordPress query:</h3>\n\n<pre class=\"lang-php prettyprint-override\"><code><?php if ( have_posts() ) :\n\n $total = $wp_query->found_posts + $wp_query->found_terms;\n $wp_query->max_num_pages = ceil( $total / $wp_query->terms_per_page );\n\n echo '<div class=\"results\">';\n\n // Display terms matching the search query.\n if ( ! empty( $wp_query->terms ) ) {\n global $term; // for use in the template part (below)\n foreach ( $wp_query->terms as $term ) {\n get_template_part( 'template-parts/content', 'search-term' );\n }\n }\n\n // Display posts matching the search query.\n if ( ! $wp_query->is_all_terms ) {\n while ( have_posts() ) {\n the_post();\n get_template_part( 'template-parts/content', 'search-post' );\n }\n }\n\n echo '</div><!-- .results -->';\n\n // Display pagination.\n //the_posts_pagination();\n echo paginate_links( [\n 'total' => $wp_query->max_num_pages,\n 'current' => max( 1, get_query_var( 'paged' ) ),\n ] );\n\nelse :\n echo '<h1>No Posts Found</h1>';\n\nendif; // end have_posts()\n?>\n</code></pre>\n\n<h3>In <code>search.php</code>, for a <em>custom</em> WordPress query:</h3>\n\n<p>You should always <em>manually</em> call <code>wpse342309_search_terms()</code>.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code><?php\n$my_query = new WP_Query( [\n 's' => 'foo',\n // ... your args here ...\n] );\n\n// Manually apply the terms search.\nwpse342309_search_terms( $my_query, 'resort' );\n\nif ( $my_query->have_posts() ) :\n\n $total = $my_query->found_posts + $my_query->found_terms;\n $my_query->max_num_pages = ceil( $total / $my_query->terms_per_page );\n\n echo '<div class=\"results\">';\n\n // Display terms matching the search query.\n if ( ! empty( $my_query->terms ) ) {\n global $term; // for use in the template part (below)\n foreach ( $my_query->terms as $term ) {\n get_template_part( 'template-parts/content', 'search-term' );\n }\n }\n\n // Display posts matching the search query.\n if ( ! $my_query->is_all_terms ) {\n while ( $my_query->have_posts() ) {\n $my_query->the_post();\n get_template_part( 'template-parts/content', 'search-post' );\n }\n }\n\n echo '</div><!-- .results -->';\n\n // Display pagination.\n echo paginate_links( [\n 'total' => $my_query->max_num_pages,\n 'current' => max( 1, get_query_var( 'paged' ) ),\n ] );\n\nelse :\n echo '<h1>No Posts Found</h1>';\n\nendif; // end have_posts()\n?>\n</code></pre>\n\n<h3>Template Part 1: <code>template-parts/content-search-term.php</code></h3>\n\n<pre class=\"lang-php prettyprint-override\"><code><?php global $term;\n$term_link = get_term_link( $term, 'resort' ); ?>\n\n<div class=\"result\">\n <div class=\"result-inner\">\n <h2><a href=\"<?php echo esc_url( $term_link ); ?>\"><?php echo esc_html( $term->name ); ?></a></h2>\n\n <p class=\"blog-more\"><a href=\"<?php echo esc_url( $term_link ); ?>\" class=\"button\">View Page</a></p>\n </div>\n</div>\n</code></pre>\n\n<h3>Template Part 2: <code>template-parts/content-search-post.php</code></h3>\n\n<pre class=\"lang-php prettyprint-override\"><code><?php $type = get_post_type(); ?>\n\n<div class=\"result\">\n <div class=\"result-inner\">\n <h2>\n <?php if ( $type == \"hotel\" ) { ?>\n Hotel:\n <?php } elseif ( $type == \"activities\" ) { ?>\n Activity:\n <?php } elseif ( $type == \"post\" ) { ?>\n Blog Post:\n <?php } elseif ( $type == \"page\" ) { ?>\n Page:\n <?php } else { ?>\n Page:\n <?php } ?>\n\n <a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a>\n </h2>\n\n <p class=\"blog-more\"><a href=\"<?php the_permalink(); ?>\" class=\"button\">View Page</a></p>\n </div>\n</div>\n</code></pre>\n"
},
{
"answer_id": 350723,
"author": "Jesse Nickles",
"author_id": 152624,
"author_profile": "https://wordpress.stackexchange.com/users/152624",
"pm_score": 0,
"selected": false,
"text": "<p>An interesting method is explained by Chandan Kumar on <a href=\"http://atiblog.com/custom-search-results/\" rel=\"nofollow noreferrer\">his blog post</a> (Jan 2019) that combines multiple queries, cleans them up, and then presents combined results:</p>\n\n<blockquote>\n <ol>\n <li>Remove the old query in the search.php file.</li>\n <li>Get all the category, tag and custom taxonomy in array format. And loop every array and find matching name in these arrays. Then store\n the ids of the matched name in a separate array.</li>\n <li>Using wp_query, query all the posts (by tax query )with these matched ids. Then store the resulting post_ids in an array.</li>\n <li>Now perform a default search_query and store all the ids in an array. </li>\n <li>Now we have got two arrays of ids which is the result.</li>\n <li>Combine these two and remove duplicates.</li>\n <li>Now we will perform a last query and show all the posts (by post__in parameter of wp_query).</li>\n </ol>\n</blockquote>\n\n<p>There is no license mentioned on his code, but he seems to be sharing it publicly:</p>\n\n<pre><code><div class=\"page-description\"><?php echo get_search_query(); ?></div>\n<?php\n$search=get_search_query();\n$all_categories = get_terms( array('taxonomy' => 'category','hide_empty' => true) ); \n$all_tags = get_terms( array('taxonomy' => 'post_tag','hide_empty' => true) );\n//if you have any custom taxonomy\n$all_custom_taxonomy = get_terms( array('taxonomy' => 'your-taxonomy-slug','hide_empty' => true) );\n\n$mcat=array();\n$mtag=array();\n$mcustom_taxonomy=array();\n\nforeach($all_categories as $all){\n$par=$all->name;\nif (strpos($par, $search) !== false) {\narray_push($mcat,$all->term_id);\n}\n}\n\nforeach($all_tags as $all){\n$par=$all->name;\nif (strpos($par, $search) !== false) {\narray_push($mtag,$all->term_id);\n}\n}\n\nforeach($all_custom_taxonomy as $all){\n$par=$all->name;\nif (strpos($par, $search) !== false) {\narray_push($mcustom_taxonomy,$all->term_id);\n}\n}\n\n$matched_posts=array();\n$args1= array( \n'post_status' => 'publish',\n'posts_per_page' => -1,\n'tax_query' => array(\n'relation' => 'OR',\narray(\n'taxonomy' => 'category',\n'field' => 'term_id',\n'terms' => $mcat\n),\narray(\n'taxonomy' => 'post_tag',\n'field' => 'term_id',\n'terms' => $mtag\n),\narray(\n'taxonomy' => 'custom_taxonomy',\n'field' => 'term_id',\n'terms' => $mcustom_taxonomy\n)\n)\n);\n\n$the_query = new WP_Query( $args1 );\nif ( $the_query->have_posts() ) {\nwhile ( $the_query->have_posts() ) {\n$the_query->the_post();\narray_push($matched_posts,get_the_id());\n//echo '<li>' . get_the_id() . '</li>';\n}\nwp_reset_postdata();\n} else {\n\n}\n\n?>\n<?php\n// now we will do the normal wordpress search\n$query2 = new WP_Query( array( 's' => $search,'posts_per_page' => -1 ) );\nif ( $query2->have_posts() ) {\nwhile ( $query2->have_posts() ) {\n$query2->the_post();\narray_push($matched_posts,get_the_id());\n}\nwp_reset_postdata();\n} else {\n\n}\n$matched_posts= array_unique($matched_posts);\n$matched_posts=array_values(array_filter($matched_posts));\n//print_r($matched_posts);\n?>\n\n<?php\n$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;\n$query3 = new WP_Query( array( 'post_type'=>'any','post__in' => $matched_posts ,'paged' => $paged) );\nif ( $query3->have_posts() ) {\nwhile ( $query3->have_posts() ) {\n$query3->the_post();\nget_template_part( 'template-parts/content/content', 'excerpt' );\n}\ntwentynineteen_the_posts_navigation();\nwp_reset_postdata();\n} else {\n\n}\n?>\n</code></pre>\n"
}
] | 2019/07/06 | [
"https://wordpress.stackexchange.com/questions/342309",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/22448/"
] | I have a custom post type of Hotel. Hotels can be can be categorised with the taxonomy Resort.
On my search page I need to be able to list hotels **and** taxonomy terms in the results, as separate results. eg:
```
Resort Name
Hotel Name
Hotel Name
Hotel Name
```
Resorts should come first, followed by hotels and anything else. As far as I know taxonomy terms are not shown by default in WordPress search.
In my functions.php I'm currently limiting the search to specific post types:
```
function filter_search($query) {
// Don't run in admin area
if(!is_admin()) {
// Limit search to posts
if($query->is_main_query() && $query->is_search()) {
$query->set('post_type', array('hotel', 'post', 'activities', 'page'));
}
// Return query
return $query;
}
}
add_filter('pre_get_posts', 'filter_search');
```
Then in my search.php I am grouping the results by post type:
```
<?php $types = array('hotel', 'post', 'activities', 'page');
foreach( $types as $type ){
echo '<div class="results"> '; ?>
<?php while( have_posts() ){
the_post();
if( $type == get_post_type() ){ ?>
<div class="result">
<div class="result-inner">
<h2>
<?php if ( $type == "hotel" ) { ?>
Hotel:
<?php } elseif ( $type == "activities" ) { ?>
Activity:
<?php } elseif ( $type == "post" ) { ?>
Blog Post:
<?php } elseif ( $type == "page" ) { ?>
Page:
<?php } else { ?>
Page:
<?php } ?>
<a href="<?php the_permalink() ?>"><?php the_title(); ?></a>
</h2>
<p class="blog-more"><a href="<?php the_permalink() ?>" class="button">View Page</a></p>
</div>
</div>
<?php }
}
rewind_posts();
echo '</div> ';
} ?>
```
What I'm struggling with is how to tell WordPress to show the taxonomy term (Resort) in the results as it's own result. Can anybody help?
UPDATE: I'm happy to preserve the default WordPress search order. The results don't have to be *grouped* by taxonomy term. I just need to be able to spit out the term *as a result itself*, with a link to the term (and be counted in the search count query). So if a search matches a taxonomy term that should come first, followed by the other results in whatever order. | >
> I just need to be able to spit out the term as a *result itself*, with
> a link to the term (and be counted in the search count query). So if a
> search matches a taxonomy term that should come first, followed by the
> other results in whatever order.
>
>
>
`WP_Query::$posts` are `WP_Post` objects and can't include (or be mixed with) term/`WP_Term` objects.
However, there's a way to achieve what you want — use `get_terms()` to search for the taxonomy terms and modify the `WP_Query`'s `posts_per_page` and `offset` parameters to make the matched terms *as if* they're part of the actual search results (which are posts).
Note though, for now, `get_terms()`/`WP_Term_Query` supports single search keywords only — i.e. `foo, bar` is treated as one keyword — in `WP_Query`, that would be two keywords (`foo` and `bar`).
The Code/Steps
--------------
### In `functions.php`:
Add this:
```php
function wpse342309_search_terms( $query, $taxonomy ) {
$per_page = absint( $query->get( 'posts_per_page' ) );
if ( ! $per_page ) {
$per_page = max( 10, get_option( 'posts_per_page' ) );
}
$paged = max( 1, $query->get( 'paged' ) );
$offset = absint( ( $paged - 1 ) * $per_page );
$args = [
'taxonomy' => $taxonomy,
// 'hide_empty' => '0',
'search' => $query->get( 's' ),
'number' => $per_page,
'offset' => $offset,
];
$query->terms = [];
$terms = get_terms( $args );
if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) {
$query->terms = $terms;
}
$args['offset'] = 0; // always 0
$args['fields'] = 'count';
$query->found_terms = get_terms( $args );
$query->term_count = count( $query->terms );
$query->terms_per_page = $per_page; // for WP_Query::$max_num_pages
$query->is_all_terms = ( (int) $per_page === $query->term_count );
$query->set( 'posts_per_page', max( 1, $per_page - $query->term_count ) );
$query->set( 'offset', $query->term_count ? 0 :
max( 0, $offset - $query->found_terms ) );
}
```
In the `filter_search()`, add `wpse342309_search_terms( $query, 'resort' );` after this line:
```php
$query->set( 'post_type', array( 'hotel', 'post', 'activities', 'page' ) );
```
### In `search.php`, for the main WordPress query:
```php
<?php if ( have_posts() ) :
$total = $wp_query->found_posts + $wp_query->found_terms;
$wp_query->max_num_pages = ceil( $total / $wp_query->terms_per_page );
echo '<div class="results">';
// Display terms matching the search query.
if ( ! empty( $wp_query->terms ) ) {
global $term; // for use in the template part (below)
foreach ( $wp_query->terms as $term ) {
get_template_part( 'template-parts/content', 'search-term' );
}
}
// Display posts matching the search query.
if ( ! $wp_query->is_all_terms ) {
while ( have_posts() ) {
the_post();
get_template_part( 'template-parts/content', 'search-post' );
}
}
echo '</div><!-- .results -->';
// Display pagination.
//the_posts_pagination();
echo paginate_links( [
'total' => $wp_query->max_num_pages,
'current' => max( 1, get_query_var( 'paged' ) ),
] );
else :
echo '<h1>No Posts Found</h1>';
endif; // end have_posts()
?>
```
### In `search.php`, for a *custom* WordPress query:
You should always *manually* call `wpse342309_search_terms()`.
```php
<?php
$my_query = new WP_Query( [
's' => 'foo',
// ... your args here ...
] );
// Manually apply the terms search.
wpse342309_search_terms( $my_query, 'resort' );
if ( $my_query->have_posts() ) :
$total = $my_query->found_posts + $my_query->found_terms;
$my_query->max_num_pages = ceil( $total / $my_query->terms_per_page );
echo '<div class="results">';
// Display terms matching the search query.
if ( ! empty( $my_query->terms ) ) {
global $term; // for use in the template part (below)
foreach ( $my_query->terms as $term ) {
get_template_part( 'template-parts/content', 'search-term' );
}
}
// Display posts matching the search query.
if ( ! $my_query->is_all_terms ) {
while ( $my_query->have_posts() ) {
$my_query->the_post();
get_template_part( 'template-parts/content', 'search-post' );
}
}
echo '</div><!-- .results -->';
// Display pagination.
echo paginate_links( [
'total' => $my_query->max_num_pages,
'current' => max( 1, get_query_var( 'paged' ) ),
] );
else :
echo '<h1>No Posts Found</h1>';
endif; // end have_posts()
?>
```
### Template Part 1: `template-parts/content-search-term.php`
```php
<?php global $term;
$term_link = get_term_link( $term, 'resort' ); ?>
<div class="result">
<div class="result-inner">
<h2><a href="<?php echo esc_url( $term_link ); ?>"><?php echo esc_html( $term->name ); ?></a></h2>
<p class="blog-more"><a href="<?php echo esc_url( $term_link ); ?>" class="button">View Page</a></p>
</div>
</div>
```
### Template Part 2: `template-parts/content-search-post.php`
```php
<?php $type = get_post_type(); ?>
<div class="result">
<div class="result-inner">
<h2>
<?php if ( $type == "hotel" ) { ?>
Hotel:
<?php } elseif ( $type == "activities" ) { ?>
Activity:
<?php } elseif ( $type == "post" ) { ?>
Blog Post:
<?php } elseif ( $type == "page" ) { ?>
Page:
<?php } else { ?>
Page:
<?php } ?>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</h2>
<p class="blog-more"><a href="<?php the_permalink(); ?>" class="button">View Page</a></p>
</div>
</div>
``` |
342,315 | <p>A custom page template which has been in use for 3 or 4 years which rendered a custom sidebar has suddenly stopped rendering it. I can't for the life work out what the problem is.</p>
<pre><code>/* functions.php */
/**
* Register Areas sidebars and widgetized areas.
*
*/
function my_widgets_init() {
register_sidebar( array(
'name' => 'My Sidebar',
'id' => 'my_sidebar',
'before_widget' => '<div>',
'after_widget' => '</div><div>&nbsp;</div>',
'before_title' => '<h2 class="rounded">',
'after_title' => '</h2>',
) );
}
add_action( 'widgets_init', 'my_widgets_init' );
/* wordpress page template file*/
<?php if ( is_active_sidebar( 'my_sidebar' ) ) : ?>
<div>
<?php dynamic_sidebar( 'my_sidebar' ); ?>
</div>
<?php endif; ?>
</code></pre>
<p>In the Wordpress dashboard, 3 or 4 widgets are assigned to the area as would be expected. But calling dynamic_sidebar() renders an empty string.</p>
<p>Any ideas?</p>
<p><strong>* UPDATE *</strong></p>
<p>This is the output of the debugging code provided in the first response.</p>
<pre><code>Sidebar ID: new_sidebar ( Active)
Sidebar Found
4 Widgets Found
All Sidebars Widgets:
Array
(
[wp_inactive_widgets] => Array
(
[0] => calendar-4
[1] => rss-3
[2] => em_calendar-4
[3] => recent-posts-2
)
[hca_alert_area] => Array
(
)
[SNIP - other sidebars]
[new_sidebar] => Array
(
[0] => search-2
[1] => nav_menu-2
[2] => em_widget-2
[3] => recent-posts-3
)
[footer-sidebar] => Array
(
[0] => nav_menu-3
)
[array_version] => 3
)
</code></pre>
<p>I've spent a crazy amount of time trying to work out the problem. The site uses a no-longer supported version of the Cherry Framework template. I'm reluctant to update the entire theme purely because of this glitch if I can fix it.</p>
| [
{
"answer_id": 342333,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 2,
"selected": true,
"text": "<p>In a case like this, you're probably going to need to check the conditions in <code>dynamic_sidebar</code> to find out what is not happening.</p>\n\n<pre><code>if (isset($_GET['debugsidebar'])) {add_action('init', 'debug_sidebar');} \nfunction debug_sidebar() {\n\n $id = $_GET['debugsidebar'];\n $sidebarswidgets = get_option('sidebars_widgets');\n\n if (is_active_sidebar($id)) {$status = \" Active\";} else {$status = \"Inactive\";}\n echo \"Sidebar ID: \".$id.\" (\".$status.\")<br>\";\n if (array_key_exists($id, $sidebarswidgets)) {\n $found = \"Sidebar Found\";\n if (is_array($sidebarswidgets[$id])) {\n $widgets = count($sidebarswidgets[$id]).\" Widgets Found\";\n } else {$widgets = \"Widget Array not Found!\";}\n echo $found.\"<br\".$widgets.\"<br>\";\n else {echo \"Sidebar Not Found<br>\";}\n\n echo \"<br>All Sidebars Widgets: \".print_r($sidebarswidgets,true).\"<br>\"; \n exit;\n}\n</code></pre>\n\n<p>Which you put in your theme <code>functions.php</code> and then can check via <code>http://example.com/?debugsidebar=my_sidebar</code></p>\n\n<p>There is a small difference in the bugout checks is <code>is_active_sidebar</code> and <code>dynamic_sidebar</code></p>\n\n<p>From <code>is_active_sidebar</code> function: </p>\n\n<pre><code>! empty( $sidebars_widgets[ $index ] );\n</code></pre>\n\n<p>From <code>dynamic_sidebar</code> function: </p>\n\n<pre><code>if ( empty( $wp_registered_sidebars[ $index ] ) || empty( $sidebars_widgets[ $index ] ) || ! is_array( $sidebars_widgets[ $index ] ) ) {\n</code></pre>\n\n<p>Since the middle condition is the same, this means that either the sidebar is not being registered correctly (unlikely as that seems fine) - but more likely, the data for that key is not an array of widgets. You will find out from running the debug function. </p>\n\n<p>It may possibly show you a mismatch or corrupt data in the <code>sidebars_widgets</code> option value (If needs be you can that check against a value from you <code>wp_options</code> table backup from when it was working.)</p>\n"
},
{
"answer_id": 345023,
"author": "fred2",
"author_id": 19216,
"author_profile": "https://wordpress.stackexchange.com/users/19216",
"pm_score": 0,
"selected": false,
"text": "<p>The following lines in the obsolete Cherry Plugin (Version 9.2.8.1, which does not support PHP 7+ in theory) caused sidebars to be hidden all the time.</p>\n\n<p><strong>In file</strong>: <code>wordpress/wp-content/plugins/cherry-plugin/includes/widgets/widgets-manager.php</code></p>\n\n<p><strong>Comment out the following code:</strong></p>\n\n<pre><code>add_filter( 'widget_display_callback', 'maybe_hide_widget', 10, 3 );\nfunction maybe_hide_widget( $instance, $widget_object, $args ) {\nif ( ! check_widget_visibility( $args['widget_id'] ) )\n return false;\n return $instance;\n}\n</code></pre>\n\n<p>It would also be possible to edit the <code>check_widget_visibility()</code> function (obviously) in the same file so that it did not always return false and continued to function as intended. However, for my purposes, simply disabling the entire mechanism was good enough.</p>\n"
}
] | 2019/07/06 | [
"https://wordpress.stackexchange.com/questions/342315",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/19216/"
] | A custom page template which has been in use for 3 or 4 years which rendered a custom sidebar has suddenly stopped rendering it. I can't for the life work out what the problem is.
```
/* functions.php */
/**
* Register Areas sidebars and widgetized areas.
*
*/
function my_widgets_init() {
register_sidebar( array(
'name' => 'My Sidebar',
'id' => 'my_sidebar',
'before_widget' => '<div>',
'after_widget' => '</div><div> </div>',
'before_title' => '<h2 class="rounded">',
'after_title' => '</h2>',
) );
}
add_action( 'widgets_init', 'my_widgets_init' );
/* wordpress page template file*/
<?php if ( is_active_sidebar( 'my_sidebar' ) ) : ?>
<div>
<?php dynamic_sidebar( 'my_sidebar' ); ?>
</div>
<?php endif; ?>
```
In the Wordpress dashboard, 3 or 4 widgets are assigned to the area as would be expected. But calling dynamic\_sidebar() renders an empty string.
Any ideas?
**\* UPDATE \***
This is the output of the debugging code provided in the first response.
```
Sidebar ID: new_sidebar ( Active)
Sidebar Found
4 Widgets Found
All Sidebars Widgets:
Array
(
[wp_inactive_widgets] => Array
(
[0] => calendar-4
[1] => rss-3
[2] => em_calendar-4
[3] => recent-posts-2
)
[hca_alert_area] => Array
(
)
[SNIP - other sidebars]
[new_sidebar] => Array
(
[0] => search-2
[1] => nav_menu-2
[2] => em_widget-2
[3] => recent-posts-3
)
[footer-sidebar] => Array
(
[0] => nav_menu-3
)
[array_version] => 3
)
```
I've spent a crazy amount of time trying to work out the problem. The site uses a no-longer supported version of the Cherry Framework template. I'm reluctant to update the entire theme purely because of this glitch if I can fix it. | In a case like this, you're probably going to need to check the conditions in `dynamic_sidebar` to find out what is not happening.
```
if (isset($_GET['debugsidebar'])) {add_action('init', 'debug_sidebar');}
function debug_sidebar() {
$id = $_GET['debugsidebar'];
$sidebarswidgets = get_option('sidebars_widgets');
if (is_active_sidebar($id)) {$status = " Active";} else {$status = "Inactive";}
echo "Sidebar ID: ".$id." (".$status.")<br>";
if (array_key_exists($id, $sidebarswidgets)) {
$found = "Sidebar Found";
if (is_array($sidebarswidgets[$id])) {
$widgets = count($sidebarswidgets[$id])." Widgets Found";
} else {$widgets = "Widget Array not Found!";}
echo $found."<br".$widgets."<br>";
else {echo "Sidebar Not Found<br>";}
echo "<br>All Sidebars Widgets: ".print_r($sidebarswidgets,true)."<br>";
exit;
}
```
Which you put in your theme `functions.php` and then can check via `http://example.com/?debugsidebar=my_sidebar`
There is a small difference in the bugout checks is `is_active_sidebar` and `dynamic_sidebar`
From `is_active_sidebar` function:
```
! empty( $sidebars_widgets[ $index ] );
```
From `dynamic_sidebar` function:
```
if ( empty( $wp_registered_sidebars[ $index ] ) || empty( $sidebars_widgets[ $index ] ) || ! is_array( $sidebars_widgets[ $index ] ) ) {
```
Since the middle condition is the same, this means that either the sidebar is not being registered correctly (unlikely as that seems fine) - but more likely, the data for that key is not an array of widgets. You will find out from running the debug function.
It may possibly show you a mismatch or corrupt data in the `sidebars_widgets` option value (If needs be you can that check against a value from you `wp_options` table backup from when it was working.) |
342,344 | <p>How do I extract just the post ID of the first item in whatever WP_Query returns? All the examples, answers, and documentation that I have seen dives off into doing things with loops. That's nice, but I just want the first ID. Nothing else. As the plugin will only ever generate a custom post type when there is none, the user should only have one. I need to get the ID of that post.</p>
<p>How do I find a post ID? Is there an easier way to find out if the user has a post available?</p>
<p>This is as far as I have gotten:</p>
<pre><code>$query = new WP_Query( array(
'author' => $current_user,
'post_type' => 'my_custom_post_type',
// etc.
) );
$author_posts = new WP_Query( $query );
if( $author_posts->have_posts() ) {
// They have at least one. Grovey, now what?
}
unset($author_posts);
</code></pre>
| [
{
"answer_id": 342333,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 2,
"selected": true,
"text": "<p>In a case like this, you're probably going to need to check the conditions in <code>dynamic_sidebar</code> to find out what is not happening.</p>\n\n<pre><code>if (isset($_GET['debugsidebar'])) {add_action('init', 'debug_sidebar');} \nfunction debug_sidebar() {\n\n $id = $_GET['debugsidebar'];\n $sidebarswidgets = get_option('sidebars_widgets');\n\n if (is_active_sidebar($id)) {$status = \" Active\";} else {$status = \"Inactive\";}\n echo \"Sidebar ID: \".$id.\" (\".$status.\")<br>\";\n if (array_key_exists($id, $sidebarswidgets)) {\n $found = \"Sidebar Found\";\n if (is_array($sidebarswidgets[$id])) {\n $widgets = count($sidebarswidgets[$id]).\" Widgets Found\";\n } else {$widgets = \"Widget Array not Found!\";}\n echo $found.\"<br\".$widgets.\"<br>\";\n else {echo \"Sidebar Not Found<br>\";}\n\n echo \"<br>All Sidebars Widgets: \".print_r($sidebarswidgets,true).\"<br>\"; \n exit;\n}\n</code></pre>\n\n<p>Which you put in your theme <code>functions.php</code> and then can check via <code>http://example.com/?debugsidebar=my_sidebar</code></p>\n\n<p>There is a small difference in the bugout checks is <code>is_active_sidebar</code> and <code>dynamic_sidebar</code></p>\n\n<p>From <code>is_active_sidebar</code> function: </p>\n\n<pre><code>! empty( $sidebars_widgets[ $index ] );\n</code></pre>\n\n<p>From <code>dynamic_sidebar</code> function: </p>\n\n<pre><code>if ( empty( $wp_registered_sidebars[ $index ] ) || empty( $sidebars_widgets[ $index ] ) || ! is_array( $sidebars_widgets[ $index ] ) ) {\n</code></pre>\n\n<p>Since the middle condition is the same, this means that either the sidebar is not being registered correctly (unlikely as that seems fine) - but more likely, the data for that key is not an array of widgets. You will find out from running the debug function. </p>\n\n<p>It may possibly show you a mismatch or corrupt data in the <code>sidebars_widgets</code> option value (If needs be you can that check against a value from you <code>wp_options</code> table backup from when it was working.)</p>\n"
},
{
"answer_id": 345023,
"author": "fred2",
"author_id": 19216,
"author_profile": "https://wordpress.stackexchange.com/users/19216",
"pm_score": 0,
"selected": false,
"text": "<p>The following lines in the obsolete Cherry Plugin (Version 9.2.8.1, which does not support PHP 7+ in theory) caused sidebars to be hidden all the time.</p>\n\n<p><strong>In file</strong>: <code>wordpress/wp-content/plugins/cherry-plugin/includes/widgets/widgets-manager.php</code></p>\n\n<p><strong>Comment out the following code:</strong></p>\n\n<pre><code>add_filter( 'widget_display_callback', 'maybe_hide_widget', 10, 3 );\nfunction maybe_hide_widget( $instance, $widget_object, $args ) {\nif ( ! check_widget_visibility( $args['widget_id'] ) )\n return false;\n return $instance;\n}\n</code></pre>\n\n<p>It would also be possible to edit the <code>check_widget_visibility()</code> function (obviously) in the same file so that it did not always return false and continued to function as intended. However, for my purposes, simply disabling the entire mechanism was good enough.</p>\n"
}
] | 2019/07/07 | [
"https://wordpress.stackexchange.com/questions/342344",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109240/"
] | How do I extract just the post ID of the first item in whatever WP\_Query returns? All the examples, answers, and documentation that I have seen dives off into doing things with loops. That's nice, but I just want the first ID. Nothing else. As the plugin will only ever generate a custom post type when there is none, the user should only have one. I need to get the ID of that post.
How do I find a post ID? Is there an easier way to find out if the user has a post available?
This is as far as I have gotten:
```
$query = new WP_Query( array(
'author' => $current_user,
'post_type' => 'my_custom_post_type',
// etc.
) );
$author_posts = new WP_Query( $query );
if( $author_posts->have_posts() ) {
// They have at least one. Grovey, now what?
}
unset($author_posts);
``` | In a case like this, you're probably going to need to check the conditions in `dynamic_sidebar` to find out what is not happening.
```
if (isset($_GET['debugsidebar'])) {add_action('init', 'debug_sidebar');}
function debug_sidebar() {
$id = $_GET['debugsidebar'];
$sidebarswidgets = get_option('sidebars_widgets');
if (is_active_sidebar($id)) {$status = " Active";} else {$status = "Inactive";}
echo "Sidebar ID: ".$id." (".$status.")<br>";
if (array_key_exists($id, $sidebarswidgets)) {
$found = "Sidebar Found";
if (is_array($sidebarswidgets[$id])) {
$widgets = count($sidebarswidgets[$id])." Widgets Found";
} else {$widgets = "Widget Array not Found!";}
echo $found."<br".$widgets."<br>";
else {echo "Sidebar Not Found<br>";}
echo "<br>All Sidebars Widgets: ".print_r($sidebarswidgets,true)."<br>";
exit;
}
```
Which you put in your theme `functions.php` and then can check via `http://example.com/?debugsidebar=my_sidebar`
There is a small difference in the bugout checks is `is_active_sidebar` and `dynamic_sidebar`
From `is_active_sidebar` function:
```
! empty( $sidebars_widgets[ $index ] );
```
From `dynamic_sidebar` function:
```
if ( empty( $wp_registered_sidebars[ $index ] ) || empty( $sidebars_widgets[ $index ] ) || ! is_array( $sidebars_widgets[ $index ] ) ) {
```
Since the middle condition is the same, this means that either the sidebar is not being registered correctly (unlikely as that seems fine) - but more likely, the data for that key is not an array of widgets. You will find out from running the debug function.
It may possibly show you a mismatch or corrupt data in the `sidebars_widgets` option value (If needs be you can that check against a value from you `wp_options` table backup from when it was working.) |
342,365 | <p>I embedded some code to generate post filters referencing an article at
<a href="https://premium.wpmudev.org/blog/add-post-filters/" rel="nofollow noreferrer">https://premium.wpmudev.org/blog/add-post-filters/</a> as displayed below:</p>
<pre><code><form class='post-filters'>
<select name="orderby">
<?php
$orderby_options = array(
'post_date' => 'Order By Date',
'post_title' => 'Order By Title',
'rand' => 'Random Order',
);
foreach( $orderby_options as $value => $label ) {
echo "<option ".selected( $_GET['orderby'], $value )."
value='$value'>$label</option>";
}
?>
</select>
<select name="order">
<?php
$order_options = array(
'DESC' => 'Descending',
'ASC' => 'Ascending',
);
foreach( $order_options as $value => $label ) {
echo "<option ".selected( $_GET['order'], $value )."
value='$value'>$label</option>";
}
?>
</select>
<input type='submit' value='Filter!'>
</form>
</code></pre>
<p>Consequently, the page the same code is embedded only returns a blank page showing no code in the source view. I also used Search & Filter plugin only to get the same blank page.</p>
<p>I cannot resolve this issue alone. Please someone help me correct the code.</p>
<p>After editing front-page.php based on the comments given:</p>
<pre><code> <?php echo get_template_part('head') ?>
<body <?php body_class(); ?>>
<?php get_header(); ?>
<main>
<div id="main">
<div class="outer">
<ul class="breadcrumb"><?php breadcrumb() ?></ul>
<form class="post-filters"><select name="orderby"><?php
$orderby_options = array(
'post_date' => 'Order By Date',
'title' => 'Order By Title',
'rand' => 'Random Order'
);
$orderby = isset( $_GET['orderby'] ) ? sanitize_text_field( $_GET['orderby'] ) : 'default value';
foreach($orderby_options as $value => $label):
echo '<option '.selected($orderby, $value, false).' value="'.$value.'">'.$label.'</option>';
endforeach;
?>
<input type="submit" value="Filter">
</form>
<div class="inner">
<?php
$filter = array('parent' => 0, 'hide_empty' => 0, 'exclude' => (5));
$categories = get_categories($filter);
shuffle($categories);
if($categories):
foreach($categories as $category):
$catName = $category->cat_name;
$catFilter = array(
'category_name' => $catName
);
echo '<div class="section"><section><h2 data-aos="fade-up">'.$catName.'</h2>'.category_description(get_cat_ID($catName)).'<div class="wrapper">';
$catquery = new WP_Query($catFilter);
if($catquery->have_posts()):
while($catquery->have_posts()): $catquery->the_post();
if(has_post_thumbnail()){
echo '<div class="item" data-aos="fade-down"><a href="'.get_the_permalink().'"><h3>'.get_the_post_thumbnail().'<span class="date">'.get_the_date().'</span></h3>'.'<dl><dt>'.get_the_title().'</dt><dd>'.get_the_content().'</dd></dl></a></div>';
}else{
echo '<div class="item" data-aos="fade-down"><a href="'.get_the_permalink().'"><h3>No Image Available<span class="date">'.get_the_date().'</span></h3>'.'<dl><dt>'.get_the_title().'</dt><dd>'.get_the_content().'</dd></dl></a></div>';
}
endwhile;
endif;
echo '</div></section></div>';
wp_reset_postdata();
endforeach;
endif;
?>
</div>
<div class="banner-ads" data-aos="fade-down"><section><?php the_ad_group(12); ?></section></div>
<?php
$catObj = get_category_by_slug('news');
$catName = $catObj->name;
echo '<div class="inner" id="'.$catName.'"><div class="wrapper"><h2 data-aos="fade-up">'.$catName.'</h2>';
$catquery = new WP_Query('category_name="news"');
if($catquery->have_posts()):
while($catquery->have_posts()): $catquery->the_post();
if(has_post_thumbnail()){
echo '<dl data-aos="fade-right"><dt style="background: url('.get_the_post_thumbnail_url().')"></dt>';
}else{
echo '<dl data-aos="fade-right"><dt><span>No Image Available</span></dt>';
}
echo '<dd>'.'<span class="date">'.get_the_date().'</span><br class="sp">';
$tags = get_the_tags();
foreach($tags as $tag){
$tagName = $tag->name;
echo '<span class="tag">'.$tagName.'</span>';
}
echo get_the_content().'</dd></dl>';
endwhile;
endif;
echo '</div></div>';
?>
</div>
</div>
</main>
<?php get_footer(); ?>
</body>
</code></pre>
<p></p>
| [
{
"answer_id": 342366,
"author": "Castiblanco",
"author_id": 44370,
"author_profile": "https://wordpress.stackexchange.com/users/44370",
"pm_score": 0,
"selected": false,
"text": "<p>You are removing necessary parts of the code, you started opening <code>form</code> and <code>select</code> HTML elements, but you never close them, use the full code:</p>\n\n<pre><code><form class='post-filters'>\n <select name=\"orderby\">\n <?php\n $orderby_options = array(\n 'post_date' => 'Order By Date',\n 'post_title' => 'Order By Title',\n 'rand' => 'Random Order',\n );\n foreach( $orderby_options as $value => $label ) {\n echo \"<option \".selected( $_GET['orderby'], $value ).\" value='$value'>$label</option>\";\n }\n ?>\n </select>\n <select name=\"order\">\n <?php\n $order_options = array(\n 'DESC' => 'Descending',\n 'ASC' => 'Ascending',\n );\n foreach( $order_options as $value => $label ) {\n echo \"<option \".selected( $_GET['order'], $value ).\" value='$value'>$label</option>\";\n }\n ?>\n </select>\n <select name=\"thumbnail\">\n <?php\n $order_options = array(\n 'all' => 'All Posts',\n 'only_thumbnailed' => 'Posts With Thumbnails',\n );\n foreach( $order_options as $value => $label ) {\n echo \"<option \".selected( $_GET['thumbnail'], $value ).\" value='$value'>$label</option>\";\n }\n ?>\n </select>\n <input type='submit' value='Filter!'>\n</form>\n</code></pre>\n\n<p>Then if you want to remove things you think you don't need, you can turn on the <a href=\"https://codex.wordpress.org/WP_DEBUG\" rel=\"nofollow noreferrer\">Debug</a> to see what is falling and why you are getting a blank page, in this case, you are getting a blank page because your code is pretty incomplete and many things should be failing.</p>\n"
},
{
"answer_id": 342461,
"author": "Fizzler",
"author_id": 141638,
"author_profile": "https://wordpress.stackexchange.com/users/141638",
"pm_score": 1,
"selected": false,
"text": "<p>It turns out the cause of this lingering filter problem was to do with the way WordPress was set up as well as the argument of <code>WP_Query</code>. Once I changed the <em>Your Homepage Displays</em> setting to the latest posts and renamed <code>front-page.php</code> to be <code>index.php</code>, the filter began working and the blank page no longer showed.</p>\n\n<p>Concerning the post filter, declaring the orderby parameter as part of the argument of <code>WP_Query</code> got it working. The code for the filter is as follows:</p>\n\n<pre><code><form class=\"post-filters\">\n <select name=\"orderby\">\n <?php\n $orderby_options = array(\n 'post_date' => 'Order By Date',\n 'post_title' => 'Order By Title',\n 'rand' => 'Random Order'\n );\n foreach($orderby_options as $value => $label):\n echo '<option '.selected($_GET['orderby'], $value, false).' value=\"'.$value.'\">'.$label.'</option>';\n endforeach;\n ?>\n </select>\n <input type=\"submit\" value=\"Filter\">\n</form>\n</code></pre>\n"
}
] | 2019/07/08 | [
"https://wordpress.stackexchange.com/questions/342365",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/141638/"
] | I embedded some code to generate post filters referencing an article at
<https://premium.wpmudev.org/blog/add-post-filters/> as displayed below:
```
<form class='post-filters'>
<select name="orderby">
<?php
$orderby_options = array(
'post_date' => 'Order By Date',
'post_title' => 'Order By Title',
'rand' => 'Random Order',
);
foreach( $orderby_options as $value => $label ) {
echo "<option ".selected( $_GET['orderby'], $value )."
value='$value'>$label</option>";
}
?>
</select>
<select name="order">
<?php
$order_options = array(
'DESC' => 'Descending',
'ASC' => 'Ascending',
);
foreach( $order_options as $value => $label ) {
echo "<option ".selected( $_GET['order'], $value )."
value='$value'>$label</option>";
}
?>
</select>
<input type='submit' value='Filter!'>
</form>
```
Consequently, the page the same code is embedded only returns a blank page showing no code in the source view. I also used Search & Filter plugin only to get the same blank page.
I cannot resolve this issue alone. Please someone help me correct the code.
After editing front-page.php based on the comments given:
```
<?php echo get_template_part('head') ?>
<body <?php body_class(); ?>>
<?php get_header(); ?>
<main>
<div id="main">
<div class="outer">
<ul class="breadcrumb"><?php breadcrumb() ?></ul>
<form class="post-filters"><select name="orderby"><?php
$orderby_options = array(
'post_date' => 'Order By Date',
'title' => 'Order By Title',
'rand' => 'Random Order'
);
$orderby = isset( $_GET['orderby'] ) ? sanitize_text_field( $_GET['orderby'] ) : 'default value';
foreach($orderby_options as $value => $label):
echo '<option '.selected($orderby, $value, false).' value="'.$value.'">'.$label.'</option>';
endforeach;
?>
<input type="submit" value="Filter">
</form>
<div class="inner">
<?php
$filter = array('parent' => 0, 'hide_empty' => 0, 'exclude' => (5));
$categories = get_categories($filter);
shuffle($categories);
if($categories):
foreach($categories as $category):
$catName = $category->cat_name;
$catFilter = array(
'category_name' => $catName
);
echo '<div class="section"><section><h2 data-aos="fade-up">'.$catName.'</h2>'.category_description(get_cat_ID($catName)).'<div class="wrapper">';
$catquery = new WP_Query($catFilter);
if($catquery->have_posts()):
while($catquery->have_posts()): $catquery->the_post();
if(has_post_thumbnail()){
echo '<div class="item" data-aos="fade-down"><a href="'.get_the_permalink().'"><h3>'.get_the_post_thumbnail().'<span class="date">'.get_the_date().'</span></h3>'.'<dl><dt>'.get_the_title().'</dt><dd>'.get_the_content().'</dd></dl></a></div>';
}else{
echo '<div class="item" data-aos="fade-down"><a href="'.get_the_permalink().'"><h3>No Image Available<span class="date">'.get_the_date().'</span></h3>'.'<dl><dt>'.get_the_title().'</dt><dd>'.get_the_content().'</dd></dl></a></div>';
}
endwhile;
endif;
echo '</div></section></div>';
wp_reset_postdata();
endforeach;
endif;
?>
</div>
<div class="banner-ads" data-aos="fade-down"><section><?php the_ad_group(12); ?></section></div>
<?php
$catObj = get_category_by_slug('news');
$catName = $catObj->name;
echo '<div class="inner" id="'.$catName.'"><div class="wrapper"><h2 data-aos="fade-up">'.$catName.'</h2>';
$catquery = new WP_Query('category_name="news"');
if($catquery->have_posts()):
while($catquery->have_posts()): $catquery->the_post();
if(has_post_thumbnail()){
echo '<dl data-aos="fade-right"><dt style="background: url('.get_the_post_thumbnail_url().')"></dt>';
}else{
echo '<dl data-aos="fade-right"><dt><span>No Image Available</span></dt>';
}
echo '<dd>'.'<span class="date">'.get_the_date().'</span><br class="sp">';
$tags = get_the_tags();
foreach($tags as $tag){
$tagName = $tag->name;
echo '<span class="tag">'.$tagName.'</span>';
}
echo get_the_content().'</dd></dl>';
endwhile;
endif;
echo '</div></div>';
?>
</div>
</div>
</main>
<?php get_footer(); ?>
</body>
``` | It turns out the cause of this lingering filter problem was to do with the way WordPress was set up as well as the argument of `WP_Query`. Once I changed the *Your Homepage Displays* setting to the latest posts and renamed `front-page.php` to be `index.php`, the filter began working and the blank page no longer showed.
Concerning the post filter, declaring the orderby parameter as part of the argument of `WP_Query` got it working. The code for the filter is as follows:
```
<form class="post-filters">
<select name="orderby">
<?php
$orderby_options = array(
'post_date' => 'Order By Date',
'post_title' => 'Order By Title',
'rand' => 'Random Order'
);
foreach($orderby_options as $value => $label):
echo '<option '.selected($_GET['orderby'], $value, false).' value="'.$value.'">'.$label.'</option>';
endforeach;
?>
</select>
<input type="submit" value="Filter">
</form>
``` |
342,376 | <p>I am trying to implement pagination for category items listing archive.php page. But this does not work. Below is the code that I am using.</p>
<p><strong>Custom Query</strong>:</p>
<pre><code>$cat = single_cat_title("", false);
$cat_ID = get_cat_ID ($cat);
$args = array(
'posts_per_page' => '2',
'post_type' => 'mathematics',
'cat' => $cat_ID,
'paged' => get_query_var('paged',1)
);
$posts = new WP_Query($args);
</code></pre>
<p><strong>Pagination code</strong>:</p>
<pre><code>echo paginate_links(array(
'base' => '%_%',
'format' => '?paged=%#%',
'total' => $posts->max_num_pages,
));
</code></pre>
<p>When the page is loaded, it displays the pagination links but when I click on next it gives 404 error.</p>
<p>main page link: <a href="http://mk.local/category/mathematics/average/" rel="nofollow noreferrer">http://mk.local/category/mathematics/average/</a>
when next is clicked : <a href="http://mk.local/category/mathematics/average/?paged=2" rel="nofollow noreferrer">http://mk.local/category/mathematics/average/?paged=2</a></p>
<p>I have already tried updating permalinks</p>
| [
{
"answer_id": 342366,
"author": "Castiblanco",
"author_id": 44370,
"author_profile": "https://wordpress.stackexchange.com/users/44370",
"pm_score": 0,
"selected": false,
"text": "<p>You are removing necessary parts of the code, you started opening <code>form</code> and <code>select</code> HTML elements, but you never close them, use the full code:</p>\n\n<pre><code><form class='post-filters'>\n <select name=\"orderby\">\n <?php\n $orderby_options = array(\n 'post_date' => 'Order By Date',\n 'post_title' => 'Order By Title',\n 'rand' => 'Random Order',\n );\n foreach( $orderby_options as $value => $label ) {\n echo \"<option \".selected( $_GET['orderby'], $value ).\" value='$value'>$label</option>\";\n }\n ?>\n </select>\n <select name=\"order\">\n <?php\n $order_options = array(\n 'DESC' => 'Descending',\n 'ASC' => 'Ascending',\n );\n foreach( $order_options as $value => $label ) {\n echo \"<option \".selected( $_GET['order'], $value ).\" value='$value'>$label</option>\";\n }\n ?>\n </select>\n <select name=\"thumbnail\">\n <?php\n $order_options = array(\n 'all' => 'All Posts',\n 'only_thumbnailed' => 'Posts With Thumbnails',\n );\n foreach( $order_options as $value => $label ) {\n echo \"<option \".selected( $_GET['thumbnail'], $value ).\" value='$value'>$label</option>\";\n }\n ?>\n </select>\n <input type='submit' value='Filter!'>\n</form>\n</code></pre>\n\n<p>Then if you want to remove things you think you don't need, you can turn on the <a href=\"https://codex.wordpress.org/WP_DEBUG\" rel=\"nofollow noreferrer\">Debug</a> to see what is falling and why you are getting a blank page, in this case, you are getting a blank page because your code is pretty incomplete and many things should be failing.</p>\n"
},
{
"answer_id": 342461,
"author": "Fizzler",
"author_id": 141638,
"author_profile": "https://wordpress.stackexchange.com/users/141638",
"pm_score": 1,
"selected": false,
"text": "<p>It turns out the cause of this lingering filter problem was to do with the way WordPress was set up as well as the argument of <code>WP_Query</code>. Once I changed the <em>Your Homepage Displays</em> setting to the latest posts and renamed <code>front-page.php</code> to be <code>index.php</code>, the filter began working and the blank page no longer showed.</p>\n\n<p>Concerning the post filter, declaring the orderby parameter as part of the argument of <code>WP_Query</code> got it working. The code for the filter is as follows:</p>\n\n<pre><code><form class=\"post-filters\">\n <select name=\"orderby\">\n <?php\n $orderby_options = array(\n 'post_date' => 'Order By Date',\n 'post_title' => 'Order By Title',\n 'rand' => 'Random Order'\n );\n foreach($orderby_options as $value => $label):\n echo '<option '.selected($_GET['orderby'], $value, false).' value=\"'.$value.'\">'.$label.'</option>';\n endforeach;\n ?>\n </select>\n <input type=\"submit\" value=\"Filter\">\n</form>\n</code></pre>\n"
}
] | 2019/07/08 | [
"https://wordpress.stackexchange.com/questions/342376",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/171484/"
] | I am trying to implement pagination for category items listing archive.php page. But this does not work. Below is the code that I am using.
**Custom Query**:
```
$cat = single_cat_title("", false);
$cat_ID = get_cat_ID ($cat);
$args = array(
'posts_per_page' => '2',
'post_type' => 'mathematics',
'cat' => $cat_ID,
'paged' => get_query_var('paged',1)
);
$posts = new WP_Query($args);
```
**Pagination code**:
```
echo paginate_links(array(
'base' => '%_%',
'format' => '?paged=%#%',
'total' => $posts->max_num_pages,
));
```
When the page is loaded, it displays the pagination links but when I click on next it gives 404 error.
main page link: <http://mk.local/category/mathematics/average/>
when next is clicked : <http://mk.local/category/mathematics/average/?paged=2>
I have already tried updating permalinks | It turns out the cause of this lingering filter problem was to do with the way WordPress was set up as well as the argument of `WP_Query`. Once I changed the *Your Homepage Displays* setting to the latest posts and renamed `front-page.php` to be `index.php`, the filter began working and the blank page no longer showed.
Concerning the post filter, declaring the orderby parameter as part of the argument of `WP_Query` got it working. The code for the filter is as follows:
```
<form class="post-filters">
<select name="orderby">
<?php
$orderby_options = array(
'post_date' => 'Order By Date',
'post_title' => 'Order By Title',
'rand' => 'Random Order'
);
foreach($orderby_options as $value => $label):
echo '<option '.selected($_GET['orderby'], $value, false).' value="'.$value.'">'.$label.'</option>';
endforeach;
?>
</select>
<input type="submit" value="Filter">
</form>
``` |
342,393 | <p>How to send an invoice with detailes to the customers when they payed via credit card using Stripe.
I want when someone buy something, he or she will get an confirmation email with the details. </p>
<p>Note: if it's possible can the customers pay via invoice with Credit Card instead of direct with Credit Card using Stripe, because I want to avoid Stripe fees.</p>
| [
{
"answer_id": 342366,
"author": "Castiblanco",
"author_id": 44370,
"author_profile": "https://wordpress.stackexchange.com/users/44370",
"pm_score": 0,
"selected": false,
"text": "<p>You are removing necessary parts of the code, you started opening <code>form</code> and <code>select</code> HTML elements, but you never close them, use the full code:</p>\n\n<pre><code><form class='post-filters'>\n <select name=\"orderby\">\n <?php\n $orderby_options = array(\n 'post_date' => 'Order By Date',\n 'post_title' => 'Order By Title',\n 'rand' => 'Random Order',\n );\n foreach( $orderby_options as $value => $label ) {\n echo \"<option \".selected( $_GET['orderby'], $value ).\" value='$value'>$label</option>\";\n }\n ?>\n </select>\n <select name=\"order\">\n <?php\n $order_options = array(\n 'DESC' => 'Descending',\n 'ASC' => 'Ascending',\n );\n foreach( $order_options as $value => $label ) {\n echo \"<option \".selected( $_GET['order'], $value ).\" value='$value'>$label</option>\";\n }\n ?>\n </select>\n <select name=\"thumbnail\">\n <?php\n $order_options = array(\n 'all' => 'All Posts',\n 'only_thumbnailed' => 'Posts With Thumbnails',\n );\n foreach( $order_options as $value => $label ) {\n echo \"<option \".selected( $_GET['thumbnail'], $value ).\" value='$value'>$label</option>\";\n }\n ?>\n </select>\n <input type='submit' value='Filter!'>\n</form>\n</code></pre>\n\n<p>Then if you want to remove things you think you don't need, you can turn on the <a href=\"https://codex.wordpress.org/WP_DEBUG\" rel=\"nofollow noreferrer\">Debug</a> to see what is falling and why you are getting a blank page, in this case, you are getting a blank page because your code is pretty incomplete and many things should be failing.</p>\n"
},
{
"answer_id": 342461,
"author": "Fizzler",
"author_id": 141638,
"author_profile": "https://wordpress.stackexchange.com/users/141638",
"pm_score": 1,
"selected": false,
"text": "<p>It turns out the cause of this lingering filter problem was to do with the way WordPress was set up as well as the argument of <code>WP_Query</code>. Once I changed the <em>Your Homepage Displays</em> setting to the latest posts and renamed <code>front-page.php</code> to be <code>index.php</code>, the filter began working and the blank page no longer showed.</p>\n\n<p>Concerning the post filter, declaring the orderby parameter as part of the argument of <code>WP_Query</code> got it working. The code for the filter is as follows:</p>\n\n<pre><code><form class=\"post-filters\">\n <select name=\"orderby\">\n <?php\n $orderby_options = array(\n 'post_date' => 'Order By Date',\n 'post_title' => 'Order By Title',\n 'rand' => 'Random Order'\n );\n foreach($orderby_options as $value => $label):\n echo '<option '.selected($_GET['orderby'], $value, false).' value=\"'.$value.'\">'.$label.'</option>';\n endforeach;\n ?>\n </select>\n <input type=\"submit\" value=\"Filter\">\n</form>\n</code></pre>\n"
}
] | 2019/07/08 | [
"https://wordpress.stackexchange.com/questions/342393",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/171497/"
] | How to send an invoice with detailes to the customers when they payed via credit card using Stripe.
I want when someone buy something, he or she will get an confirmation email with the details.
Note: if it's possible can the customers pay via invoice with Credit Card instead of direct with Credit Card using Stripe, because I want to avoid Stripe fees. | It turns out the cause of this lingering filter problem was to do with the way WordPress was set up as well as the argument of `WP_Query`. Once I changed the *Your Homepage Displays* setting to the latest posts and renamed `front-page.php` to be `index.php`, the filter began working and the blank page no longer showed.
Concerning the post filter, declaring the orderby parameter as part of the argument of `WP_Query` got it working. The code for the filter is as follows:
```
<form class="post-filters">
<select name="orderby">
<?php
$orderby_options = array(
'post_date' => 'Order By Date',
'post_title' => 'Order By Title',
'rand' => 'Random Order'
);
foreach($orderby_options as $value => $label):
echo '<option '.selected($_GET['orderby'], $value, false).' value="'.$value.'">'.$label.'</option>';
endforeach;
?>
</select>
<input type="submit" value="Filter">
</form>
``` |
342,399 | <p>I'm working on a WP website with many CPTs and Custom Taxonomies, but also using the regular "post" post type for the regular blog section of the site.</p>
<p>I want the blog posts and archive and categories to have /blog/ in their permalink, but also want to specify permalink structure for the other CPTs without the /blog/ interfering.</p>
<p>for example:
I have an "events" CPT, which has a custom taxonomy named "ecat".</p>
<p>Now I got an archive page with permalink <strong>sitename.com/events</strong> working well</p>
<p>And the single event page has permalink like <strong>sitename.com/events/event-name</strong> as well.</p>
<p>But the custom taxonomy archive is in <strong>sitename.com/ecat/ategory-name</strong>.
I want the custom taxonomy to have the cpt slug in its permalink like: <strong>sitename.com/events/ecat/category-name</strong></p>
<p>Note: I don't want the single event to have the taxonomy term in its permalink.</p>
<p>My CPT registration Code: </p>
<pre><code> $labels = array(
'name' => _x( 'Events', 'Post Type General Name', 'textdomain' ),
'singular_name' => _x( 'Event', 'Post Type Singular Name', 'textdomain' ),
'menu_name' => __( 'Events', 'textdomain' ),
'name_admin_bar' => __( 'Event', 'textdomain' ),
'archives' => __( 'Item Archives', 'textdomain' ),
'attributes' => __( 'Item Attributes', 'textdomain' ),
'parent_item_colon' => __( 'Parent Item:', 'textdomain' ),
'all_items' => __( 'All Items', 'textdomain' ),
'add_new_item' => __( 'Add New Item', 'textdomain' ),
'add_new' => __( 'Add New', 'textdomain' ),
'new_item' => __( 'New Item', 'textdomain' ),
'edit_item' => __( 'Edit Item', 'textdomain' ),
'update_item' => __( 'Update Item', 'textdomain' ),
'view_item' => __( 'View Item', 'textdomain' ),
'view_items' => __( 'View Items', 'textdomain' ),
'search_items' => __( 'Search Item', 'textdomain' ),
'not_found' => __( 'Not found', 'textdomain' ),
'not_found_in_trash' => __( 'Not found in Trash', 'textdomain' ),
'featured_image' => __( 'Featured Image', 'textdomain' ),
'set_featured_image' => __( 'Set featured image', 'textdomain' ),
'remove_featured_image' => __( 'Remove featured image', 'textdomain' ),
'use_featured_image' => __( 'Use as featured image', 'textdomain' ),
'insert_into_item' => __( 'Insert into item', 'textdomain' ),
'uploaded_to_this_item' => __( 'Uploaded to this item', 'textdomain' ),
'items_list' => __( 'Items list', 'textdomain' ),
'items_list_navigation' => __( 'Items list navigation', 'textdomain' ),
'filter_items_list' => __( 'Filter items list', 'textdomain' ),
);
$args = array(
'label' => __( 'Event', 'textdomain' ),
'description' => __( 'Events custom post type', 'textdomain' ),
'labels' => $labels,
'supports' => array( 'title' ),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'menu_icon' => 'dashicons-calendar-alt',
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'page',
'show_in_rest' => false,
'rewrite' => array( 'slug' => 'events','with_front' => false ),
);
register_post_type( 'events', $args );
</code></pre>
<p>My Custom Taxonomy register code:</p>
<pre><code>//Event Categories
$labels = array(
'name' => _x( 'Events Categories', 'textdomain' ),
'singular_name' => _x( 'Events Category', 'textdomain' ),
'menu_name' => __( 'Events Categories', 'textdomain' ),
'all_items' => __( 'All Items', 'textdomain' ),
'parent_item' => __( 'Parent Item', 'textdomain' ),
'parent_item_colon' => __( 'Parent Item:', 'textdomain' ),
'new_item_name' => __( 'New Item Name', 'textdomain' ),
'add_new_item' => __( 'Add New Item', 'textdomain' ),
'edit_item' => __( 'Edit Item', 'textdomain' ),
'update_item' => __( 'Update Item', 'textdomain' ),
'view_item' => __( 'View Item', 'textdomain' ),
'separate_items_with_commas' => __( 'Separate items with commas', 'textdomain' ),
'add_or_remove_items' => __( 'Add or remove items', 'textdomain' ),
'choose_from_most_used' => __( 'Choose from the most used', 'textdomain' ),
'popular_items' => __( 'Popular Items', 'textdomain' ),
'search_items' => __( 'Search Items', 'textdomain' ),
'not_found' => __( 'Not Found', 'textdomain' ),
'no_terms' => __( 'No items', 'textdomain' ),
'items_list' => __( 'Items list', 'textdomain' ),
'items_list_navigation' => __( 'Items list navigation', 'textdomain' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_nav_menus' => true,
'show_tagcloud' => false,
'show_in_rest' => false,
);
register_taxonomy( 'ecat', array( 'events' ), $args );
</code></pre>
| [
{
"answer_id": 342366,
"author": "Castiblanco",
"author_id": 44370,
"author_profile": "https://wordpress.stackexchange.com/users/44370",
"pm_score": 0,
"selected": false,
"text": "<p>You are removing necessary parts of the code, you started opening <code>form</code> and <code>select</code> HTML elements, but you never close them, use the full code:</p>\n\n<pre><code><form class='post-filters'>\n <select name=\"orderby\">\n <?php\n $orderby_options = array(\n 'post_date' => 'Order By Date',\n 'post_title' => 'Order By Title',\n 'rand' => 'Random Order',\n );\n foreach( $orderby_options as $value => $label ) {\n echo \"<option \".selected( $_GET['orderby'], $value ).\" value='$value'>$label</option>\";\n }\n ?>\n </select>\n <select name=\"order\">\n <?php\n $order_options = array(\n 'DESC' => 'Descending',\n 'ASC' => 'Ascending',\n );\n foreach( $order_options as $value => $label ) {\n echo \"<option \".selected( $_GET['order'], $value ).\" value='$value'>$label</option>\";\n }\n ?>\n </select>\n <select name=\"thumbnail\">\n <?php\n $order_options = array(\n 'all' => 'All Posts',\n 'only_thumbnailed' => 'Posts With Thumbnails',\n );\n foreach( $order_options as $value => $label ) {\n echo \"<option \".selected( $_GET['thumbnail'], $value ).\" value='$value'>$label</option>\";\n }\n ?>\n </select>\n <input type='submit' value='Filter!'>\n</form>\n</code></pre>\n\n<p>Then if you want to remove things you think you don't need, you can turn on the <a href=\"https://codex.wordpress.org/WP_DEBUG\" rel=\"nofollow noreferrer\">Debug</a> to see what is falling and why you are getting a blank page, in this case, you are getting a blank page because your code is pretty incomplete and many things should be failing.</p>\n"
},
{
"answer_id": 342461,
"author": "Fizzler",
"author_id": 141638,
"author_profile": "https://wordpress.stackexchange.com/users/141638",
"pm_score": 1,
"selected": false,
"text": "<p>It turns out the cause of this lingering filter problem was to do with the way WordPress was set up as well as the argument of <code>WP_Query</code>. Once I changed the <em>Your Homepage Displays</em> setting to the latest posts and renamed <code>front-page.php</code> to be <code>index.php</code>, the filter began working and the blank page no longer showed.</p>\n\n<p>Concerning the post filter, declaring the orderby parameter as part of the argument of <code>WP_Query</code> got it working. The code for the filter is as follows:</p>\n\n<pre><code><form class=\"post-filters\">\n <select name=\"orderby\">\n <?php\n $orderby_options = array(\n 'post_date' => 'Order By Date',\n 'post_title' => 'Order By Title',\n 'rand' => 'Random Order'\n );\n foreach($orderby_options as $value => $label):\n echo '<option '.selected($_GET['orderby'], $value, false).' value=\"'.$value.'\">'.$label.'</option>';\n endforeach;\n ?>\n </select>\n <input type=\"submit\" value=\"Filter\">\n</form>\n</code></pre>\n"
}
] | 2019/07/08 | [
"https://wordpress.stackexchange.com/questions/342399",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/171506/"
] | I'm working on a WP website with many CPTs and Custom Taxonomies, but also using the regular "post" post type for the regular blog section of the site.
I want the blog posts and archive and categories to have /blog/ in their permalink, but also want to specify permalink structure for the other CPTs without the /blog/ interfering.
for example:
I have an "events" CPT, which has a custom taxonomy named "ecat".
Now I got an archive page with permalink **sitename.com/events** working well
And the single event page has permalink like **sitename.com/events/event-name** as well.
But the custom taxonomy archive is in **sitename.com/ecat/ategory-name**.
I want the custom taxonomy to have the cpt slug in its permalink like: **sitename.com/events/ecat/category-name**
Note: I don't want the single event to have the taxonomy term in its permalink.
My CPT registration Code:
```
$labels = array(
'name' => _x( 'Events', 'Post Type General Name', 'textdomain' ),
'singular_name' => _x( 'Event', 'Post Type Singular Name', 'textdomain' ),
'menu_name' => __( 'Events', 'textdomain' ),
'name_admin_bar' => __( 'Event', 'textdomain' ),
'archives' => __( 'Item Archives', 'textdomain' ),
'attributes' => __( 'Item Attributes', 'textdomain' ),
'parent_item_colon' => __( 'Parent Item:', 'textdomain' ),
'all_items' => __( 'All Items', 'textdomain' ),
'add_new_item' => __( 'Add New Item', 'textdomain' ),
'add_new' => __( 'Add New', 'textdomain' ),
'new_item' => __( 'New Item', 'textdomain' ),
'edit_item' => __( 'Edit Item', 'textdomain' ),
'update_item' => __( 'Update Item', 'textdomain' ),
'view_item' => __( 'View Item', 'textdomain' ),
'view_items' => __( 'View Items', 'textdomain' ),
'search_items' => __( 'Search Item', 'textdomain' ),
'not_found' => __( 'Not found', 'textdomain' ),
'not_found_in_trash' => __( 'Not found in Trash', 'textdomain' ),
'featured_image' => __( 'Featured Image', 'textdomain' ),
'set_featured_image' => __( 'Set featured image', 'textdomain' ),
'remove_featured_image' => __( 'Remove featured image', 'textdomain' ),
'use_featured_image' => __( 'Use as featured image', 'textdomain' ),
'insert_into_item' => __( 'Insert into item', 'textdomain' ),
'uploaded_to_this_item' => __( 'Uploaded to this item', 'textdomain' ),
'items_list' => __( 'Items list', 'textdomain' ),
'items_list_navigation' => __( 'Items list navigation', 'textdomain' ),
'filter_items_list' => __( 'Filter items list', 'textdomain' ),
);
$args = array(
'label' => __( 'Event', 'textdomain' ),
'description' => __( 'Events custom post type', 'textdomain' ),
'labels' => $labels,
'supports' => array( 'title' ),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'menu_icon' => 'dashicons-calendar-alt',
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'page',
'show_in_rest' => false,
'rewrite' => array( 'slug' => 'events','with_front' => false ),
);
register_post_type( 'events', $args );
```
My Custom Taxonomy register code:
```
//Event Categories
$labels = array(
'name' => _x( 'Events Categories', 'textdomain' ),
'singular_name' => _x( 'Events Category', 'textdomain' ),
'menu_name' => __( 'Events Categories', 'textdomain' ),
'all_items' => __( 'All Items', 'textdomain' ),
'parent_item' => __( 'Parent Item', 'textdomain' ),
'parent_item_colon' => __( 'Parent Item:', 'textdomain' ),
'new_item_name' => __( 'New Item Name', 'textdomain' ),
'add_new_item' => __( 'Add New Item', 'textdomain' ),
'edit_item' => __( 'Edit Item', 'textdomain' ),
'update_item' => __( 'Update Item', 'textdomain' ),
'view_item' => __( 'View Item', 'textdomain' ),
'separate_items_with_commas' => __( 'Separate items with commas', 'textdomain' ),
'add_or_remove_items' => __( 'Add or remove items', 'textdomain' ),
'choose_from_most_used' => __( 'Choose from the most used', 'textdomain' ),
'popular_items' => __( 'Popular Items', 'textdomain' ),
'search_items' => __( 'Search Items', 'textdomain' ),
'not_found' => __( 'Not Found', 'textdomain' ),
'no_terms' => __( 'No items', 'textdomain' ),
'items_list' => __( 'Items list', 'textdomain' ),
'items_list_navigation' => __( 'Items list navigation', 'textdomain' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_nav_menus' => true,
'show_tagcloud' => false,
'show_in_rest' => false,
);
register_taxonomy( 'ecat', array( 'events' ), $args );
``` | It turns out the cause of this lingering filter problem was to do with the way WordPress was set up as well as the argument of `WP_Query`. Once I changed the *Your Homepage Displays* setting to the latest posts and renamed `front-page.php` to be `index.php`, the filter began working and the blank page no longer showed.
Concerning the post filter, declaring the orderby parameter as part of the argument of `WP_Query` got it working. The code for the filter is as follows:
```
<form class="post-filters">
<select name="orderby">
<?php
$orderby_options = array(
'post_date' => 'Order By Date',
'post_title' => 'Order By Title',
'rand' => 'Random Order'
);
foreach($orderby_options as $value => $label):
echo '<option '.selected($_GET['orderby'], $value, false).' value="'.$value.'">'.$label.'</option>';
endforeach;
?>
</select>
<input type="submit" value="Filter">
</form>
``` |
342,409 | <p>I have found a code here that will randomize the date of all posts to a random date. Here is the code that someone has posted:</p>
<pre><code><?php
/**
* Plugin Name: WPSE 259750 Random Dates
* Description: On activation, change the dates of all posts to random dates
*/
//* We want to do this only once, so add hook to plugin activation
register_activation_hook( __FILE__ , 'wpse_259750_activation' );
function wpse_259750_activation() {
//* Get all the posts
$posts = get_posts( array( 'numberposts' => -1, 'post_status' => 'any' ) );
foreach( $posts as $post ) {
//* Generate a random date between January 1st, 2015 and now
$random_date = mt_rand( strtotime( '1 January 2015' ), time() );
$date_format = 'Y-m-d H:i:s';
//* Format the date that WordPress likes
$post_date = date( $date_format, $random_date );
//* We only want to update the post date
$update = array(
'ID' => $post->ID,
'post_date' => $post_date,
'post_date_gmt' => null,
);
//* Update the post
wp_update_post( $update );
}
}
</code></pre>
<p>How would you do the same, but only randomize the time without randomizing the date of the post. So, the posts should keep the same date they currently have, but only randomize the time of the day they were posted.</p>
<p>I tried changing the post_date to post_time and changing the random_date to time() only. Then of course changing the date_format to 'H:i:s' however it did nothing.</p>
| [
{
"answer_id": 342366,
"author": "Castiblanco",
"author_id": 44370,
"author_profile": "https://wordpress.stackexchange.com/users/44370",
"pm_score": 0,
"selected": false,
"text": "<p>You are removing necessary parts of the code, you started opening <code>form</code> and <code>select</code> HTML elements, but you never close them, use the full code:</p>\n\n<pre><code><form class='post-filters'>\n <select name=\"orderby\">\n <?php\n $orderby_options = array(\n 'post_date' => 'Order By Date',\n 'post_title' => 'Order By Title',\n 'rand' => 'Random Order',\n );\n foreach( $orderby_options as $value => $label ) {\n echo \"<option \".selected( $_GET['orderby'], $value ).\" value='$value'>$label</option>\";\n }\n ?>\n </select>\n <select name=\"order\">\n <?php\n $order_options = array(\n 'DESC' => 'Descending',\n 'ASC' => 'Ascending',\n );\n foreach( $order_options as $value => $label ) {\n echo \"<option \".selected( $_GET['order'], $value ).\" value='$value'>$label</option>\";\n }\n ?>\n </select>\n <select name=\"thumbnail\">\n <?php\n $order_options = array(\n 'all' => 'All Posts',\n 'only_thumbnailed' => 'Posts With Thumbnails',\n );\n foreach( $order_options as $value => $label ) {\n echo \"<option \".selected( $_GET['thumbnail'], $value ).\" value='$value'>$label</option>\";\n }\n ?>\n </select>\n <input type='submit' value='Filter!'>\n</form>\n</code></pre>\n\n<p>Then if you want to remove things you think you don't need, you can turn on the <a href=\"https://codex.wordpress.org/WP_DEBUG\" rel=\"nofollow noreferrer\">Debug</a> to see what is falling and why you are getting a blank page, in this case, you are getting a blank page because your code is pretty incomplete and many things should be failing.</p>\n"
},
{
"answer_id": 342461,
"author": "Fizzler",
"author_id": 141638,
"author_profile": "https://wordpress.stackexchange.com/users/141638",
"pm_score": 1,
"selected": false,
"text": "<p>It turns out the cause of this lingering filter problem was to do with the way WordPress was set up as well as the argument of <code>WP_Query</code>. Once I changed the <em>Your Homepage Displays</em> setting to the latest posts and renamed <code>front-page.php</code> to be <code>index.php</code>, the filter began working and the blank page no longer showed.</p>\n\n<p>Concerning the post filter, declaring the orderby parameter as part of the argument of <code>WP_Query</code> got it working. The code for the filter is as follows:</p>\n\n<pre><code><form class=\"post-filters\">\n <select name=\"orderby\">\n <?php\n $orderby_options = array(\n 'post_date' => 'Order By Date',\n 'post_title' => 'Order By Title',\n 'rand' => 'Random Order'\n );\n foreach($orderby_options as $value => $label):\n echo '<option '.selected($_GET['orderby'], $value, false).' value=\"'.$value.'\">'.$label.'</option>';\n endforeach;\n ?>\n </select>\n <input type=\"submit\" value=\"Filter\">\n</form>\n</code></pre>\n"
}
] | 2019/07/08 | [
"https://wordpress.stackexchange.com/questions/342409",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/171508/"
] | I have found a code here that will randomize the date of all posts to a random date. Here is the code that someone has posted:
```
<?php
/**
* Plugin Name: WPSE 259750 Random Dates
* Description: On activation, change the dates of all posts to random dates
*/
//* We want to do this only once, so add hook to plugin activation
register_activation_hook( __FILE__ , 'wpse_259750_activation' );
function wpse_259750_activation() {
//* Get all the posts
$posts = get_posts( array( 'numberposts' => -1, 'post_status' => 'any' ) );
foreach( $posts as $post ) {
//* Generate a random date between January 1st, 2015 and now
$random_date = mt_rand( strtotime( '1 January 2015' ), time() );
$date_format = 'Y-m-d H:i:s';
//* Format the date that WordPress likes
$post_date = date( $date_format, $random_date );
//* We only want to update the post date
$update = array(
'ID' => $post->ID,
'post_date' => $post_date,
'post_date_gmt' => null,
);
//* Update the post
wp_update_post( $update );
}
}
```
How would you do the same, but only randomize the time without randomizing the date of the post. So, the posts should keep the same date they currently have, but only randomize the time of the day they were posted.
I tried changing the post\_date to post\_time and changing the random\_date to time() only. Then of course changing the date\_format to 'H:i:s' however it did nothing. | It turns out the cause of this lingering filter problem was to do with the way WordPress was set up as well as the argument of `WP_Query`. Once I changed the *Your Homepage Displays* setting to the latest posts and renamed `front-page.php` to be `index.php`, the filter began working and the blank page no longer showed.
Concerning the post filter, declaring the orderby parameter as part of the argument of `WP_Query` got it working. The code for the filter is as follows:
```
<form class="post-filters">
<select name="orderby">
<?php
$orderby_options = array(
'post_date' => 'Order By Date',
'post_title' => 'Order By Title',
'rand' => 'Random Order'
);
foreach($orderby_options as $value => $label):
echo '<option '.selected($_GET['orderby'], $value, false).' value="'.$value.'">'.$label.'</option>';
endforeach;
?>
</select>
<input type="submit" value="Filter">
</form>
``` |
342,433 | <p>I'm struggling to get tabbed plugin settings, created with WordPress Settings API to work.</p>
<p>The first tab saves settings correctly. However, every time when I click on "Save Changes" button for any other tab, a white screen with the following error appears:</p>
<blockquote>
<p>ERROR: Options page not found</p>
</blockquote>
<p>Chrome and Apache log show POST 500 error. I see that form data to submit appears to be correct and according to what is submitted for the first tab that works <code>general_section</code> :</p>
<pre><code>option_page: account_section
action: update
_wpnonce: 2d40b0a357
_wp_http_referer: /staging/wp-admin/options-general.php?page=woo-extra-settings&tab=account
eswc_settingz[eswc_redirect]: 1
submit: Save Changes
</code></pre>
<p>The fields are registered only when the proper tab is selected to avoid resetting values in other tabs to defaults on save.</p>
<p>The code from this topic is included in my example, but it didn't fix the problem:</p>
<p><a href="https://wordpress.stackexchange.com/questions/139660/error-options-page-not-found-on-settings-page-submission-for-an-oop-plugin">"Error: Options Page Not Found" on Settings Page Submission for an OOP Plugin</a></p>
<p>I used PHP console extension for Chrome and a plugin to print values to Chrome console for troubleshooting, for example:</p>
<pre><code>PC::debug( 'general', 'tab name' );
</code></pre>
<p>This is now commented. The code can be used as a minimal part of my plugin to generate a 2-tab settings page in the default "Settings" menu and reproduce the issue that I'm having.</p>
<p>On tab activation, the console returns the following values (<code>whitelist_custom_options_page</code> function doesn't execute):</p>
<p>"General" (1st tab):</p>
<pre><code>tab name: general
add settings section - page: woo-extra-settings
add settings section - id: general_section
</code></pre>
<p>"Account" (2nd tab)</p>
<pre><code>tab name: account
add settings section - page: woo-extra-settings
add settings section - id: account_section
</code></pre>
<p>On settings save, the values are:</p>
<p>"General" (1st tab):</p>
<pre><code>tab name: general
add settings section - page: woo-extra-settings
add settings section - id: general_section
whitelist page: woo-extra-settings
whitelist section: general_section
whitelist option: eswc_settingz
</code></pre>
<p>For "Account" (2nd tab) the values are all the same, which means that on saving the settings, my code incorrectly perceives any tab as 1st tab, what is the reason for the problem that I have.</p>
<p>How can I fix this issue in a way that is close to my current implementation?</p>
<p>Here is the code:</p>
<pre><code>class extra_settings_settings {
private $options;
private $settings_page_name;
private $settings_menu_name;
public function __construct() {
if ( is_admin() ) {
$this->settings_page_name = 'woo-extra-settings';
$this->settings_menu_name = 'Woo Extra Settings';
// Tracks new sections for whitelist_custom_options_page()
$this->page_sections = array();
// Must run after option_update_filter(), so priority > 10
add_action( 'whitelist_options', array( $this, 'whitelist_custom_options_page' ),11 );
// Initialize and register settings.
add_action( 'admin_init', array( $this, 'display_options' ) );
// Add settings page.
add_action( 'admin_menu', array( $this, 'add_settings_page' ) );
}
}
public function display_options() {
$active_tab = isset( $_GET[ 'tab' ] ) ? $_GET[ 'tab' ] : 'general';
if ( $active_tab == 'general' ) {
//PC::debug( 'general', 'tab name:' );
register_setting( 'general_section', 'eswc_settingz', array( $this, 'sanitize_general' ) );
// ID / title / cb / page
$this->add_settings_section( 'general_section', null, array( $this, 'general_section_cb' ), $this->settings_page_name );
// ID / title / cb / page / section /args
add_settings_field( 'eswc_kill_gutenberg', __( 'Gutenberg', 'extra-settings-for-woocommerce' ), array( $this, 'eswc_kill_gutenberg_cb' ), $this->settings_page_name, 'general_section' );
add_settings_field( 'eswc_change_email_author', __( 'WP core email author', 'extra-settings-for-woocommerce' ), array( $this, 'eswc_change_email_author_cb' ), $this->settings_page_name, 'general_section' );
} else if ( $active_tab == 'account' ) {
//PC::debug( 'account', 'tab name:' );
register_setting( 'account_section', 'eswc_settingz', array( $this, 'sanitize_account' ) );
$this->add_settings_section( 'account_section', null, array( $this, 'account_section_cb' ), $this->settings_page_name );
add_settings_field( 'eswc_redirect', __( 'Login redirect', 'extra-settings-for-woocommerce' ), array( $this, 'eswc_redirect_cb' ), $this->settings_page_name, 'account_section' );
}
}
public function add_settings_page() {
// This page will be under "Settings"
$this->plugin_hook_suffix = add_options_page(
'Settings Admin', $this->settings_menu_name, 'manage_options', $this->settings_page_name, array( $this, 'create_settings_page' )
);
}
// Wrapper for wp's `add_settings_section()` that tracks custom sections
private function add_settings_section( $id, $title, $cb, $page ){
add_settings_section( $id, $title, $cb, $page );
if( $id != $page ){
if( !isset($this->page_sections[$page]))
//PC::debug( $page, 'add settings section - page:' );
//PC::debug( $id, 'add settings section - id:' );
$this->page_sections[$page] = array();
$this->page_sections[$page][$id] = $id;
}
}
// White-lists options on custom pages.
public function whitelist_custom_options_page( $whitelist_options ){
// Custom options are mapped by section id; Re-map by page slug.
foreach($this->page_sections as $page => $sections ){
//PC::debug( $page, 'whitelist page:' );
$whitelist_options[$page] = array();
foreach( $sections as $section )
//PC::debug( $section, 'whitelist section:' );
if( !empty( $whitelist_options[$section] ) )
foreach( $whitelist_options[$section] as $option )
$whitelist_options[$page][] = $option;
//PC::debug( $option, 'whitelist option:' );
}
return $whitelist_options;
}
/**
* Get the option that is saved or the default.
*
* @param string $index. The option we want to get.
*/
public function eswc_get_settings( $index = false ) {
$defaults = array ( 'eswc_kill_gutenberg' => false, 'eswc_change_email_author' => false, 'eswc_redirect' => false);
$settings = get_option( 'eswc_settingz', $defaults );
if ( $index && isset( $settings[ $index ] ) ) {
return $settings[ $index ];
}
return $settings;
}
public function create_settings_page() {
$this->options = $this->eswc_get_settings();
?>
<div class="wrap">
<h1>Extra Settings For WooCommerce</h1>
<?php
$active_tab = isset( $_GET[ 'tab' ] ) ? $_GET[ 'tab' ] : 'general';
?>
<h2 class="nav-tab-wrapper">
<a href="?page=woo-extra-settings&tab=general" class="nav-tab <?php echo $active_tab == 'general' ? 'nav-tab-active' : ''; ?>">General</a>
<a href="?page=woo-extra-settings&tab=account" class="nav-tab <?php echo $active_tab == 'account' ? 'nav-tab-active' : ''; ?>">Account</a>
<form method="post" action="options.php">
<?php
// Output nonce, action, and option_page fields for a settings page.
if( $active_tab == 'general' ) {
settings_fields( 'general_section' );
echo '<table class="form-table">';
do_settings_fields ($this->settings_page_name, 'general_section');
echo '</table>';
} else if ( $active_tab == 'account' ){
settings_fields( 'account_section' );
echo '<table class="form-table">';
do_settings_fields ($this->settings_page_name, 'account_section');
echo '</table>';
}
submit_button();
?>
</form>
</div>
<?php
}
/**
* Sanitize each setting field as needed
*
* @param array $input Contains all settings fields as array keys
*/
public function sanitize_general( $input ) {
$new_input = array();
if( isset( $input['eswc_kill_gutenberg'] ) )
$new_input['eswc_kill_gutenberg'] = ( $input['eswc_kill_gutenberg'] == 1 ? 1 : 0 );
if( isset( $input['eswc_change_email_author'] ) )
$new_input['eswc_change_email_author'] = ( $input['eswc_change_email_author'] == 1 ? 1 : 0 );
return $new_input;
}
public function sanitize_account( $input ) {
$new_input = array();
if( isset( $input['eswc_redirect'] ) )
$new_input['eswc_redirect'] = ( $input['eswc_redirect'] == 1 ? 1 : 0 );
return $new_input;
}
/**
* Get the settings option array and print one of its values
*/
public function eswc_kill_gutenberg_cb() {
printf(
'<fieldset>
<label><input id="eswc_kill_gutenberg" type="checkbox" name="eswc_settingz[eswc_kill_gutenberg]" value="1" %1$s />%2$s</label>
</fieldset>',
isset( $this->options['eswc_kill_gutenberg'] ) && ( 1 == $this->options['eswc_kill_gutenberg'] ) ? 'checked="checked" ':'',
__( 'Disable Gutenberg editor. Don\'t load Gutenberg-related stylesheets from WordPress core, WooCommerce and Storefront.', 'extra-settings-for-woocommerce' )
);
}
public function eswc_change_email_author_cb() {
printf(
'<fieldset>
<label><input id="eswc_change_email_author" type="checkbox" name="eswc_settingz[eswc_change_email_author]" value="1" %1$s />%2$s</label>
</fieldset>',
isset( $this->options['eswc_change_email_author'] ) && ( 1 == $this->options['eswc_change_email_author'] ) ? 'checked="checked" ':'',
__( 'Default is WordPress, [email protected]. Change to: "Site Title" from Settings > General, custom email entered below.', 'extra-settings-for-woocommerce' )
);
}
public function eswc_redirect_cb() {
printf(
'<fieldset>
<label><input id="eswc_redirect" type="checkbox" name="eswc_settingz[eswc_redirect]" value="1" %1$s />%2$s</label>
</fieldset>
<p class="description">%3$s</p>',
isset( $this->options['eswc_redirect'] ) && ( 1 == $this->options['eswc_redirect'] ) ? 'checked="checked" ':'',
__( 'After a successful login, redirect customers to previously visited page and users with admin access to dashboard.', 'extra-settings-for-woocommerce' ),
__( 'By default WooCommerce redirects to "My account" page. Customer roles: customer, subscriber. Admin access roles: administrator, shop_manager, editor, author, contributor.', 'extra-settings-for-woocommerce' )
);
}
}
$eswc_settingz_page = new extra_settings_settings();
</code></pre>
| [
{
"answer_id": 342457,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 3,
"selected": true,
"text": "<h2>First Thing</h2>\n\n<blockquote>\n <p>The fields are registered only when the proper tab is selected to\n avoid resetting values in other tabs to defaults on save.</p>\n</blockquote>\n\n<p>And because of that, you should pass the proper tab name/slug to the <code>wp-admin/options.php</code> page which is where the form is being submitted to.</p>\n\n<ol>\n<li><p>You can simply pass it as a query string in the form <code>action</code> attribute value:</p>\n\n<pre><code><form method=\"post\" action=\"<?php echo esc_url( add_query_arg( // wrapped for clarity\n 'tab', $active_tab, admin_url( 'options.php' )\n) ); ?>\">\n</code></pre></li>\n<li><p><em>Or</em> in <code>create_settings_page()</code>, add a hidden input field having the tab slug as the value:</p>\n\n<pre><code>echo '<input type=\"hidden\" name=\"tab\" value=\"' . esc_attr( $active_tab ) . '\" />';\nsubmit_button();\n</code></pre>\n\n<p>And then in the <code>display_options()</code>, retrieve the tab slug using <code>$_REQUEST</code>:</p>\n\n<pre><code>$active_tab = isset( $_REQUEST['tab'] ) ? $_REQUEST['tab'] : 'general';\n</code></pre></li>\n</ol>\n\n<p>Either way, the point is so that the <code>register_setting()</code> calls in the <code>display_options()</code> are invoked. Because otherwise, WordPress would throw the \"options page not found\" error because the option page is <em>not registered</em>.</p>\n\n<p>You could use the <code>whitelist_options</code> filter, but I'd rather want the <code>register_setting()</code> calls be invoked, so I removed this and the associated callback (<code>whitelist_custom_options_page()</code>):</p>\n\n<pre><code>add_action( 'whitelist_options', array( $this, 'whitelist_custom_options_page' ),11 );\n</code></pre>\n\n<h2>Second Thing</h2>\n\n<p>Since you're using the same database <em>option name</em> (<code>eswc_settingz</code>) for all tabs/fields, you should then merge the saved data with the one being submitted:</p>\n\n<pre><code>public function sanitize_general( $input ) {\n $new_input = (array) get_option( 'eswc_settingz' ); // get saved data\n ... add/update new data\n return $new_input;\n}\n\npublic function sanitize_account( $input ) {\n $new_input = (array) get_option( 'eswc_settingz' ); // get saved data\n ... add/update new data\n return $new_input;\n}\n</code></pre>\n\n<p>Or you could use <em>different</em> database option names:</p>\n\n<pre><code>register_setting( 'general_section', 'eswc_general_settingz', array( $this, 'sanitize_general' ) );\nregister_setting( 'account_section', 'eswc_account_settingz', array( $this, 'sanitize_account' ) );\n</code></pre>\n\n<p>Btw, is that \"z\" in the <code>settingz</code> a typo? Maybe it was meant to be <code>settings</code>?...</p>\n"
},
{
"answer_id": 342513,
"author": "Ryszard Jędraszyk",
"author_id": 153903,
"author_profile": "https://wordpress.stackexchange.com/users/153903",
"pm_score": 1,
"selected": false,
"text": "<p>The solution of Sally CJ perfectly solves the problems that I had, but one new problem appeared with this implementation.</p>\n\n<p>Merging settings from the current tab with all existing database settings (<code>eswc_settingz</code>) in this way makes the <code>$new_input</code> array populated with all the settings, instead of empty as before. <code>isset( $input['eswc_redirect']</code> returns <code>false</code> if the checkbox is unchecked. Previously it would result in an empty array item being submitted and the database would treat the checkbox as unchecked. Now as this item is already populated with database value, it must also save a 0 (unchecked) checkbox state to an array, so I added <code>else</code> statement:</p>\n\n<pre><code>public function sanitize_account( $input ) {\n // $new_input = (array) get_option( 'eswc_settingz' );\n $new_input = $this->eswc_get_settings();\n if( isset( $input['eswc_redirect'] ) ) {\n $new_input['eswc_redirect'] = ( $input['eswc_redirect'] == 1 ? 1 : 0 );\n } else {\n $new_input['eswc_redirect'] = 0;\n }\n return $new_input;\n}\n</code></pre>\n\n<p>Edit:</p>\n\n<p>I commented out one line and replaced it with a line below, to use my function <code>eswc_get_settings</code> that merges existing database settings with an array of defaults.</p>\n"
}
] | 2019/07/08 | [
"https://wordpress.stackexchange.com/questions/342433",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/153903/"
] | I'm struggling to get tabbed plugin settings, created with WordPress Settings API to work.
The first tab saves settings correctly. However, every time when I click on "Save Changes" button for any other tab, a white screen with the following error appears:
>
> ERROR: Options page not found
>
>
>
Chrome and Apache log show POST 500 error. I see that form data to submit appears to be correct and according to what is submitted for the first tab that works `general_section` :
```
option_page: account_section
action: update
_wpnonce: 2d40b0a357
_wp_http_referer: /staging/wp-admin/options-general.php?page=woo-extra-settings&tab=account
eswc_settingz[eswc_redirect]: 1
submit: Save Changes
```
The fields are registered only when the proper tab is selected to avoid resetting values in other tabs to defaults on save.
The code from this topic is included in my example, but it didn't fix the problem:
["Error: Options Page Not Found" on Settings Page Submission for an OOP Plugin](https://wordpress.stackexchange.com/questions/139660/error-options-page-not-found-on-settings-page-submission-for-an-oop-plugin)
I used PHP console extension for Chrome and a plugin to print values to Chrome console for troubleshooting, for example:
```
PC::debug( 'general', 'tab name' );
```
This is now commented. The code can be used as a minimal part of my plugin to generate a 2-tab settings page in the default "Settings" menu and reproduce the issue that I'm having.
On tab activation, the console returns the following values (`whitelist_custom_options_page` function doesn't execute):
"General" (1st tab):
```
tab name: general
add settings section - page: woo-extra-settings
add settings section - id: general_section
```
"Account" (2nd tab)
```
tab name: account
add settings section - page: woo-extra-settings
add settings section - id: account_section
```
On settings save, the values are:
"General" (1st tab):
```
tab name: general
add settings section - page: woo-extra-settings
add settings section - id: general_section
whitelist page: woo-extra-settings
whitelist section: general_section
whitelist option: eswc_settingz
```
For "Account" (2nd tab) the values are all the same, which means that on saving the settings, my code incorrectly perceives any tab as 1st tab, what is the reason for the problem that I have.
How can I fix this issue in a way that is close to my current implementation?
Here is the code:
```
class extra_settings_settings {
private $options;
private $settings_page_name;
private $settings_menu_name;
public function __construct() {
if ( is_admin() ) {
$this->settings_page_name = 'woo-extra-settings';
$this->settings_menu_name = 'Woo Extra Settings';
// Tracks new sections for whitelist_custom_options_page()
$this->page_sections = array();
// Must run after option_update_filter(), so priority > 10
add_action( 'whitelist_options', array( $this, 'whitelist_custom_options_page' ),11 );
// Initialize and register settings.
add_action( 'admin_init', array( $this, 'display_options' ) );
// Add settings page.
add_action( 'admin_menu', array( $this, 'add_settings_page' ) );
}
}
public function display_options() {
$active_tab = isset( $_GET[ 'tab' ] ) ? $_GET[ 'tab' ] : 'general';
if ( $active_tab == 'general' ) {
//PC::debug( 'general', 'tab name:' );
register_setting( 'general_section', 'eswc_settingz', array( $this, 'sanitize_general' ) );
// ID / title / cb / page
$this->add_settings_section( 'general_section', null, array( $this, 'general_section_cb' ), $this->settings_page_name );
// ID / title / cb / page / section /args
add_settings_field( 'eswc_kill_gutenberg', __( 'Gutenberg', 'extra-settings-for-woocommerce' ), array( $this, 'eswc_kill_gutenberg_cb' ), $this->settings_page_name, 'general_section' );
add_settings_field( 'eswc_change_email_author', __( 'WP core email author', 'extra-settings-for-woocommerce' ), array( $this, 'eswc_change_email_author_cb' ), $this->settings_page_name, 'general_section' );
} else if ( $active_tab == 'account' ) {
//PC::debug( 'account', 'tab name:' );
register_setting( 'account_section', 'eswc_settingz', array( $this, 'sanitize_account' ) );
$this->add_settings_section( 'account_section', null, array( $this, 'account_section_cb' ), $this->settings_page_name );
add_settings_field( 'eswc_redirect', __( 'Login redirect', 'extra-settings-for-woocommerce' ), array( $this, 'eswc_redirect_cb' ), $this->settings_page_name, 'account_section' );
}
}
public function add_settings_page() {
// This page will be under "Settings"
$this->plugin_hook_suffix = add_options_page(
'Settings Admin', $this->settings_menu_name, 'manage_options', $this->settings_page_name, array( $this, 'create_settings_page' )
);
}
// Wrapper for wp's `add_settings_section()` that tracks custom sections
private function add_settings_section( $id, $title, $cb, $page ){
add_settings_section( $id, $title, $cb, $page );
if( $id != $page ){
if( !isset($this->page_sections[$page]))
//PC::debug( $page, 'add settings section - page:' );
//PC::debug( $id, 'add settings section - id:' );
$this->page_sections[$page] = array();
$this->page_sections[$page][$id] = $id;
}
}
// White-lists options on custom pages.
public function whitelist_custom_options_page( $whitelist_options ){
// Custom options are mapped by section id; Re-map by page slug.
foreach($this->page_sections as $page => $sections ){
//PC::debug( $page, 'whitelist page:' );
$whitelist_options[$page] = array();
foreach( $sections as $section )
//PC::debug( $section, 'whitelist section:' );
if( !empty( $whitelist_options[$section] ) )
foreach( $whitelist_options[$section] as $option )
$whitelist_options[$page][] = $option;
//PC::debug( $option, 'whitelist option:' );
}
return $whitelist_options;
}
/**
* Get the option that is saved or the default.
*
* @param string $index. The option we want to get.
*/
public function eswc_get_settings( $index = false ) {
$defaults = array ( 'eswc_kill_gutenberg' => false, 'eswc_change_email_author' => false, 'eswc_redirect' => false);
$settings = get_option( 'eswc_settingz', $defaults );
if ( $index && isset( $settings[ $index ] ) ) {
return $settings[ $index ];
}
return $settings;
}
public function create_settings_page() {
$this->options = $this->eswc_get_settings();
?>
<div class="wrap">
<h1>Extra Settings For WooCommerce</h1>
<?php
$active_tab = isset( $_GET[ 'tab' ] ) ? $_GET[ 'tab' ] : 'general';
?>
<h2 class="nav-tab-wrapper">
<a href="?page=woo-extra-settings&tab=general" class="nav-tab <?php echo $active_tab == 'general' ? 'nav-tab-active' : ''; ?>">General</a>
<a href="?page=woo-extra-settings&tab=account" class="nav-tab <?php echo $active_tab == 'account' ? 'nav-tab-active' : ''; ?>">Account</a>
<form method="post" action="options.php">
<?php
// Output nonce, action, and option_page fields for a settings page.
if( $active_tab == 'general' ) {
settings_fields( 'general_section' );
echo '<table class="form-table">';
do_settings_fields ($this->settings_page_name, 'general_section');
echo '</table>';
} else if ( $active_tab == 'account' ){
settings_fields( 'account_section' );
echo '<table class="form-table">';
do_settings_fields ($this->settings_page_name, 'account_section');
echo '</table>';
}
submit_button();
?>
</form>
</div>
<?php
}
/**
* Sanitize each setting field as needed
*
* @param array $input Contains all settings fields as array keys
*/
public function sanitize_general( $input ) {
$new_input = array();
if( isset( $input['eswc_kill_gutenberg'] ) )
$new_input['eswc_kill_gutenberg'] = ( $input['eswc_kill_gutenberg'] == 1 ? 1 : 0 );
if( isset( $input['eswc_change_email_author'] ) )
$new_input['eswc_change_email_author'] = ( $input['eswc_change_email_author'] == 1 ? 1 : 0 );
return $new_input;
}
public function sanitize_account( $input ) {
$new_input = array();
if( isset( $input['eswc_redirect'] ) )
$new_input['eswc_redirect'] = ( $input['eswc_redirect'] == 1 ? 1 : 0 );
return $new_input;
}
/**
* Get the settings option array and print one of its values
*/
public function eswc_kill_gutenberg_cb() {
printf(
'<fieldset>
<label><input id="eswc_kill_gutenberg" type="checkbox" name="eswc_settingz[eswc_kill_gutenberg]" value="1" %1$s />%2$s</label>
</fieldset>',
isset( $this->options['eswc_kill_gutenberg'] ) && ( 1 == $this->options['eswc_kill_gutenberg'] ) ? 'checked="checked" ':'',
__( 'Disable Gutenberg editor. Don\'t load Gutenberg-related stylesheets from WordPress core, WooCommerce and Storefront.', 'extra-settings-for-woocommerce' )
);
}
public function eswc_change_email_author_cb() {
printf(
'<fieldset>
<label><input id="eswc_change_email_author" type="checkbox" name="eswc_settingz[eswc_change_email_author]" value="1" %1$s />%2$s</label>
</fieldset>',
isset( $this->options['eswc_change_email_author'] ) && ( 1 == $this->options['eswc_change_email_author'] ) ? 'checked="checked" ':'',
__( 'Default is WordPress, [email protected]. Change to: "Site Title" from Settings > General, custom email entered below.', 'extra-settings-for-woocommerce' )
);
}
public function eswc_redirect_cb() {
printf(
'<fieldset>
<label><input id="eswc_redirect" type="checkbox" name="eswc_settingz[eswc_redirect]" value="1" %1$s />%2$s</label>
</fieldset>
<p class="description">%3$s</p>',
isset( $this->options['eswc_redirect'] ) && ( 1 == $this->options['eswc_redirect'] ) ? 'checked="checked" ':'',
__( 'After a successful login, redirect customers to previously visited page and users with admin access to dashboard.', 'extra-settings-for-woocommerce' ),
__( 'By default WooCommerce redirects to "My account" page. Customer roles: customer, subscriber. Admin access roles: administrator, shop_manager, editor, author, contributor.', 'extra-settings-for-woocommerce' )
);
}
}
$eswc_settingz_page = new extra_settings_settings();
``` | First Thing
-----------
>
> The fields are registered only when the proper tab is selected to
> avoid resetting values in other tabs to defaults on save.
>
>
>
And because of that, you should pass the proper tab name/slug to the `wp-admin/options.php` page which is where the form is being submitted to.
1. You can simply pass it as a query string in the form `action` attribute value:
```
<form method="post" action="<?php echo esc_url( add_query_arg( // wrapped for clarity
'tab', $active_tab, admin_url( 'options.php' )
) ); ?>">
```
2. *Or* in `create_settings_page()`, add a hidden input field having the tab slug as the value:
```
echo '<input type="hidden" name="tab" value="' . esc_attr( $active_tab ) . '" />';
submit_button();
```
And then in the `display_options()`, retrieve the tab slug using `$_REQUEST`:
```
$active_tab = isset( $_REQUEST['tab'] ) ? $_REQUEST['tab'] : 'general';
```
Either way, the point is so that the `register_setting()` calls in the `display_options()` are invoked. Because otherwise, WordPress would throw the "options page not found" error because the option page is *not registered*.
You could use the `whitelist_options` filter, but I'd rather want the `register_setting()` calls be invoked, so I removed this and the associated callback (`whitelist_custom_options_page()`):
```
add_action( 'whitelist_options', array( $this, 'whitelist_custom_options_page' ),11 );
```
Second Thing
------------
Since you're using the same database *option name* (`eswc_settingz`) for all tabs/fields, you should then merge the saved data with the one being submitted:
```
public function sanitize_general( $input ) {
$new_input = (array) get_option( 'eswc_settingz' ); // get saved data
... add/update new data
return $new_input;
}
public function sanitize_account( $input ) {
$new_input = (array) get_option( 'eswc_settingz' ); // get saved data
... add/update new data
return $new_input;
}
```
Or you could use *different* database option names:
```
register_setting( 'general_section', 'eswc_general_settingz', array( $this, 'sanitize_general' ) );
register_setting( 'account_section', 'eswc_account_settingz', array( $this, 'sanitize_account' ) );
```
Btw, is that "z" in the `settingz` a typo? Maybe it was meant to be `settings`?... |
342,458 | <p>I'm trying to get some Javascript to run on one of my pages. But nothing I do seems to work. I ran the code in a sandbox and it is functional.</p>
<p>I tried:
- Inserting and HTML builder element and putting the code in tags
- uploading the .js file in the theme and linking to it in my html code
- Multiple script plugins</p>
<p>How does one simply execute Javascript on a Wordpress page?</p>
| [
{
"answer_id": 342459,
"author": "Oscprofessionals",
"author_id": 171102,
"author_profile": "https://wordpress.stackexchange.com/users/171102",
"pm_score": 0,
"selected": false,
"text": "<p>add js file using function.php</p>\n\n<pre><code>function add_theme_scripts() {\n wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js', array ( 'jquery' ), 1.1, true);\n}\nadd_action( 'wp_enqueue_scripts', 'add_theme_scripts' );\n</code></pre>\n\n<p>or</p>\n\n<pre><code>//if you want to add script in plugin use this code in plugin:\nfunction yourScript() {\n wp_register_script( 'script', plugins_url('js/jqueryfile.js',__FILE__),array('jquery'),'1.1', true );\n wp_enqueue_script('script');\n}\nadd_action( 'admin_enqueue_scripts', yourScript);\n</code></pre>\n"
},
{
"answer_id": 342474,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 2,
"selected": false,
"text": "<pre><code><?php\nfunction enqueue_javascript_for_certain_page() {\n\n $page_id = 100; // change this to fit your needs\n\n if ( is_page( $page_id ) ) { // check the page you are on\n\n wp_enqueue_script(\n 'my_script_name', // script handle\n get_template_directory_uri() . '/js/my-js-file.js', // script URI\n array( // your script is dependent on following:\n 'jquery',\n 'jquery-ui'\n ),\n NULL, // script version (NULL means no version to display in query string)\n true // load script right before </body> tag\n );\n\n }\n\n}\n\nadd_action( 'wp_enqueue_scripts', 'enqueue_javascript_for_certain_page' );\n</code></pre>\n"
}
] | 2019/07/09 | [
"https://wordpress.stackexchange.com/questions/342458",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/167714/"
] | I'm trying to get some Javascript to run on one of my pages. But nothing I do seems to work. I ran the code in a sandbox and it is functional.
I tried:
- Inserting and HTML builder element and putting the code in tags
- uploading the .js file in the theme and linking to it in my html code
- Multiple script plugins
How does one simply execute Javascript on a Wordpress page? | ```
<?php
function enqueue_javascript_for_certain_page() {
$page_id = 100; // change this to fit your needs
if ( is_page( $page_id ) ) { // check the page you are on
wp_enqueue_script(
'my_script_name', // script handle
get_template_directory_uri() . '/js/my-js-file.js', // script URI
array( // your script is dependent on following:
'jquery',
'jquery-ui'
),
NULL, // script version (NULL means no version to display in query string)
true // load script right before </body> tag
);
}
}
add_action( 'wp_enqueue_scripts', 'enqueue_javascript_for_certain_page' );
``` |
342,479 | <p>So I installed a fresh 5.2 WP and set up the Multisite network working with subdomains, then created 2 new test sites. </p>
<p>From the outside all works great, I can browse the main site and the 2 test sites properly.</p>
<p>On the admin panel though, I can go and change the main site settings tab under network admin -> Sites and it saves properly. </p>
<p>When I try to do the same on any of the 2 test sites though I get a 403 forbidden error, the php script URL the form sends the into to is the same as the main site though (<strong>/wp-admin/network/site-settings.php?action=update-site</strong>) which has me puzzled as it should be working.</p>
<p>I've checked several guides on 403 errors and all checks are OK:</p>
<ul>
<li>DB multisite tables are there</li>
<li>File permissions seems ok, I'm even trying with all 755 atm.</li>
<li>Config wise it's all WP default since it's a new installation</li>
<li>Created subdomain wildcard which path is set to the same as domain</li>
<li>I'm using the HTACCESS code from the network installation:</li>
</ul>
<pre><code>Options FollowSymlinks
# BEGIN WordPress
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
# add a trailing slash to /wp-admin
RewriteRule ^wp-admin$ wp-admin/ [R=301,L]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^(wp-(content|admin|includes).*) $1 [L]
RewriteRule ^(.*\.php)$ $1 [L]
RewriteRule . index.php [L]
# END WordPress
</code></pre>
<ul>
<li><p>Added the network installation lines to wp-config.php as well:</p>
<pre><code>/* MULTISITE */
define('WP_ALLOW_MULTISITE', true);
define('MULTISITE', true);
define('SUBDOMAIN_INSTALL', true);
define('DOMAIN_CURRENT_SITE', 'mydomain.com');
define('PATH_CURRENT_SITE', '/');
define('SITE_ID_CURRENT_SITE', 1);
define('BLOG_ID_CURRENT_SITE', 1);
/* That's all, stop editing! Happy blogging. */
/** Absolute path to the WordPress directory. */
if ( ! defined( 'ABSPATH' ) )
define( 'ABSPATH', dirname( __FILE__ ) . '/' );
/** Sets up WordPress vars and included files. */
require_once ABSPATH . 'wp-settings.php';`
</code></pre></li>
</ul>
<p>Any idea what the problem could be?</p>
| [
{
"answer_id": 342498,
"author": "robwatson_dev",
"author_id": 137115,
"author_profile": "https://wordpress.stackexchange.com/users/137115",
"pm_score": 0,
"selected": false,
"text": "<p>I know this sounds ridiculous what I'm about to suggest but I've had a similar issue a number of times when running WordPress locally in Network mode. </p>\n\n<p>Clear your entire cache (possibly more than once). This seems to be more problematic in Chrome than other browsers with my own experience.</p>\n\n<p>Failing that, scrap your wildcard on the sub domain and set them up in either your host file (for local only) or with the correct DNS settings with your domain provider.</p>\n"
},
{
"answer_id": 352728,
"author": "Jrggv",
"author_id": 178462,
"author_profile": "https://wordpress.stackexchange.com/users/178462",
"pm_score": 1,
"selected": false,
"text": "<p>I had the same problem - I found the rules in Apache modsecurity that include a set of exclusions for Wordpress didn't cover <code>/network/site-settings.php</code>, so I could do everything except edit sites in my multisite setup.\nIn the file <code>/usr/share/modsecurity-crs/rules/REQUEST-903.9002-WORDPRESS-EXCLUSION-RULES.conf</code> I added the following lines:</p>\n\n<pre><code>SecRule REQUEST_FILENAME \"@endsWith /wp-admin/network/site-settings.php\" \\\n \"id:9009999,\\\n phase:1,\\\n pass,\\\n t:none,\\\n nolog,\\\n ctl:ruleRemoveById=941140,\\\n ctl:ruleRemoveById=941160,\\\n ctl:ruleRemoveById=942190,\\\n ctl:ruleRemoveById=942240,\\\n ctl:ruleRemoveById=942240,\\\n ctl:ruleRemoveById=980130,\\\n ctl:ruleRemoveById=949110\"\n</code></pre>\n\n<p>...it's my first experience of editing modsecurity rules, so there is probably a better way of doing it - but it worked.</p>\n"
}
] | 2019/07/09 | [
"https://wordpress.stackexchange.com/questions/342479",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/171556/"
] | So I installed a fresh 5.2 WP and set up the Multisite network working with subdomains, then created 2 new test sites.
From the outside all works great, I can browse the main site and the 2 test sites properly.
On the admin panel though, I can go and change the main site settings tab under network admin -> Sites and it saves properly.
When I try to do the same on any of the 2 test sites though I get a 403 forbidden error, the php script URL the form sends the into to is the same as the main site though (**/wp-admin/network/site-settings.php?action=update-site**) which has me puzzled as it should be working.
I've checked several guides on 403 errors and all checks are OK:
* DB multisite tables are there
* File permissions seems ok, I'm even trying with all 755 atm.
* Config wise it's all WP default since it's a new installation
* Created subdomain wildcard which path is set to the same as domain
* I'm using the HTACCESS code from the network installation:
```
Options FollowSymlinks
# BEGIN WordPress
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
# add a trailing slash to /wp-admin
RewriteRule ^wp-admin$ wp-admin/ [R=301,L]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^(wp-(content|admin|includes).*) $1 [L]
RewriteRule ^(.*\.php)$ $1 [L]
RewriteRule . index.php [L]
# END WordPress
```
* Added the network installation lines to wp-config.php as well:
```
/* MULTISITE */
define('WP_ALLOW_MULTISITE', true);
define('MULTISITE', true);
define('SUBDOMAIN_INSTALL', true);
define('DOMAIN_CURRENT_SITE', 'mydomain.com');
define('PATH_CURRENT_SITE', '/');
define('SITE_ID_CURRENT_SITE', 1);
define('BLOG_ID_CURRENT_SITE', 1);
/* That's all, stop editing! Happy blogging. */
/** Absolute path to the WordPress directory. */
if ( ! defined( 'ABSPATH' ) )
define( 'ABSPATH', dirname( __FILE__ ) . '/' );
/** Sets up WordPress vars and included files. */
require_once ABSPATH . 'wp-settings.php';`
```
Any idea what the problem could be? | I had the same problem - I found the rules in Apache modsecurity that include a set of exclusions for Wordpress didn't cover `/network/site-settings.php`, so I could do everything except edit sites in my multisite setup.
In the file `/usr/share/modsecurity-crs/rules/REQUEST-903.9002-WORDPRESS-EXCLUSION-RULES.conf` I added the following lines:
```
SecRule REQUEST_FILENAME "@endsWith /wp-admin/network/site-settings.php" \
"id:9009999,\
phase:1,\
pass,\
t:none,\
nolog,\
ctl:ruleRemoveById=941140,\
ctl:ruleRemoveById=941160,\
ctl:ruleRemoveById=942190,\
ctl:ruleRemoveById=942240,\
ctl:ruleRemoveById=942240,\
ctl:ruleRemoveById=980130,\
ctl:ruleRemoveById=949110"
```
...it's my first experience of editing modsecurity rules, so there is probably a better way of doing it - but it worked. |
342,527 | <p>I embedded standard code for pagination links and everything is working fine except that clicking the Previous or Page 1 link does not take me back to the first paginated page. This is different from other problems with pagination links reported elsewhere. </p>
<p>The code for the pagination links is as follows:</p>
<pre><code> $total_pages = $wp_query->max_num_pages;
$current_page = max(1, get_query_var('paged'));
echo paginate_links(array(
'base' => '%_%',
'format' => '?paged=%#%',
'show_all' => false,
'current' => $current_page,
'total' => $total_pages,
'end_size' => 2,
'mid_size' => 2,
'prev_next' => true,
'prev_text' => __('« Previous'),
'next_text' => __('Next »'),
'type' => 'plain',
'add_args' => false,
'add_fragment' => '',
'before_page_number' => '',
'after_page_number' => ''
));
</code></pre>
<p>The max number of the posts to be displayed is set to 2 and every page is showing two posts.</p>
<p>If you spot any potential problem with the code, please let me know.</p>
<p>Thank you for reading.</p>
| [
{
"answer_id": 342530,
"author": "Justin Waulters",
"author_id": 137235,
"author_profile": "https://wordpress.stackexchange.com/users/137235",
"pm_score": 0,
"selected": false,
"text": "<p>It looks like <code>$current_page</code> can be a minimum of <code>1</code>. in the <a href=\"https://codex.wordpress.org/Function_Reference/paginate_links\" rel=\"nofollow noreferrer\">WP Codex</a> the default is <code>0</code>. If you change <code>$current_page = max(1, get_query_var('paged'));</code> to <code>$current_page = max(0, get_query_var('paged'));</code> you may get it to work how you want it to work.\nIf this is the solution (or part of it), you may also have to adjust your logic elsewhere to make <code>0</code> the first page instead of <code>1</code>.</p>\n"
},
{
"answer_id": 342550,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 3,
"selected": true,
"text": "<p>To get the canonical (not <code>?page=1</code>) reference URL to start the pagination from you have to change</p>\n\n<pre><code>'base' => '%_%'\n</code></pre>\n\n<p>to</p>\n\n<pre><code>'base' => get_pagenum_link() . '%_%' // get_pagenum_link() default is '1'\n</code></pre>\n\n<p>which will give you the first page of paginated posts and <code>%_%</code> will be replaced by <code>'format'</code> parameter on the next pages.</p>\n"
}
] | 2019/07/10 | [
"https://wordpress.stackexchange.com/questions/342527",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/141638/"
] | I embedded standard code for pagination links and everything is working fine except that clicking the Previous or Page 1 link does not take me back to the first paginated page. This is different from other problems with pagination links reported elsewhere.
The code for the pagination links is as follows:
```
$total_pages = $wp_query->max_num_pages;
$current_page = max(1, get_query_var('paged'));
echo paginate_links(array(
'base' => '%_%',
'format' => '?paged=%#%',
'show_all' => false,
'current' => $current_page,
'total' => $total_pages,
'end_size' => 2,
'mid_size' => 2,
'prev_next' => true,
'prev_text' => __('« Previous'),
'next_text' => __('Next »'),
'type' => 'plain',
'add_args' => false,
'add_fragment' => '',
'before_page_number' => '',
'after_page_number' => ''
));
```
The max number of the posts to be displayed is set to 2 and every page is showing two posts.
If you spot any potential problem with the code, please let me know.
Thank you for reading. | To get the canonical (not `?page=1`) reference URL to start the pagination from you have to change
```
'base' => '%_%'
```
to
```
'base' => get_pagenum_link() . '%_%' // get_pagenum_link() default is '1'
```
which will give you the first page of paginated posts and `%_%` will be replaced by `'format'` parameter on the next pages. |
342,540 | <p>I use a third party plugin and plugin has created a custom post type called "creations".</p>
<p>Bu there is no archive page, there is no single page, there is no admin menu page... But data are saving on database correctly.</p>
<p>Is there a possible way to the active admin menu, archive page & single page? </p>
<p>Other all behaviours of custom post type should be there like( Eg: if <code>exclude_from_search</code> is true, this shouldn't change)</p>
| [
{
"answer_id": 342577,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 2,
"selected": false,
"text": "<p>If the plugin only registers the CPT, remove it and build your own.</p>\n\n<p>If the plugin does other things you need to keep on your site, you can unregister the post type and re-register it with your own plugin. You'll just need to keep in mind that changing settings may affect the way the original plugin works - it may rely on certain options in the CPT.</p>\n\n<p>Either way, copy the part of the plugin that registers the CPT and then adjust just the options you need. Make sure to replace \"post_type\" below with the actual CPT name.</p>\n\n<pre><code><?php\n// Optionally unregister the post type to clear all settings\n// (this does not delete any of the posts from the database)\nunregister_post_type( 'post_type' );\n\n// Now, re-register it as in the plugin, but with\n// the adjusted settings you need\n$args = array(\n // has_archive will provide an archive page\n 'has_archive' => true,\n // 'supports' will enable an Editor for single pages\n 'supports' => array('title', 'editor', 'author', 'revisions', 'page-attributes'),\n // 'public' makes it available in a number of places like menus\n 'public' => true\n);\nregister_post_type( 'post_type', $args );\n?>\n</code></pre>\n"
},
{
"answer_id": 343056,
"author": "nmr",
"author_id": 147428,
"author_profile": "https://wordpress.stackexchange.com/users/147428",
"pm_score": 5,
"selected": true,
"text": "<p>You can change <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type#Arguments\" rel=\"noreferrer\"><code>register_post_type()</code></a> arguments before the new type is created. To do this, use the <a href=\"https://developer.wordpress.org/reference/hooks/register_post_type_args/\" rel=\"noreferrer\"><code>register_post_type_args</code></a> filter.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'register_post_type_args', 'se342540_change_post_type_args', 10, 2 );\nfunction se342540_change_post_type_args( $args, $post_name )\n{\n if ( $post_name != 'cpt_slug' )\n return $args;\n\n $args['has_archive'] = true;\n // \n // other arguments\n\n return $args;\n}\n</code></pre>\n"
}
] | 2019/07/10 | [
"https://wordpress.stackexchange.com/questions/342540",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123092/"
] | I use a third party plugin and plugin has created a custom post type called "creations".
Bu there is no archive page, there is no single page, there is no admin menu page... But data are saving on database correctly.
Is there a possible way to the active admin menu, archive page & single page?
Other all behaviours of custom post type should be there like( Eg: if `exclude_from_search` is true, this shouldn't change) | You can change [`register_post_type()`](https://codex.wordpress.org/Function_Reference/register_post_type#Arguments) arguments before the new type is created. To do this, use the [`register_post_type_args`](https://developer.wordpress.org/reference/hooks/register_post_type_args/) filter.
```php
add_filter( 'register_post_type_args', 'se342540_change_post_type_args', 10, 2 );
function se342540_change_post_type_args( $args, $post_name )
{
if ( $post_name != 'cpt_slug' )
return $args;
$args['has_archive'] = true;
//
// other arguments
return $args;
}
``` |
342,571 | <p>Have a widget that's currently filtering a set of categories, and need to make it support more than one set of categories.</p>
<p>Right now the code is something like this:</p>
<pre><code>$query_args = array(
'post_type' => 'product',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $categories,
'operator' => 'AND',
),
),
);
</code></pre>
<p>So, basically, it's filtering products that have x, y and z categories.
Now I need it to filter products that have x and y, OR x and z.
I've sketched this:</p>
<pre><code> $query_args = array(
'post_type' => 'product',
'tax_query' => array(
'relation' => 'AND'
),
);
if(is_array($tags)){
$query_args['tax_query']['relation'] = 'OR';
foreach($tags as $tagGroup){
array_push($query_args['tax_query'], array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => implode(',', $tagGroup),
'operator' => 'AND'
));
}
}else{
array_push($query_args['tax_query'], array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $categories,
'operator' => 'AND',
));
}
</code></pre>
<p>But it's still not filtering products as I need.
What am I doing wrong?</p>
| [
{
"answer_id": 342580,
"author": "honk31",
"author_id": 10994,
"author_profile": "https://wordpress.stackexchange.com/users/10994",
"pm_score": 0,
"selected": false,
"text": "<p>you can nest multiple tax queries like so:</p>\n\n<pre><code>$query_args = array(\n 'post_type' => 'product',\n 'tax_query' => [\n 'relation' => 'OR',\n [\n [\n 'taxonomy' => 'product_cat',\n 'field' => 'slug',\n 'terms' => $x_y,\n 'operator' => 'AND',\n ],\n ],\n [\n 'relation' => 'AND',\n [\n 'taxonomy' => 'product_cat',\n 'field' => 'slug',\n 'terms' => $x_z,\n 'operator' => 'AND',\n ],\n [\n 'taxonomy' => 'something_something',\n 'field' => 'slug',\n 'terms' => $z,\n 'operator' => 'AND',\n ]\n ],\n\n ],\n );\n</code></pre>\n\n<p>i took your example code, so not sure about all the values you have there, but basically you can combine AND and OR..\nmore info <a href=\"https://developer.wordpress.org/reference/classes/wp_query/#taxonomy-parameters\" rel=\"nofollow noreferrer\">here</a></p>\n"
},
{
"answer_id": 342583,
"author": "Antti Koskinen",
"author_id": 144392,
"author_profile": "https://wordpress.stackexchange.com/users/144392",
"pm_score": 1,
"selected": false,
"text": "<p>You can nest your tax queries. Just make sure you use <code>OR</code> as the first relation and <code>AND</code> relation on the nested tax queries.</p>\n\n<pre><code>$filter_group_a = array(\n 'relation' => 'AND',\n array(\n 'taxonomy' => 'product_cat',\n 'field' => 'slug',\n 'terms' => $term_a,\n ),\n array(\n 'taxonomy' => 'product_cat',\n 'field' => 'slug',\n 'terms' => $term_b,\n ),\n);\n\n$filter_group_b = array(\n 'relation' => 'AND',\n array(\n 'taxonomy' => 'product_cat',\n 'field' => 'slug',\n 'terms' => $term_a,\n ),\n array(\n 'taxonomy' => 'product_cat',\n 'field' => 'slug',\n 'terms' => $term_c,\n ),\n)\n\n$query_args = array(\n 'tax_query' => array(\n 'relation' => 'OR',\n $filter_group_a,\n $filter_group_b,\n )\n);\n</code></pre>\n\n<p>You could write some fancy loop that builds the <code>$filter_groups</code> and pushes them to the <code>$query_args['tax_query']</code> array.</p>\n"
}
] | 2019/07/10 | [
"https://wordpress.stackexchange.com/questions/342571",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/60311/"
] | Have a widget that's currently filtering a set of categories, and need to make it support more than one set of categories.
Right now the code is something like this:
```
$query_args = array(
'post_type' => 'product',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $categories,
'operator' => 'AND',
),
),
);
```
So, basically, it's filtering products that have x, y and z categories.
Now I need it to filter products that have x and y, OR x and z.
I've sketched this:
```
$query_args = array(
'post_type' => 'product',
'tax_query' => array(
'relation' => 'AND'
),
);
if(is_array($tags)){
$query_args['tax_query']['relation'] = 'OR';
foreach($tags as $tagGroup){
array_push($query_args['tax_query'], array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => implode(',', $tagGroup),
'operator' => 'AND'
));
}
}else{
array_push($query_args['tax_query'], array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $categories,
'operator' => 'AND',
));
}
```
But it's still not filtering products as I need.
What am I doing wrong? | You can nest your tax queries. Just make sure you use `OR` as the first relation and `AND` relation on the nested tax queries.
```
$filter_group_a = array(
'relation' => 'AND',
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $term_a,
),
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $term_b,
),
);
$filter_group_b = array(
'relation' => 'AND',
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $term_a,
),
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $term_c,
),
)
$query_args = array(
'tax_query' => array(
'relation' => 'OR',
$filter_group_a,
$filter_group_b,
)
);
```
You could write some fancy loop that builds the `$filter_groups` and pushes them to the `$query_args['tax_query']` array. |
342,654 | <p>I'm trying to show related videos on my single post template. I've set up a custom taxonomy called 'sub-category' in Posts. I want to get the sub-category of the current post and loop through any posts with the same sub-category, outputting them to the page.
Any ideas on the best way of achieving this?</p>
| [
{
"answer_id": 342656,
"author": "Oscprofessionals",
"author_id": 171102,
"author_profile": "https://wordpress.stackexchange.com/users/171102",
"pm_score": -1,
"selected": false,
"text": "<pre><code>function get_the_terms( $post, $taxonomy ) {\nif ( ! $post = get_post( $post ) ) {\n return false;\n}\n\n$terms = get_object_term_cache( $post->ID, $taxonomy );\nif ( false === $terms ) {\n $terms = wp_get_object_terms( $post->ID, $taxonomy );\n if ( ! is_wp_error( $terms ) ) {\n $term_ids = wp_list_pluck( $terms, 'term_id' );\n wp_cache_add( $post->ID, $term_ids, $taxonomy . '_relationships' );\n }\n}\n\n/**\n * Filters the list of terms attached to the given post.\n *\n * @since 3.1.0\n *\n * @param WP_Term[]|WP_Error $terms Array of attached terms, or WP_Error on failure.\n * @param int $post_id Post ID.\n * @param string $taxonomy Name of the taxonomy.\n */\n$terms = apply_filters( 'get_the_terms', $terms, $post->ID, $taxonomy );\n\nif ( empty( $terms ) ) {\n return false;\n}\n\nreturn $terms;}\n</code></pre>\n"
},
{
"answer_id": 342657,
"author": "user108167",
"author_id": 108167,
"author_profile": "https://wordpress.stackexchange.com/users/108167",
"pm_score": -1,
"selected": false,
"text": "<p>I think I confused myself on this actually, here's how I did it:</p>\n\n<pre><code>$_terms = wp_get_post_terms($post->ID, 'sub-category', array(\"fields\" => \"all\"));\n foreach ($_terms as $term) :\n $term_slug = $term->slug;\n $_posts = new WP_Query( array(\n 'post_type' => 'post',\n 'posts_per_page' => 4,\n 'tax_query' => array(\n array(\n 'taxonomy' => 'sub-category',\n 'field' => 'slug',\n 'terms' => $term_slug,\n ),\n ),\n ));\n if( $_posts->have_posts() ) :\n while ( $_posts->have_posts() ) : $_posts->the_post();\n //Output\n endwhile;\n endif;\n wp_reset_postdata();\n endforeach;\n</code></pre>\n"
},
{
"answer_id": 342709,
"author": "Giang D.MAI",
"author_id": 145055,
"author_profile": "https://wordpress.stackexchange.com/users/145055",
"pm_score": 0,
"selected": false,
"text": "<p>try with this function</p>\n\n<pre><code>function get_posts_in_taxonomy($post_type, $taxonomy, $term_id, $include_children=false, $limit)\n{\n$args = [\n 'post_type' => $post_type,\n 'posts_per_page' => $limit,\n 'tax_query' => [\n [\n 'taxonomy' => $taxonomy,\n 'terms' => $term_id,\n 'include_children' => $include_children\n ],\n ],\n // Rest of your arguments\n];\n\n$posts = new WP_Query( $args );\n\nif($posts->have_posts()) {\n while($posts->have_posts()) {\n $posts->the_post();\n\n //code todo here\n\n }\n}\n} //end func\n</code></pre>\n"
}
] | 2019/07/11 | [
"https://wordpress.stackexchange.com/questions/342654",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108167/"
] | I'm trying to show related videos on my single post template. I've set up a custom taxonomy called 'sub-category' in Posts. I want to get the sub-category of the current post and loop through any posts with the same sub-category, outputting them to the page.
Any ideas on the best way of achieving this? | try with this function
```
function get_posts_in_taxonomy($post_type, $taxonomy, $term_id, $include_children=false, $limit)
{
$args = [
'post_type' => $post_type,
'posts_per_page' => $limit,
'tax_query' => [
[
'taxonomy' => $taxonomy,
'terms' => $term_id,
'include_children' => $include_children
],
],
// Rest of your arguments
];
$posts = new WP_Query( $args );
if($posts->have_posts()) {
while($posts->have_posts()) {
$posts->the_post();
//code todo here
}
}
} //end func
``` |
342,655 | <p>first off, I am sorry if this question has been asked before, don't seem to get it.</p>
<p>I would like to change the markup of link in Wordpress to something like this</p>
<pre><code><a href="#" class="s1 s1--top" data-hint="tooltip here">Just Words.</a>
</code></pre>
<p>Where the href would have two extra classes, and I would be able to add words to the data hint dynamically (through the text editor). - It's a tooltip</p>
<p>I have enqueued the stylesheet of the CSS, my main challenge is how to append those extra classes to the a tag, thanks.</p>
<p>I don't mind if someone can help me with JQuery, and lastly, how do I make the tooltip show up.</p>
| [
{
"answer_id": 342656,
"author": "Oscprofessionals",
"author_id": 171102,
"author_profile": "https://wordpress.stackexchange.com/users/171102",
"pm_score": -1,
"selected": false,
"text": "<pre><code>function get_the_terms( $post, $taxonomy ) {\nif ( ! $post = get_post( $post ) ) {\n return false;\n}\n\n$terms = get_object_term_cache( $post->ID, $taxonomy );\nif ( false === $terms ) {\n $terms = wp_get_object_terms( $post->ID, $taxonomy );\n if ( ! is_wp_error( $terms ) ) {\n $term_ids = wp_list_pluck( $terms, 'term_id' );\n wp_cache_add( $post->ID, $term_ids, $taxonomy . '_relationships' );\n }\n}\n\n/**\n * Filters the list of terms attached to the given post.\n *\n * @since 3.1.0\n *\n * @param WP_Term[]|WP_Error $terms Array of attached terms, or WP_Error on failure.\n * @param int $post_id Post ID.\n * @param string $taxonomy Name of the taxonomy.\n */\n$terms = apply_filters( 'get_the_terms', $terms, $post->ID, $taxonomy );\n\nif ( empty( $terms ) ) {\n return false;\n}\n\nreturn $terms;}\n</code></pre>\n"
},
{
"answer_id": 342657,
"author": "user108167",
"author_id": 108167,
"author_profile": "https://wordpress.stackexchange.com/users/108167",
"pm_score": -1,
"selected": false,
"text": "<p>I think I confused myself on this actually, here's how I did it:</p>\n\n<pre><code>$_terms = wp_get_post_terms($post->ID, 'sub-category', array(\"fields\" => \"all\"));\n foreach ($_terms as $term) :\n $term_slug = $term->slug;\n $_posts = new WP_Query( array(\n 'post_type' => 'post',\n 'posts_per_page' => 4,\n 'tax_query' => array(\n array(\n 'taxonomy' => 'sub-category',\n 'field' => 'slug',\n 'terms' => $term_slug,\n ),\n ),\n ));\n if( $_posts->have_posts() ) :\n while ( $_posts->have_posts() ) : $_posts->the_post();\n //Output\n endwhile;\n endif;\n wp_reset_postdata();\n endforeach;\n</code></pre>\n"
},
{
"answer_id": 342709,
"author": "Giang D.MAI",
"author_id": 145055,
"author_profile": "https://wordpress.stackexchange.com/users/145055",
"pm_score": 0,
"selected": false,
"text": "<p>try with this function</p>\n\n<pre><code>function get_posts_in_taxonomy($post_type, $taxonomy, $term_id, $include_children=false, $limit)\n{\n$args = [\n 'post_type' => $post_type,\n 'posts_per_page' => $limit,\n 'tax_query' => [\n [\n 'taxonomy' => $taxonomy,\n 'terms' => $term_id,\n 'include_children' => $include_children\n ],\n ],\n // Rest of your arguments\n];\n\n$posts = new WP_Query( $args );\n\nif($posts->have_posts()) {\n while($posts->have_posts()) {\n $posts->the_post();\n\n //code todo here\n\n }\n}\n} //end func\n</code></pre>\n"
}
] | 2019/07/11 | [
"https://wordpress.stackexchange.com/questions/342655",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/167786/"
] | first off, I am sorry if this question has been asked before, don't seem to get it.
I would like to change the markup of link in Wordpress to something like this
```
<a href="#" class="s1 s1--top" data-hint="tooltip here">Just Words.</a>
```
Where the href would have two extra classes, and I would be able to add words to the data hint dynamically (through the text editor). - It's a tooltip
I have enqueued the stylesheet of the CSS, my main challenge is how to append those extra classes to the a tag, thanks.
I don't mind if someone can help me with JQuery, and lastly, how do I make the tooltip show up. | try with this function
```
function get_posts_in_taxonomy($post_type, $taxonomy, $term_id, $include_children=false, $limit)
{
$args = [
'post_type' => $post_type,
'posts_per_page' => $limit,
'tax_query' => [
[
'taxonomy' => $taxonomy,
'terms' => $term_id,
'include_children' => $include_children
],
],
// Rest of your arguments
];
$posts = new WP_Query( $args );
if($posts->have_posts()) {
while($posts->have_posts()) {
$posts->the_post();
//code todo here
}
}
} //end func
``` |
342,678 | <p>Any help with this would be greatly appreciated - I've been grappling with it for days :)</p>
<p>I have 2 post types - <code>product</code> + <code>offer</code></p>
<p>I have an ACF relationship field <code>related_products</code>. </p>
<p>This field returns an array of post IDs <code>Array ( [0] => 395 [1] => 120 [2] => 388 [3] => 391 )</code></p>
<p>I am using <code>related_products</code> on the <code>offer</code> post type - it's a one-way relationship (not bi-directional). </p>
<p>Each of my post types has a "card" template part that I use in all my loops - that's what I want to do here ... use the <code>related_products</code> IDs to get the <code>product</code> card parts and show them on the <code>offer</code>. </p>
<p>I had no luck with the ACF documentation - but that's probably because I'm a noob. </p>
<ul>
<li><a href="https://www.advancedcustomfields.com/resources/querying-relationship-fields/" rel="nofollow noreferrer">https://www.advancedcustomfields.com/resources/querying-relationship-fields/</a></li>
<li><a href="https://www.advancedcustomfields.com/resources/acf-fields-relationship-query/" rel="nofollow noreferrer">https://www.advancedcustomfields.com/resources/acf-fields-relationship-query/</a></li>
</ul>
<p>Instead, I set up a custom <code>WP_Query</code> that get's me close, but not there. </p>
<p>The <code>if ( $custom_query->have_posts() )</code> IS working - when an <code>offer</code> has related products, the correct product cards ARE displayed. </p>
<p>But, when an <code>offer</code> has no <code>related_products</code>, ALL products are being shown. </p>
<p>My questions are:</p>
<ul>
<li>Is a custom <code>WP_QUERY</code> the right/best way to go about this?</li>
<li>If so, what do I need to fix in the query? </li>
</ul>
<p>Thank you for your time and help :)</p>
<pre><code>// Array ( [0] => 395 [1] => 120 [2] => 388 [3] => 391 )
$related_products = get_field('related_products');
$args = array(
'post_type' => 'product',
'post__in' => $related_products,
'fields' => 'ids',
'cache_results' => false,
'update_post_meta_cache' => false,
'update_post_term_cache' => false,
'posts_per_page' => -1,
'paged' => false,
);
$custom_query = new WP_Query( $args );
if ( $custom_query->have_posts() ) :
while ( $custom_query->have_posts() ) :
$custom_query->the_post();
get_template_part( 'parts/card', get_post_type() );
endwhile;
else :
// do something else
endif;
wp_reset_query();
</code></pre>
| [
{
"answer_id": 342692,
"author": "Faye",
"author_id": 76600,
"author_profile": "https://wordpress.stackexchange.com/users/76600",
"pm_score": 2,
"selected": false,
"text": "<p>I could be wrong, but it looks like you're trying to do something much simpler than what you've got going there. I use the method <a href=\"https://www.advancedcustomfields.com/resources/relationship/\" rel=\"nofollow noreferrer\">shown here</a> on a regular basis and it works just fine.</p>\n\n<pre><code><?php \n\n$posts = get_field('related_products');\n\nif( $posts ): ?>\n\n <?php foreach( $posts as $post): // variable must be called $post (IMPORTANT) ?>\n <?php setup_postdata($post); ?>\n\n <?php get_template_part( 'parts/card', get_post_type() );?> \n <!-- this is the only thing I'm not sure if you'd want to just directly call 'parts/card', 'product' -->\n\n <?php endforeach; ?>\n <?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?>\n<?php endif; ?>\n</code></pre>\n"
},
{
"answer_id": 342708,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>But, when an offer has no related_products, ALL products are being\n shown.</p>\n</blockquote>\n\n<p>This is because you're not doing anything to check if the field has a value before running your query. If this is empty:</p>\n\n<pre><code>$related_products = get_field('related_products');\n</code></pre>\n\n<p>Then that makes the query argument equivalent to:</p>\n\n<pre><code>'post__in' => [],\n</code></pre>\n\n<p>And if that argument value is empty, it doesn't query no posts, it just gets ignored, which means you're query is the equivalent of:</p>\n\n<pre><code>$args = array( \n 'post_type' => 'product',\n 'fields' => 'ids',\n 'cache_results' => false,\n 'update_post_meta_cache' => false, \n 'update_post_term_cache' => false, \n 'posts_per_page' => -1, \n 'paged' => false,\n);\n</code></pre>\n\n<p>Which is querying <em>all</em> products.</p>\n\n<p>So you need to check if your field has any values before doing anything, then only querying if there are any.</p>\n\n<p>Your other problem is that you have <code>fields</code> set to <code>ids</code>. If you do this then the result is just an array of posts IDs, which you already have because that's what you're querying. If you want to use the loop with your results, you need to remove that line. So all you should have is:</p>\n\n<pre><code>$related_products = get_field( 'related_products' );\n\nif ( $related_products ) {\n $args = array( \n 'post_type' => 'product',\n 'post__in' => $related_products, \n );\n\n $custom_query = new WP_Query( $args );\n\n if ( $custom_query->have_posts() ) : \n while ( $custom_query->have_posts() ) : \n $custom_query->the_post(); \n get_template_part( 'parts/card', get_post_type() );\n endwhile;\n else : \n // do something else\n endif;\n\n wp_reset_postdata();\n}\n</code></pre>\n\n<p>But doing this query at all is unnecessary. If you set the field to return post objects, rather than IDs, you can just loop through those:</p>\n\n<pre><code>$related_products = get_field( 'related_products' );\n\nif ( $related_products ) {\n global $post; // Necessary.\n\n foreach ( $related_products as $post ) : // Must be called $post. \n setup_postdata( $post ); \n get_template_part( 'parts/card', get_post_type() );\n endforeach;\n\n wp_reset_postdata();\n}\n</code></pre>\n\n<p>This is the same as <a href=\"https://wordpress.stackexchange.com/a/342692/39152\">Faye's answer</a>, I'm just including it for completeness. If you're receiving any errors from that, then the issue is somewhere else. Probably inside your card template.</p>\n"
},
{
"answer_id": 343015,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 2,
"selected": true,
"text": "<p>My OP is about using the ACF relationship field in <code>WP_QUERY</code>. The ACF documentation leaves out one helpful bit that @JacobPeattie supplied. </p>\n\n<p>My final working code looks like this:</p>\n\n<pre><code>// ACF field is set to return IDs.\n// Array ( [0] => 395 [1] => 120 [2] => 388 [3] => 391 )\n\n$related_product = get_field( 'related_product' );\n\nif ( $related_product ) :\n\n global $post; // missing from ACF documentation\n\n foreach ( $related_product as $post ) : // Must be called $post. \n setup_postdata( $post ); \n get_template_part( 'parts/card', get_post_type() );\n endforeach;\n\n wp_reset_postdata();\n\nendif;\n</code></pre>\n\n<p>However, part of Jacob's explanation and subsequent comments are wrong. Because I rely on this community for accurate information, I can't accept his answer as correct. </p>\n\n<p>Jacob incorrectly asserts that passing an array of IDs to <code>WP_QUERY</code> and then using the <code>fields</code> parameter to return only IDs is redundant and won't work. </p>\n\n<p>You can use any number of things to inform <code>WP_QUERY</code> which posts to GET - terms, post type, IDs. This is completely separate from what you tell the query to RETURN - there is nothing redundant about passing then returning IDs. </p>\n\n<p>The <code>fields</code> parameter defaults to returning all fields. Alternatively, you can set <code>fields</code> to return <code>ids</code> (note plural). </p>\n\n<p>Deciding to return all fields or just IDs is a matter of optimization - if you don't need all fields, then don't return them. </p>\n\n<p>Here are two examples from my live site demonstrating that YOU DO NOT NEED ALL FIELDS in many common scenarios. You can easily try these for yourself and I've linked to more info below. </p>\n\n<p>This example displays a field - <code>the_title</code> ... super common, I use it all the time and you don't need to return all fields to do it. </p>\n\n<pre><code>$args = array( \n 'post_type' => 'product',\n 'fields' => 'ids',\n);\n\n$custom_query = new WP_Query( $args );\n\nif ( $custom_query->have_posts() ) : \n\n while ( $custom_query->have_posts() ) : \n $custom_query->the_post(); \n the_title();\n endwhile;\n\nelse : \n // do something else\nendif; \n\nwp_reset_query();\n</code></pre>\n\n<p>Here's an even more complex / optimized example. This one is for displaying a template part. This part has standard stuff like <code>the_title</code> + ACF fields + an Add Favorite feature + pulls in other parts. The results are filterable by FacetWP.</p>\n\n<p>Again, you only need <code>WP_QUERY</code> to return IDs. </p>\n\n<pre><code>$args = array( \n 'post_type' => 'product',\n 'fields' => 'ids',\n 'cache_results' => false,\n 'update_post_meta_cache' => false, \n 'update_post_term_cache' => false, \n 'facetwp' => true, \n);\n\n$custom_query = new WP_Query( $args );\n\nif ( $custom_query->have_posts() ) : \n\n while ( $custom_query->have_posts() ) : \n $custom_query->the_post(); \n get_template_part( 'parts/card', get_post_type() ); \n endwhile;\n\nelse :\n // do something else\nendif;\n\nwp_reset_query();\n</code></pre>\n\n<p>You can read more about optimizing <code>WP_QUERY</code> here (and lots of other places):</p>\n\n<ul>\n<li><a href=\"https://kinsta.com/blog/wp-query/\" rel=\"nofollow noreferrer\">https://kinsta.com/blog/wp-query/</a></li>\n</ul>\n\n<p>Thinking about it, these examples make perfect sense - things like <code>global Spost</code> and <code>setup_postdata($post)</code> and <code>$custom_query->the_post()</code> are specifically for setting context and ensuring the correct ID is referenced so you can then get the right field, template etc ...</p>\n\n<p>And why would a database need anything more than an ID to get a record's associated fields? ... The only answer I can think of is if the database is poorly designed ... In fact, I have never had a scenario where returning just IDs hasn't worked. </p>\n\n<p>I'm not claiming to be an expert - I only know that you can return just IDs because I read about it, tried it in my own projects, and it works. </p>\n"
}
] | 2019/07/11 | [
"https://wordpress.stackexchange.com/questions/342678",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] | Any help with this would be greatly appreciated - I've been grappling with it for days :)
I have 2 post types - `product` + `offer`
I have an ACF relationship field `related_products`.
This field returns an array of post IDs `Array ( [0] => 395 [1] => 120 [2] => 388 [3] => 391 )`
I am using `related_products` on the `offer` post type - it's a one-way relationship (not bi-directional).
Each of my post types has a "card" template part that I use in all my loops - that's what I want to do here ... use the `related_products` IDs to get the `product` card parts and show them on the `offer`.
I had no luck with the ACF documentation - but that's probably because I'm a noob.
* <https://www.advancedcustomfields.com/resources/querying-relationship-fields/>
* <https://www.advancedcustomfields.com/resources/acf-fields-relationship-query/>
Instead, I set up a custom `WP_Query` that get's me close, but not there.
The `if ( $custom_query->have_posts() )` IS working - when an `offer` has related products, the correct product cards ARE displayed.
But, when an `offer` has no `related_products`, ALL products are being shown.
My questions are:
* Is a custom `WP_QUERY` the right/best way to go about this?
* If so, what do I need to fix in the query?
Thank you for your time and help :)
```
// Array ( [0] => 395 [1] => 120 [2] => 388 [3] => 391 )
$related_products = get_field('related_products');
$args = array(
'post_type' => 'product',
'post__in' => $related_products,
'fields' => 'ids',
'cache_results' => false,
'update_post_meta_cache' => false,
'update_post_term_cache' => false,
'posts_per_page' => -1,
'paged' => false,
);
$custom_query = new WP_Query( $args );
if ( $custom_query->have_posts() ) :
while ( $custom_query->have_posts() ) :
$custom_query->the_post();
get_template_part( 'parts/card', get_post_type() );
endwhile;
else :
// do something else
endif;
wp_reset_query();
``` | My OP is about using the ACF relationship field in `WP_QUERY`. The ACF documentation leaves out one helpful bit that @JacobPeattie supplied.
My final working code looks like this:
```
// ACF field is set to return IDs.
// Array ( [0] => 395 [1] => 120 [2] => 388 [3] => 391 )
$related_product = get_field( 'related_product' );
if ( $related_product ) :
global $post; // missing from ACF documentation
foreach ( $related_product as $post ) : // Must be called $post.
setup_postdata( $post );
get_template_part( 'parts/card', get_post_type() );
endforeach;
wp_reset_postdata();
endif;
```
However, part of Jacob's explanation and subsequent comments are wrong. Because I rely on this community for accurate information, I can't accept his answer as correct.
Jacob incorrectly asserts that passing an array of IDs to `WP_QUERY` and then using the `fields` parameter to return only IDs is redundant and won't work.
You can use any number of things to inform `WP_QUERY` which posts to GET - terms, post type, IDs. This is completely separate from what you tell the query to RETURN - there is nothing redundant about passing then returning IDs.
The `fields` parameter defaults to returning all fields. Alternatively, you can set `fields` to return `ids` (note plural).
Deciding to return all fields or just IDs is a matter of optimization - if you don't need all fields, then don't return them.
Here are two examples from my live site demonstrating that YOU DO NOT NEED ALL FIELDS in many common scenarios. You can easily try these for yourself and I've linked to more info below.
This example displays a field - `the_title` ... super common, I use it all the time and you don't need to return all fields to do it.
```
$args = array(
'post_type' => 'product',
'fields' => 'ids',
);
$custom_query = new WP_Query( $args );
if ( $custom_query->have_posts() ) :
while ( $custom_query->have_posts() ) :
$custom_query->the_post();
the_title();
endwhile;
else :
// do something else
endif;
wp_reset_query();
```
Here's an even more complex / optimized example. This one is for displaying a template part. This part has standard stuff like `the_title` + ACF fields + an Add Favorite feature + pulls in other parts. The results are filterable by FacetWP.
Again, you only need `WP_QUERY` to return IDs.
```
$args = array(
'post_type' => 'product',
'fields' => 'ids',
'cache_results' => false,
'update_post_meta_cache' => false,
'update_post_term_cache' => false,
'facetwp' => true,
);
$custom_query = new WP_Query( $args );
if ( $custom_query->have_posts() ) :
while ( $custom_query->have_posts() ) :
$custom_query->the_post();
get_template_part( 'parts/card', get_post_type() );
endwhile;
else :
// do something else
endif;
wp_reset_query();
```
You can read more about optimizing `WP_QUERY` here (and lots of other places):
* <https://kinsta.com/blog/wp-query/>
Thinking about it, these examples make perfect sense - things like `global Spost` and `setup_postdata($post)` and `$custom_query->the_post()` are specifically for setting context and ensuring the correct ID is referenced so you can then get the right field, template etc ...
And why would a database need anything more than an ID to get a record's associated fields? ... The only answer I can think of is if the database is poorly designed ... In fact, I have never had a scenario where returning just IDs hasn't worked.
I'm not claiming to be an expert - I only know that you can return just IDs because I read about it, tried it in my own projects, and it works. |
342,704 | <p>Using latest WP with Gutenberg. The excerpt metabox is (as you'd expect) over in the right column with the Document settings.</p>
<p>Is there any way to get it out of that column and into the main area where the textarea would then be of a <em>useful</em> size?</p>
| [
{
"answer_id": 342692,
"author": "Faye",
"author_id": 76600,
"author_profile": "https://wordpress.stackexchange.com/users/76600",
"pm_score": 2,
"selected": false,
"text": "<p>I could be wrong, but it looks like you're trying to do something much simpler than what you've got going there. I use the method <a href=\"https://www.advancedcustomfields.com/resources/relationship/\" rel=\"nofollow noreferrer\">shown here</a> on a regular basis and it works just fine.</p>\n\n<pre><code><?php \n\n$posts = get_field('related_products');\n\nif( $posts ): ?>\n\n <?php foreach( $posts as $post): // variable must be called $post (IMPORTANT) ?>\n <?php setup_postdata($post); ?>\n\n <?php get_template_part( 'parts/card', get_post_type() );?> \n <!-- this is the only thing I'm not sure if you'd want to just directly call 'parts/card', 'product' -->\n\n <?php endforeach; ?>\n <?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?>\n<?php endif; ?>\n</code></pre>\n"
},
{
"answer_id": 342708,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>But, when an offer has no related_products, ALL products are being\n shown.</p>\n</blockquote>\n\n<p>This is because you're not doing anything to check if the field has a value before running your query. If this is empty:</p>\n\n<pre><code>$related_products = get_field('related_products');\n</code></pre>\n\n<p>Then that makes the query argument equivalent to:</p>\n\n<pre><code>'post__in' => [],\n</code></pre>\n\n<p>And if that argument value is empty, it doesn't query no posts, it just gets ignored, which means you're query is the equivalent of:</p>\n\n<pre><code>$args = array( \n 'post_type' => 'product',\n 'fields' => 'ids',\n 'cache_results' => false,\n 'update_post_meta_cache' => false, \n 'update_post_term_cache' => false, \n 'posts_per_page' => -1, \n 'paged' => false,\n);\n</code></pre>\n\n<p>Which is querying <em>all</em> products.</p>\n\n<p>So you need to check if your field has any values before doing anything, then only querying if there are any.</p>\n\n<p>Your other problem is that you have <code>fields</code> set to <code>ids</code>. If you do this then the result is just an array of posts IDs, which you already have because that's what you're querying. If you want to use the loop with your results, you need to remove that line. So all you should have is:</p>\n\n<pre><code>$related_products = get_field( 'related_products' );\n\nif ( $related_products ) {\n $args = array( \n 'post_type' => 'product',\n 'post__in' => $related_products, \n );\n\n $custom_query = new WP_Query( $args );\n\n if ( $custom_query->have_posts() ) : \n while ( $custom_query->have_posts() ) : \n $custom_query->the_post(); \n get_template_part( 'parts/card', get_post_type() );\n endwhile;\n else : \n // do something else\n endif;\n\n wp_reset_postdata();\n}\n</code></pre>\n\n<p>But doing this query at all is unnecessary. If you set the field to return post objects, rather than IDs, you can just loop through those:</p>\n\n<pre><code>$related_products = get_field( 'related_products' );\n\nif ( $related_products ) {\n global $post; // Necessary.\n\n foreach ( $related_products as $post ) : // Must be called $post. \n setup_postdata( $post ); \n get_template_part( 'parts/card', get_post_type() );\n endforeach;\n\n wp_reset_postdata();\n}\n</code></pre>\n\n<p>This is the same as <a href=\"https://wordpress.stackexchange.com/a/342692/39152\">Faye's answer</a>, I'm just including it for completeness. If you're receiving any errors from that, then the issue is somewhere else. Probably inside your card template.</p>\n"
},
{
"answer_id": 343015,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 2,
"selected": true,
"text": "<p>My OP is about using the ACF relationship field in <code>WP_QUERY</code>. The ACF documentation leaves out one helpful bit that @JacobPeattie supplied. </p>\n\n<p>My final working code looks like this:</p>\n\n<pre><code>// ACF field is set to return IDs.\n// Array ( [0] => 395 [1] => 120 [2] => 388 [3] => 391 )\n\n$related_product = get_field( 'related_product' );\n\nif ( $related_product ) :\n\n global $post; // missing from ACF documentation\n\n foreach ( $related_product as $post ) : // Must be called $post. \n setup_postdata( $post ); \n get_template_part( 'parts/card', get_post_type() );\n endforeach;\n\n wp_reset_postdata();\n\nendif;\n</code></pre>\n\n<p>However, part of Jacob's explanation and subsequent comments are wrong. Because I rely on this community for accurate information, I can't accept his answer as correct. </p>\n\n<p>Jacob incorrectly asserts that passing an array of IDs to <code>WP_QUERY</code> and then using the <code>fields</code> parameter to return only IDs is redundant and won't work. </p>\n\n<p>You can use any number of things to inform <code>WP_QUERY</code> which posts to GET - terms, post type, IDs. This is completely separate from what you tell the query to RETURN - there is nothing redundant about passing then returning IDs. </p>\n\n<p>The <code>fields</code> parameter defaults to returning all fields. Alternatively, you can set <code>fields</code> to return <code>ids</code> (note plural). </p>\n\n<p>Deciding to return all fields or just IDs is a matter of optimization - if you don't need all fields, then don't return them. </p>\n\n<p>Here are two examples from my live site demonstrating that YOU DO NOT NEED ALL FIELDS in many common scenarios. You can easily try these for yourself and I've linked to more info below. </p>\n\n<p>This example displays a field - <code>the_title</code> ... super common, I use it all the time and you don't need to return all fields to do it. </p>\n\n<pre><code>$args = array( \n 'post_type' => 'product',\n 'fields' => 'ids',\n);\n\n$custom_query = new WP_Query( $args );\n\nif ( $custom_query->have_posts() ) : \n\n while ( $custom_query->have_posts() ) : \n $custom_query->the_post(); \n the_title();\n endwhile;\n\nelse : \n // do something else\nendif; \n\nwp_reset_query();\n</code></pre>\n\n<p>Here's an even more complex / optimized example. This one is for displaying a template part. This part has standard stuff like <code>the_title</code> + ACF fields + an Add Favorite feature + pulls in other parts. The results are filterable by FacetWP.</p>\n\n<p>Again, you only need <code>WP_QUERY</code> to return IDs. </p>\n\n<pre><code>$args = array( \n 'post_type' => 'product',\n 'fields' => 'ids',\n 'cache_results' => false,\n 'update_post_meta_cache' => false, \n 'update_post_term_cache' => false, \n 'facetwp' => true, \n);\n\n$custom_query = new WP_Query( $args );\n\nif ( $custom_query->have_posts() ) : \n\n while ( $custom_query->have_posts() ) : \n $custom_query->the_post(); \n get_template_part( 'parts/card', get_post_type() ); \n endwhile;\n\nelse :\n // do something else\nendif;\n\nwp_reset_query();\n</code></pre>\n\n<p>You can read more about optimizing <code>WP_QUERY</code> here (and lots of other places):</p>\n\n<ul>\n<li><a href=\"https://kinsta.com/blog/wp-query/\" rel=\"nofollow noreferrer\">https://kinsta.com/blog/wp-query/</a></li>\n</ul>\n\n<p>Thinking about it, these examples make perfect sense - things like <code>global Spost</code> and <code>setup_postdata($post)</code> and <code>$custom_query->the_post()</code> are specifically for setting context and ensuring the correct ID is referenced so you can then get the right field, template etc ...</p>\n\n<p>And why would a database need anything more than an ID to get a record's associated fields? ... The only answer I can think of is if the database is poorly designed ... In fact, I have never had a scenario where returning just IDs hasn't worked. </p>\n\n<p>I'm not claiming to be an expert - I only know that you can return just IDs because I read about it, tried it in my own projects, and it works. </p>\n"
}
] | 2019/07/12 | [
"https://wordpress.stackexchange.com/questions/342704",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105507/"
] | Using latest WP with Gutenberg. The excerpt metabox is (as you'd expect) over in the right column with the Document settings.
Is there any way to get it out of that column and into the main area where the textarea would then be of a *useful* size? | My OP is about using the ACF relationship field in `WP_QUERY`. The ACF documentation leaves out one helpful bit that @JacobPeattie supplied.
My final working code looks like this:
```
// ACF field is set to return IDs.
// Array ( [0] => 395 [1] => 120 [2] => 388 [3] => 391 )
$related_product = get_field( 'related_product' );
if ( $related_product ) :
global $post; // missing from ACF documentation
foreach ( $related_product as $post ) : // Must be called $post.
setup_postdata( $post );
get_template_part( 'parts/card', get_post_type() );
endforeach;
wp_reset_postdata();
endif;
```
However, part of Jacob's explanation and subsequent comments are wrong. Because I rely on this community for accurate information, I can't accept his answer as correct.
Jacob incorrectly asserts that passing an array of IDs to `WP_QUERY` and then using the `fields` parameter to return only IDs is redundant and won't work.
You can use any number of things to inform `WP_QUERY` which posts to GET - terms, post type, IDs. This is completely separate from what you tell the query to RETURN - there is nothing redundant about passing then returning IDs.
The `fields` parameter defaults to returning all fields. Alternatively, you can set `fields` to return `ids` (note plural).
Deciding to return all fields or just IDs is a matter of optimization - if you don't need all fields, then don't return them.
Here are two examples from my live site demonstrating that YOU DO NOT NEED ALL FIELDS in many common scenarios. You can easily try these for yourself and I've linked to more info below.
This example displays a field - `the_title` ... super common, I use it all the time and you don't need to return all fields to do it.
```
$args = array(
'post_type' => 'product',
'fields' => 'ids',
);
$custom_query = new WP_Query( $args );
if ( $custom_query->have_posts() ) :
while ( $custom_query->have_posts() ) :
$custom_query->the_post();
the_title();
endwhile;
else :
// do something else
endif;
wp_reset_query();
```
Here's an even more complex / optimized example. This one is for displaying a template part. This part has standard stuff like `the_title` + ACF fields + an Add Favorite feature + pulls in other parts. The results are filterable by FacetWP.
Again, you only need `WP_QUERY` to return IDs.
```
$args = array(
'post_type' => 'product',
'fields' => 'ids',
'cache_results' => false,
'update_post_meta_cache' => false,
'update_post_term_cache' => false,
'facetwp' => true,
);
$custom_query = new WP_Query( $args );
if ( $custom_query->have_posts() ) :
while ( $custom_query->have_posts() ) :
$custom_query->the_post();
get_template_part( 'parts/card', get_post_type() );
endwhile;
else :
// do something else
endif;
wp_reset_query();
```
You can read more about optimizing `WP_QUERY` here (and lots of other places):
* <https://kinsta.com/blog/wp-query/>
Thinking about it, these examples make perfect sense - things like `global Spost` and `setup_postdata($post)` and `$custom_query->the_post()` are specifically for setting context and ensuring the correct ID is referenced so you can then get the right field, template etc ...
And why would a database need anything more than an ID to get a record's associated fields? ... The only answer I can think of is if the database is poorly designed ... In fact, I have never had a scenario where returning just IDs hasn't worked.
I'm not claiming to be an expert - I only know that you can return just IDs because I read about it, tried it in my own projects, and it works. |
342,713 | <p>How can I put a loop in my single.php that shows the posts of the current category of the single and following the code structure that I have? The question comes, because I can not find the correct code.</p>
<p>I have tried with this code</p>
<pre><code><?php
$categories = get_the_category($post->ID);
if ( $categories ) {
$category_ids = array();
foreach ( $categories as $individual_category ) {
$category_ids[] = $individual_category->term_id;
}
$args=array(
'category__in' => $category_ids,
'post__not_in' => array($post->ID),
'showposts'=>3, // Number of related posts that will be shown.
'ignore_sticky_posts'=>1
);
$my_query = new wp_query( $args );
if( $my_query->have_posts() ) {
echo '<h3>Related Articles</h3>'; // You can edit this
echo '<ul>';
while ($my_query->have_posts()) {
$my_query->the_post();
?>
<!-- do stuff -->
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php
}
echo '</ul>';
}
}
?>
</code></pre>
<p>But as is obvious, this would only give me the category with ID number 3, and I need it to be the same as the single post that is being viewed.</p>
<p>Thanks </p>
<p><strong>-EDIT-</strong></p>
<p>This is my full single.php code</p>
<pre><code><div class="container">
<div id="breadcrumbs">
<?php if (function_exists('nav_breadcrumb')) nav_breadcrumb(); ?>
</div>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div class="single">
<div class="columns is-centered">
<div class="column is-two-fifths is-content">
<?php the_post_thumbnail(); ?>
<div class="title">
<?php the_title(); ?>
</div>
</div>
</div>
</div>
<?php the_content(); ?>
<?php endwhile; endif; ?>
<hr/>
<?php
$categories = get_the_category($post->ID);
if ($categories) {
$category_ids = array();
foreach ($categories as $individual_category) {
$category_ids[] = $individual_category->term_id;
}
$args = array(
'category__in' => $category_ids,
'post__not_in' => array($post->ID),
'showposts' => 3, // Number of related posts that will be shown.
'ignore_sticky_posts' => 1
);
$my_query = new wp_query($args);
if ($my_query->have_posts()) {
echo '<h3>Related Articles</h3>'; // You can edit this
echo '<ul>';
while ($my_query->have_posts()) {
$my_query->the_post();
?>
<!-- do stuff -->
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php
}
echo '</ul>';
}
}
?></div>
</code></pre>
| [
{
"answer_id": 342714,
"author": "Bhupen",
"author_id": 128529,
"author_profile": "https://wordpress.stackexchange.com/users/128529",
"pm_score": -1,
"selected": false,
"text": "<p>If you are trying to get \"Related Posts\" by category for custom taxonomy then see the code given below:</p>\n\n<pre><code>$categories = get_the_terms($post->ID, 'your-taxonomy-name');\nif ($categories) {\n$category_ids = array();\nforeach ($categories as $individual_category) {\n $category_ids[] = $individual_category->term_id;\n}\n$args = array(\n 'post_type' => 'your-post-type',\n 'post__not_in' => array($post->ID),\n 'showposts' => 3, // Number of related posts that will be shown.\n 'ignore_sticky_posts' => 1,\n 'tax_query' => array(\n array(\n 'taxonomy' => 'your-taxonomy-name',\n 'field' => 'id',\n 'terms' => $category_ids,\n 'operator'=> 'IN'\n )\n ),\n);\n$my_query = new wp_query($args);\n</code></pre>\n\n<p>Replace \"your-taxonomy-name\" and \"your-post-type\" with valid data.</p>\n"
},
{
"answer_id": 342717,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>I suggest the following:</p>\n\n<pre><code>$categories = get_the_category();\n$category_ids = wp_list_pluck( $categories, 'term_id' );\n\n$args = [\n 'numberposts' => 4,\n 'category__in' => $category_ids,\n];\n\n$related_posts = get_posts( $args );\n$related_posts = wp_list_filter( $related_posts, [ 'ID' => get_queried_oject_id() ], 'NOT' );\n\nif ( count( $related_posts > 3 ) ) {\n array_pop( $related_posts );\n}\n\nglobal $post;\n\nforeach ( $related_posts as $post ) {\n setup_postdata( $post );\n\n // Output posts.\n}\n\nwp_reset_postdata();\n</code></pre>\n\n<p>Note the following points about the code:</p>\n\n<ol>\n<li>I use <a href=\"https://developer.wordpress.org/reference/functions/wp_list_pluck/\" rel=\"nofollow noreferrer\"><code>wp_list_pluck()</code></a> to get the category IDs in a single line.</li>\n<li>I don't use <code>post__not_in</code>. This has known <a href=\"https://wpvip.com/documentation/performance-improvements-by-removing-usage-of-post__not_in/\" rel=\"nofollow noreferrer\">performance issues</a>. Instead I query for 1 more post than we need so that we can remove the current post later if it appears in the results. This will be faster than using <code>post__not_in</code>.</li>\n<li>I use <code>get_posts()</code> instead of <code>WP_Query</code>. This is because it has more appropriate defaults for secondary queries (such as setting <code>ignore_sticky_posts</code> and <code>no_found_rows</code> to <code>true</code>.</li>\n<li>Once we have results I use <code>wp_list_filter()</code> to remove the current post, if it appears in the results. I do this by using <code>get_queried_oject_id()</code> to get the ID of the current post. If it doesn't appear in the results then I use <code>array_pop()</code> to remove the last post to get back down to 3 posts.</li>\n</ol>\n"
}
] | 2019/07/12 | [
"https://wordpress.stackexchange.com/questions/342713",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/149472/"
] | How can I put a loop in my single.php that shows the posts of the current category of the single and following the code structure that I have? The question comes, because I can not find the correct code.
I have tried with this code
```
<?php
$categories = get_the_category($post->ID);
if ( $categories ) {
$category_ids = array();
foreach ( $categories as $individual_category ) {
$category_ids[] = $individual_category->term_id;
}
$args=array(
'category__in' => $category_ids,
'post__not_in' => array($post->ID),
'showposts'=>3, // Number of related posts that will be shown.
'ignore_sticky_posts'=>1
);
$my_query = new wp_query( $args );
if( $my_query->have_posts() ) {
echo '<h3>Related Articles</h3>'; // You can edit this
echo '<ul>';
while ($my_query->have_posts()) {
$my_query->the_post();
?>
<!-- do stuff -->
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php
}
echo '</ul>';
}
}
?>
```
But as is obvious, this would only give me the category with ID number 3, and I need it to be the same as the single post that is being viewed.
Thanks
**-EDIT-**
This is my full single.php code
```
<div class="container">
<div id="breadcrumbs">
<?php if (function_exists('nav_breadcrumb')) nav_breadcrumb(); ?>
</div>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div class="single">
<div class="columns is-centered">
<div class="column is-two-fifths is-content">
<?php the_post_thumbnail(); ?>
<div class="title">
<?php the_title(); ?>
</div>
</div>
</div>
</div>
<?php the_content(); ?>
<?php endwhile; endif; ?>
<hr/>
<?php
$categories = get_the_category($post->ID);
if ($categories) {
$category_ids = array();
foreach ($categories as $individual_category) {
$category_ids[] = $individual_category->term_id;
}
$args = array(
'category__in' => $category_ids,
'post__not_in' => array($post->ID),
'showposts' => 3, // Number of related posts that will be shown.
'ignore_sticky_posts' => 1
);
$my_query = new wp_query($args);
if ($my_query->have_posts()) {
echo '<h3>Related Articles</h3>'; // You can edit this
echo '<ul>';
while ($my_query->have_posts()) {
$my_query->the_post();
?>
<!-- do stuff -->
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php
}
echo '</ul>';
}
}
?></div>
``` | I suggest the following:
```
$categories = get_the_category();
$category_ids = wp_list_pluck( $categories, 'term_id' );
$args = [
'numberposts' => 4,
'category__in' => $category_ids,
];
$related_posts = get_posts( $args );
$related_posts = wp_list_filter( $related_posts, [ 'ID' => get_queried_oject_id() ], 'NOT' );
if ( count( $related_posts > 3 ) ) {
array_pop( $related_posts );
}
global $post;
foreach ( $related_posts as $post ) {
setup_postdata( $post );
// Output posts.
}
wp_reset_postdata();
```
Note the following points about the code:
1. I use [`wp_list_pluck()`](https://developer.wordpress.org/reference/functions/wp_list_pluck/) to get the category IDs in a single line.
2. I don't use `post__not_in`. This has known [performance issues](https://wpvip.com/documentation/performance-improvements-by-removing-usage-of-post__not_in/). Instead I query for 1 more post than we need so that we can remove the current post later if it appears in the results. This will be faster than using `post__not_in`.
3. I use `get_posts()` instead of `WP_Query`. This is because it has more appropriate defaults for secondary queries (such as setting `ignore_sticky_posts` and `no_found_rows` to `true`.
4. Once we have results I use `wp_list_filter()` to remove the current post, if it appears in the results. I do this by using `get_queried_oject_id()` to get the ID of the current post. If it doesn't appear in the results then I use `array_pop()` to remove the last post to get back down to 3 posts. |
342,743 | <p>How can I prevent my custom user role to not be able to add new pages.</p>
<p>I have this array of capabilities for my user role:</p>
<pre><code> $args = array(
'delete_others_pages' => false,
'delete_others_posts' => false,
'delete_pages' => false,
'delete_posts' => true,
'delete_private_pages' => false,
'delete_private_posts' => true,
'delete_published_pages' => false,
'delete_published_posts' => true,
'edit_others_pages' => true,
'edit_others_posts' => true,
'edit_pages' => true,
'edit_posts' => true,
'edit_private_pages' => true,
'edit_private_posts' => true,
'edit_published_pages' => true,
'edit_published_posts' => true,
'manage_categories' => true,
'manage_links' => true,
'moderate_comments' => true,
'publish_pages' => false,
'publish_posts' => true,
'create_pages' => false, //THIS SETTING DOES NOT WORK / EXISTS
'read' => true,
'read_private_pages' => true,
'read_private_posts' => true,
'upload_files' => true,
}
</code></pre>
<p>With these settings my user role can still "Add new page" but the page will then be submitted for "review" by an administrator.</p>
<p>My user should be able to "edit existing pages" but may not "add new" or "delete" any pages.</p>
<p>For "posts" the user should be able to "add new", "update" and "delete" any posts (full control). And the same for "Custom Post Types".</p>
<p>Best Regards</p>
<p>Shane Madsen</p>
| [
{
"answer_id": 342744,
"author": "Oscprofessionals",
"author_id": 171102,
"author_profile": "https://wordpress.stackexchange.com/users/171102",
"pm_score": -1,
"selected": false,
"text": "<blockquote>\n <p>this parameter should work for this</p>\n</blockquote>\n\n<pre><code>'publish_pages' => false,\n</code></pre>\n"
},
{
"answer_id": 342747,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p>Post types in WordPress have a list of capabilities that govern permissions surrounding them. These are:</p>\n\n<pre><code>edit_post\nread_post\ndelete_post\nedit_posts\nedit_others_posts\npublish_posts\nread_private_posts\nread\ndelete_posts\ndelete_private_posts\ndelete_published_posts\ndelete_others_posts\nedit_private_posts\nedit_published_posts\ncreate_posts\n</code></pre>\n\n<p>Internally each post type matches these to the <em>actual</em> capabilities that can be given in WordPress. Most of the time these have the exact same name. So the <code>edit_posts</code> capability of the <code>post</code> post type is <code>edit_posts</code>, while the <code>edit_posts</code> capability for the <code>page</code> post type is <code>edit_pages</code>.</p>\n\n<p>The one exception to this is <code>create_posts</code>. This is the post type capability that WordPress checks to decide whether a user can create a new post of that type. It checks this:</p>\n\n<pre><code>if ( current_user_can( get_post_type_object( 'page' )->cap->create_posts ) ) {}\n</code></pre>\n\n<p>Unlike the other capabilities, for posts and pages <code>create_posts</code> is actually mapped to <code>edit_posts</code> and <code>edit_pages</code> respectively, not <code>create_posts</code> or <code>create_pages</code>, which don't exist. </p>\n\n<p>So if you printed <code>get_post_type_object( 'page' )->cap->create_posts</code> you'd see that the value is <code>edit_pages</code>, and users with that capability can see the Add New button. Because this is <code>edit_pages</code> and not <code>publish_pages</code>, it allows users to create new pages and posts even if they can't publish them, they'll just be put into pending review, which is the behaviour you want to prevent.</p>\n\n<p>For custom post types you can control this behaviour by setting <code>create_posts</code> in the <code>capabilities</code> argument to something else:</p>\n\n<pre><code>register_post_type(\n 'my_custom_type',\n [\n 'capabilities' => [\n 'create_posts' => 'manage_options',\n ],\n ]\n);\n</code></pre>\n\n<p>For that custom post types, only users with <code>manage_options</code> will be able to add new posts.</p>\n\n<p>For the built in post types you can use the <code>register_post_type_args</code> filter to set this capability however you'd like for the default post types:</p>\n\n<pre><code>function wpse_342743_create_page_capability( $args, $post_type ) {\n if ( 'page' === $post_type ) {\n $args['capabilities'] = [ \n 'create_posts' => 'manage_options',\n ];\n }\n\n return $args;\n}\nadd_filter( 'register_post_type_args', 'wpse_342743_create_page_capability', 10, 2 );\n</code></pre>\n\n<p>With that code only users with <code>manage_options</code> will be able to create new pages, but they will still be able to update them without review if they otherwise have <code>edit_pages</code> and <code>publish_pages</code>. You can change this capability to be <code>delete_pages</code> so that only users who can delete pages can create them, or you could pass your own custom capability that you'll give to users to give them the ability to create pages.</p>\n"
}
] | 2019/07/12 | [
"https://wordpress.stackexchange.com/questions/342743",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/169647/"
] | How can I prevent my custom user role to not be able to add new pages.
I have this array of capabilities for my user role:
```
$args = array(
'delete_others_pages' => false,
'delete_others_posts' => false,
'delete_pages' => false,
'delete_posts' => true,
'delete_private_pages' => false,
'delete_private_posts' => true,
'delete_published_pages' => false,
'delete_published_posts' => true,
'edit_others_pages' => true,
'edit_others_posts' => true,
'edit_pages' => true,
'edit_posts' => true,
'edit_private_pages' => true,
'edit_private_posts' => true,
'edit_published_pages' => true,
'edit_published_posts' => true,
'manage_categories' => true,
'manage_links' => true,
'moderate_comments' => true,
'publish_pages' => false,
'publish_posts' => true,
'create_pages' => false, //THIS SETTING DOES NOT WORK / EXISTS
'read' => true,
'read_private_pages' => true,
'read_private_posts' => true,
'upload_files' => true,
}
```
With these settings my user role can still "Add new page" but the page will then be submitted for "review" by an administrator.
My user should be able to "edit existing pages" but may not "add new" or "delete" any pages.
For "posts" the user should be able to "add new", "update" and "delete" any posts (full control). And the same for "Custom Post Types".
Best Regards
Shane Madsen | Post types in WordPress have a list of capabilities that govern permissions surrounding them. These are:
```
edit_post
read_post
delete_post
edit_posts
edit_others_posts
publish_posts
read_private_posts
read
delete_posts
delete_private_posts
delete_published_posts
delete_others_posts
edit_private_posts
edit_published_posts
create_posts
```
Internally each post type matches these to the *actual* capabilities that can be given in WordPress. Most of the time these have the exact same name. So the `edit_posts` capability of the `post` post type is `edit_posts`, while the `edit_posts` capability for the `page` post type is `edit_pages`.
The one exception to this is `create_posts`. This is the post type capability that WordPress checks to decide whether a user can create a new post of that type. It checks this:
```
if ( current_user_can( get_post_type_object( 'page' )->cap->create_posts ) ) {}
```
Unlike the other capabilities, for posts and pages `create_posts` is actually mapped to `edit_posts` and `edit_pages` respectively, not `create_posts` or `create_pages`, which don't exist.
So if you printed `get_post_type_object( 'page' )->cap->create_posts` you'd see that the value is `edit_pages`, and users with that capability can see the Add New button. Because this is `edit_pages` and not `publish_pages`, it allows users to create new pages and posts even if they can't publish them, they'll just be put into pending review, which is the behaviour you want to prevent.
For custom post types you can control this behaviour by setting `create_posts` in the `capabilities` argument to something else:
```
register_post_type(
'my_custom_type',
[
'capabilities' => [
'create_posts' => 'manage_options',
],
]
);
```
For that custom post types, only users with `manage_options` will be able to add new posts.
For the built in post types you can use the `register_post_type_args` filter to set this capability however you'd like for the default post types:
```
function wpse_342743_create_page_capability( $args, $post_type ) {
if ( 'page' === $post_type ) {
$args['capabilities'] = [
'create_posts' => 'manage_options',
];
}
return $args;
}
add_filter( 'register_post_type_args', 'wpse_342743_create_page_capability', 10, 2 );
```
With that code only users with `manage_options` will be able to create new pages, but they will still be able to update them without review if they otherwise have `edit_pages` and `publish_pages`. You can change this capability to be `delete_pages` so that only users who can delete pages can create them, or you could pass your own custom capability that you'll give to users to give them the ability to create pages. |
342,791 | <p>I have the plugin iThemes Security Pro installed on a couple of my websites. Recently, I've noticed that my Sucuri SiteCheck (both automated and not) scans are failing, but I have no idea why that is the case. The log is also ambiguous, telling me: <code>Unable to properly scan your site. Timeout reached</code>.</p>
<p>Below is the raw log the plugin gives me. Appreciate if anyone can tell me what the problem is. I don't have firewalls enabled, either on the plugin or on the Apache level, though I have ModSecurity enabled.</p>
<p>ModSecurity's logs don't give me any errors whenever I try a SiteCheck though, so it seems like the request is not even getting to Apache.</p>
<pre><code>id => 15729
module => malware
type => warning
code => sucuri-system-error
timestamp => 2019-07-13 09:06:55
init_timestamp => 2019-07-13 09:06:48
remote_ip => 10.20.30.40
user_id => 1
url => https://domain.com/wp-admin/admin-ajax.php
memory_current => 21832592
memory_peak => 21915880
data => Array
results => Array
BLACKLIST => Array
INFO => Array
0 => Array
0 => Domain clean by Google Safe Browsing: www.domain.com
1 => https://transparencyreport.google.com/safe-browsing/search?url=domain.com
1 => Array
0 => Domain clean by Norton Safe Web: www.domain.com
1 => https://safeweb.norton.com/report/show?url=domain.com
2 => Array
0 => Domain clean by McAfee: www.domain.com
1 => https://www.siteadvisor.com/sitereport.html?url=domain.com
3 => Array
0 => Domain clean by Sucuri Labs: www.domain.com
1 => https://labs.sucuri.net/?blacklist=domain.com
4 => Array
0 => Domain clean by ESET: www.domain.com
1 => https://labs.sucuri.net/?eset
5 => Array
0 => Domain clean by PhishTank: www.domain.com
1 => https://www.phishtank.com
6 => Array
0 => Domain clean by Yandex: www.domain.com
1 => https://www.yandex.com/infected?url=domain.com
7 => Array
0 => Domain clean by Opera: www.domain.com
1 => https://www.opera.com
8 => Array
0 => Domain clean by Spamhaus: www.domain.com
1 => http://www.spamhaus.org/query/domain/domain.com
SCAN => Array
DOMAIN => Array
0 => www.domain.com
INPUT => Array
0 => http://www.domain.com/
IP => Array
0 => 10.20.30.40
SITE => Array
0 => http://www.domain.com/
SYSTEM => Array
ERROR => Array
0 => Unable to properly scan your site. Timeout reached
VERSION => Array
DBDATE => Array
0 => 03 Jul 2019 15:05 UTC
VERSION => Array
0 => 2.6
cached => [boolean] false
</code></pre>
| [
{
"answer_id": 342744,
"author": "Oscprofessionals",
"author_id": 171102,
"author_profile": "https://wordpress.stackexchange.com/users/171102",
"pm_score": -1,
"selected": false,
"text": "<blockquote>\n <p>this parameter should work for this</p>\n</blockquote>\n\n<pre><code>'publish_pages' => false,\n</code></pre>\n"
},
{
"answer_id": 342747,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p>Post types in WordPress have a list of capabilities that govern permissions surrounding them. These are:</p>\n\n<pre><code>edit_post\nread_post\ndelete_post\nedit_posts\nedit_others_posts\npublish_posts\nread_private_posts\nread\ndelete_posts\ndelete_private_posts\ndelete_published_posts\ndelete_others_posts\nedit_private_posts\nedit_published_posts\ncreate_posts\n</code></pre>\n\n<p>Internally each post type matches these to the <em>actual</em> capabilities that can be given in WordPress. Most of the time these have the exact same name. So the <code>edit_posts</code> capability of the <code>post</code> post type is <code>edit_posts</code>, while the <code>edit_posts</code> capability for the <code>page</code> post type is <code>edit_pages</code>.</p>\n\n<p>The one exception to this is <code>create_posts</code>. This is the post type capability that WordPress checks to decide whether a user can create a new post of that type. It checks this:</p>\n\n<pre><code>if ( current_user_can( get_post_type_object( 'page' )->cap->create_posts ) ) {}\n</code></pre>\n\n<p>Unlike the other capabilities, for posts and pages <code>create_posts</code> is actually mapped to <code>edit_posts</code> and <code>edit_pages</code> respectively, not <code>create_posts</code> or <code>create_pages</code>, which don't exist. </p>\n\n<p>So if you printed <code>get_post_type_object( 'page' )->cap->create_posts</code> you'd see that the value is <code>edit_pages</code>, and users with that capability can see the Add New button. Because this is <code>edit_pages</code> and not <code>publish_pages</code>, it allows users to create new pages and posts even if they can't publish them, they'll just be put into pending review, which is the behaviour you want to prevent.</p>\n\n<p>For custom post types you can control this behaviour by setting <code>create_posts</code> in the <code>capabilities</code> argument to something else:</p>\n\n<pre><code>register_post_type(\n 'my_custom_type',\n [\n 'capabilities' => [\n 'create_posts' => 'manage_options',\n ],\n ]\n);\n</code></pre>\n\n<p>For that custom post types, only users with <code>manage_options</code> will be able to add new posts.</p>\n\n<p>For the built in post types you can use the <code>register_post_type_args</code> filter to set this capability however you'd like for the default post types:</p>\n\n<pre><code>function wpse_342743_create_page_capability( $args, $post_type ) {\n if ( 'page' === $post_type ) {\n $args['capabilities'] = [ \n 'create_posts' => 'manage_options',\n ];\n }\n\n return $args;\n}\nadd_filter( 'register_post_type_args', 'wpse_342743_create_page_capability', 10, 2 );\n</code></pre>\n\n<p>With that code only users with <code>manage_options</code> will be able to create new pages, but they will still be able to update them without review if they otherwise have <code>edit_pages</code> and <code>publish_pages</code>. You can change this capability to be <code>delete_pages</code> so that only users who can delete pages can create them, or you could pass your own custom capability that you'll give to users to give them the ability to create pages.</p>\n"
}
] | 2019/07/13 | [
"https://wordpress.stackexchange.com/questions/342791",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78806/"
] | I have the plugin iThemes Security Pro installed on a couple of my websites. Recently, I've noticed that my Sucuri SiteCheck (both automated and not) scans are failing, but I have no idea why that is the case. The log is also ambiguous, telling me: `Unable to properly scan your site. Timeout reached`.
Below is the raw log the plugin gives me. Appreciate if anyone can tell me what the problem is. I don't have firewalls enabled, either on the plugin or on the Apache level, though I have ModSecurity enabled.
ModSecurity's logs don't give me any errors whenever I try a SiteCheck though, so it seems like the request is not even getting to Apache.
```
id => 15729
module => malware
type => warning
code => sucuri-system-error
timestamp => 2019-07-13 09:06:55
init_timestamp => 2019-07-13 09:06:48
remote_ip => 10.20.30.40
user_id => 1
url => https://domain.com/wp-admin/admin-ajax.php
memory_current => 21832592
memory_peak => 21915880
data => Array
results => Array
BLACKLIST => Array
INFO => Array
0 => Array
0 => Domain clean by Google Safe Browsing: www.domain.com
1 => https://transparencyreport.google.com/safe-browsing/search?url=domain.com
1 => Array
0 => Domain clean by Norton Safe Web: www.domain.com
1 => https://safeweb.norton.com/report/show?url=domain.com
2 => Array
0 => Domain clean by McAfee: www.domain.com
1 => https://www.siteadvisor.com/sitereport.html?url=domain.com
3 => Array
0 => Domain clean by Sucuri Labs: www.domain.com
1 => https://labs.sucuri.net/?blacklist=domain.com
4 => Array
0 => Domain clean by ESET: www.domain.com
1 => https://labs.sucuri.net/?eset
5 => Array
0 => Domain clean by PhishTank: www.domain.com
1 => https://www.phishtank.com
6 => Array
0 => Domain clean by Yandex: www.domain.com
1 => https://www.yandex.com/infected?url=domain.com
7 => Array
0 => Domain clean by Opera: www.domain.com
1 => https://www.opera.com
8 => Array
0 => Domain clean by Spamhaus: www.domain.com
1 => http://www.spamhaus.org/query/domain/domain.com
SCAN => Array
DOMAIN => Array
0 => www.domain.com
INPUT => Array
0 => http://www.domain.com/
IP => Array
0 => 10.20.30.40
SITE => Array
0 => http://www.domain.com/
SYSTEM => Array
ERROR => Array
0 => Unable to properly scan your site. Timeout reached
VERSION => Array
DBDATE => Array
0 => 03 Jul 2019 15:05 UTC
VERSION => Array
0 => 2.6
cached => [boolean] false
``` | Post types in WordPress have a list of capabilities that govern permissions surrounding them. These are:
```
edit_post
read_post
delete_post
edit_posts
edit_others_posts
publish_posts
read_private_posts
read
delete_posts
delete_private_posts
delete_published_posts
delete_others_posts
edit_private_posts
edit_published_posts
create_posts
```
Internally each post type matches these to the *actual* capabilities that can be given in WordPress. Most of the time these have the exact same name. So the `edit_posts` capability of the `post` post type is `edit_posts`, while the `edit_posts` capability for the `page` post type is `edit_pages`.
The one exception to this is `create_posts`. This is the post type capability that WordPress checks to decide whether a user can create a new post of that type. It checks this:
```
if ( current_user_can( get_post_type_object( 'page' )->cap->create_posts ) ) {}
```
Unlike the other capabilities, for posts and pages `create_posts` is actually mapped to `edit_posts` and `edit_pages` respectively, not `create_posts` or `create_pages`, which don't exist.
So if you printed `get_post_type_object( 'page' )->cap->create_posts` you'd see that the value is `edit_pages`, and users with that capability can see the Add New button. Because this is `edit_pages` and not `publish_pages`, it allows users to create new pages and posts even if they can't publish them, they'll just be put into pending review, which is the behaviour you want to prevent.
For custom post types you can control this behaviour by setting `create_posts` in the `capabilities` argument to something else:
```
register_post_type(
'my_custom_type',
[
'capabilities' => [
'create_posts' => 'manage_options',
],
]
);
```
For that custom post types, only users with `manage_options` will be able to add new posts.
For the built in post types you can use the `register_post_type_args` filter to set this capability however you'd like for the default post types:
```
function wpse_342743_create_page_capability( $args, $post_type ) {
if ( 'page' === $post_type ) {
$args['capabilities'] = [
'create_posts' => 'manage_options',
];
}
return $args;
}
add_filter( 'register_post_type_args', 'wpse_342743_create_page_capability', 10, 2 );
```
With that code only users with `manage_options` will be able to create new pages, but they will still be able to update them without review if they otherwise have `edit_pages` and `publish_pages`. You can change this capability to be `delete_pages` so that only users who can delete pages can create them, or you could pass your own custom capability that you'll give to users to give them the ability to create pages. |
342,804 | <p>Im looking to edit a parent theme, and not just the functions and style files. I find that child themes don’t have the flexibility i want. How can i edit the parent theme without all the risk and the possibility of an update overriding all my changes?</p>
| [
{
"answer_id": 342744,
"author": "Oscprofessionals",
"author_id": 171102,
"author_profile": "https://wordpress.stackexchange.com/users/171102",
"pm_score": -1,
"selected": false,
"text": "<blockquote>\n <p>this parameter should work for this</p>\n</blockquote>\n\n<pre><code>'publish_pages' => false,\n</code></pre>\n"
},
{
"answer_id": 342747,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p>Post types in WordPress have a list of capabilities that govern permissions surrounding them. These are:</p>\n\n<pre><code>edit_post\nread_post\ndelete_post\nedit_posts\nedit_others_posts\npublish_posts\nread_private_posts\nread\ndelete_posts\ndelete_private_posts\ndelete_published_posts\ndelete_others_posts\nedit_private_posts\nedit_published_posts\ncreate_posts\n</code></pre>\n\n<p>Internally each post type matches these to the <em>actual</em> capabilities that can be given in WordPress. Most of the time these have the exact same name. So the <code>edit_posts</code> capability of the <code>post</code> post type is <code>edit_posts</code>, while the <code>edit_posts</code> capability for the <code>page</code> post type is <code>edit_pages</code>.</p>\n\n<p>The one exception to this is <code>create_posts</code>. This is the post type capability that WordPress checks to decide whether a user can create a new post of that type. It checks this:</p>\n\n<pre><code>if ( current_user_can( get_post_type_object( 'page' )->cap->create_posts ) ) {}\n</code></pre>\n\n<p>Unlike the other capabilities, for posts and pages <code>create_posts</code> is actually mapped to <code>edit_posts</code> and <code>edit_pages</code> respectively, not <code>create_posts</code> or <code>create_pages</code>, which don't exist. </p>\n\n<p>So if you printed <code>get_post_type_object( 'page' )->cap->create_posts</code> you'd see that the value is <code>edit_pages</code>, and users with that capability can see the Add New button. Because this is <code>edit_pages</code> and not <code>publish_pages</code>, it allows users to create new pages and posts even if they can't publish them, they'll just be put into pending review, which is the behaviour you want to prevent.</p>\n\n<p>For custom post types you can control this behaviour by setting <code>create_posts</code> in the <code>capabilities</code> argument to something else:</p>\n\n<pre><code>register_post_type(\n 'my_custom_type',\n [\n 'capabilities' => [\n 'create_posts' => 'manage_options',\n ],\n ]\n);\n</code></pre>\n\n<p>For that custom post types, only users with <code>manage_options</code> will be able to add new posts.</p>\n\n<p>For the built in post types you can use the <code>register_post_type_args</code> filter to set this capability however you'd like for the default post types:</p>\n\n<pre><code>function wpse_342743_create_page_capability( $args, $post_type ) {\n if ( 'page' === $post_type ) {\n $args['capabilities'] = [ \n 'create_posts' => 'manage_options',\n ];\n }\n\n return $args;\n}\nadd_filter( 'register_post_type_args', 'wpse_342743_create_page_capability', 10, 2 );\n</code></pre>\n\n<p>With that code only users with <code>manage_options</code> will be able to create new pages, but they will still be able to update them without review if they otherwise have <code>edit_pages</code> and <code>publish_pages</code>. You can change this capability to be <code>delete_pages</code> so that only users who can delete pages can create them, or you could pass your own custom capability that you'll give to users to give them the ability to create pages.</p>\n"
}
] | 2019/07/13 | [
"https://wordpress.stackexchange.com/questions/342804",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/170494/"
] | Im looking to edit a parent theme, and not just the functions and style files. I find that child themes don’t have the flexibility i want. How can i edit the parent theme without all the risk and the possibility of an update overriding all my changes? | Post types in WordPress have a list of capabilities that govern permissions surrounding them. These are:
```
edit_post
read_post
delete_post
edit_posts
edit_others_posts
publish_posts
read_private_posts
read
delete_posts
delete_private_posts
delete_published_posts
delete_others_posts
edit_private_posts
edit_published_posts
create_posts
```
Internally each post type matches these to the *actual* capabilities that can be given in WordPress. Most of the time these have the exact same name. So the `edit_posts` capability of the `post` post type is `edit_posts`, while the `edit_posts` capability for the `page` post type is `edit_pages`.
The one exception to this is `create_posts`. This is the post type capability that WordPress checks to decide whether a user can create a new post of that type. It checks this:
```
if ( current_user_can( get_post_type_object( 'page' )->cap->create_posts ) ) {}
```
Unlike the other capabilities, for posts and pages `create_posts` is actually mapped to `edit_posts` and `edit_pages` respectively, not `create_posts` or `create_pages`, which don't exist.
So if you printed `get_post_type_object( 'page' )->cap->create_posts` you'd see that the value is `edit_pages`, and users with that capability can see the Add New button. Because this is `edit_pages` and not `publish_pages`, it allows users to create new pages and posts even if they can't publish them, they'll just be put into pending review, which is the behaviour you want to prevent.
For custom post types you can control this behaviour by setting `create_posts` in the `capabilities` argument to something else:
```
register_post_type(
'my_custom_type',
[
'capabilities' => [
'create_posts' => 'manage_options',
],
]
);
```
For that custom post types, only users with `manage_options` will be able to add new posts.
For the built in post types you can use the `register_post_type_args` filter to set this capability however you'd like for the default post types:
```
function wpse_342743_create_page_capability( $args, $post_type ) {
if ( 'page' === $post_type ) {
$args['capabilities'] = [
'create_posts' => 'manage_options',
];
}
return $args;
}
add_filter( 'register_post_type_args', 'wpse_342743_create_page_capability', 10, 2 );
```
With that code only users with `manage_options` will be able to create new pages, but they will still be able to update them without review if they otherwise have `edit_pages` and `publish_pages`. You can change this capability to be `delete_pages` so that only users who can delete pages can create them, or you could pass your own custom capability that you'll give to users to give them the ability to create pages. |
342,867 | <p>My need is to have a <code>.php</code> file that is located in the root folders of all WordPress websites I manage, which can flush all cache of all sites.</p>
<p>Therefore, I created a file "flush-cache.php" in the root folder of the first website, and I added the following code: </p>
<pre><code><?php
/**
* Flushing the W3TC Plugin's Cache entirely, and specifically, also page cache (as it does not seem to be part of flush-all)
*
* @package WordPress
*/
ignore_user_abort( true );
/* Don't make the request block till we finish, if possible. */
if ( function_exists( 'fastcgi_finish_request' ) && version_compare( phpversion(), '7.0.16', '>=' ) ) {
fastcgi_finish_request();
}
if ( ! empty( $_POST ) || defined( 'DOING_AJAX' ) || defined( 'DOING_CRON' ) ) {
die();
}
// Flush W3TC Cache right now
function flush_w3tc_cache() {
$w3_plugin_totalcache->flush_all();
}
add_action( 'wp', 'flush_w3tc_cache' );
function flush_w3tc_page() {
$w3_plugin_totalcache->flush_pgcache();
}
add_action( 'wp', 'flush_w3tc_page' );
// END Flush W3TC Cache right now
</code></pre>
<p>I found most of it here: <a href="https://stackoverflow.com/questions/34509492/w3-total-cache-clear-page-cache-every-hour-automatic">https://stackoverflow.com/questions/34509492/w3-total-cache-clear-page-cache-every-hour-automatic</a></p>
<p>However, when I open the file <a href="https://domain.xyz/flush-cache.php" rel="nofollow noreferrer">https://domain.xyz/flush-cache.php</a>, it does not seem to work. I don't get an error message or any other output (expected), but in the backend of that site, I still see that the page cache needs to be cleared.</p>
<p>Any suggestions what could be wrong?</p>
| [
{
"answer_id": 343472,
"author": "codingforworlddomination",
"author_id": 171633,
"author_profile": "https://wordpress.stackexchange.com/users/171633",
"pm_score": 1,
"selected": false,
"text": "<p>The working solution is:</p>\n\n<pre><code><?php\n/*\n * Flushing the W3TC Plugin's Cache entirely\n * @package WordPress\n */\nignore_user_abort( true );\ninclude('/home/clients/<client-directory>/<website-directory>' . '/wp-load.php');\nw3tc_flush_all();\n</code></pre>\n"
},
{
"answer_id": 344927,
"author": "codingforworlddomination",
"author_id": 171633,
"author_profile": "https://wordpress.stackexchange.com/users/171633",
"pm_score": 0,
"selected": false,
"text": "<p>I ended up creating a tool that can flush multiple W3TC websites simultaneously using one password-protected control panel. It’s available on Github, if this could help anyone: <a href=\"https://github.com/web-butler/w3tc-remote-flush-multiple\" rel=\"nofollow noreferrer\">https://github.com/web-butler/w3tc-remote-flush-multiple</a></p>\n"
}
] | 2019/07/15 | [
"https://wordpress.stackexchange.com/questions/342867",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/171633/"
] | My need is to have a `.php` file that is located in the root folders of all WordPress websites I manage, which can flush all cache of all sites.
Therefore, I created a file "flush-cache.php" in the root folder of the first website, and I added the following code:
```
<?php
/**
* Flushing the W3TC Plugin's Cache entirely, and specifically, also page cache (as it does not seem to be part of flush-all)
*
* @package WordPress
*/
ignore_user_abort( true );
/* Don't make the request block till we finish, if possible. */
if ( function_exists( 'fastcgi_finish_request' ) && version_compare( phpversion(), '7.0.16', '>=' ) ) {
fastcgi_finish_request();
}
if ( ! empty( $_POST ) || defined( 'DOING_AJAX' ) || defined( 'DOING_CRON' ) ) {
die();
}
// Flush W3TC Cache right now
function flush_w3tc_cache() {
$w3_plugin_totalcache->flush_all();
}
add_action( 'wp', 'flush_w3tc_cache' );
function flush_w3tc_page() {
$w3_plugin_totalcache->flush_pgcache();
}
add_action( 'wp', 'flush_w3tc_page' );
// END Flush W3TC Cache right now
```
I found most of it here: <https://stackoverflow.com/questions/34509492/w3-total-cache-clear-page-cache-every-hour-automatic>
However, when I open the file <https://domain.xyz/flush-cache.php>, it does not seem to work. I don't get an error message or any other output (expected), but in the backend of that site, I still see that the page cache needs to be cleared.
Any suggestions what could be wrong? | The working solution is:
```
<?php
/*
* Flushing the W3TC Plugin's Cache entirely
* @package WordPress
*/
ignore_user_abort( true );
include('/home/clients/<client-directory>/<website-directory>' . '/wp-load.php');
w3tc_flush_all();
``` |
342,940 | <p>I'm just starting to create new theme and i'm new to code. I'm stuck in customizing the post thumbnail code, i tried add </p>
<pre><code><?php previous_post_link(get_the_post_thumbnail(get_previous_post(), array(
'class' => 'rounded-lg object-cover'
)) . '<h4 class="text-center">%link</h4>',
'%title',false
);
?>
</code></pre>
<p>but it doesn't seem to work. did my array mistakenly placed in the code?</p>
| [
{
"answer_id": 342941,
"author": "haiz85",
"author_id": 171911,
"author_profile": "https://wordpress.stackexchange.com/users/171911",
"pm_score": -1,
"selected": false,
"text": "<p>i think i already fix it, and now i have problem with customizing image width and height, here are my latest code.</p>\n\n<pre><code> $prev_post = get_previous_post();\n previous_post_link(\n get_the_post_thumbnail($prev_post->ID, 'custom-size-image', array(\n 'class' => 'rounded-lg object-cover',\n 'sizes' => 'width=\"371\" height=\"270\"'\n )) . '<h4 class=\"text-center\">%link</h4>',\n '%title',\n false\n );\n</code></pre>\n\n<p>but 'sizes' part doesn't seem to work, please help</p>\n"
},
{
"answer_id": 343308,
"author": "haiz85",
"author_id": 171911,
"author_profile": "https://wordpress.stackexchange.com/users/171911",
"pm_score": 1,
"selected": false,
"text": "<p>Sorry for late reply, already fixed, i miss understood about array, so here the code that completely run as i want it.</p>\n\n<pre><code> <?php\n $next_post = get_next_post();\n next_post_link('%link',\n get_the_post_thumbnail($next_post->ID, 'prev_next_img', array(\n 'class' => 'rounded-lg object-fill w-full max-h-full' \n )) . '<h4 class=\"text-center mt-2 lg:text-base text-sm no-underline text-black leading-snug font-medium\">%title</h4>', \n false);\n ?>\n</code></pre>\n\n<p>in function.php</p>\n\n<p>i put custome image size</p>\n\n<pre><code>add_image_size('prev_next_img', 370, 270, true);\n</code></pre>\n"
}
] | 2019/07/16 | [
"https://wordpress.stackexchange.com/questions/342940",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/171911/"
] | I'm just starting to create new theme and i'm new to code. I'm stuck in customizing the post thumbnail code, i tried add
```
<?php previous_post_link(get_the_post_thumbnail(get_previous_post(), array(
'class' => 'rounded-lg object-cover'
)) . '<h4 class="text-center">%link</h4>',
'%title',false
);
?>
```
but it doesn't seem to work. did my array mistakenly placed in the code? | Sorry for late reply, already fixed, i miss understood about array, so here the code that completely run as i want it.
```
<?php
$next_post = get_next_post();
next_post_link('%link',
get_the_post_thumbnail($next_post->ID, 'prev_next_img', array(
'class' => 'rounded-lg object-fill w-full max-h-full'
)) . '<h4 class="text-center mt-2 lg:text-base text-sm no-underline text-black leading-snug font-medium">%title</h4>',
false);
?>
```
in function.php
i put custome image size
```
add_image_size('prev_next_img', 370, 270, true);
``` |
342,978 | <p>I want to get the Woocommerce variable product variation name.
If, for example, I have a product that is available in different sizes: small, medium and large. Then I would like to print for example "large".
I have almost got it to work. The problem is, I also get the product name at the same time like: "Product name - Large"
Here is my code:</p>
<p><code>$product_variation = wc_get_product($variation['variation_id']);</code>
<code>$product_variation->get_name()</code></p>
<p>Hope someone can help, thanks. :-)</p>
| [
{
"answer_id": 342983,
"author": "Chetan Vaghela",
"author_id": 169856,
"author_profile": "https://wordpress.stackexchange.com/users/169856",
"pm_score": -1,
"selected": false,
"text": "<p>Please try below code. it will output a variation name of attribute size by variation id.</p>\n\n<pre><code>$variation = wc_get_product($variation['variation_id']);\n$variation_attributes = $variation->get_variation_attributes();\n$variation_name = ucfirst($variation_attributes['attribute_pa_size']);\necho $variation_name;\n</code></pre>\n\n<p>let me know if this works for you.</p>\n"
},
{
"answer_id": 342987,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 0,
"selected": false,
"text": "<p>Use the <code>get_varation()</code> method. If the attribute is a global attribute it will properly get the name from the taxonomy term for the attribute, and if it's not it will return the value stored with the product.</p>\n\n<pre><code>$product_variation = wc_get_product( $variation['variation_id'] ); \necho $product_variation->get_attribute( 'size' );\n</code></pre>\n"
},
{
"answer_id": 342998,
"author": "Oscprofessionals",
"author_id": 171102,
"author_profile": "https://wordpress.stackexchange.com/users/171102",
"pm_score": -1,
"selected": false,
"text": "<blockquote>\n <p>use this here you get variation name</p>\n</blockquote>\n\n<pre><code>$productId = 1; //product id here\n$handle = new WC_Product_Variable($productId);\n$variationData = $handle->get_children();\nforeach ($variationData as $value) {\n$variation_id = $value;\n$single_variation = new WC_Product_Variation($value);\n$var_slug = $single_variation->slug;\necho \"<br/>\".$name = implode(\" / \", $single_variation->get_variation_attributes());//here you get product name\n}\n</code></pre>\n"
},
{
"answer_id": 343091,
"author": "Oscprofessionals",
"author_id": 171102,
"author_profile": "https://wordpress.stackexchange.com/users/171102",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>i have tested below code it works properly for variation name</p>\n</blockquote>\n\n<pre><code>$variationId = 39;\n$variation = new WC_Product_Variation($variationId);\n$variationName = implode(\" / \", $variation->get_variation_attributes());\necho $variationName;\n</code></pre>\n"
},
{
"answer_id": 376674,
"author": "Amirhossein Hosseinpour",
"author_id": 146720,
"author_profile": "https://wordpress.stackexchange.com/users/146720",
"pm_score": 0,
"selected": false,
"text": "<p>I believe this should work fine :</p>\n<pre class=\"lang-php prettyprint-override\"><code>$string = WC_Product_Variation::get_formatted_name();\n</code></pre>\n<p>ref: <a href=\"https://woocommerce.wp-a2z.org/oik_api/wc_product_variationget_formatted_name/\" rel=\"nofollow noreferrer\">https://woocommerce.wp-a2z.org/oik_api/wc_product_variationget_formatted_name/</a></p>\n"
}
] | 2019/07/16 | [
"https://wordpress.stackexchange.com/questions/342978",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/162231/"
] | I want to get the Woocommerce variable product variation name.
If, for example, I have a product that is available in different sizes: small, medium and large. Then I would like to print for example "large".
I have almost got it to work. The problem is, I also get the product name at the same time like: "Product name - Large"
Here is my code:
`$product_variation = wc_get_product($variation['variation_id']);`
`$product_variation->get_name()`
Hope someone can help, thanks. :-) | >
> i have tested below code it works properly for variation name
>
>
>
```
$variationId = 39;
$variation = new WC_Product_Variation($variationId);
$variationName = implode(" / ", $variation->get_variation_attributes());
echo $variationName;
``` |
343,037 | <p>I am writing a migration script which has to read the post_content of posts and then dynamically change some attributes of some custom Gutenberg blocks.</p>
<p>I was able to read the post_content and then convert them into block objects by using the <code>parse_blocks</code> function. I was also able to dynamically change the attributes of the custom blocks by manipulating the block objects.</p>
<p>But I am not able to convert these block objects into the special HTML comments that Gutenberg uses to serialize them so that I can update the post_content.</p>
<p>I found that the PHP part of WordPress core only has <code>parse_blocks</code> function to parse the special HTML comments into block objects and <code>render_block</code> function to render the blocks, but there is no <code>serialize_block</code> function.</p>
<p>I found that in JavaScript there is a function called <a href="https://github.com/WordPress/gutenberg/blob/master/packages/blocks/src/api/serializer.js#L269" rel="noreferrer"><code>serializeBlock</code></a> which does this. But is there an equivalent of it in PHP which I can call from my migration scripts?</p>
| [
{
"answer_id": 343330,
"author": "SkyShab",
"author_id": 63263,
"author_profile": "https://wordpress.stackexchange.com/users/63263",
"pm_score": 4,
"selected": true,
"text": "<p>This markup is generated on the js side of things and saved in the content of the block editor, which is why there doesn't seem to be a native PHP function for this. </p>\n\n<p>However, I found a PHP method that does exactly this in an \"experimental\" class in the Gutenberg plugin. You can see this here: <a href=\"https://github.com/WordPress/gutenberg/blob/master/lib/class-experimental-wp-widget-blocks-manager.php#L265\" rel=\"nofollow noreferrer\">https://github.com/WordPress/gutenberg/blob/master/lib/class-experimental-wp-widget-blocks-manager.php#L265</a></p>\n\n<p>You could add it as a method in your own class or convert to a standard function like so:</p>\n\n<pre><code>/**\n * Serializes a block.\n *\n * @param array $block Block object.\n * @return string String representing the block.\n */\nfunction serialize_block( $block ) {\n if ( ! isset( $block['blockName'] ) ) {\n return false;\n }\n $name = $block['blockName'];\n if ( 0 === strpos( $name, 'core/' ) ) {\n $name = substr( $name, strlen( 'core/' ) );\n }\n if ( empty( $block['attrs'] ) ) {\n $opening_tag_suffix = '';\n } else {\n $opening_tag_suffix = ' ' . json_encode( $block['attrs'] );\n }\n if ( empty( $block['innerHTML'] ) ) {\n return sprintf(\n '<!-- wp:%s%s /-->',\n $name,\n $opening_tag_suffix\n );\n } else {\n return sprintf(\n '<!-- wp:%1$s%2$s -->%3$s<!-- /wp:%1$s -->',\n $name,\n $opening_tag_suffix,\n $block['innerHTML']\n );\n }\n}\n</code></pre>\n"
},
{
"answer_id": 361071,
"author": "uryga",
"author_id": 184541,
"author_profile": "https://wordpress.stackexchange.com/users/184541",
"pm_score": 3,
"selected": false,
"text": "<p>March 2020 update: Looks like <code>serialize_block()</code> is included with WP since 5.3.1, though i think it's undocumented right now. <a href=\"https://core.trac.wordpress.org/browser/tags/5.3.1/src/wp-includes/blocks.php#L226\" rel=\"noreferrer\">Here's the source on Trac</a>. The docstring says:</p>\n\n<pre><code>/* [...]\n *\n * Returns the content of a block, including comment delimiters, serializing all\n * attributes from the given parsed block.\n *\n * This should be used when preparing a block to be saved to post content.\n * Prefer `render_block` when preparing a block for display. Unlike\n * `render_block`, this does not evaluate a block's `render_callback`, and will\n * instead preserve the markup as parsed.\n */\n</code></pre>\n\n<p>It seems to work fine from a few simple tests I did, but I'm not sure if it's intended for public usage yet, because there's also this Trac ticket with a different implementation (marked as \"awaiting review\" as of 2020.03.20): <a href=\"https://core.trac.wordpress.org/ticket/47375\" rel=\"noreferrer\">#47375 - Blocks API: Add server-side <code>serialize_block()</code></a></p>\n"
}
] | 2019/07/17 | [
"https://wordpress.stackexchange.com/questions/343037",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/24579/"
] | I am writing a migration script which has to read the post\_content of posts and then dynamically change some attributes of some custom Gutenberg blocks.
I was able to read the post\_content and then convert them into block objects by using the `parse_blocks` function. I was also able to dynamically change the attributes of the custom blocks by manipulating the block objects.
But I am not able to convert these block objects into the special HTML comments that Gutenberg uses to serialize them so that I can update the post\_content.
I found that the PHP part of WordPress core only has `parse_blocks` function to parse the special HTML comments into block objects and `render_block` function to render the blocks, but there is no `serialize_block` function.
I found that in JavaScript there is a function called [`serializeBlock`](https://github.com/WordPress/gutenberg/blob/master/packages/blocks/src/api/serializer.js#L269) which does this. But is there an equivalent of it in PHP which I can call from my migration scripts? | This markup is generated on the js side of things and saved in the content of the block editor, which is why there doesn't seem to be a native PHP function for this.
However, I found a PHP method that does exactly this in an "experimental" class in the Gutenberg plugin. You can see this here: <https://github.com/WordPress/gutenberg/blob/master/lib/class-experimental-wp-widget-blocks-manager.php#L265>
You could add it as a method in your own class or convert to a standard function like so:
```
/**
* Serializes a block.
*
* @param array $block Block object.
* @return string String representing the block.
*/
function serialize_block( $block ) {
if ( ! isset( $block['blockName'] ) ) {
return false;
}
$name = $block['blockName'];
if ( 0 === strpos( $name, 'core/' ) ) {
$name = substr( $name, strlen( 'core/' ) );
}
if ( empty( $block['attrs'] ) ) {
$opening_tag_suffix = '';
} else {
$opening_tag_suffix = ' ' . json_encode( $block['attrs'] );
}
if ( empty( $block['innerHTML'] ) ) {
return sprintf(
'<!-- wp:%s%s /-->',
$name,
$opening_tag_suffix
);
} else {
return sprintf(
'<!-- wp:%1$s%2$s -->%3$s<!-- /wp:%1$s -->',
$name,
$opening_tag_suffix,
$block['innerHTML']
);
}
}
``` |
343,055 | <p>I have a SQL query that get all events ordering by Startdate, and i define startday as $today.</p>
<p>but this query didn't take events that start yestarday and that endday is tomorow.</p>
<p>how can i make my query to use BETWEEN ?</p>
<p>my query </p>
<pre><code>SELECT * FROM wp_posts, `wp_mec_dates` AS mecd, wp_icl_translations WHERE wp_posts.ID = mecd.post_id and post_status='publish' AND wp_icl_translations.language_code='$lang' AND dstart>'$startday' and wp_posts.ID = wp_icl_translations.element_id ORDER BY dstart LIMIT 0,6
</code></pre>
<p>startdate is <code>$startday = date("Y-m-d");</code></p>
<p>EDIT : with documentation & help, i'm here now : </p>
<pre><code>SELECT * FROM wp_posts, wp_mec_dates AS mecd, wp_icl_translations WHERE wp_posts.ID = mecd.post_id and post_status='publish' AND wp_icl_translations.language_code='$lang' AND ($startday BETWEEN dstart AND dend)AND wp_posts.ID = wp_icl_translations.element_id ORDER BY dstart LIMIT 0,6
</code></pre>
<p>but it return 0 results.
Any help will be apreciated !</p>
| [
{
"answer_id": 343059,
"author": "user2243593",
"author_id": 56443,
"author_profile": "https://wordpress.stackexchange.com/users/56443",
"pm_score": -1,
"selected": false,
"text": "<p>Try this </p>\n\n<pre><code>WHERE dstart BETWEEN '$startdate' AND '$enddate'\n</code></pre>\n"
},
{
"answer_id": 343071,
"author": "Gregory",
"author_id": 139936,
"author_profile": "https://wordpress.stackexchange.com/users/139936",
"pm_score": 1,
"selected": true,
"text": "<p>found the solution <3</p>\n\n<p>Used WHERE '$startday' BETWEEN dstart AND dend</p>\n\n<p>plus : OR dstart >= '$startday'</p>\n\n<pre><code>SELECT * FROM wp_posts, wp_mec_dates AS mecd, wp_icl_translations WHERE wp_posts.ID = mecd.post_id and post_status='publish' AND wp_icl_translations.language_code='$lang' AND ('$startday' BETWEEN dstart AND dend OR dstart >= '$startday') AND wp_posts.ID = wp_icl_translations.element_id ORDER BY dstart LIMIT 0,6\n</code></pre>\n"
}
] | 2019/07/17 | [
"https://wordpress.stackexchange.com/questions/343055",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/139936/"
] | I have a SQL query that get all events ordering by Startdate, and i define startday as $today.
but this query didn't take events that start yestarday and that endday is tomorow.
how can i make my query to use BETWEEN ?
my query
```
SELECT * FROM wp_posts, `wp_mec_dates` AS mecd, wp_icl_translations WHERE wp_posts.ID = mecd.post_id and post_status='publish' AND wp_icl_translations.language_code='$lang' AND dstart>'$startday' and wp_posts.ID = wp_icl_translations.element_id ORDER BY dstart LIMIT 0,6
```
startdate is `$startday = date("Y-m-d");`
EDIT : with documentation & help, i'm here now :
```
SELECT * FROM wp_posts, wp_mec_dates AS mecd, wp_icl_translations WHERE wp_posts.ID = mecd.post_id and post_status='publish' AND wp_icl_translations.language_code='$lang' AND ($startday BETWEEN dstart AND dend)AND wp_posts.ID = wp_icl_translations.element_id ORDER BY dstart LIMIT 0,6
```
but it return 0 results.
Any help will be apreciated ! | found the solution <3
Used WHERE '$startday' BETWEEN dstart AND dend
plus : OR dstart >= '$startday'
```
SELECT * FROM wp_posts, wp_mec_dates AS mecd, wp_icl_translations WHERE wp_posts.ID = mecd.post_id and post_status='publish' AND wp_icl_translations.language_code='$lang' AND ('$startday' BETWEEN dstart AND dend OR dstart >= '$startday') AND wp_posts.ID = wp_icl_translations.element_id ORDER BY dstart LIMIT 0,6
``` |
343,123 | <p>I want to remove the WordPress tag from the From section in when using the contact 7 plugin on WordPress. How can i do this?</p>
<p><a href="https://i.stack.imgur.com/rKHaW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rKHaW.png" alt="wordpress email from tag"></a></p>
<p>See below for the settings I use for the Contact 7 Plugin.</p>
<p><a href="https://i.stack.imgur.com/equvC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/equvC.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 343059,
"author": "user2243593",
"author_id": 56443,
"author_profile": "https://wordpress.stackexchange.com/users/56443",
"pm_score": -1,
"selected": false,
"text": "<p>Try this </p>\n\n<pre><code>WHERE dstart BETWEEN '$startdate' AND '$enddate'\n</code></pre>\n"
},
{
"answer_id": 343071,
"author": "Gregory",
"author_id": 139936,
"author_profile": "https://wordpress.stackexchange.com/users/139936",
"pm_score": 1,
"selected": true,
"text": "<p>found the solution <3</p>\n\n<p>Used WHERE '$startday' BETWEEN dstart AND dend</p>\n\n<p>plus : OR dstart >= '$startday'</p>\n\n<pre><code>SELECT * FROM wp_posts, wp_mec_dates AS mecd, wp_icl_translations WHERE wp_posts.ID = mecd.post_id and post_status='publish' AND wp_icl_translations.language_code='$lang' AND ('$startday' BETWEEN dstart AND dend OR dstart >= '$startday') AND wp_posts.ID = wp_icl_translations.element_id ORDER BY dstart LIMIT 0,6\n</code></pre>\n"
}
] | 2019/07/18 | [
"https://wordpress.stackexchange.com/questions/343123",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/172055/"
] | I want to remove the WordPress tag from the From section in when using the contact 7 plugin on WordPress. How can i do this?
[](https://i.stack.imgur.com/rKHaW.png)
See below for the settings I use for the Contact 7 Plugin.
[](https://i.stack.imgur.com/equvC.png) | found the solution <3
Used WHERE '$startday' BETWEEN dstart AND dend
plus : OR dstart >= '$startday'
```
SELECT * FROM wp_posts, wp_mec_dates AS mecd, wp_icl_translations WHERE wp_posts.ID = mecd.post_id and post_status='publish' AND wp_icl_translations.language_code='$lang' AND ('$startday' BETWEEN dstart AND dend OR dstart >= '$startday') AND wp_posts.ID = wp_icl_translations.element_id ORDER BY dstart LIMIT 0,6
``` |
343,182 | <p>I have custom fields in the user profile that displays in the team page. It reads "director" "researcher" "graduate" "intern" and some others. When adding a new team member, you pick from a select box with the options.</p>
<p>Right now the page displays the users in date of creation order but I need to show them in hierarchy order (all directors first, then the researchers, then graduate, etc, etc).</p>
<p>The new fields for the profile are in functions.php with the following code:</p>
<pre><code><!-- ROLE -->
<?php $role = get_user_meta($user->ID, 'member_role', true); ?>
<table class="form-table">
<tr>
<th><label for="member_role">Lab Role</label></th>
<td>
<select name="member_role" id="member_role">
<option value="" <?php if($role == ''){echo('selected="selected"');}?>>Choose role</option>
<option value="principal-investigator" <?php if($role == 'principal-investigator'){echo('selected="selected"');}?>>Principal Investigator</option>
<option value="labmanager" <?php if($role == 'labmanager'){echo('selected="selected"');}?>>Lab Manager</option>
<option value="administrativeassistant" <?php if($role == 'administrativeassistant'){echo('selected="selected"');}?>>Administrative Assistant</option>
<option value="postdoc" <?php if($role == 'postdoc'){echo('selected="selected"');}?>>Postdoctoral Fellow</option>
<option value="gradstudent" <?php if($role == 'gradstudent'){echo('selected="selected"');}?>>Graduate Student</option>
<option value="researchtech" <?php if($role == 'researchtech'){echo('selected="selected"');}?>>Research Technician</option>
<option value="undergradstudent" <?php if($role == 'undergradstudent'){echo('selected="selected"');}?>>Undergraduate Student</option>
<option value="labsupport" <?php if($role == 'labsupport'){echo('selected="selected"');}?>>Lab Support</option>
</select>
<br />
<span class="description">Please select your role at the lab.</span>
</td>
</tr>
</table>
<?php }
add_action( 'personal_options_update', 'my_save_extra_profile_fields' );
add_action( 'edit_user_profile_update', 'my_save_extra_profile_fields' );
add_action('user_register', 'my_save_extra_profile_fields');
add_action('profile_update', 'my_save_extra_profile_fields');
function my_save_extra_profile_fields( $user_id ) {
if ( !current_user_can( 'edit_user', $user_id ) )
return false;
update_usermeta( absint( $user_id ), 'degrees_and_affiliations', wp_kses_post( $_POST['degrees_and_affiliations'] ) );
update_usermeta( absint( $user_id ), 'member_role', wp_kses_post( $_POST['member_role'] ) );
$items = array('principal-investigator', 'labmanager', 'administrativeassistant', 'postdoc', 'gradstudent', 'researchtech', 'undergradstudent', 'labsupport' );
$role = get_user_meta($user_id, 'member_role', true);
$order = array_search($role, $items);
update_user_meta( absint( $user_id ), 'lab_member_order', $order);
}
</code></pre>
<p>Then the code that shows the users in the page is as follows:</p>
<pre><code>$results = get_users();
foreach ($results as $result) {
// Get data about each user as an object
$user = get_userdata($result->ID);
// Create a flat array with only the fields we need
$directors[$user->ID] = array(
'dir_order' => $user->menu_order,
'dir_id' => $user->ID,
'dir_name' => $user->first_name.' '.$user->last_name,
'dir_email' => $user->user_email,
);
}
// Sort
sort($directors);
// The list
echo '<ul id="rightcolumndirector">';
// For each result
foreach ($directors as $director) {
// Set up the variables
$dir_id = $director['dir_id'];
$dir_order = $director['dir_order'];
$dir_name = $director['dir_name'];
$dir_email = $director['dir_email'];
$dir_link = get_bloginfo('home').'/?author='.$director['dir_id'];
$dir_status = get_field('alumni', 'user_'.$dir_id);
if ($dir_status == 0 && $dir_id !== 24) { ?>
<div class="author-nucleus">
<a href="<?php echo get_author_posts_url( $dir_id ); ?>">
<div class="author-avatar">
<div class="hexa">
<div class="hex1">
<div class="hex2">
<?php echo get_wp_user_avatar( $dir_email, 'large' ); ?>
</div>
</div>
</div>
</div>
</a>
<div class="author-info">
<h2>
<a class="author-name" href="<?php echo get_author_posts_url( $dir_id ); ?>">
<?php echo $dir_name; ?>
</a><?php
if($dir_email != '')
{
printf('<a href="mailto:%s">%s</a>', $dir_email, '<span class="dashicons dashicons-email-alt"></span>');
}
?>
</h2>
<hr />
<?php
get_member_role($dir_id);
?>
<ul class="nucleus-icons-test">
<li>
<div>
<img src="<?php $user_icon = get_field('user_icon', 'user_'.$dir_id);
echo $user_icon['url']; ?>" />
<span><?php echo $dir_name; ?></span>
</div>
</li>
<?php
get_subjects($dir_id, 'post', 4);
?>
</ul>
</div>
</div>
<?php
}
}
?>
</code></pre>
| [
{
"answer_id": 343197,
"author": "Faham Shaikh",
"author_id": 147414,
"author_profile": "https://wordpress.stackexchange.com/users/147414",
"pm_score": 2,
"selected": true,
"text": "<p>@CynthiaLara</p>\n\n<p>I suppose that you are using a container of <code>WP_USER_QUERY::__construct</code> in the form or <code>WP_USER_QUERY</code> or <code>get_users</code> or something to that effect.</p>\n\n<p>You can use <code>'meta_key' => '<YOUR_DESIGNATION_META_KEY>','orderby' => 'meta_value_num,</code> to get results sorted by your meta key's value.</p>\n\n<p>If you have used a texted based value in for this meta_key, please consider using a numeric value based system. eg. </p>\n\n<ul>\n<li>0 = 'Director'</li>\n<li>1 = 'CTO'\nand so on as this will allow you to achieve what you want with ease and you can event have the designation array globally defined, store the index as user meta based on selected designation and show the designation based on the stored meta value.</li>\n</ul>\n\n<p>Good luck!!</p>\n\n<blockquote>\n <p>Update with code sample</p>\n</blockquote>\n\n<pre><code>$args = array(\n 'meta_key' => 'member_role',\n 'orderby' => 'meta_value_num',\n 'order' => 'ASC'\n); \n$results = get_users( $args );\n</code></pre>\n\n<p>and then you can iterate with your <code>foreach</code> loop.</p>\n\n<p>And do not that the option values for the select drop down must be like 0,1,2,3 etc.</p>\n"
},
{
"answer_id": 343215,
"author": "Oscprofessionals",
"author_id": 171102,
"author_profile": "https://wordpress.stackexchange.com/users/171102",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>use below code to get user by role</p>\n</blockquote>\n\n<pre><code>global $wpdb;\n$blog_id = get_current_blog_id();\n$user_query = new WP_User_Query( array(\n'meta_query' => array(\n'relation' => 'OR',\narray(\n'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities',\n'value' => 'customer', //change your user role here which you want to display\n'compare' => 'like'\n),\narray(\n'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities',\n'value' => 'subscriber',\n'compare' => 'like'\n)\n)\n) );\nforeach ( $user_query->results as $user ) {\necho \"<br/>\";\necho \"ID:\".$user->ID;\necho ' Username:' . $user->user_login ;\n}\n</code></pre>\n"
}
] | 2019/07/18 | [
"https://wordpress.stackexchange.com/questions/343182",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/34034/"
] | I have custom fields in the user profile that displays in the team page. It reads "director" "researcher" "graduate" "intern" and some others. When adding a new team member, you pick from a select box with the options.
Right now the page displays the users in date of creation order but I need to show them in hierarchy order (all directors first, then the researchers, then graduate, etc, etc).
The new fields for the profile are in functions.php with the following code:
```
<!-- ROLE -->
<?php $role = get_user_meta($user->ID, 'member_role', true); ?>
<table class="form-table">
<tr>
<th><label for="member_role">Lab Role</label></th>
<td>
<select name="member_role" id="member_role">
<option value="" <?php if($role == ''){echo('selected="selected"');}?>>Choose role</option>
<option value="principal-investigator" <?php if($role == 'principal-investigator'){echo('selected="selected"');}?>>Principal Investigator</option>
<option value="labmanager" <?php if($role == 'labmanager'){echo('selected="selected"');}?>>Lab Manager</option>
<option value="administrativeassistant" <?php if($role == 'administrativeassistant'){echo('selected="selected"');}?>>Administrative Assistant</option>
<option value="postdoc" <?php if($role == 'postdoc'){echo('selected="selected"');}?>>Postdoctoral Fellow</option>
<option value="gradstudent" <?php if($role == 'gradstudent'){echo('selected="selected"');}?>>Graduate Student</option>
<option value="researchtech" <?php if($role == 'researchtech'){echo('selected="selected"');}?>>Research Technician</option>
<option value="undergradstudent" <?php if($role == 'undergradstudent'){echo('selected="selected"');}?>>Undergraduate Student</option>
<option value="labsupport" <?php if($role == 'labsupport'){echo('selected="selected"');}?>>Lab Support</option>
</select>
<br />
<span class="description">Please select your role at the lab.</span>
</td>
</tr>
</table>
<?php }
add_action( 'personal_options_update', 'my_save_extra_profile_fields' );
add_action( 'edit_user_profile_update', 'my_save_extra_profile_fields' );
add_action('user_register', 'my_save_extra_profile_fields');
add_action('profile_update', 'my_save_extra_profile_fields');
function my_save_extra_profile_fields( $user_id ) {
if ( !current_user_can( 'edit_user', $user_id ) )
return false;
update_usermeta( absint( $user_id ), 'degrees_and_affiliations', wp_kses_post( $_POST['degrees_and_affiliations'] ) );
update_usermeta( absint( $user_id ), 'member_role', wp_kses_post( $_POST['member_role'] ) );
$items = array('principal-investigator', 'labmanager', 'administrativeassistant', 'postdoc', 'gradstudent', 'researchtech', 'undergradstudent', 'labsupport' );
$role = get_user_meta($user_id, 'member_role', true);
$order = array_search($role, $items);
update_user_meta( absint( $user_id ), 'lab_member_order', $order);
}
```
Then the code that shows the users in the page is as follows:
```
$results = get_users();
foreach ($results as $result) {
// Get data about each user as an object
$user = get_userdata($result->ID);
// Create a flat array with only the fields we need
$directors[$user->ID] = array(
'dir_order' => $user->menu_order,
'dir_id' => $user->ID,
'dir_name' => $user->first_name.' '.$user->last_name,
'dir_email' => $user->user_email,
);
}
// Sort
sort($directors);
// The list
echo '<ul id="rightcolumndirector">';
// For each result
foreach ($directors as $director) {
// Set up the variables
$dir_id = $director['dir_id'];
$dir_order = $director['dir_order'];
$dir_name = $director['dir_name'];
$dir_email = $director['dir_email'];
$dir_link = get_bloginfo('home').'/?author='.$director['dir_id'];
$dir_status = get_field('alumni', 'user_'.$dir_id);
if ($dir_status == 0 && $dir_id !== 24) { ?>
<div class="author-nucleus">
<a href="<?php echo get_author_posts_url( $dir_id ); ?>">
<div class="author-avatar">
<div class="hexa">
<div class="hex1">
<div class="hex2">
<?php echo get_wp_user_avatar( $dir_email, 'large' ); ?>
</div>
</div>
</div>
</div>
</a>
<div class="author-info">
<h2>
<a class="author-name" href="<?php echo get_author_posts_url( $dir_id ); ?>">
<?php echo $dir_name; ?>
</a><?php
if($dir_email != '')
{
printf('<a href="mailto:%s">%s</a>', $dir_email, '<span class="dashicons dashicons-email-alt"></span>');
}
?>
</h2>
<hr />
<?php
get_member_role($dir_id);
?>
<ul class="nucleus-icons-test">
<li>
<div>
<img src="<?php $user_icon = get_field('user_icon', 'user_'.$dir_id);
echo $user_icon['url']; ?>" />
<span><?php echo $dir_name; ?></span>
</div>
</li>
<?php
get_subjects($dir_id, 'post', 4);
?>
</ul>
</div>
</div>
<?php
}
}
?>
``` | @CynthiaLara
I suppose that you are using a container of `WP_USER_QUERY::__construct` in the form or `WP_USER_QUERY` or `get_users` or something to that effect.
You can use `'meta_key' => '<YOUR_DESIGNATION_META_KEY>','orderby' => 'meta_value_num,` to get results sorted by your meta key's value.
If you have used a texted based value in for this meta\_key, please consider using a numeric value based system. eg.
* 0 = 'Director'
* 1 = 'CTO'
and so on as this will allow you to achieve what you want with ease and you can event have the designation array globally defined, store the index as user meta based on selected designation and show the designation based on the stored meta value.
Good luck!!
>
> Update with code sample
>
>
>
```
$args = array(
'meta_key' => 'member_role',
'orderby' => 'meta_value_num',
'order' => 'ASC'
);
$results = get_users( $args );
```
and then you can iterate with your `foreach` loop.
And do not that the option values for the select drop down must be like 0,1,2,3 etc. |
343,213 | <p>please I would like some help about these 2 options:</p>
<p>1) how could I show add to cart button instead of "VEDI PRODOTTO" (view product) button?</p>
<p>2) how could I display on the left the units (number with "+" and "-") to add for each product with add to cart button on the right?</p>
<p>If you know a plugin or some php code working.</p>
<p>Link: <a href="https://erboristerialofficinale.it/shop/" rel="nofollow noreferrer">https://erboristerialofficinale.it/shop/</a></p>
<p>Thank you in advance</p>
<p>S</p>
| [
{
"answer_id": 343232,
"author": "Tanmay Patel",
"author_id": 62026,
"author_profile": "https://wordpress.stackexchange.com/users/62026",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p><strong>Point 1:</strong> To change \"VEDI PRODOTTO\" (view product) button instead of \"Add to Cart\" button on product archives: Put below code in <strong>functions.php</strong> file.</p>\n</blockquote>\n\n<pre><code>remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart' );\nadd_action('woocommerce_after_shop_loop_item', 'add_a_custom_button', 5 );\nfunction add_a_custom_button() {\n global $product;\n if( $product->is_type('variable') || $product->is_type('grouped') ) return;\n echo '<div style=\"margin-bottom:10px;\">\n <a class=\"button custom-button\" href=\"' . esc_attr( $product->get_permalink() ) . '\">' . __('VEDI PRODOTTO') . '</a>\n </div>';\n}\n</code></pre>\n\n<blockquote>\n <p><strong>Point 2:</strong> display on the left the units (number with \"+\" and \"-\") to add for each product with add to cart button on the right. Put below code in <strong>functions.php</strong> file and add CSS code in <strong>style.css</strong> file.</p>\n</blockquote>\n\n<pre><code>// 1. Show Buttons\n\nadd_action( 'woocommerce_before_add_to_cart_quantity', 'bbloomer_display_quantity_plus' );\n\nfunction bbloomer_display_quantity_plus() {\n echo '<button type=\"button\" class=\"plus\" >+</button>';\n}\n\nadd_action( 'woocommerce_after_add_to_cart_quantity', 'bbloomer_display_quantity_minus' );\n\nfunction bbloomer_display_quantity_minus() {\n echo '<button type=\"button\" class=\"minus\" >-</button>';\n}\n\n\n// 2. Trigger jQuery script\n\nadd_action( 'wp_footer', 'bbloomer_add_cart_quantity_plus_minus' );\n\nfunction bbloomer_add_cart_quantity_plus_minus() {\n // Only run this on the single product page\n if ( ! is_product() ) return;\n ?>\n <script type=\"text/javascript\">\n\n jQuery(document).ready(function($){ \n\n $('form.cart').on( 'click', 'button.plus, button.minus', function() {\n\n // Get current quantity values\n var qty = $( this ).closest( 'form.cart' ).find( '.qty' );\n var val = parseFloat(qty.val());\n var max = parseFloat(qty.attr( 'max' ));\n var min = parseFloat(qty.attr( 'min' ));\n var step = parseFloat(qty.attr( 'step' ));\n\n // Change the value if plus or minus\n if ( $( this ).is( '.plus' ) ) {\n if ( max && ( max <= val ) ) {\n qty.val( max );\n } else {\n qty.val( val + step );\n }\n } else {\n if ( min && ( min >= val ) ) {\n qty.val( min );\n } else if ( val > 1 ) {\n qty.val( val - step );\n }\n }\n\n });\n\n });\n\n </script>\n <?php\n}\n</code></pre>\n\n<blockquote>\n <p>CSS code</p>\n</blockquote>\n\n<pre><code>.woocommerce div.product .entry-summary .cart div.quantity{\n float: none;\n margin: 0;\n display: inline-block;\n}\n.woocommerce div.product form.cart .button {\n vertical-align: middle;\n float: none;\n}\n</code></pre>\n"
},
{
"answer_id": 343236,
"author": "vikas jain",
"author_id": 172136,
"author_profile": "https://wordpress.stackexchange.com/users/172136",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Add this code in function.php</strong></p>\n\n<pre><code>function vk_shop_page_add_quantity_field() {\n /** @var WC_Product $product */\n $product = wc_get_product( get_the_ID() );\n if ( ! $product->is_sold_individually() && 'variable' != $product->get_type() && $product->is_purchasable() ) {\n woocommerce_quantity_input( array( 'min_value' => 1, 'max_value' => $product->backorders_allowed() ? '' : $product->get_stock_quantity() ) );\n }\n}\n\nadd_action( 'woocommerce_after_shop_loop_item', 'vk_shop_page_add_quantity_field', 12 );\n\n\n/**\n * Add required JavaScript.\n */\nfunction vk_shop_page_quantity_add_to_cart_handler() {\n wc_enqueue_js( '\n $(\".woocommerce .products\").on(\"click\", \".quantity input\", function() {\n return false;\n });\n $(\".woocommerce .products\").on(\"change input\", \".quantity .qty\", function() {\n var add_to_cart_button = $(this).parents( \".product\" ).find(\".add_to_cart_button\");\n // For AJAX add-to-cart actions\n add_to_cart_button.data(\"quantity\", $(this).val());\n // For non-AJAX add-to-cart actions\n add_to_cart_button.attr(\"href\", \"?add-to-cart=\" + add_to_cart_button.attr(\"data-product_id\") + \"&quantity=\" + $(this).val());\n });\n // Trigger on Enter press\n $(\".woocommerce .products\").on(\"keypress\", \".quantity .qty\", function(e) {\n if ((e.which||e.keyCode) === 13) {\n $( this ).parents(\".product\").find(\".add_to_cart_button\").trigger(\"click\");\n }\n });\n ' );\n}\nadd_action( 'init', 'vk_shop_page_quantity_add_to_cart_handler' );\n</code></pre>\n\n<p>Happy coding...</p>\n"
}
] | 2019/07/19 | [
"https://wordpress.stackexchange.com/questions/343213",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/172119/"
] | please I would like some help about these 2 options:
1) how could I show add to cart button instead of "VEDI PRODOTTO" (view product) button?
2) how could I display on the left the units (number with "+" and "-") to add for each product with add to cart button on the right?
If you know a plugin or some php code working.
Link: <https://erboristerialofficinale.it/shop/>
Thank you in advance
S | >
> **Point 1:** To change "VEDI PRODOTTO" (view product) button instead of "Add to Cart" button on product archives: Put below code in **functions.php** file.
>
>
>
```
remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart' );
add_action('woocommerce_after_shop_loop_item', 'add_a_custom_button', 5 );
function add_a_custom_button() {
global $product;
if( $product->is_type('variable') || $product->is_type('grouped') ) return;
echo '<div style="margin-bottom:10px;">
<a class="button custom-button" href="' . esc_attr( $product->get_permalink() ) . '">' . __('VEDI PRODOTTO') . '</a>
</div>';
}
```
>
> **Point 2:** display on the left the units (number with "+" and "-") to add for each product with add to cart button on the right. Put below code in **functions.php** file and add CSS code in **style.css** file.
>
>
>
```
// 1. Show Buttons
add_action( 'woocommerce_before_add_to_cart_quantity', 'bbloomer_display_quantity_plus' );
function bbloomer_display_quantity_plus() {
echo '<button type="button" class="plus" >+</button>';
}
add_action( 'woocommerce_after_add_to_cart_quantity', 'bbloomer_display_quantity_minus' );
function bbloomer_display_quantity_minus() {
echo '<button type="button" class="minus" >-</button>';
}
// 2. Trigger jQuery script
add_action( 'wp_footer', 'bbloomer_add_cart_quantity_plus_minus' );
function bbloomer_add_cart_quantity_plus_minus() {
// Only run this on the single product page
if ( ! is_product() ) return;
?>
<script type="text/javascript">
jQuery(document).ready(function($){
$('form.cart').on( 'click', 'button.plus, button.minus', function() {
// Get current quantity values
var qty = $( this ).closest( 'form.cart' ).find( '.qty' );
var val = parseFloat(qty.val());
var max = parseFloat(qty.attr( 'max' ));
var min = parseFloat(qty.attr( 'min' ));
var step = parseFloat(qty.attr( 'step' ));
// Change the value if plus or minus
if ( $( this ).is( '.plus' ) ) {
if ( max && ( max <= val ) ) {
qty.val( max );
} else {
qty.val( val + step );
}
} else {
if ( min && ( min >= val ) ) {
qty.val( min );
} else if ( val > 1 ) {
qty.val( val - step );
}
}
});
});
</script>
<?php
}
```
>
> CSS code
>
>
>
```
.woocommerce div.product .entry-summary .cart div.quantity{
float: none;
margin: 0;
display: inline-block;
}
.woocommerce div.product form.cart .button {
vertical-align: middle;
float: none;
}
``` |
343,231 | <p>I can make wordpress website but I have an issue with this. I want to fetch data from another third party website to my own wordpress site with the mysql database.
I want to fetch only one table with the dynamic entries form the third party website.</p>
| [
{
"answer_id": 343234,
"author": "Abdul Rafay",
"author_id": 172133,
"author_profile": "https://wordpress.stackexchange.com/users/172133",
"pm_score": 0,
"selected": false,
"text": "<p>You should have a remote mysql option in your cpanel to allow you to do that if not then you may ask your hosting provider for more assistance after that:</p>\n\n<p><strong>Use the following configuration settings for connecting to your database:</strong></p>\n\n<p>Host name = (use the server IP address)</p>\n\n<p>Database name = (cpanelUsername_databaseName)</p>\n\n<p>Database username = (cpanelUsername_databaseUsername)</p>\n\n<p>Database password = (the password you entered for that database user)\nMySQL Connection Port = 3306</p>\n"
},
{
"answer_id": 343235,
"author": "vikas jain",
"author_id": 172136,
"author_profile": "https://wordpress.stackexchange.com/users/172136",
"pm_score": 1,
"selected": false,
"text": "<p>You can set up a new connection from function:</p>\n\n<pre><code>$wpdb_b = new wpdb( \"user\", \"password\", \"brian_db\", \"localhost\" );\n$wpdb_b->get_results( \"SELECT * FROM brian_table\" );\n</code></pre>\n\n<p>Happy Coding</p>\n"
}
] | 2019/07/19 | [
"https://wordpress.stackexchange.com/questions/343231",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/172130/"
] | I can make wordpress website but I have an issue with this. I want to fetch data from another third party website to my own wordpress site with the mysql database.
I want to fetch only one table with the dynamic entries form the third party website. | You can set up a new connection from function:
```
$wpdb_b = new wpdb( "user", "password", "brian_db", "localhost" );
$wpdb_b->get_results( "SELECT * FROM brian_table" );
```
Happy Coding |
343,249 | <p>I add this code on my website </p>
<pre><code>[display-posts image_size="thumbnail" wrapper="div"
wrapper_class="display-posts-listing grid" meta_key="_thumbnail_id"
display-post category="<code>αρχείο-εκδηλώσεων</code>" posts_per_page="20"
display-posts include_excerpt="true" excerpt_length="15"
excerpt_more="Διαβάστε Περισσότερα" excerpt_more_link="true" ]
</code></pre>
<p>is it possible to put etc 20 posts and then the 21st post will be added on a second page ? </p>
| [
{
"answer_id": 343234,
"author": "Abdul Rafay",
"author_id": 172133,
"author_profile": "https://wordpress.stackexchange.com/users/172133",
"pm_score": 0,
"selected": false,
"text": "<p>You should have a remote mysql option in your cpanel to allow you to do that if not then you may ask your hosting provider for more assistance after that:</p>\n\n<p><strong>Use the following configuration settings for connecting to your database:</strong></p>\n\n<p>Host name = (use the server IP address)</p>\n\n<p>Database name = (cpanelUsername_databaseName)</p>\n\n<p>Database username = (cpanelUsername_databaseUsername)</p>\n\n<p>Database password = (the password you entered for that database user)\nMySQL Connection Port = 3306</p>\n"
},
{
"answer_id": 343235,
"author": "vikas jain",
"author_id": 172136,
"author_profile": "https://wordpress.stackexchange.com/users/172136",
"pm_score": 1,
"selected": false,
"text": "<p>You can set up a new connection from function:</p>\n\n<pre><code>$wpdb_b = new wpdb( \"user\", \"password\", \"brian_db\", \"localhost\" );\n$wpdb_b->get_results( \"SELECT * FROM brian_table\" );\n</code></pre>\n\n<p>Happy Coding</p>\n"
}
] | 2019/07/19 | [
"https://wordpress.stackexchange.com/questions/343249",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/172149/"
] | I add this code on my website
```
[display-posts image_size="thumbnail" wrapper="div"
wrapper_class="display-posts-listing grid" meta_key="_thumbnail_id"
display-post category="<code>αρχείο-εκδηλώσεων</code>" posts_per_page="20"
display-posts include_excerpt="true" excerpt_length="15"
excerpt_more="Διαβάστε Περισσότερα" excerpt_more_link="true" ]
```
is it possible to put etc 20 posts and then the 21st post will be added on a second page ? | You can set up a new connection from function:
```
$wpdb_b = new wpdb( "user", "password", "brian_db", "localhost" );
$wpdb_b->get_results( "SELECT * FROM brian_table" );
```
Happy Coding |
343,324 | <p>How I can update Existing (Back-End) metabox variable from front-End, I tried many times but I don't know why doesn't this work? Showing only old value not update, what i did wrong?</p>
<p>This is my Front-End Page, I'm using this code inside normal Page With shortCode and also this code between post loop.</p>
<pre><code>if ( isset( $_POST['zon_testimonial_nonce'] ) && wp_verify_nonce($_POST['zon_testimonial_nonce'],'zon_testimonial') )
{ //if nonce check succeeds.
$post_id = $post->ID;
$data = array(
'package' => sanitize_text_field( $_POST['zon_package'] )
);
update_post_meta( $post_id, '_zon_testimonial_key', $data );
}
$data = get_post_meta($post->ID, '_zon_testimonial_key', true);
$package = isset($data['package']) ? $data['package'] : '';
print_r($_POST);
?>
<form method="post" action="">
<?php wp_nonce_field('zon_testimonial','zon_testimonial_nonce'); ?>
<label>This is label</label>
<input type='text' name='zon_package' value='<?php echo $package; ?>' />
<input type='submit' value='save' />
</form>
</code></pre>
| [
{
"answer_id": 343234,
"author": "Abdul Rafay",
"author_id": 172133,
"author_profile": "https://wordpress.stackexchange.com/users/172133",
"pm_score": 0,
"selected": false,
"text": "<p>You should have a remote mysql option in your cpanel to allow you to do that if not then you may ask your hosting provider for more assistance after that:</p>\n\n<p><strong>Use the following configuration settings for connecting to your database:</strong></p>\n\n<p>Host name = (use the server IP address)</p>\n\n<p>Database name = (cpanelUsername_databaseName)</p>\n\n<p>Database username = (cpanelUsername_databaseUsername)</p>\n\n<p>Database password = (the password you entered for that database user)\nMySQL Connection Port = 3306</p>\n"
},
{
"answer_id": 343235,
"author": "vikas jain",
"author_id": 172136,
"author_profile": "https://wordpress.stackexchange.com/users/172136",
"pm_score": 1,
"selected": false,
"text": "<p>You can set up a new connection from function:</p>\n\n<pre><code>$wpdb_b = new wpdb( \"user\", \"password\", \"brian_db\", \"localhost\" );\n$wpdb_b->get_results( \"SELECT * FROM brian_table\" );\n</code></pre>\n\n<p>Happy Coding</p>\n"
}
] | 2019/07/21 | [
"https://wordpress.stackexchange.com/questions/343324",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/149857/"
] | How I can update Existing (Back-End) metabox variable from front-End, I tried many times but I don't know why doesn't this work? Showing only old value not update, what i did wrong?
This is my Front-End Page, I'm using this code inside normal Page With shortCode and also this code between post loop.
```
if ( isset( $_POST['zon_testimonial_nonce'] ) && wp_verify_nonce($_POST['zon_testimonial_nonce'],'zon_testimonial') )
{ //if nonce check succeeds.
$post_id = $post->ID;
$data = array(
'package' => sanitize_text_field( $_POST['zon_package'] )
);
update_post_meta( $post_id, '_zon_testimonial_key', $data );
}
$data = get_post_meta($post->ID, '_zon_testimonial_key', true);
$package = isset($data['package']) ? $data['package'] : '';
print_r($_POST);
?>
<form method="post" action="">
<?php wp_nonce_field('zon_testimonial','zon_testimonial_nonce'); ?>
<label>This is label</label>
<input type='text' name='zon_package' value='<?php echo $package; ?>' />
<input type='submit' value='save' />
</form>
``` | You can set up a new connection from function:
```
$wpdb_b = new wpdb( "user", "password", "brian_db", "localhost" );
$wpdb_b->get_results( "SELECT * FROM brian_table" );
```
Happy Coding |
343,355 | <p>So when I am creating a post, I would like to only be able to see images (after clicking ,add media above wp editor) that have been uploaded and attached to posts of the same family of the current post i'm creating.</p>
<p>My current code does not seem to work.</p>
<pre><code>global $post;
$parentID = $post->post_parent; //Shows 2068
$currID = $post->ID; //Shows 2069
$args = array('post_parent' => $post->ID, 'post_type' => 'projects', 'numberposts' => -1 );
$children = get_children($args);
foreach ($children as $child):
$childIDs .= " ".$child->ID; //Get Children IDs
endforeach;
$allIDs = $parentID." ".$currID.$childIDs; //shows 2068 2069 2070 2071
add_filter( 'ajax_query_attachments_args', 'wpb_show_current_user_attachments');
function wpb_show_current_user_attachments( $query, $allIDs ) {
$allIDarray = explode (" ", $allIDs);
//$user_id = get_current_user_id();
if ( $user_id && !current_user_can('activate_plugins') && !current_user_can('edit_others_posts') ) {
// $query['author'] = $user_id;
$query['post_parent'] = $allIDarray;
}
return $query;
}
</code></pre>
| [
{
"answer_id": 343234,
"author": "Abdul Rafay",
"author_id": 172133,
"author_profile": "https://wordpress.stackexchange.com/users/172133",
"pm_score": 0,
"selected": false,
"text": "<p>You should have a remote mysql option in your cpanel to allow you to do that if not then you may ask your hosting provider for more assistance after that:</p>\n\n<p><strong>Use the following configuration settings for connecting to your database:</strong></p>\n\n<p>Host name = (use the server IP address)</p>\n\n<p>Database name = (cpanelUsername_databaseName)</p>\n\n<p>Database username = (cpanelUsername_databaseUsername)</p>\n\n<p>Database password = (the password you entered for that database user)\nMySQL Connection Port = 3306</p>\n"
},
{
"answer_id": 343235,
"author": "vikas jain",
"author_id": 172136,
"author_profile": "https://wordpress.stackexchange.com/users/172136",
"pm_score": 1,
"selected": false,
"text": "<p>You can set up a new connection from function:</p>\n\n<pre><code>$wpdb_b = new wpdb( \"user\", \"password\", \"brian_db\", \"localhost\" );\n$wpdb_b->get_results( \"SELECT * FROM brian_table\" );\n</code></pre>\n\n<p>Happy Coding</p>\n"
}
] | 2019/07/22 | [
"https://wordpress.stackexchange.com/questions/343355",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/29133/"
] | So when I am creating a post, I would like to only be able to see images (after clicking ,add media above wp editor) that have been uploaded and attached to posts of the same family of the current post i'm creating.
My current code does not seem to work.
```
global $post;
$parentID = $post->post_parent; //Shows 2068
$currID = $post->ID; //Shows 2069
$args = array('post_parent' => $post->ID, 'post_type' => 'projects', 'numberposts' => -1 );
$children = get_children($args);
foreach ($children as $child):
$childIDs .= " ".$child->ID; //Get Children IDs
endforeach;
$allIDs = $parentID." ".$currID.$childIDs; //shows 2068 2069 2070 2071
add_filter( 'ajax_query_attachments_args', 'wpb_show_current_user_attachments');
function wpb_show_current_user_attachments( $query, $allIDs ) {
$allIDarray = explode (" ", $allIDs);
//$user_id = get_current_user_id();
if ( $user_id && !current_user_can('activate_plugins') && !current_user_can('edit_others_posts') ) {
// $query['author'] = $user_id;
$query['post_parent'] = $allIDarray;
}
return $query;
}
``` | You can set up a new connection from function:
```
$wpdb_b = new wpdb( "user", "password", "brian_db", "localhost" );
$wpdb_b->get_results( "SELECT * FROM brian_table" );
```
Happy Coding |
343,388 | <p>I have the following really simple code:</p>
<pre><code>function load_peoplesoft_results() {
global $wpdb;
echo "<h2>Results</h2>";
}
add_shortcode('load_peoplesoft_result_page', 'load_peoplesoft_results()');
</code></pre>
<p>And I put the following on the page I want to display the page:</p>
<pre><code>[load_peoplesoft_result_page]
</code></pre>
<p>But when I load the page, it just displays the above. I checked the error log, and got the following:</p>
<pre><code>[22-Jul-2019 10:26:49] PHP Notice: do_shortcode_tag was called <strong>incorrectly</strong>.
Attempting to parse a shortcode without a valid callback:
load_peoplesoft_result_page Please see
<a href="https://codex.wordpress.org/Debugging_in_WordPress">Debugging in WordPress</a>
for more information. (This message was added in version 4.3.0.)
in \wp-includes\functions.php on line 4231
</code></pre>
<p>I also tried putting it in a plugin in a different site where I have some shortcodes implemented that are working fine, but had the same issue. No idea what is going on.</p>
<p>Any advice or ideas are greatly appreciated. Thanks in advance.</p>
| [
{
"answer_id": 343392,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": true,
"text": "<p>Your shortcode callback function is incorrect:</p>\n\n<pre><code>add_shortcode('load_peoplesoft_result_page', 'load_peoplesoft_results()');\n</code></pre>\n\n<p>You've included the <code>()</code>, but only the function name should be passed:</p>\n\n<pre><code>add_shortcode( 'load_peoplesoft_result_page', 'load_peoplesoft_results' );\n</code></pre>\n\n<p>Note that the second argument of <code>add_shortcode()</code> is a \"callable\". This is a standard PHP feature, and you can read documentation for them <a href=\"https://www.php.net/manual/en/language.types.callable.php\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 408730,
"author": "Baseer Ebadi",
"author_id": 225044,
"author_profile": "https://wordpress.stackexchange.com/users/225044",
"pm_score": 1,
"selected": false,
"text": "<p>While using the add_shortcode() inside Plugin, So please use as bellow script to explicitly understandable by Plugin, otherwise the Plugin Can't even know about the Shortcode that you are using.</p>\n<p>The magic part is to use callback function with <code>array()</code> and <code>$this</code> variable to introduce the shortcode for Plugin.</p>\n<pre><code>add_shortcode('geo_date_converter', array($this, 'geo_date_converter_shortcode'));\n</code></pre>\n<p>Follow bellow script:</p>\n<pre><code>class EbDateConverter{\n\n public function __construct(){\n\n add_shortcode('geo_date_converter', array($this, 'geo_date_converter_shortcode'));\n \n } \n\n\n public function geo_date_converter_shortcode() {\n\n ob_start();\n\n $this->call_dateConverter();\n\n return ob_get_clean();\n\n }\n\n public function call_dateConverter() {\n\n echo 'Shortcode is Working';\n\n } \n\n }\n \n $EbDateConverter = new EbDateConverter();\n</code></pre>\n"
}
] | 2019/07/22 | [
"https://wordpress.stackexchange.com/questions/343388",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/154429/"
] | I have the following really simple code:
```
function load_peoplesoft_results() {
global $wpdb;
echo "<h2>Results</h2>";
}
add_shortcode('load_peoplesoft_result_page', 'load_peoplesoft_results()');
```
And I put the following on the page I want to display the page:
```
[load_peoplesoft_result_page]
```
But when I load the page, it just displays the above. I checked the error log, and got the following:
```
[22-Jul-2019 10:26:49] PHP Notice: do_shortcode_tag was called <strong>incorrectly</strong>.
Attempting to parse a shortcode without a valid callback:
load_peoplesoft_result_page Please see
<a href="https://codex.wordpress.org/Debugging_in_WordPress">Debugging in WordPress</a>
for more information. (This message was added in version 4.3.0.)
in \wp-includes\functions.php on line 4231
```
I also tried putting it in a plugin in a different site where I have some shortcodes implemented that are working fine, but had the same issue. No idea what is going on.
Any advice or ideas are greatly appreciated. Thanks in advance. | Your shortcode callback function is incorrect:
```
add_shortcode('load_peoplesoft_result_page', 'load_peoplesoft_results()');
```
You've included the `()`, but only the function name should be passed:
```
add_shortcode( 'load_peoplesoft_result_page', 'load_peoplesoft_results' );
```
Note that the second argument of `add_shortcode()` is a "callable". This is a standard PHP feature, and you can read documentation for them [here](https://www.php.net/manual/en/language.types.callable.php). |
343,389 | <p>I am working on a WordPress that someone else started and then disappeared. She created a few custom content types and variables using different plugins and I now want to access the data sets in the functions she created for her template.</p>
<pre><code>$args = array(
'suppress_filters' => 0,
'posts_per_page' => -1,
'sort_order' => 'ASC',
'sort_column' => 'post_title',
'post_type' => 'inst',
'post_status' => 'publish'
);
$content = get_posts($args);
</code></pre>
<p>I have been looking around and different findings suggested using the following variable to get the SQL used:</p>
<pre><code>echo $GLOBALS['wp_query']->request;
</code></pre>
<p>However, what this returns is not the query that shows the post data appearing on the page. When I run that in MySQL directly, it returns exactly 1 result and I think it's the whole page? Because I defined two datasets and there are two fields appearing on the page but only 1 row in the query that's echoed by above line.</p>
<p>I need to know the exact attributes of the <code>WP_Query</code> object in $content but <code>var_dump($content)</code> also doesn't contain the fields I defined. I need to get the image that's in the content typeset, but I can only get the name of the set accessing <code>$content->post_title</code>.</p>
<p>Is there a way to dig into what <code>get_posts()</code> gets from the database and how I can access the attributes I need?</p>
| [
{
"answer_id": 343392,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": true,
"text": "<p>Your shortcode callback function is incorrect:</p>\n\n<pre><code>add_shortcode('load_peoplesoft_result_page', 'load_peoplesoft_results()');\n</code></pre>\n\n<p>You've included the <code>()</code>, but only the function name should be passed:</p>\n\n<pre><code>add_shortcode( 'load_peoplesoft_result_page', 'load_peoplesoft_results' );\n</code></pre>\n\n<p>Note that the second argument of <code>add_shortcode()</code> is a \"callable\". This is a standard PHP feature, and you can read documentation for them <a href=\"https://www.php.net/manual/en/language.types.callable.php\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 408730,
"author": "Baseer Ebadi",
"author_id": 225044,
"author_profile": "https://wordpress.stackexchange.com/users/225044",
"pm_score": 1,
"selected": false,
"text": "<p>While using the add_shortcode() inside Plugin, So please use as bellow script to explicitly understandable by Plugin, otherwise the Plugin Can't even know about the Shortcode that you are using.</p>\n<p>The magic part is to use callback function with <code>array()</code> and <code>$this</code> variable to introduce the shortcode for Plugin.</p>\n<pre><code>add_shortcode('geo_date_converter', array($this, 'geo_date_converter_shortcode'));\n</code></pre>\n<p>Follow bellow script:</p>\n<pre><code>class EbDateConverter{\n\n public function __construct(){\n\n add_shortcode('geo_date_converter', array($this, 'geo_date_converter_shortcode'));\n \n } \n\n\n public function geo_date_converter_shortcode() {\n\n ob_start();\n\n $this->call_dateConverter();\n\n return ob_get_clean();\n\n }\n\n public function call_dateConverter() {\n\n echo 'Shortcode is Working';\n\n } \n\n }\n \n $EbDateConverter = new EbDateConverter();\n</code></pre>\n"
}
] | 2019/07/22 | [
"https://wordpress.stackexchange.com/questions/343389",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/161748/"
] | I am working on a WordPress that someone else started and then disappeared. She created a few custom content types and variables using different plugins and I now want to access the data sets in the functions she created for her template.
```
$args = array(
'suppress_filters' => 0,
'posts_per_page' => -1,
'sort_order' => 'ASC',
'sort_column' => 'post_title',
'post_type' => 'inst',
'post_status' => 'publish'
);
$content = get_posts($args);
```
I have been looking around and different findings suggested using the following variable to get the SQL used:
```
echo $GLOBALS['wp_query']->request;
```
However, what this returns is not the query that shows the post data appearing on the page. When I run that in MySQL directly, it returns exactly 1 result and I think it's the whole page? Because I defined two datasets and there are two fields appearing on the page but only 1 row in the query that's echoed by above line.
I need to know the exact attributes of the `WP_Query` object in $content but `var_dump($content)` also doesn't contain the fields I defined. I need to get the image that's in the content typeset, but I can only get the name of the set accessing `$content->post_title`.
Is there a way to dig into what `get_posts()` gets from the database and how I can access the attributes I need? | Your shortcode callback function is incorrect:
```
add_shortcode('load_peoplesoft_result_page', 'load_peoplesoft_results()');
```
You've included the `()`, but only the function name should be passed:
```
add_shortcode( 'load_peoplesoft_result_page', 'load_peoplesoft_results' );
```
Note that the second argument of `add_shortcode()` is a "callable". This is a standard PHP feature, and you can read documentation for them [here](https://www.php.net/manual/en/language.types.callable.php). |
343,394 | <p>I have a database of <code>50,000 articles</code>, One of my categories contains <code>post of 30k</code>, I mistakenly Deleted a category that contains 30k Post, But all the posts still exist.</p>
<p>I have search google for the past 2days now but I still can't find a way to move this 30k to a new category I just created.</p>
<p>Please help me out, I have access to PHPMyAdmin</p>
<pre><code>INSERT IGNORE INTO wp_term_relationships
(object_id, term_taxonomy_id)
(
SELECT DISTINCT ID, 3
FROM wp_posts
WHERE post_type = 'post' AND post_status = 'publish'
);
</code></pre>
<p>I find the above code helpful but it moves <strong>ALL the posts of the entire site</strong> to a category, I just need only the post that was deleted</p>
| [
{
"answer_id": 343396,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 1,
"selected": false,
"text": "<p>Option 1: backup - Many hosts offer backups. Sometimes you have to pay for them, but often even when you do, they've actually been backing everything up and paying just allows you to access them. Worth checking as this will be fastest.</p>\n\n<p>Option 2: post listing screen - If these posts all had only 1 category, the one that was deleted, they'll be uncategorized now. You can go to the All Posts screen in wp-admin to find all the uncategorized posts, use Screen Options up at the top to show however many you want at a time - I'd suggest 100 at a time - and page by page, check all and bulk edit to assign the new category.</p>\n\n<p>Option 3: if all else fails - If you have no backup and the posts have other categories, but you have a list of the particular posts you want to put back in the category, you can run queries in phpMyAdmin to associate these posts to that category. You'll want to first find the post ID of every post you're trying to add into the category, and then you can find the query that will associate those post IDs to the category.</p>\n"
},
{
"answer_id": 343402,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 0,
"selected": false,
"text": "<p>You can't just restore a backup? If not, this is the simplest thing I can think of...</p>\n\n<p>Sounds like you want to move all posts with category \"Uncategorized\" to a new category. You could do this with SQL but a quicker way might be to just change the name and slug of the uncategorized category.</p>\n\n<p>Go into the <code>admin > Posts > Categories</code> and hit the edit button by \"Uncategorized\". Change the Name and Slug and all those posts will be in the new category.</p>\n\n<p>You can then create a new default category then change the default category in <code>Settings > Writing</code>.</p>\n\n<p><strong>Note</strong>: Be sure to backup your database before messing around with any of this.</p>\n"
}
] | 2019/07/22 | [
"https://wordpress.stackexchange.com/questions/343394",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159376/"
] | I have a database of `50,000 articles`, One of my categories contains `post of 30k`, I mistakenly Deleted a category that contains 30k Post, But all the posts still exist.
I have search google for the past 2days now but I still can't find a way to move this 30k to a new category I just created.
Please help me out, I have access to PHPMyAdmin
```
INSERT IGNORE INTO wp_term_relationships
(object_id, term_taxonomy_id)
(
SELECT DISTINCT ID, 3
FROM wp_posts
WHERE post_type = 'post' AND post_status = 'publish'
);
```
I find the above code helpful but it moves **ALL the posts of the entire site** to a category, I just need only the post that was deleted | Option 1: backup - Many hosts offer backups. Sometimes you have to pay for them, but often even when you do, they've actually been backing everything up and paying just allows you to access them. Worth checking as this will be fastest.
Option 2: post listing screen - If these posts all had only 1 category, the one that was deleted, they'll be uncategorized now. You can go to the All Posts screen in wp-admin to find all the uncategorized posts, use Screen Options up at the top to show however many you want at a time - I'd suggest 100 at a time - and page by page, check all and bulk edit to assign the new category.
Option 3: if all else fails - If you have no backup and the posts have other categories, but you have a list of the particular posts you want to put back in the category, you can run queries in phpMyAdmin to associate these posts to that category. You'll want to first find the post ID of every post you're trying to add into the category, and then you can find the query that will associate those post IDs to the category. |
343,432 | <p>I have a custom post type with a custom taxonomy that has been working fine for years, but recently I've seen that the <strong>custom taxonomy doesn't show up in the individual custom post type anymore</strong>. However, it does show up in the listing and I can quick edit it just fine.</p>
<p><a href="https://i.stack.imgur.com/UpBV7.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UpBV7.jpg" alt="enter image description here"></a></p>
<p>I disabled all our plugins and the same issue. Any ideas on what I'm missing?</p>
<p>This is the code I have to build the custom post type and taxonomy.</p>
<pre><code>// Register Profiles
function cpt_profiles() {
$labels = array(
'name' => __( 'Profile', 'profile' ),
'singular_name' => __( 'Profile', 'profile' ),
'add_new' => __( 'Add Profile', 'profile' ),
'all_items' => __( 'All Profiles', 'profile' ),
'add_new_item' => __( 'Add New Profile', 'profile' ),
'edit_item' => __( 'Edit Profile', 'profile' ),
'new_item' => __( 'New Profile', 'profile' ),
'view_item' => __( 'View Profile', 'profile' ),
'search_items' => __( 'Search Profiles', 'profile' ),
'not_found' => __( 'No Profiles found', 'profile' ),
'not_found_in_trash' => __( 'No Profiles found in Trash', 'profile' ),
'parent_item_colon' => __( 'Parent Profile:', 'profile' ),
'menu_name' => __( 'Profiles', 'profile' ),
);
$rewrite = array(
'slug' => 'profile',
'with_front' => false,
'pages' => true,
'feeds' => true,
);
$args = array(
'labels' => $labels,
'hierarchical' => false,
'supports' => array( 'title', 'editor', 'author', 'revisions', 'thumbnail'),
'taxonomies' => array( 'profile_category'),
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_rest' => true,
'menu_position' => 10,
'menu_icon' => 'dashicons-universal-access',
'show_in_nav_menus' => false,
'publicly_queryable' => true,
'exclude_from_search' => false,
'has_archive' => true,
'query_var' => true,
'can_export' => true,
'rewrite' => $rewrite,
'capability_type' => 'post'
);
register_post_type( 'profile', $args );
}
add_action( 'init', 'cpt_profiles' );
// Register Profile Areas
function tax_profile_topics() {
$labels = array(
'name' => _x( 'Areas', 'Taxonomy General Name', 'text_domain' ),
'singular_name' => _x( 'Area', 'Taxonomy Singular Name', 'text_domain' ),
'menu_name' => __( 'Areas', '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 Area', 'text_domain' ),
'add_new_item' => __( 'Add Area', 'text_domain' ),
'edit_item' => __( 'Edit Area', 'text_domain' ),
'update_item' => __( 'Update Area', 'text_domain' ),
'view_item' => __( 'View Area', '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' => false,
'show_tagcloud' => false,
);
register_taxonomy( 'profile_category', array( 'profile' ), $args );
}
add_action( 'init', 'tax_profile_topics');
</code></pre>
| [
{
"answer_id": 343434,
"author": "Joel Garcia Nuño",
"author_id": 135555,
"author_profile": "https://wordpress.stackexchange.com/users/135555",
"pm_score": 0,
"selected": false,
"text": "<p>I think so that will help you.</p>\n\n<p><strong><em>setup at register_taxonomy $args:</em></strong></p>\n\n<pre><code>$capabilities = array (\n 'manage_terms' => 'publish_mysuffix', //by default only admin\n 'edit_terms' => 'publish_mysuffix',\n 'delete_terms' => 'publish_mysuffix',\n 'assign_terms' => 'publish_mysuffix' \n );\n</code></pre>\n\n<p><strong><em>changes, capatability_type property at cpt 'post' to:</em></strong></p>\n\n<pre><code>'capability_type' => 'mysuffix'\n</code></pre>\n\n<p>Then should be <strong>grant</strong> the <strong>role's</strong>:</p>\n\n<pre><code>$admin = get_role('my_role_name_may_admin');\n$admin_caps = array(\n 'read',\n 'edit_pages',\n 'edit_published_pages',\n 'edit_others_pages',\n 'publish_pages',\n 'edit_mysuffix',\n 'edit_others_mysuffix',\n 'edit_private_mysuffix',\n 'edit_published_mysuffix',\n 'publish_mysuffix',\n 'read_private_mysuffixs',\n 'delete_mysuffix',\n 'delete_others_mysuffix',\n 'delete_private_mysuffix',\n 'delete_published_mysuffix'\n);\nforeach ($admin_caps as $cap) {\n $admin->add_cap($cap);\n}\n</code></pre>\n\n<p><strong>hook</strong> add_action('after_setup_theme', 'add_custom_roles');</p>\n"
},
{
"answer_id": 343435,
"author": "nmr",
"author_id": 147428,
"author_profile": "https://wordpress.stackexchange.com/users/147428",
"pm_score": 3,
"selected": true,
"text": "<p>You missed the <code>'show_in_rest' => true</code> in <code>register_taxonomy()</code>. The default value is <code>FALSE</code>, so if you use Gutenberg editor, your custom taxonomy will not be visible.</p>\n"
}
] | 2019/07/22 | [
"https://wordpress.stackexchange.com/questions/343432",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3577/"
] | I have a custom post type with a custom taxonomy that has been working fine for years, but recently I've seen that the **custom taxonomy doesn't show up in the individual custom post type anymore**. However, it does show up in the listing and I can quick edit it just fine.
[](https://i.stack.imgur.com/UpBV7.jpg)
I disabled all our plugins and the same issue. Any ideas on what I'm missing?
This is the code I have to build the custom post type and taxonomy.
```
// Register Profiles
function cpt_profiles() {
$labels = array(
'name' => __( 'Profile', 'profile' ),
'singular_name' => __( 'Profile', 'profile' ),
'add_new' => __( 'Add Profile', 'profile' ),
'all_items' => __( 'All Profiles', 'profile' ),
'add_new_item' => __( 'Add New Profile', 'profile' ),
'edit_item' => __( 'Edit Profile', 'profile' ),
'new_item' => __( 'New Profile', 'profile' ),
'view_item' => __( 'View Profile', 'profile' ),
'search_items' => __( 'Search Profiles', 'profile' ),
'not_found' => __( 'No Profiles found', 'profile' ),
'not_found_in_trash' => __( 'No Profiles found in Trash', 'profile' ),
'parent_item_colon' => __( 'Parent Profile:', 'profile' ),
'menu_name' => __( 'Profiles', 'profile' ),
);
$rewrite = array(
'slug' => 'profile',
'with_front' => false,
'pages' => true,
'feeds' => true,
);
$args = array(
'labels' => $labels,
'hierarchical' => false,
'supports' => array( 'title', 'editor', 'author', 'revisions', 'thumbnail'),
'taxonomies' => array( 'profile_category'),
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_rest' => true,
'menu_position' => 10,
'menu_icon' => 'dashicons-universal-access',
'show_in_nav_menus' => false,
'publicly_queryable' => true,
'exclude_from_search' => false,
'has_archive' => true,
'query_var' => true,
'can_export' => true,
'rewrite' => $rewrite,
'capability_type' => 'post'
);
register_post_type( 'profile', $args );
}
add_action( 'init', 'cpt_profiles' );
// Register Profile Areas
function tax_profile_topics() {
$labels = array(
'name' => _x( 'Areas', 'Taxonomy General Name', 'text_domain' ),
'singular_name' => _x( 'Area', 'Taxonomy Singular Name', 'text_domain' ),
'menu_name' => __( 'Areas', '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 Area', 'text_domain' ),
'add_new_item' => __( 'Add Area', 'text_domain' ),
'edit_item' => __( 'Edit Area', 'text_domain' ),
'update_item' => __( 'Update Area', 'text_domain' ),
'view_item' => __( 'View Area', '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' => false,
'show_tagcloud' => false,
);
register_taxonomy( 'profile_category', array( 'profile' ), $args );
}
add_action( 'init', 'tax_profile_topics');
``` | You missed the `'show_in_rest' => true` in `register_taxonomy()`. The default value is `FALSE`, so if you use Gutenberg editor, your custom taxonomy will not be visible. |
343,475 | <p>I would like to read from a .css file and inject it as an inline style in wp_head. it's possible?</p>
<p>i've tried this "<a href="https://wordpress.stackexchange.com/questions/263656/add-inline-css-to-theme">Add inline css to theme</a>" solution but it doesn't do what I expect because I expect all the style to be injected into </p>
<p><code><style> [mystile.css] </style></code></p>
<p>and not </p>
<p><code><link href="[mystile.css]"></code></p>
| [
{
"answer_id": 343481,
"author": "user3135691",
"author_id": 59755,
"author_profile": "https://wordpress.stackexchange.com/users/59755",
"pm_score": 1,
"selected": false,
"text": "<p>You need to add your css to wp_head. In order to do so, you need to get your dynamic CSS first, load in into a variable and then add that variable to the head output. Just like so:</p>\n\n<p>(This code can go into your functions.php, plugin file or somewhere else in your theme, make sure you include this code in a file where it can be called properly)</p>\n\n<pre><code><?php\n\n function so_output_dynamic_css() {\n // do some stuff to get your CSS here..\n $some_dynamic_css = \"body {background: green;}\";\n ?>\n <style type=\"text/css\" id=\"so-dynamic-css\">\n <?php echo $some_dynamic_css; ?>\n </style>\n <?php }\n add_action('wp_head', 'so_output_dynamic_css');\n</code></pre>\n"
},
{
"answer_id": 343521,
"author": "Erik",
"author_id": 127675,
"author_profile": "https://wordpress.stackexchange.com/users/127675",
"pm_score": 0,
"selected": false,
"text": "<p>I found a solution to include a css file without using \"file_get_contents()\" since it might require php.ini edits (allow_url_fopen). \nin other hands wp_add_inline_style() needs a registered style to be outputted and, in this case, i can't use it because this is the above the fold style (the rest were loaded into the footer).</p>\n\n<p>as the @user3135691 had pointed out you need to have a variable all the css and then append it to the head. </p>\n\n<p>my solution is:</p>\n\n<pre><code>function inject_css_style() {\n\n // get the acf.css file and store into a variable\n ob_start();\n include 'wp-content/themes/my-theme/inline.css';\n $atf_css = ob_get_clean();\n\n // return the stored style\n if ($atf_css != \"\" ) {\n echo '<style id=\"inline-css\" type=\"text/css\">'. $atf_css . '</style>';\n }\n}\n</code></pre>\n"
}
] | 2019/07/23 | [
"https://wordpress.stackexchange.com/questions/343475",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/127675/"
] | I would like to read from a .css file and inject it as an inline style in wp\_head. it's possible?
i've tried this "[Add inline css to theme](https://wordpress.stackexchange.com/questions/263656/add-inline-css-to-theme)" solution but it doesn't do what I expect because I expect all the style to be injected into
`<style> [mystile.css] </style>`
and not
`<link href="[mystile.css]">` | You need to add your css to wp\_head. In order to do so, you need to get your dynamic CSS first, load in into a variable and then add that variable to the head output. Just like so:
(This code can go into your functions.php, plugin file or somewhere else in your theme, make sure you include this code in a file where it can be called properly)
```
<?php
function so_output_dynamic_css() {
// do some stuff to get your CSS here..
$some_dynamic_css = "body {background: green;}";
?>
<style type="text/css" id="so-dynamic-css">
<?php echo $some_dynamic_css; ?>
</style>
<?php }
add_action('wp_head', 'so_output_dynamic_css');
``` |
343,485 | <p>I'm using "Passwordless Login with OTP / SMS & Email - Facebook Account Kit" for login.</p>
<p>I want to redirect user to <code>http://www.domain.com/author/<username>/screen</code> after they log in</p>
<p>this is the code I used</p>
<pre><code>$current_user = wp_get_current_user();
if ( is_user_logged_in() ) {
$redirect = ('http://www.domain.com/author/'.$current_user->user_login.'/screen'); }
</code></pre>
<p>It redirect to <code>http://www.domain.com/author/screen</code> without the username. can anyone help me with this</p>
| [
{
"answer_id": 343481,
"author": "user3135691",
"author_id": 59755,
"author_profile": "https://wordpress.stackexchange.com/users/59755",
"pm_score": 1,
"selected": false,
"text": "<p>You need to add your css to wp_head. In order to do so, you need to get your dynamic CSS first, load in into a variable and then add that variable to the head output. Just like so:</p>\n\n<p>(This code can go into your functions.php, plugin file or somewhere else in your theme, make sure you include this code in a file where it can be called properly)</p>\n\n<pre><code><?php\n\n function so_output_dynamic_css() {\n // do some stuff to get your CSS here..\n $some_dynamic_css = \"body {background: green;}\";\n ?>\n <style type=\"text/css\" id=\"so-dynamic-css\">\n <?php echo $some_dynamic_css; ?>\n </style>\n <?php }\n add_action('wp_head', 'so_output_dynamic_css');\n</code></pre>\n"
},
{
"answer_id": 343521,
"author": "Erik",
"author_id": 127675,
"author_profile": "https://wordpress.stackexchange.com/users/127675",
"pm_score": 0,
"selected": false,
"text": "<p>I found a solution to include a css file without using \"file_get_contents()\" since it might require php.ini edits (allow_url_fopen). \nin other hands wp_add_inline_style() needs a registered style to be outputted and, in this case, i can't use it because this is the above the fold style (the rest were loaded into the footer).</p>\n\n<p>as the @user3135691 had pointed out you need to have a variable all the css and then append it to the head. </p>\n\n<p>my solution is:</p>\n\n<pre><code>function inject_css_style() {\n\n // get the acf.css file and store into a variable\n ob_start();\n include 'wp-content/themes/my-theme/inline.css';\n $atf_css = ob_get_clean();\n\n // return the stored style\n if ($atf_css != \"\" ) {\n echo '<style id=\"inline-css\" type=\"text/css\">'. $atf_css . '</style>';\n }\n}\n</code></pre>\n"
}
] | 2019/07/23 | [
"https://wordpress.stackexchange.com/questions/343485",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/172321/"
] | I'm using "Passwordless Login with OTP / SMS & Email - Facebook Account Kit" for login.
I want to redirect user to `http://www.domain.com/author/<username>/screen` after they log in
this is the code I used
```
$current_user = wp_get_current_user();
if ( is_user_logged_in() ) {
$redirect = ('http://www.domain.com/author/'.$current_user->user_login.'/screen'); }
```
It redirect to `http://www.domain.com/author/screen` without the username. can anyone help me with this | You need to add your css to wp\_head. In order to do so, you need to get your dynamic CSS first, load in into a variable and then add that variable to the head output. Just like so:
(This code can go into your functions.php, plugin file or somewhere else in your theme, make sure you include this code in a file where it can be called properly)
```
<?php
function so_output_dynamic_css() {
// do some stuff to get your CSS here..
$some_dynamic_css = "body {background: green;}";
?>
<style type="text/css" id="so-dynamic-css">
<?php echo $some_dynamic_css; ?>
</style>
<?php }
add_action('wp_head', 'so_output_dynamic_css');
``` |
343,491 | <p>I have a simple terms page made up of heading and paragraph blocks. I'd like to filter the_content before output in order to get the content of any heading blocks and create a menu with links to named anchors at the top. Of course, by the time I filter <code>the_content</code> passing <code>$content</code> it's already just a string of HTML, no block info. </p>
<p>How might I fetch an array of all the 'blocked' content in my the_content filter? Or is there a better way to achieve this that I'm missing? </p>
<p>EDIT</p>
<p>Or perhaps I should be running a filter on save rather than at output..?</p>
| [
{
"answer_id": 343507,
"author": "Mattimator",
"author_id": 168561,
"author_profile": "https://wordpress.stackexchange.com/users/168561",
"pm_score": 3,
"selected": true,
"text": "<p>Have you tried using <code>parse_blocks()</code> (pass in <code>get_the_content()</code>)? That returns an array of all the blocks in your content. From there you can pull out block names and id attributes using an array map or foreach.</p>\n\n<p>Assuming you only want to pull anchor tags from the headings, you could do something like:</p>\n\n<pre><code> $blocks = parse_blocks( get_the_content() );\n $block_ids = array();\n\n function get_block_id( $block ) {\n if ( $block['blockName'] !== 'core/heading' ) return;\n\n $block_html = $block['innerHTML'];\n $id_start = strpos( $block_html, 'id=\"' ) + 4;\n\n if ( $id_start === false ) return;\n\n $id_end = strpos( $block_html, '\"', $id_start );\n $block_id = substr( $block_html, $id_start, $id_end - $id_start );\n\n return $block_id;\n }\n\n foreach( $blocks as $block ) {\n $block_id = get_block_id( $block );\n if ( $block_id ) array_push ( $block_ids, $block_id );\n }\n</code></pre>\n"
},
{
"answer_id": 343597,
"author": "Kevin Nugent",
"author_id": 45504,
"author_profile": "https://wordpress.stackexchange.com/users/45504",
"pm_score": 1,
"selected": false,
"text": "<p>As per my comment above, I arrived at a similair solution to the one suggested by @Mattimator. Posting my code here in case it's useful. </p>\n\n<pre><code>add_filter( 'the_content', 'airpets_terms_nav' );\nfunction airpets_terms_nav($content) {\n\n if( is_page_template( 'page-terms.php' ) ):\n\n $menu = '<div id=\"top\" class=\"anchor-menu\"><ul class=\"menu\">';\n\n $blocks_arr = parse_blocks( get_the_content() );\n\n foreach( $blocks_arr as $block ):\n\n $text = strip_tags( $block['innerHTML'] );\n\n $slug = slugify( $text );\n\n foreach( $block as $key => $value ):\n\n if( $key == 'blockName' && $value == 'core/heading' ) $menu .= '<li><a class=\"btn\" href=\"#' . $slug . '\">' . $text . '</a></li>';\n\n endforeach;\n\n endforeach;\n\n $menu .= '</ul></div>';\n\n $content = $menu . $content;\n\n endif;\n\n return $content;\n}\n\nadd_filter( 'render_block', 'my_wrap_quote_block_fitler', 10, 3);\nfunction my_wrap_quote_block_fitler( $block_content, $block ) {\n\n if( is_admin() || ! is_page_template( 'page-terms.php' ) ) return $block_content;\n\n if( \"core/heading\" !== $block['blockName'] ) return $block_content;\n\n $slug = slugify( strip_tags( $block_content ) );\n\n $output = '<div class=\"term-header\">' . $block_content . '<a id=\"' . $slug . '\" class=\"anchor\"></a></div>';\n\n return $output;\n}\n</code></pre>\n"
}
] | 2019/07/23 | [
"https://wordpress.stackexchange.com/questions/343491",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/45504/"
] | I have a simple terms page made up of heading and paragraph blocks. I'd like to filter the\_content before output in order to get the content of any heading blocks and create a menu with links to named anchors at the top. Of course, by the time I filter `the_content` passing `$content` it's already just a string of HTML, no block info.
How might I fetch an array of all the 'blocked' content in my the\_content filter? Or is there a better way to achieve this that I'm missing?
EDIT
Or perhaps I should be running a filter on save rather than at output..? | Have you tried using `parse_blocks()` (pass in `get_the_content()`)? That returns an array of all the blocks in your content. From there you can pull out block names and id attributes using an array map or foreach.
Assuming you only want to pull anchor tags from the headings, you could do something like:
```
$blocks = parse_blocks( get_the_content() );
$block_ids = array();
function get_block_id( $block ) {
if ( $block['blockName'] !== 'core/heading' ) return;
$block_html = $block['innerHTML'];
$id_start = strpos( $block_html, 'id="' ) + 4;
if ( $id_start === false ) return;
$id_end = strpos( $block_html, '"', $id_start );
$block_id = substr( $block_html, $id_start, $id_end - $id_start );
return $block_id;
}
foreach( $blocks as $block ) {
$block_id = get_block_id( $block );
if ( $block_id ) array_push ( $block_ids, $block_id );
}
``` |
343,498 | <p>I am trying to set up my site so that my WooCommerce product categories only show images on my home page. Currently I have this:</p>
<pre><code><?php
function fp_categories() {
if( is_front_page() ) {
add_action( 'woocommerce_before_subcategory_title', 'woocommerce_subcategory_thumbnail', 10 ) ;
} else {
remove_action( 'woocommerce_before_subcategory_title', 'woocommerce_subcategory_thumbnail', 10 ) ;
}
}
?>
</code></pre>
<p>This does remove the images, but it does so from every page. I've tried using <code>is_home</code> instead of <code>is_front_page</code>, but it didn't help either. Any suggestions?</p>
| [
{
"answer_id": 343507,
"author": "Mattimator",
"author_id": 168561,
"author_profile": "https://wordpress.stackexchange.com/users/168561",
"pm_score": 3,
"selected": true,
"text": "<p>Have you tried using <code>parse_blocks()</code> (pass in <code>get_the_content()</code>)? That returns an array of all the blocks in your content. From there you can pull out block names and id attributes using an array map or foreach.</p>\n\n<p>Assuming you only want to pull anchor tags from the headings, you could do something like:</p>\n\n<pre><code> $blocks = parse_blocks( get_the_content() );\n $block_ids = array();\n\n function get_block_id( $block ) {\n if ( $block['blockName'] !== 'core/heading' ) return;\n\n $block_html = $block['innerHTML'];\n $id_start = strpos( $block_html, 'id=\"' ) + 4;\n\n if ( $id_start === false ) return;\n\n $id_end = strpos( $block_html, '\"', $id_start );\n $block_id = substr( $block_html, $id_start, $id_end - $id_start );\n\n return $block_id;\n }\n\n foreach( $blocks as $block ) {\n $block_id = get_block_id( $block );\n if ( $block_id ) array_push ( $block_ids, $block_id );\n }\n</code></pre>\n"
},
{
"answer_id": 343597,
"author": "Kevin Nugent",
"author_id": 45504,
"author_profile": "https://wordpress.stackexchange.com/users/45504",
"pm_score": 1,
"selected": false,
"text": "<p>As per my comment above, I arrived at a similair solution to the one suggested by @Mattimator. Posting my code here in case it's useful. </p>\n\n<pre><code>add_filter( 'the_content', 'airpets_terms_nav' );\nfunction airpets_terms_nav($content) {\n\n if( is_page_template( 'page-terms.php' ) ):\n\n $menu = '<div id=\"top\" class=\"anchor-menu\"><ul class=\"menu\">';\n\n $blocks_arr = parse_blocks( get_the_content() );\n\n foreach( $blocks_arr as $block ):\n\n $text = strip_tags( $block['innerHTML'] );\n\n $slug = slugify( $text );\n\n foreach( $block as $key => $value ):\n\n if( $key == 'blockName' && $value == 'core/heading' ) $menu .= '<li><a class=\"btn\" href=\"#' . $slug . '\">' . $text . '</a></li>';\n\n endforeach;\n\n endforeach;\n\n $menu .= '</ul></div>';\n\n $content = $menu . $content;\n\n endif;\n\n return $content;\n}\n\nadd_filter( 'render_block', 'my_wrap_quote_block_fitler', 10, 3);\nfunction my_wrap_quote_block_fitler( $block_content, $block ) {\n\n if( is_admin() || ! is_page_template( 'page-terms.php' ) ) return $block_content;\n\n if( \"core/heading\" !== $block['blockName'] ) return $block_content;\n\n $slug = slugify( strip_tags( $block_content ) );\n\n $output = '<div class=\"term-header\">' . $block_content . '<a id=\"' . $slug . '\" class=\"anchor\"></a></div>';\n\n return $output;\n}\n</code></pre>\n"
}
] | 2019/07/23 | [
"https://wordpress.stackexchange.com/questions/343498",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/172327/"
] | I am trying to set up my site so that my WooCommerce product categories only show images on my home page. Currently I have this:
```
<?php
function fp_categories() {
if( is_front_page() ) {
add_action( 'woocommerce_before_subcategory_title', 'woocommerce_subcategory_thumbnail', 10 ) ;
} else {
remove_action( 'woocommerce_before_subcategory_title', 'woocommerce_subcategory_thumbnail', 10 ) ;
}
}
?>
```
This does remove the images, but it does so from every page. I've tried using `is_home` instead of `is_front_page`, but it didn't help either. Any suggestions? | Have you tried using `parse_blocks()` (pass in `get_the_content()`)? That returns an array of all the blocks in your content. From there you can pull out block names and id attributes using an array map or foreach.
Assuming you only want to pull anchor tags from the headings, you could do something like:
```
$blocks = parse_blocks( get_the_content() );
$block_ids = array();
function get_block_id( $block ) {
if ( $block['blockName'] !== 'core/heading' ) return;
$block_html = $block['innerHTML'];
$id_start = strpos( $block_html, 'id="' ) + 4;
if ( $id_start === false ) return;
$id_end = strpos( $block_html, '"', $id_start );
$block_id = substr( $block_html, $id_start, $id_end - $id_start );
return $block_id;
}
foreach( $blocks as $block ) {
$block_id = get_block_id( $block );
if ( $block_id ) array_push ( $block_ids, $block_id );
}
``` |
343,526 | <p>Im having a loop with count to add a clear after 4 items. It is working pretty well but theres one rebell row that will only take 1 post.</p>
<p>Code:</p>
<pre><code> <section class="bonds-funding">
<h1>Funders</h1>
<?php the_field( "funding_subtitle" ); ?>
<?php $loop = new WP_Query( array( 'post_type' => 'institution', )
);
$counter = 0;
while ( $loop->have_posts() ) : $loop->the_post();
if ($counter % 4 == 0) :
echo $counter > 0 ? "</div>" : ""; // close div if it's not the first
echo "<div class='clearfix'>";
endif;
$colors = get_field('institution_status');
if( $colors && in_array('funding', $colors) ){ ?>
<div class="author-nucleus">
<a href="<?php echo get_field('institution_website', $user->ID); ?>">
<div class="author-avatar">
<!-- <div class="hexa">
<div class="hex1">
<div class="hex2"> -->
<img src="
<?php echo get_the_post_thumbnail_url( $user->ID ); ?>" />
<!-- </div>
</div>
</div> -->
</div>
</a>
<div class="author-info">
<div class="institution-padding">
<h2>
<?php the_title(); ?>
</h2>
</div>
<hr />
<?php
echo get_field('institution_subhead', $user->ID) ?>
<ul class="nucleus-icons-test">
<?php
$post_id = get_the_ID();
get_subjects($post_id, 'post', 6);
?>
</ul>
</div>
</div>
<?php }
$counter++;
endwhile;
wp_reset_query(); ?>
</section>
</code></pre>
<p>First 4 posts display correctly inside a div then, the next div displays only one post, then two more divs with correct count.</p>
<p>What the....?</p>
| [
{
"answer_id": 343527,
"author": "user3135691",
"author_id": 59755,
"author_profile": "https://wordpress.stackexchange.com/users/59755",
"pm_score": 0,
"selected": false,
"text": "<p>Why don't you just:</p>\n\n<pre><code><style>\n.author-nucleus:nth-of-type(4):after {\n clear:both;\n display: table;\n content: \"\";\n}\n</style>\n</code></pre>\n\n<p>That's all you basically need in my opinion. The true beauty of css!\nNo need to do weired counting with opening and closing div's.</p>\n\n<p>Explaination: this css-rule will add a pseudo element after four row's/div's which will clear your float.\nPro: lightweight, easyly changeable\nCons: /</p>\n"
},
{
"answer_id": 343532,
"author": "Nathan Powell",
"author_id": 27196,
"author_profile": "https://wordpress.stackexchange.com/users/27196",
"pm_score": 1,
"selected": false,
"text": "<p>For your clearfix wrapper you are doing it wrong. You have this:</p>\n\n<pre><code>$counter = 0;\nwhile ( $loop->have_posts() ) : $loop->the_post();\nif ($counter % 4 == 0) :\n echo $counter > 0 ? \"</div>\" : \"\"; // close div if it's not the first\n echo \"<div class='clearfix'>\";\nendif;\n// BUILDS INTERNAL DIVS\n$counter++;\nendwhile;\n</code></pre>\n\n<p>So you are opening the div for numbers 0 and multiples of the number 4. Then inside that statement you are only closing a div if the <code>$counter</code> is greater than 0. So you end up closing the div, then opening a new one that may not get closed.</p>\n\n<p>You need to do two things. First, move the closing <code>div</code> to echo at the end of the <code>while</code> statement. Second, wrap the closing <code>div</code> in a different conditional. Here it is corrected:</p>\n\n<pre><code>$counter = 0;\nwhile ( $loop->have_posts() ) : $loop->the_post();\nif ($counter % 4 == 0) {\n echo \"<div class='clearfix'>\";\n}\n// BUILDS INTERNAL DIVS\n\n/**\n * Closing div for loop \n *\n * $counter is more than 0 AND $counter plus 1 is multiple of 4\n * OR $counter plus 1 is the total posts found (the plus 1 here is because we start with 0 which counts toward our total)\n */\nif ( ($counter > 0 && ($counter+1) % 4 == 0 ) || ($counter+1) == $loop->found_posts ) {\n echo \"</div>\";\n}\n$counter++;\nendwhile;\n</code></pre>\n"
}
] | 2019/07/23 | [
"https://wordpress.stackexchange.com/questions/343526",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/34034/"
] | Im having a loop with count to add a clear after 4 items. It is working pretty well but theres one rebell row that will only take 1 post.
Code:
```
<section class="bonds-funding">
<h1>Funders</h1>
<?php the_field( "funding_subtitle" ); ?>
<?php $loop = new WP_Query( array( 'post_type' => 'institution', )
);
$counter = 0;
while ( $loop->have_posts() ) : $loop->the_post();
if ($counter % 4 == 0) :
echo $counter > 0 ? "</div>" : ""; // close div if it's not the first
echo "<div class='clearfix'>";
endif;
$colors = get_field('institution_status');
if( $colors && in_array('funding', $colors) ){ ?>
<div class="author-nucleus">
<a href="<?php echo get_field('institution_website', $user->ID); ?>">
<div class="author-avatar">
<!-- <div class="hexa">
<div class="hex1">
<div class="hex2"> -->
<img src="
<?php echo get_the_post_thumbnail_url( $user->ID ); ?>" />
<!-- </div>
</div>
</div> -->
</div>
</a>
<div class="author-info">
<div class="institution-padding">
<h2>
<?php the_title(); ?>
</h2>
</div>
<hr />
<?php
echo get_field('institution_subhead', $user->ID) ?>
<ul class="nucleus-icons-test">
<?php
$post_id = get_the_ID();
get_subjects($post_id, 'post', 6);
?>
</ul>
</div>
</div>
<?php }
$counter++;
endwhile;
wp_reset_query(); ?>
</section>
```
First 4 posts display correctly inside a div then, the next div displays only one post, then two more divs with correct count.
What the....? | For your clearfix wrapper you are doing it wrong. You have this:
```
$counter = 0;
while ( $loop->have_posts() ) : $loop->the_post();
if ($counter % 4 == 0) :
echo $counter > 0 ? "</div>" : ""; // close div if it's not the first
echo "<div class='clearfix'>";
endif;
// BUILDS INTERNAL DIVS
$counter++;
endwhile;
```
So you are opening the div for numbers 0 and multiples of the number 4. Then inside that statement you are only closing a div if the `$counter` is greater than 0. So you end up closing the div, then opening a new one that may not get closed.
You need to do two things. First, move the closing `div` to echo at the end of the `while` statement. Second, wrap the closing `div` in a different conditional. Here it is corrected:
```
$counter = 0;
while ( $loop->have_posts() ) : $loop->the_post();
if ($counter % 4 == 0) {
echo "<div class='clearfix'>";
}
// BUILDS INTERNAL DIVS
/**
* Closing div for loop
*
* $counter is more than 0 AND $counter plus 1 is multiple of 4
* OR $counter plus 1 is the total posts found (the plus 1 here is because we start with 0 which counts toward our total)
*/
if ( ($counter > 0 && ($counter+1) % 4 == 0 ) || ($counter+1) == $loop->found_posts ) {
echo "</div>";
}
$counter++;
endwhile;
``` |
343,542 | <p>I have an HTML form that is used to send messages to a back end server. When the user clicks the send button, it triggers a javascript that makes an Ajax call to WordPress which in turn, makes an API call to the back end server to send the message. This part works flawlessly. The server then responds with a string which I want to return to the javascript to display in the form.</p>
<p>For some reason, I can't get the return value to javascript. I've stripped my function down to bare bones as follows:</p>
<pre><code>function smsgte_admin_send() {
check_ajax_referer('smsgte_nonce', 'security');
$response = admin_server_send(filter_input(INPUT_POST, 'message', FILTER_SANITIZE_STRING));
$result = array (
//'response' => $repsonse,
'response' => 'just a response',
);
return $result;
}
</code></pre>
<p>The <code>admin_server_send</code> triggers the message being sent to the server. The message reaches the server, so that's working. I was questioning the response from the server, so I just populated my result array with a random string, but the javascript never receives the string.</p>
<p>The javascript code is:</p>
<pre><code>function smsgteAdminSend(button) {
var message = document.getElementById("smsgte_admin_message").value;
jQuery(document).ready(function ($) {
var data = {
'action': 'smsgte_admin_send',
'message': message,
'security': smsgte_Ajax.ajax_nonce,
};
jQuery.post(smsgte_Ajax.ajaxurl, data, function (response, status) {
document.getElementById("smsgte_admin_send_response").innerHTML = response.response;
});
});
}
</code></pre>
<p>Originally, I was sending the response as a string instead of a key/value pair, but that wasn't working either. Can't help think I'm missing something simple.</p>
| [
{
"answer_id": 343553,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 3,
"selected": true,
"text": "<p>Returning the result array will only return to the PHP function calling it, instead you actually need to output it by echoing it, and in this case because it is an array, encoding it with JSON before outputting. So <code>return $result</code> becomes:</p>\n\n<pre><code>echo json_encode($result); exit;\n</code></pre>\n\n<p>and then add dataType to the javascript call so it can recognize the array data:</p>\n\n<pre><code> var data = {\n 'action': 'smsgte_admin_send',\n 'message': message,\n 'security': smsgte_Ajax.ajax_nonce,\n 'dataType': 'json'\n };\n</code></pre>\n\n<p>See this answer for a more complete example:\n<a href=\"https://stackoverflow.com/a/8823995/5240159\">https://stackoverflow.com/a/8823995/5240159</a></p>\n"
},
{
"answer_id": 343567,
"author": "Prdufresne",
"author_id": 92841,
"author_profile": "https://wordpress.stackexchange.com/users/92841",
"pm_score": 0,
"selected": false,
"text": "<p>The answer provided by @majick is the correct answer. I am posting this answer to show how I modified the code sample.</p>\n\n<pre><code>function smsgte_admin_send() {\n check_ajax_referer('smsgte_nonce', 'security'); \n $response = admin_server_send(filter_input(INPUT_POST, 'message', FILTER_SANITIZE_STRING));\n echo $response;\n wp_die();\n}\n</code></pre>\n\n<p>The javascript code was changed to:</p>\n\n<pre><code>function smsgteAdminSend(button) {\n var message = document.getElementById(\"smsgte_admin_message\").value;\n\n jQuery(document).ready(function ($) {\n var data = {\n 'action': 'smsgte_admin_send',\n 'message': message,\n 'security': smsgte_Ajax.ajax_nonce,\n };\n jQuery.post(smsgte_Ajax.ajaxurl, data, function (response, status) {\n\n document.getElementById(\"smsgte_admin_send_response\").innerHTML = response;\n\n });\n });\n\n}\n</code></pre>\n\n<p>In the question, I was sending a key/value pair because I thought jQuery was expecting an object. Since what I needed to do was echo the response, the key/value pair was unnecessary and I simply echo'd the response string.</p>\n"
}
] | 2019/07/24 | [
"https://wordpress.stackexchange.com/questions/343542",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/92841/"
] | I have an HTML form that is used to send messages to a back end server. When the user clicks the send button, it triggers a javascript that makes an Ajax call to WordPress which in turn, makes an API call to the back end server to send the message. This part works flawlessly. The server then responds with a string which I want to return to the javascript to display in the form.
For some reason, I can't get the return value to javascript. I've stripped my function down to bare bones as follows:
```
function smsgte_admin_send() {
check_ajax_referer('smsgte_nonce', 'security');
$response = admin_server_send(filter_input(INPUT_POST, 'message', FILTER_SANITIZE_STRING));
$result = array (
//'response' => $repsonse,
'response' => 'just a response',
);
return $result;
}
```
The `admin_server_send` triggers the message being sent to the server. The message reaches the server, so that's working. I was questioning the response from the server, so I just populated my result array with a random string, but the javascript never receives the string.
The javascript code is:
```
function smsgteAdminSend(button) {
var message = document.getElementById("smsgte_admin_message").value;
jQuery(document).ready(function ($) {
var data = {
'action': 'smsgte_admin_send',
'message': message,
'security': smsgte_Ajax.ajax_nonce,
};
jQuery.post(smsgte_Ajax.ajaxurl, data, function (response, status) {
document.getElementById("smsgte_admin_send_response").innerHTML = response.response;
});
});
}
```
Originally, I was sending the response as a string instead of a key/value pair, but that wasn't working either. Can't help think I'm missing something simple. | Returning the result array will only return to the PHP function calling it, instead you actually need to output it by echoing it, and in this case because it is an array, encoding it with JSON before outputting. So `return $result` becomes:
```
echo json_encode($result); exit;
```
and then add dataType to the javascript call so it can recognize the array data:
```
var data = {
'action': 'smsgte_admin_send',
'message': message,
'security': smsgte_Ajax.ajax_nonce,
'dataType': 'json'
};
```
See this answer for a more complete example:
<https://stackoverflow.com/a/8823995/5240159> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.