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
|
---|---|---|---|---|---|---|
330,574 | <p>Maybe this topic needs updating because i have certainly used this in the past, but today adobe illustrator ai files are not uploading.</p>
<p>So I'm using <a href="https://docs.gravityforms.com/security/#file-upload-security" rel="nofollow noreferrer">gravity forms plugin</a> to upload my files.</p>
<p>When I tried to initially uploading these file formats...</p>
<ol>
<li>PSD</li>
<li>EPS</li>
<li>AI</li>
<li>SVG</li>
</ol>
<p>I was getting this message: <strong>Sorry, this file extension is not permitted for security reasons</strong> for all of these file formats.</p>
<p>So I filtered my upload mimes by adding this function to my class...</p>
<pre><code>/**
* my class constructor
*/
public function __construct()
{
// allow extra mime type uploads
add_filter( 'upload_mimes' , array ($this, 'custom_upload_mimes'));
}
/**
* Allow extra mime types for the sample upload
*
* @return array
*/
public function custom_upload_mimes ( $existing_mimes = [] )
{
$existing_mimes['psd'] = 'image/vnd.adobe.photoshop';
$existing_mimes['eps'] = 'application/postscript';
$existing_mimes['ai'] = 'application/postscript';
$existing_mimes['svg'] = 'image/svg+xml';
return $existing_mimes;
}
</code></pre>
<p>After a bit of testing, all those file types listed above uploaded fine... apart from the illustrator file.</p>
<p>I removed this function and I was not able to upload any of these formats. I re-invoked the function and again, only the illustrator <code>.ai</code> file was returning the error message.</p>
<p>I also tried a very old illustrator file to see if was a file issue but the result was the same.</p>
<p>What should I do to fix this?</p>
| [
{
"answer_id": 353721,
"author": "Mushrit Shabnam",
"author_id": 111284,
"author_profile": "https://wordpress.stackexchange.com/users/111284",
"pm_score": 3,
"selected": true,
"text": "<p>Please try this:</p>\n\n<pre><code>$mime_types[ 'eps' ] = 'application/postscript';\n$mime_types[ 'ai' ] = 'application/pdf';\n$mime_types[ 'svg' ] = 'image/svg+xml';`\n</code></pre>\n\n<p>and then return <code>$mime_types</code></p>\n"
},
{
"answer_id": 400723,
"author": "mindlid",
"author_id": 217366,
"author_profile": "https://wordpress.stackexchange.com/users/217366",
"pm_score": 0,
"selected": false,
"text": "<p>im putting this info here (not about upload) but according to <a href=\"https://experienceleague.adobe.com/docs/experience-manager-65/assets/administer/assets-formats.html?lang=en#supported-mime-types\" rel=\"nofollow noreferrer\">adobe docs</a> the mime types list as following</p>\n<p>for <code>.ai</code> is <code>application/postscript</code></p>\n<p>for <code>eps</code> can be any of the following EPS</p>\n<ol>\n<li><code>application/postscript</code></li>\n<li><code>application/eps</code></li>\n<li><code>application/x-eps</code></li>\n<li><code>image/eps</code></li>\n<li><code>image/x-eps</code></li>\n</ol>\n<p>for <code>psd</code> is <code>image/vnd.adobe.photoshop</code></p>\n<p>for <code>svg</code> is <code>image/svg+xml</code></p>\n"
}
] | 2019/03/04 | [
"https://wordpress.stackexchange.com/questions/330574",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111152/"
] | Maybe this topic needs updating because i have certainly used this in the past, but today adobe illustrator ai files are not uploading.
So I'm using [gravity forms plugin](https://docs.gravityforms.com/security/#file-upload-security) to upload my files.
When I tried to initially uploading these file formats...
1. PSD
2. EPS
3. AI
4. SVG
I was getting this message: **Sorry, this file extension is not permitted for security reasons** for all of these file formats.
So I filtered my upload mimes by adding this function to my class...
```
/**
* my class constructor
*/
public function __construct()
{
// allow extra mime type uploads
add_filter( 'upload_mimes' , array ($this, 'custom_upload_mimes'));
}
/**
* Allow extra mime types for the sample upload
*
* @return array
*/
public function custom_upload_mimes ( $existing_mimes = [] )
{
$existing_mimes['psd'] = 'image/vnd.adobe.photoshop';
$existing_mimes['eps'] = 'application/postscript';
$existing_mimes['ai'] = 'application/postscript';
$existing_mimes['svg'] = 'image/svg+xml';
return $existing_mimes;
}
```
After a bit of testing, all those file types listed above uploaded fine... apart from the illustrator file.
I removed this function and I was not able to upload any of these formats. I re-invoked the function and again, only the illustrator `.ai` file was returning the error message.
I also tried a very old illustrator file to see if was a file issue but the result was the same.
What should I do to fix this? | Please try this:
```
$mime_types[ 'eps' ] = 'application/postscript';
$mime_types[ 'ai' ] = 'application/pdf';
$mime_types[ 'svg' ] = 'image/svg+xml';`
```
and then return `$mime_types` |
330,748 | <p>Is there a way to append the image id class to existing attached images in the post content automagically with a php function? That would be incredibly awesome.</p>
<p>Here is what I have so far. It seems like it should work, in theory. What am I doing wrong?</p>
<pre><code>function be_attachment_id_on_images( $attr, $attachment ) {
if( !strpos( $attr['class'], 'wp-image-' . $attachment->ID ) )
$attr['class'] .= ' wp-image-' . $attachment->ID;
return $attr;
}
add_filter( 'wp_get_attachment_image_attributes', 'be_attachment_id_on_images', 10, 2 );
if ( current_user_can( 'manage_options' ) && is_admin()){
function my_update_posts() {
$args = array(
'post_type' => 'post',
'numberposts' => -1,
'category' => 1,
'ID' => 1,
);
$myposts = get_posts($args);
foreach ($myposts as $mypost){
$content = $mypost->post_content;
apply_filters('be_attachment_id_on_images', $content);
$mypost->post_content = $content;
wp_update_post( $mypost );
}
}
add_action( 'admin_init', 'my_update_posts' );
}
</code></pre>
| [
{
"answer_id": 331032,
"author": "Loren Rosen",
"author_id": 158993,
"author_profile": "https://wordpress.stackexchange.com/users/158993",
"pm_score": 1,
"selected": false,
"text": "<p>According to <a href=\"https://wordpress.stackexchange.com/questions/266702/wp-get-attachment-image-attributes-not-working-for-me\">this</a> earlier answer, the <code>wp_get_attachment_image_attributes</code> filter only works for the Featured Image/Post Thumbnail, although I'm not sure if the assertion is correct. Other places claim it doesn't work with the block editor. You might try the <code>get_image_tag_class()</code> filter. Or, depending on your goals, it might suffice to use a slightly different approach: add a class to the body (using the <code>body_class()</code> filter), then use a css selector like <code>body.special img</code> (that doesn't give the ID, though).</p>\n"
},
{
"answer_id": 378375,
"author": "GDY",
"author_id": 52227,
"author_profile": "https://wordpress.stackexchange.com/users/52227",
"pm_score": 2,
"selected": false,
"text": "<p>Shamelessly copied from here:\n<a href=\"https://letswp.io/add-attachment-id-to-the-class-of-wordpress-images/\" rel=\"nofollow noreferrer\">https://letswp.io/add-attachment-id-to-the-class-of-wordpress-images/</a></p>\n<pre><code>add_filter( 'wp_get_attachment_image_attributes', 'add_image_id_class', 10, 2 );\n\n\nfunction add_image_id_class( $attr, $attachment ) {\n\n $class_attr = isset( $attr['class'] ) ? $attr['class'] : '';\n\n $has_class = preg_match( '/wpimage\\_[0-9]+/', $class_attr, $matches );\n\n\n if ( !$has_class ) {\n\n $class_attr .= sprintf( ' wpimage_%d', $attachment->ID );\n\n $attr['class'] = ltrim( $class_attr );\n\n }\n\n return $attr;\n\n}\n</code></pre>\n<p>This add a class like <code>wpimage_{ATTACHMENT_ID}</code> for example <code>wpimage_22</code>.</p>\n"
}
] | 2019/03/05 | [
"https://wordpress.stackexchange.com/questions/330748",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/138460/"
] | Is there a way to append the image id class to existing attached images in the post content automagically with a php function? That would be incredibly awesome.
Here is what I have so far. It seems like it should work, in theory. What am I doing wrong?
```
function be_attachment_id_on_images( $attr, $attachment ) {
if( !strpos( $attr['class'], 'wp-image-' . $attachment->ID ) )
$attr['class'] .= ' wp-image-' . $attachment->ID;
return $attr;
}
add_filter( 'wp_get_attachment_image_attributes', 'be_attachment_id_on_images', 10, 2 );
if ( current_user_can( 'manage_options' ) && is_admin()){
function my_update_posts() {
$args = array(
'post_type' => 'post',
'numberposts' => -1,
'category' => 1,
'ID' => 1,
);
$myposts = get_posts($args);
foreach ($myposts as $mypost){
$content = $mypost->post_content;
apply_filters('be_attachment_id_on_images', $content);
$mypost->post_content = $content;
wp_update_post( $mypost );
}
}
add_action( 'admin_init', 'my_update_posts' );
}
``` | Shamelessly copied from here:
<https://letswp.io/add-attachment-id-to-the-class-of-wordpress-images/>
```
add_filter( 'wp_get_attachment_image_attributes', 'add_image_id_class', 10, 2 );
function add_image_id_class( $attr, $attachment ) {
$class_attr = isset( $attr['class'] ) ? $attr['class'] : '';
$has_class = preg_match( '/wpimage\_[0-9]+/', $class_attr, $matches );
if ( !$has_class ) {
$class_attr .= sprintf( ' wpimage_%d', $attachment->ID );
$attr['class'] = ltrim( $class_attr );
}
return $attr;
}
```
This add a class like `wpimage_{ATTACHMENT_ID}` for example `wpimage_22`. |
330,762 | <p>I have this underscore template to add and delete row :</p>
<pre><code><#
jQuery( document ).ready( function() {
jQuery( '.add-ingr' ).click( function() {
jQuery( '#re-ingr .ingr' ).append( '<div><input
type="text" name="ingr[]" value=""/><a href="#"
class="remove_field" style="margin-left:10px;">Remove</a><div>');
});
jQuery( '.remove_field' ).on("click", function(e){
e.preventDefault(); jQuery(this).parent('div').remove();
});
});
#>
</code></pre>
<p>the add row with remove link works , it generates the good html output:</p>
<pre><code> <div><input type="text" name="ingredients[]" value=""><a href="#"
class="remove_field" style="margin-left:10px;">Remove</a><div></div>
</div>
</code></pre>
<p>But not the remove , nothing happen when i click on the remove hyperlink
Any idea pls </p>
| [
{
"answer_id": 330764,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 2,
"selected": true,
"text": "<p>This isn't WP related but Its not working because you are trying to add an event to a dynamically created element.</p>\n\n<p>Replace...</p>\n\n<pre><code>jQuery( '.remove_field' ).on(\"click\", function(e){ \n e.preventDefault(); jQuery(this).parent('div').remove();\n});\n</code></pre>\n\n<p>With</p>\n\n<pre><code>jQuery( 'body' ).on(\"click\", '.remove_field', function(e){ \n e.preventDefault(); jQuery(this).parent('div').remove();\n});\n</code></pre>\n\n<p>You can <a href=\"https://stackoverflow.com/questions/1359018/in-jquery-how-to-attach-events-to-dynamic-html-elements\">read more about your issue here</a>.</p>\n"
},
{
"answer_id": 330765,
"author": "mrben522",
"author_id": 84703,
"author_profile": "https://wordpress.stackexchange.com/users/84703",
"pm_score": 0,
"selected": false,
"text": "<p>The div's you are trying to bind that event to don't exist when you create the listener. you need to use jQuery <a href=\"https://learn.jquery.com/events/event-delegation/\" rel=\"nofollow noreferrer\">event delegation</a> for this. like so:</p>\n\n<pre><code>jQuery( 'body' ).on(\"click\", '.remove_field', function(e){\n e.preventDefault(); jQuery(this).parent('div').remove();\n});\n</code></pre>\n"
}
] | 2019/03/05 | [
"https://wordpress.stackexchange.com/questions/330762",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/158913/"
] | I have this underscore template to add and delete row :
```
<#
jQuery( document ).ready( function() {
jQuery( '.add-ingr' ).click( function() {
jQuery( '#re-ingr .ingr' ).append( '<div><input
type="text" name="ingr[]" value=""/><a href="#"
class="remove_field" style="margin-left:10px;">Remove</a><div>');
});
jQuery( '.remove_field' ).on("click", function(e){
e.preventDefault(); jQuery(this).parent('div').remove();
});
});
#>
```
the add row with remove link works , it generates the good html output:
```
<div><input type="text" name="ingredients[]" value=""><a href="#"
class="remove_field" style="margin-left:10px;">Remove</a><div></div>
</div>
```
But not the remove , nothing happen when i click on the remove hyperlink
Any idea pls | This isn't WP related but Its not working because you are trying to add an event to a dynamically created element.
Replace...
```
jQuery( '.remove_field' ).on("click", function(e){
e.preventDefault(); jQuery(this).parent('div').remove();
});
```
With
```
jQuery( 'body' ).on("click", '.remove_field', function(e){
e.preventDefault(); jQuery(this).parent('div').remove();
});
```
You can [read more about your issue here](https://stackoverflow.com/questions/1359018/in-jquery-how-to-attach-events-to-dynamic-html-elements). |
330,832 | <p>I would like to insert and execute some WordPress shortcode through <code>main.js</code> file, in a string "", but the problem is that it won't execute!</p>
<p>Here is an example of my <code>main.js</code>:</p>
<pre><code>..
},
"March 6": {
"title": "6 March",
"subtitle": "Sample text",
"content": "[sc name=\"sampleshortcode\"]"
},
..
</code></pre>
<p>So with this, I see only <code>[sc name="sampleshortcode"]</code> as executed on my WordPress page.</p>
<p>Looking to find the solution to show WordPress shortcode through "string". Or any other idea.</p>
| [
{
"answer_id": 330764,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 2,
"selected": true,
"text": "<p>This isn't WP related but Its not working because you are trying to add an event to a dynamically created element.</p>\n\n<p>Replace...</p>\n\n<pre><code>jQuery( '.remove_field' ).on(\"click\", function(e){ \n e.preventDefault(); jQuery(this).parent('div').remove();\n});\n</code></pre>\n\n<p>With</p>\n\n<pre><code>jQuery( 'body' ).on(\"click\", '.remove_field', function(e){ \n e.preventDefault(); jQuery(this).parent('div').remove();\n});\n</code></pre>\n\n<p>You can <a href=\"https://stackoverflow.com/questions/1359018/in-jquery-how-to-attach-events-to-dynamic-html-elements\">read more about your issue here</a>.</p>\n"
},
{
"answer_id": 330765,
"author": "mrben522",
"author_id": 84703,
"author_profile": "https://wordpress.stackexchange.com/users/84703",
"pm_score": 0,
"selected": false,
"text": "<p>The div's you are trying to bind that event to don't exist when you create the listener. you need to use jQuery <a href=\"https://learn.jquery.com/events/event-delegation/\" rel=\"nofollow noreferrer\">event delegation</a> for this. like so:</p>\n\n<pre><code>jQuery( 'body' ).on(\"click\", '.remove_field', function(e){\n e.preventDefault(); jQuery(this).parent('div').remove();\n});\n</code></pre>\n"
}
] | 2019/03/06 | [
"https://wordpress.stackexchange.com/questions/330832",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/162605/"
] | I would like to insert and execute some WordPress shortcode through `main.js` file, in a string "", but the problem is that it won't execute!
Here is an example of my `main.js`:
```
..
},
"March 6": {
"title": "6 March",
"subtitle": "Sample text",
"content": "[sc name=\"sampleshortcode\"]"
},
..
```
So with this, I see only `[sc name="sampleshortcode"]` as executed on my WordPress page.
Looking to find the solution to show WordPress shortcode through "string". Or any other idea. | This isn't WP related but Its not working because you are trying to add an event to a dynamically created element.
Replace...
```
jQuery( '.remove_field' ).on("click", function(e){
e.preventDefault(); jQuery(this).parent('div').remove();
});
```
With
```
jQuery( 'body' ).on("click", '.remove_field', function(e){
e.preventDefault(); jQuery(this).parent('div').remove();
});
```
You can [read more about your issue here](https://stackoverflow.com/questions/1359018/in-jquery-how-to-attach-events-to-dynamic-html-elements). |
330,838 | <p>I am creating a website that would need to only allow some specific email addresses to signup (for example "[email protected]"). Do you guys know of any wordpress email confirmation plugins that would allow me to do that?</p>
<p>To clear some confusion: What I am looking for is only allowing some email addresses (for example all emails ending in @unimail.co.uk), I don't want to have to write down all of them independently. I don't really know how to code php so it would be super helpful if someone could help. Once again, sorry for the confusion created with the first question.</p>
<p>Thank you</p>
| [
{
"answer_id": 330935,
"author": "Tanmay Patel",
"author_id": 62026,
"author_profile": "https://wordpress.stackexchange.com/users/62026",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>Just <strong>copy the above code and paste it into your theme’s functions.php file</strong>.\n Here I am going to show you the code which <strong>will reject registration from all others email addresses</strong> and <strong>Only allowing some email addresses to create an account</strong>. See the code below</p>\n</blockquote>\n\n<pre><code>function is_valid_emails($login, $email, $errors ){\n $valid_emails = array(\"[email protected]\");\n $valid = false;\n foreach( $valid_emails as $valid_email ){\n $valid_emails_list = strtolower($valid_email);\n $current_email = strtolower($email);\n if( $current_email == $valid_emails_list ){\n $valid = true;\n break;\n }\n }\n if( $valid === false ){\n $errors->add('domain_whitelist_error',__( \"<strong>ERROR</strong>: you can't register email because only allow some specific email addresses\" ));\n }\n }\n add_action('register_post', 'is_valid_emails',10,3 );\n</code></pre>\n\n<blockquote>\n <p>You can <strong>add more email addresses</strong> by adding more inside the code:</p>\n</blockquote>\n\n<pre><code>$valid_emails = array(\"[email protected]\",\"[email protected]\");\n</code></pre>\n"
},
{
"answer_id": 330936,
"author": "bjornredemption",
"author_id": 64380,
"author_profile": "https://wordpress.stackexchange.com/users/64380",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://wordpress.org/plugins/wp-approve-user/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wp-approve-user/</a> Is a plugin that allows you to approve user registrations before they are allowed to login to your site.\nAll user registrations essentially go into a Pending state until the admin user approves them.</p>\n"
},
{
"answer_id": 331057,
"author": "Debbie Kurth",
"author_id": 119560,
"author_profile": "https://wordpress.stackexchange.com/users/119560",
"pm_score": -1,
"selected": false,
"text": "<p>The plugin woocommerce memberships does this. But it is pricey for just that feature. Better to use the code suggested above.</p>\n"
},
{
"answer_id": 331059,
"author": "HU is Sebastian",
"author_id": 56587,
"author_profile": "https://wordpress.stackexchange.com/users/56587",
"pm_score": 1,
"selected": false,
"text": "<p>Instead of using the register_post action, you should use the registration_errors filter like this (copied from codex, then modified):</p>\n\n<pre><code>function my_awesome_email_validation_filter( $errors, $sanitized_user_login, $user_email ) {\n $allowed_email_addresses = array('[email protected]','[email protected]'); //be sure to write all the allowed addresses in lowercase\n if(!in_array(mb_strotolower($user_email),$allowed_email_addresses)){\n $errors->add( 'email_not_allowed', __( '<strong>ERROR</strong>: Sorry, but you are not allowed to register.', 'my_textdomain' ) );\n }\n return $errors;\n}\n\nadd_filter( 'registration_errors', 'my_awesome_email_validation_filter', 10, 3 );\n</code></pre>\n\n<p>Happy Coding!</p>\n"
}
] | 2019/03/06 | [
"https://wordpress.stackexchange.com/questions/330838",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/162614/"
] | I am creating a website that would need to only allow some specific email addresses to signup (for example "[email protected]"). Do you guys know of any wordpress email confirmation plugins that would allow me to do that?
To clear some confusion: What I am looking for is only allowing some email addresses (for example all emails ending in @unimail.co.uk), I don't want to have to write down all of them independently. I don't really know how to code php so it would be super helpful if someone could help. Once again, sorry for the confusion created with the first question.
Thank you | >
> Just **copy the above code and paste it into your theme’s functions.php file**.
> Here I am going to show you the code which **will reject registration from all others email addresses** and **Only allowing some email addresses to create an account**. See the code below
>
>
>
```
function is_valid_emails($login, $email, $errors ){
$valid_emails = array("[email protected]");
$valid = false;
foreach( $valid_emails as $valid_email ){
$valid_emails_list = strtolower($valid_email);
$current_email = strtolower($email);
if( $current_email == $valid_emails_list ){
$valid = true;
break;
}
}
if( $valid === false ){
$errors->add('domain_whitelist_error',__( "<strong>ERROR</strong>: you can't register email because only allow some specific email addresses" ));
}
}
add_action('register_post', 'is_valid_emails',10,3 );
```
>
> You can **add more email addresses** by adding more inside the code:
>
>
>
```
$valid_emails = array("[email protected]","[email protected]");
``` |
330,852 | <p>I have a custom meta box for saving values from two input fields into a single post meta field.</p>
<p>The data is saved serialized in the DB:</p>
<pre><code>get_post_meta( $post->ID, '_custom_key', true )
</code></pre>
<p>will return:</p>
<pre><code>a:2:{s:5:"email";s:10:"[email protected]";s:6:"number";i:15;}
</code></pre>
<p>Now, with Gutenberg, I want to move that whole custom meta box into a separate sidebar plugin. So in order to do this, first, I had to add the <code>__back_compat_meta_box</code> argument when adding the meta box, so it won't appear in <code>Sidebar -> Settings -> Document</code> anymore:</p>
<pre><code> add_meta_box(
'options',
'Options',
[ $this, 'renderOptionsBox' ],
[ 'post', 'page', 'attachement' ], // the meta field is registered for multiple post types
'side',
'high',
[ '__back_compat_meta_box' => true ]
);
</code></pre>
<p>For the meta field (<code>_custom_key</code>) to work with the block editor, it has to be registered using the <code>register_meta</code> function:</p>
<pre><code>register_meta( string $object_type, string $meta_key, array $args, string|array $deprecated = null )
</code></pre>
<p>My questions are:</p>
<ol>
<li>[updated] How can I register the custom meta field for <strong>all</strong> of the post types in this list <code>[ 'post', 'page', 'attachement' ]</code>?</li>
<li>How can I still follow the same serialized way of saving the data in a <em>single</em> field if the types ($args->type) supported when registering a meta are only 'string', 'boolean', 'integer', and 'number'?</li>
</ol>
<p>Right now if I just register the <code>_custom_key</code> meta using:</p>
<pre><code> register_meta( 'post', '_custom_key', [
'show_in_rest' => true,
'single' => true,
'type' => 'string',
'auth_callback' => function () {
return current_user_can( 'edit_posts' );
}
]);
</code></pre>
<p>I will get a <code>Notice: Array to string conversion in .../wp-includes/rest-api/fields/class-wp-rest-meta-fields.php</code> because already saved data from the DB is serialized.</p>
<p>and typing in the console: <code>wp.data.select( 'core/editor' ).getCurrentPost().meta;</code> will return a string: <code>{_custom_key: "Array"}</code>.</p>
| [
{
"answer_id": 341735,
"author": "rsborn",
"author_id": 170908,
"author_profile": "https://wordpress.stackexchange.com/users/170908",
"pm_score": 1,
"selected": false,
"text": "<p>Here's an answer to question 1 that uses <a href=\"https://developer.wordpress.org/reference/functions/register_post_meta/\" rel=\"nofollow noreferrer\"><code>register_post_meta</code></a>. It's also the start of an answer to question 2 by use of the <code>prepare_callback</code> option in <code>show_in_rest</code> .</p>\n\n<pre><code>add_action( 'init', 'wpse_89033_register_custom_meta' );\nfunction wpse_89033_register_custom_meta() {\n\n $post_types = [ \n 'post',\n 'page',\n 'attachment',\n ];\n\n foreach ( $post_types as $post_type ) {\n\n register_post_meta( \n $post_type,\n '_custom_key',\n array(\n 'type' => 'string',\n 'single' => true,\n 'auth_callback' => function() { \n return current_user_can( 'edit_posts' );\n },\n 'show_in_rest' => [\n 'prepare_callback' => function( $value ) {\n return wp_json_encode( $value );\n }\n ],\n ) \n );\n\n }\n\n}\n</code></pre>\n\n<p>The documentation for <code>show_in_rest</code> (see <a href=\"https://developer.wordpress.org/reference/functions/register_meta/\" rel=\"nofollow noreferrer\"><code>register_meta</code></a>) says it's a boolean parameter. But it will accept an options array. To see the options, look at the body of <a href=\"https://developer.wordpress.org/reference/classes/wp_rest_meta_fields/get_registered_fields/\" rel=\"nofollow noreferrer\"><code>get_registered_fields</code></a>, in particular the value of <code>$default_args</code>. The <code>prepare_callback</code> overrides <a href=\"https://developer.wordpress.org/reference/classes/wp_rest_meta_fields/prepare_value/\" rel=\"nofollow noreferrer\"><code>prepare_value</code></a>, the method in <code>WP_REST_Meta_Fields</code> that converted your custom meta value from an array to a string. With our callback, that array will instead be encoded as JSON.</p>\n\n<p>On the JavaScript side, here are some key declarations.</p>\n\n<pre><code>// Get the custom meta\nlet customMeta = wp.data.select('core/editor').getEditedPostAttribute('meta');\n\n// Parse the meta so you can do some JS with it\nlet parsed = JSON.parse(customMeta._custom_key);\n\n// Do some JS with the parsed meta...\n\n// Stringify the parsed meta before dispatching it\nlet stringified = JSON.stringify(parsed);\n\n/*\n * Dispatch (update) the meta (and don't forget to\n * save/publish/update the post to ensure the meta goes in the database)\n */ \nwp.data.dispatch('core/editor').editPost({meta: {_custom_key: stringified}}); \n</code></pre>\n\n<p>Back in PHP land, getting and updating your custom meta will now work differently. When you call <code>get_post_meta</code>, you're used to getting an array, and you'll probably still want one sometimes. But if you last updated your custom meta via the WP REST API, you're getting a JSON string. In that case, you'll have to use <a href=\"https://developer.wordpress.org/reference/functions/json_decode/\" rel=\"nofollow noreferrer\"><code>json_decode</code></a>. One approach would be to wrap calls to <code>get_post_meta</code> like so:</p>\n\n<pre><code>function wpse_89033_get_custom_meta( $post_id, $meta_key ) {\n\n $post_meta = get_post_meta( $post_id, $meta_key, true );\n\n // If $post_meta is a string that's not empty\n if ( $post_meta && is_string( $post_meta ) ) {\n\n /*\n * Use the decoded JSON string or else the original string \n * if decoding fails, e.g., if the string isn't JSON\n */ \n $post_meta = json_decode( $post_meta, true ) ?: $post_meta;\n\n }\n\n return $post_meta;\n\n}\n</code></pre>\n\n<p>If you make changes to your custom meta as an array, don't worry about re-encoding before calling <code>update_post_meta</code>. The <code>prepare_callback</code> will handle re-encoding.</p>\n\n<p>About updating in PHP, calling <code>update_post_meta</code> during <code>save_post</code>, as shown in the <a href=\"https://developer.wordpress.org/plugins/metadata/custom-meta-boxes/#saving-values\" rel=\"nofollow noreferrer\">official plugin handbook</a>, appears to override updates made via the WP REST API. So one more thing to consider is conditioning any <code>save_post</code> update to your custom meta on whether the post is being edited in Gutenberg. If it is, leave the update to the REST API.</p>\n"
},
{
"answer_id": 350233,
"author": "shazahm1",
"author_id": 59053,
"author_profile": "https://wordpress.stackexchange.com/users/59053",
"pm_score": 0,
"selected": false,
"text": "<p>In WordPress 5.3 you can now register meta with the <code>array</code> and <code>object</code> meta type. Here is the post from Make WordPress Core which gives all the details with examples:</p>\n\n<ul>\n<li><a href=\"https://make.wordpress.org/core/2019/10/03/wp-5-3-supports-object-and-array-meta-types-in-the-rest-api/\" rel=\"nofollow noreferrer\">https://make.wordpress.org/core/2019/10/03/wp-5-3-supports-object-and-array-meta-types-in-the-rest-api/</a></li>\n</ul>\n"
}
] | 2019/03/06 | [
"https://wordpress.stackexchange.com/questions/330852",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/162620/"
] | I have a custom meta box for saving values from two input fields into a single post meta field.
The data is saved serialized in the DB:
```
get_post_meta( $post->ID, '_custom_key', true )
```
will return:
```
a:2:{s:5:"email";s:10:"[email protected]";s:6:"number";i:15;}
```
Now, with Gutenberg, I want to move that whole custom meta box into a separate sidebar plugin. So in order to do this, first, I had to add the `__back_compat_meta_box` argument when adding the meta box, so it won't appear in `Sidebar -> Settings -> Document` anymore:
```
add_meta_box(
'options',
'Options',
[ $this, 'renderOptionsBox' ],
[ 'post', 'page', 'attachement' ], // the meta field is registered for multiple post types
'side',
'high',
[ '__back_compat_meta_box' => true ]
);
```
For the meta field (`_custom_key`) to work with the block editor, it has to be registered using the `register_meta` function:
```
register_meta( string $object_type, string $meta_key, array $args, string|array $deprecated = null )
```
My questions are:
1. [updated] How can I register the custom meta field for **all** of the post types in this list `[ 'post', 'page', 'attachement' ]`?
2. How can I still follow the same serialized way of saving the data in a *single* field if the types ($args->type) supported when registering a meta are only 'string', 'boolean', 'integer', and 'number'?
Right now if I just register the `_custom_key` meta using:
```
register_meta( 'post', '_custom_key', [
'show_in_rest' => true,
'single' => true,
'type' => 'string',
'auth_callback' => function () {
return current_user_can( 'edit_posts' );
}
]);
```
I will get a `Notice: Array to string conversion in .../wp-includes/rest-api/fields/class-wp-rest-meta-fields.php` because already saved data from the DB is serialized.
and typing in the console: `wp.data.select( 'core/editor' ).getCurrentPost().meta;` will return a string: `{_custom_key: "Array"}`. | Here's an answer to question 1 that uses [`register_post_meta`](https://developer.wordpress.org/reference/functions/register_post_meta/). It's also the start of an answer to question 2 by use of the `prepare_callback` option in `show_in_rest` .
```
add_action( 'init', 'wpse_89033_register_custom_meta' );
function wpse_89033_register_custom_meta() {
$post_types = [
'post',
'page',
'attachment',
];
foreach ( $post_types as $post_type ) {
register_post_meta(
$post_type,
'_custom_key',
array(
'type' => 'string',
'single' => true,
'auth_callback' => function() {
return current_user_can( 'edit_posts' );
},
'show_in_rest' => [
'prepare_callback' => function( $value ) {
return wp_json_encode( $value );
}
],
)
);
}
}
```
The documentation for `show_in_rest` (see [`register_meta`](https://developer.wordpress.org/reference/functions/register_meta/)) says it's a boolean parameter. But it will accept an options array. To see the options, look at the body of [`get_registered_fields`](https://developer.wordpress.org/reference/classes/wp_rest_meta_fields/get_registered_fields/), in particular the value of `$default_args`. The `prepare_callback` overrides [`prepare_value`](https://developer.wordpress.org/reference/classes/wp_rest_meta_fields/prepare_value/), the method in `WP_REST_Meta_Fields` that converted your custom meta value from an array to a string. With our callback, that array will instead be encoded as JSON.
On the JavaScript side, here are some key declarations.
```
// Get the custom meta
let customMeta = wp.data.select('core/editor').getEditedPostAttribute('meta');
// Parse the meta so you can do some JS with it
let parsed = JSON.parse(customMeta._custom_key);
// Do some JS with the parsed meta...
// Stringify the parsed meta before dispatching it
let stringified = JSON.stringify(parsed);
/*
* Dispatch (update) the meta (and don't forget to
* save/publish/update the post to ensure the meta goes in the database)
*/
wp.data.dispatch('core/editor').editPost({meta: {_custom_key: stringified}});
```
Back in PHP land, getting and updating your custom meta will now work differently. When you call `get_post_meta`, you're used to getting an array, and you'll probably still want one sometimes. But if you last updated your custom meta via the WP REST API, you're getting a JSON string. In that case, you'll have to use [`json_decode`](https://developer.wordpress.org/reference/functions/json_decode/). One approach would be to wrap calls to `get_post_meta` like so:
```
function wpse_89033_get_custom_meta( $post_id, $meta_key ) {
$post_meta = get_post_meta( $post_id, $meta_key, true );
// If $post_meta is a string that's not empty
if ( $post_meta && is_string( $post_meta ) ) {
/*
* Use the decoded JSON string or else the original string
* if decoding fails, e.g., if the string isn't JSON
*/
$post_meta = json_decode( $post_meta, true ) ?: $post_meta;
}
return $post_meta;
}
```
If you make changes to your custom meta as an array, don't worry about re-encoding before calling `update_post_meta`. The `prepare_callback` will handle re-encoding.
About updating in PHP, calling `update_post_meta` during `save_post`, as shown in the [official plugin handbook](https://developer.wordpress.org/plugins/metadata/custom-meta-boxes/#saving-values), appears to override updates made via the WP REST API. So one more thing to consider is conditioning any `save_post` update to your custom meta on whether the post is being edited in Gutenberg. If it is, leave the update to the REST API. |
330,855 | <p>For example, I want to add a custom user metadata field for projects he is assigned to. But this field must have a foreign key constraint to another table to make sure that the project it is referencing, is valid.</p>
<p>Is there a way to handle this scenario with pure user metadata instead of creating an extra table to link the users with the projects?</p>
| [
{
"answer_id": 341735,
"author": "rsborn",
"author_id": 170908,
"author_profile": "https://wordpress.stackexchange.com/users/170908",
"pm_score": 1,
"selected": false,
"text": "<p>Here's an answer to question 1 that uses <a href=\"https://developer.wordpress.org/reference/functions/register_post_meta/\" rel=\"nofollow noreferrer\"><code>register_post_meta</code></a>. It's also the start of an answer to question 2 by use of the <code>prepare_callback</code> option in <code>show_in_rest</code> .</p>\n\n<pre><code>add_action( 'init', 'wpse_89033_register_custom_meta' );\nfunction wpse_89033_register_custom_meta() {\n\n $post_types = [ \n 'post',\n 'page',\n 'attachment',\n ];\n\n foreach ( $post_types as $post_type ) {\n\n register_post_meta( \n $post_type,\n '_custom_key',\n array(\n 'type' => 'string',\n 'single' => true,\n 'auth_callback' => function() { \n return current_user_can( 'edit_posts' );\n },\n 'show_in_rest' => [\n 'prepare_callback' => function( $value ) {\n return wp_json_encode( $value );\n }\n ],\n ) \n );\n\n }\n\n}\n</code></pre>\n\n<p>The documentation for <code>show_in_rest</code> (see <a href=\"https://developer.wordpress.org/reference/functions/register_meta/\" rel=\"nofollow noreferrer\"><code>register_meta</code></a>) says it's a boolean parameter. But it will accept an options array. To see the options, look at the body of <a href=\"https://developer.wordpress.org/reference/classes/wp_rest_meta_fields/get_registered_fields/\" rel=\"nofollow noreferrer\"><code>get_registered_fields</code></a>, in particular the value of <code>$default_args</code>. The <code>prepare_callback</code> overrides <a href=\"https://developer.wordpress.org/reference/classes/wp_rest_meta_fields/prepare_value/\" rel=\"nofollow noreferrer\"><code>prepare_value</code></a>, the method in <code>WP_REST_Meta_Fields</code> that converted your custom meta value from an array to a string. With our callback, that array will instead be encoded as JSON.</p>\n\n<p>On the JavaScript side, here are some key declarations.</p>\n\n<pre><code>// Get the custom meta\nlet customMeta = wp.data.select('core/editor').getEditedPostAttribute('meta');\n\n// Parse the meta so you can do some JS with it\nlet parsed = JSON.parse(customMeta._custom_key);\n\n// Do some JS with the parsed meta...\n\n// Stringify the parsed meta before dispatching it\nlet stringified = JSON.stringify(parsed);\n\n/*\n * Dispatch (update) the meta (and don't forget to\n * save/publish/update the post to ensure the meta goes in the database)\n */ \nwp.data.dispatch('core/editor').editPost({meta: {_custom_key: stringified}}); \n</code></pre>\n\n<p>Back in PHP land, getting and updating your custom meta will now work differently. When you call <code>get_post_meta</code>, you're used to getting an array, and you'll probably still want one sometimes. But if you last updated your custom meta via the WP REST API, you're getting a JSON string. In that case, you'll have to use <a href=\"https://developer.wordpress.org/reference/functions/json_decode/\" rel=\"nofollow noreferrer\"><code>json_decode</code></a>. One approach would be to wrap calls to <code>get_post_meta</code> like so:</p>\n\n<pre><code>function wpse_89033_get_custom_meta( $post_id, $meta_key ) {\n\n $post_meta = get_post_meta( $post_id, $meta_key, true );\n\n // If $post_meta is a string that's not empty\n if ( $post_meta && is_string( $post_meta ) ) {\n\n /*\n * Use the decoded JSON string or else the original string \n * if decoding fails, e.g., if the string isn't JSON\n */ \n $post_meta = json_decode( $post_meta, true ) ?: $post_meta;\n\n }\n\n return $post_meta;\n\n}\n</code></pre>\n\n<p>If you make changes to your custom meta as an array, don't worry about re-encoding before calling <code>update_post_meta</code>. The <code>prepare_callback</code> will handle re-encoding.</p>\n\n<p>About updating in PHP, calling <code>update_post_meta</code> during <code>save_post</code>, as shown in the <a href=\"https://developer.wordpress.org/plugins/metadata/custom-meta-boxes/#saving-values\" rel=\"nofollow noreferrer\">official plugin handbook</a>, appears to override updates made via the WP REST API. So one more thing to consider is conditioning any <code>save_post</code> update to your custom meta on whether the post is being edited in Gutenberg. If it is, leave the update to the REST API.</p>\n"
},
{
"answer_id": 350233,
"author": "shazahm1",
"author_id": 59053,
"author_profile": "https://wordpress.stackexchange.com/users/59053",
"pm_score": 0,
"selected": false,
"text": "<p>In WordPress 5.3 you can now register meta with the <code>array</code> and <code>object</code> meta type. Here is the post from Make WordPress Core which gives all the details with examples:</p>\n\n<ul>\n<li><a href=\"https://make.wordpress.org/core/2019/10/03/wp-5-3-supports-object-and-array-meta-types-in-the-rest-api/\" rel=\"nofollow noreferrer\">https://make.wordpress.org/core/2019/10/03/wp-5-3-supports-object-and-array-meta-types-in-the-rest-api/</a></li>\n</ul>\n"
}
] | 2019/03/06 | [
"https://wordpress.stackexchange.com/questions/330855",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/158512/"
] | For example, I want to add a custom user metadata field for projects he is assigned to. But this field must have a foreign key constraint to another table to make sure that the project it is referencing, is valid.
Is there a way to handle this scenario with pure user metadata instead of creating an extra table to link the users with the projects? | Here's an answer to question 1 that uses [`register_post_meta`](https://developer.wordpress.org/reference/functions/register_post_meta/). It's also the start of an answer to question 2 by use of the `prepare_callback` option in `show_in_rest` .
```
add_action( 'init', 'wpse_89033_register_custom_meta' );
function wpse_89033_register_custom_meta() {
$post_types = [
'post',
'page',
'attachment',
];
foreach ( $post_types as $post_type ) {
register_post_meta(
$post_type,
'_custom_key',
array(
'type' => 'string',
'single' => true,
'auth_callback' => function() {
return current_user_can( 'edit_posts' );
},
'show_in_rest' => [
'prepare_callback' => function( $value ) {
return wp_json_encode( $value );
}
],
)
);
}
}
```
The documentation for `show_in_rest` (see [`register_meta`](https://developer.wordpress.org/reference/functions/register_meta/)) says it's a boolean parameter. But it will accept an options array. To see the options, look at the body of [`get_registered_fields`](https://developer.wordpress.org/reference/classes/wp_rest_meta_fields/get_registered_fields/), in particular the value of `$default_args`. The `prepare_callback` overrides [`prepare_value`](https://developer.wordpress.org/reference/classes/wp_rest_meta_fields/prepare_value/), the method in `WP_REST_Meta_Fields` that converted your custom meta value from an array to a string. With our callback, that array will instead be encoded as JSON.
On the JavaScript side, here are some key declarations.
```
// Get the custom meta
let customMeta = wp.data.select('core/editor').getEditedPostAttribute('meta');
// Parse the meta so you can do some JS with it
let parsed = JSON.parse(customMeta._custom_key);
// Do some JS with the parsed meta...
// Stringify the parsed meta before dispatching it
let stringified = JSON.stringify(parsed);
/*
* Dispatch (update) the meta (and don't forget to
* save/publish/update the post to ensure the meta goes in the database)
*/
wp.data.dispatch('core/editor').editPost({meta: {_custom_key: stringified}});
```
Back in PHP land, getting and updating your custom meta will now work differently. When you call `get_post_meta`, you're used to getting an array, and you'll probably still want one sometimes. But if you last updated your custom meta via the WP REST API, you're getting a JSON string. In that case, you'll have to use [`json_decode`](https://developer.wordpress.org/reference/functions/json_decode/). One approach would be to wrap calls to `get_post_meta` like so:
```
function wpse_89033_get_custom_meta( $post_id, $meta_key ) {
$post_meta = get_post_meta( $post_id, $meta_key, true );
// If $post_meta is a string that's not empty
if ( $post_meta && is_string( $post_meta ) ) {
/*
* Use the decoded JSON string or else the original string
* if decoding fails, e.g., if the string isn't JSON
*/
$post_meta = json_decode( $post_meta, true ) ?: $post_meta;
}
return $post_meta;
}
```
If you make changes to your custom meta as an array, don't worry about re-encoding before calling `update_post_meta`. The `prepare_callback` will handle re-encoding.
About updating in PHP, calling `update_post_meta` during `save_post`, as shown in the [official plugin handbook](https://developer.wordpress.org/plugins/metadata/custom-meta-boxes/#saving-values), appears to override updates made via the WP REST API. So one more thing to consider is conditioning any `save_post` update to your custom meta on whether the post is being edited in Gutenberg. If it is, leave the update to the REST API. |
330,885 | <p>I have created a custom taxonomy that I have associated to my CPT. both appear on my dashboard, the issue is that when I add content and I want to choose a term from the list of the custom taxonomy, there is no value (no list, no checkbox...) . I am using wordpress 5.1. Here is the code added to functions.php : </p>
<pre><code>function type_custom_taxonomy() {
$labels = array(
'name' => _x( 'Types', 'taxonomy general name' ),
'singular_name' => _x( 'Type', 'taxonomy singular name' ),
'menu_name' => __( 'Types' ),
);
register_taxonomy('types',array('action'), array(
'labels' => $labels,
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_rest' => true,
'show_tagcloud' => false,
));
}
add_action( 'init', 'type_custom_taxonomy', 0 );
</code></pre>
<p><a href="https://i.stack.imgur.com/mQ05S.png" rel="noreferrer"><img src="https://i.stack.imgur.com/mQ05S.png" alt="enter image description here"></a> </p>
<pre><code>//CPT
function action_post_type() {
register_post_type( 'action',
array(
'labels' => array(
'name' => __( 'Actions' ),
'singular_name' => __( 'Action' )
),
'public' => true,
'has_archive' => true,
'show_in_rest' => true,
'supports' => array('title', 'editor','thumbnail'),
'taxonomies' => array('types')
)
);
}
add_action( 'init', 'action_post_type' );
</code></pre>
| [
{
"answer_id": 330892,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 0,
"selected": false,
"text": "<p>My guess would be that it's caused by priorities...</p>\n\n<p>Both of your actions are using the same priority. So if <code>type_custom_taxonomy</code> function is called as first one, then the <code>action</code> post type doesn't exist at that moment.</p>\n\n<p>I would try something like this:</p>\n\n<pre><code>function action_post_type() {\n register_post_type( 'action',\n array(\n 'labels' => array(\n 'name' => __( 'Actions' ),\n 'singular_name' => __( 'Action' )\n ),\n 'public' => true,\n 'has_archive' => true,\n 'show_in_rest' => true,\n 'supports' => array('title', 'editor','thumbnail'),\n )\n );\n\n $labels = array(\n 'name' => _x( 'Types', 'taxonomy general name' ),\n 'singular_name' => _x( 'Type', 'taxonomy singular name' ),\n 'menu_name' => __( 'Types' ),\n ); \n\n register_taxonomy('types',array('action'), array(\n 'labels' => $labels,\n 'hierarchical' => true,\n 'public' => true,\n 'show_ui' => true,\n 'show_admin_column' => true,\n 'show_in_rest' => true,\n 'show_tagcloud' => false,\n ));\n}\nadd_action( 'init', 'action_post_type' );\n</code></pre>\n\n<p>This way you can be sure that the CPT is registered before the taxonomy and you can assign that taxonomy to that CPT.</p>\n"
},
{
"answer_id": 330893,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Have you added some term to taxonomy \"Types\"?</strong><br>\nI think there is nothing wrong with code. Add a \"Type\" by clicking the link shown in screenshot '<strong>ajouter uni nouvelle categorie</strong>' . After you add some \"Types\" you will be able to select.</p>\n"
},
{
"answer_id": 331372,
"author": "Mehmood Ahmad",
"author_id": 149796,
"author_profile": "https://wordpress.stackexchange.com/users/149796",
"pm_score": 3,
"selected": true,
"text": "<p>Changing the slug of taxonomy works for me. Don't know the reason behind it but it works.</p>\n"
},
{
"answer_id": 334361,
"author": "Ali Gamaan",
"author_id": 165065,
"author_profile": "https://wordpress.stackexchange.com/users/165065",
"pm_score": 5,
"selected": false,
"text": "<p>I face the same as your problem and solved as the following </p>\n\n<p>you must add <code>'show_in_rest' => true,</code> for both post_type and taxonomies int the last line of array such as </p>\n\n<pre><code>register_post_type(\n'portfolio',\n array(\n 'labels' => $labels,\n 'exclude_from_search' => false,\n'has_archive' => true,\n'public' => true,\n'publicly_queryable' => false,\n'rewrite' => false,\n'can_export' => true,\n'show_in_nav_menus' => true,\n'supports' => array('title', 'editor', 'thumbnail', 'comments', 'page-attributes','excerpt'),\n'show_in_rest' =>true,\n )\n);\n</code></pre>\n\n<p>THE Taxonomy </p>\n\n<pre><code>register_taxonomy(\n'portfoliocat',\n'portfolio',\n array(\n 'hierarchical' => true,\n 'show_in_nav_menus' => true,\n'labels' =>array(),\n 'query_var' => true,\n 'rewrite' => array('slug' => 'portfoliocat'),\n 'show_in_rest' => true,\n )\n );\n</code></pre>\n"
},
{
"answer_id": 350119,
"author": "Alchem",
"author_id": 176519,
"author_profile": "https://wordpress.stackexchange.com/users/176519",
"pm_score": 0,
"selected": false,
"text": "<p>I can reproduce the same issue.</p>\n\n<p>He sees the Tab, but no entries. So the <code>show_in_rest</code> is not the solution and was already setup properly.</p>\n\n<p>The issue is and empty Rest-API Response. This is no happening on a clean install.</p>\n\n<p>Go (on a local instance) through your plugins, deactivate one by one.\nLook at <code>http://domain.test/wp-json/wp/v2/taxonomyname</code> in a separate window to see if it affects your output. </p>\n\n<p>In my case it was the \"User Access Manager\" Plugin with the default setting \"Taxonomies settings\"->Hide empty Taxonomies option turned to yes!</p>\n\n<p>In this case Select your Taxonomy under \"Object type\" and put the option to No.</p>\n"
},
{
"answer_id": 356763,
"author": "Pekka",
"author_id": 181310,
"author_profile": "https://wordpress.stackexchange.com/users/181310",
"pm_score": 2,
"selected": false,
"text": "<p>I can reproduce this as well. Adding <code>show_in_rest</code> in <code>register_taxonomy</code> function, as suggested by many, would normally be proper answer, but not full answer in your case. This is because rest endpoint <code>types</code> is already in use by Wordpress itself. <code>https://example.com/wp-json/wp/v2/types</code> will return registered post types and therefore Gutenberg does not understand it. See <a href=\"https://developer.wordpress.org/rest-api/reference/post-types/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/rest-api/reference/post-types/</a></p>\n\n<p>Thus, changing slug is probably the best way to go. If your site is live, then you might want to consider some rewrite rules so SEO won't take hit. </p>\n\n<p>Still, even if you change the slug, you need to add <code>show_in_rest</code> as well when using Gutenberg.</p>\n"
}
] | 2019/03/06 | [
"https://wordpress.stackexchange.com/questions/330885",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/162634/"
] | I have created a custom taxonomy that I have associated to my CPT. both appear on my dashboard, the issue is that when I add content and I want to choose a term from the list of the custom taxonomy, there is no value (no list, no checkbox...) . I am using wordpress 5.1. Here is the code added to functions.php :
```
function type_custom_taxonomy() {
$labels = array(
'name' => _x( 'Types', 'taxonomy general name' ),
'singular_name' => _x( 'Type', 'taxonomy singular name' ),
'menu_name' => __( 'Types' ),
);
register_taxonomy('types',array('action'), array(
'labels' => $labels,
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_rest' => true,
'show_tagcloud' => false,
));
}
add_action( 'init', 'type_custom_taxonomy', 0 );
```
[](https://i.stack.imgur.com/mQ05S.png)
```
//CPT
function action_post_type() {
register_post_type( 'action',
array(
'labels' => array(
'name' => __( 'Actions' ),
'singular_name' => __( 'Action' )
),
'public' => true,
'has_archive' => true,
'show_in_rest' => true,
'supports' => array('title', 'editor','thumbnail'),
'taxonomies' => array('types')
)
);
}
add_action( 'init', 'action_post_type' );
``` | Changing the slug of taxonomy works for me. Don't know the reason behind it but it works. |
330,886 | <h2>Cant access admin-ajax from https. In my js i wrote</h2>
<pre><code>$.ajax({
url: 'https://'+window.location.host+'/admin/admin-ajax.php',
type:'post',
data:'action=bid_now_live_me&_pid='+ mypid ,
success: function (data) {
</code></pre>
<h2>So I changed every url to https but still no luck. In chrome network I get</h2>
<p><a href="https://i.stack.imgur.com/yYt0m.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yYt0m.png" alt="enter image description here"></a> </p>
<h2>In console just lot's of errors</h2>
<p><a href="https://i.stack.imgur.com/Sltri.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Sltri.png" alt="enter image description here"></a></p>
<p>Tried to force ssl by modifing my htaccess, wp-config and by using force ssl plugin. And of course I tried to disable all plugins.</p>
| [
{
"answer_id": 330889,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 0,
"selected": false,
"text": "<p>for a default Wordpress installation, </p>\n\n<pre><code>url: 'https://'+window.location.host+'/admin/admin-ajax.php',\n</code></pre>\n\n<p>should be</p>\n\n<pre><code> url: 'https://'+window.location.host+'/wp-admin/admin-ajax.php',\n</code></pre>\n\n<p>i.e <code>/admin/</code> should be <code>/wp-admin/</code>.<br>\nI hope this helps.</p>\n"
},
{
"answer_id": 330890,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>You shouldn't do something like this in your JS code:</p>\n\n<pre><code>url: 'https://'+window.location.host+'/admin/admin-ajax.php',\n</code></pre>\n\n<p>You should use <a href=\"https://codex.wordpress.org/Function_Reference/wp_localize_script\" rel=\"nofollow noreferrer\"><code>wp_localize_script</code></a> and pass proper URL in there.</p>\n\n<p>Let's say your AJAX call is located in file <code>my-js-file.js</code>. Somewhere in your theme/plugin you have something like this </p>\n\n<pre><code>wp_enqueue_script( '<SOME_HANDLE>', ... . 'my-js-file.js' , ...);\n</code></pre>\n\n<p>You should add this after it:</p>\n\n<pre><code>wp_localize_script( '<SOME_HANDLE>', 'MyScriptData', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );\n</code></pre>\n\n<p>And in your JS file it should be </p>\n\n<pre><code>$.ajax({\n url: MyScriptData.ajax_url,\n type:'post',\n</code></pre>\n"
}
] | 2019/03/06 | [
"https://wordpress.stackexchange.com/questions/330886",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/162636/"
] | Cant access admin-ajax from https. In my js i wrote
---------------------------------------------------
```
$.ajax({
url: 'https://'+window.location.host+'/admin/admin-ajax.php',
type:'post',
data:'action=bid_now_live_me&_pid='+ mypid ,
success: function (data) {
```
So I changed every url to https but still no luck. In chrome network I get
--------------------------------------------------------------------------
[](https://i.stack.imgur.com/yYt0m.png)
In console just lot's of errors
-------------------------------
[](https://i.stack.imgur.com/Sltri.png)
Tried to force ssl by modifing my htaccess, wp-config and by using force ssl plugin. And of course I tried to disable all plugins. | You shouldn't do something like this in your JS code:
```
url: 'https://'+window.location.host+'/admin/admin-ajax.php',
```
You should use [`wp_localize_script`](https://codex.wordpress.org/Function_Reference/wp_localize_script) and pass proper URL in there.
Let's say your AJAX call is located in file `my-js-file.js`. Somewhere in your theme/plugin you have something like this
```
wp_enqueue_script( '<SOME_HANDLE>', ... . 'my-js-file.js' , ...);
```
You should add this after it:
```
wp_localize_script( '<SOME_HANDLE>', 'MyScriptData', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
```
And in your JS file it should be
```
$.ajax({
url: MyScriptData.ajax_url,
type:'post',
``` |
330,920 | <p>Orderby of get_terms() does not accept array type. How do I make this code works?</p>
<pre><code>$allcities = get_terms( array(
'taxonomy' => 'city',
'hide_empty' => false,
'orderby' => array( 'meta_value_num' => 'ASC', 'count' => 'ASC' ),
'meta_query' => array(
array(
'key' => 'country',
'type' => 'NUMERIC',
)
),
) );
</code></pre>
| [
{
"answer_id": 330889,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 0,
"selected": false,
"text": "<p>for a default Wordpress installation, </p>\n\n<pre><code>url: 'https://'+window.location.host+'/admin/admin-ajax.php',\n</code></pre>\n\n<p>should be</p>\n\n<pre><code> url: 'https://'+window.location.host+'/wp-admin/admin-ajax.php',\n</code></pre>\n\n<p>i.e <code>/admin/</code> should be <code>/wp-admin/</code>.<br>\nI hope this helps.</p>\n"
},
{
"answer_id": 330890,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>You shouldn't do something like this in your JS code:</p>\n\n<pre><code>url: 'https://'+window.location.host+'/admin/admin-ajax.php',\n</code></pre>\n\n<p>You should use <a href=\"https://codex.wordpress.org/Function_Reference/wp_localize_script\" rel=\"nofollow noreferrer\"><code>wp_localize_script</code></a> and pass proper URL in there.</p>\n\n<p>Let's say your AJAX call is located in file <code>my-js-file.js</code>. Somewhere in your theme/plugin you have something like this </p>\n\n<pre><code>wp_enqueue_script( '<SOME_HANDLE>', ... . 'my-js-file.js' , ...);\n</code></pre>\n\n<p>You should add this after it:</p>\n\n<pre><code>wp_localize_script( '<SOME_HANDLE>', 'MyScriptData', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );\n</code></pre>\n\n<p>And in your JS file it should be </p>\n\n<pre><code>$.ajax({\n url: MyScriptData.ajax_url,\n type:'post',\n</code></pre>\n"
}
] | 2019/03/07 | [
"https://wordpress.stackexchange.com/questions/330920",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/136218/"
] | Orderby of get\_terms() does not accept array type. How do I make this code works?
```
$allcities = get_terms( array(
'taxonomy' => 'city',
'hide_empty' => false,
'orderby' => array( 'meta_value_num' => 'ASC', 'count' => 'ASC' ),
'meta_query' => array(
array(
'key' => 'country',
'type' => 'NUMERIC',
)
),
) );
``` | You shouldn't do something like this in your JS code:
```
url: 'https://'+window.location.host+'/admin/admin-ajax.php',
```
You should use [`wp_localize_script`](https://codex.wordpress.org/Function_Reference/wp_localize_script) and pass proper URL in there.
Let's say your AJAX call is located in file `my-js-file.js`. Somewhere in your theme/plugin you have something like this
```
wp_enqueue_script( '<SOME_HANDLE>', ... . 'my-js-file.js' , ...);
```
You should add this after it:
```
wp_localize_script( '<SOME_HANDLE>', 'MyScriptData', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
```
And in your JS file it should be
```
$.ajax({
url: MyScriptData.ajax_url,
type:'post',
``` |
330,943 | <p>In my WP Plugin I have made an error handler. It works so far but I'd like to <strong>not echo in admin_notices</strong>, but have that nice little message box of wordpress if sth is going wrong: </p>
<p><a href="https://i.stack.imgur.com/lZcK8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lZcK8.png" alt="red box"></a></p>
<p>How can I do so? </p>
| [
{
"answer_id": 330889,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 0,
"selected": false,
"text": "<p>for a default Wordpress installation, </p>\n\n<pre><code>url: 'https://'+window.location.host+'/admin/admin-ajax.php',\n</code></pre>\n\n<p>should be</p>\n\n<pre><code> url: 'https://'+window.location.host+'/wp-admin/admin-ajax.php',\n</code></pre>\n\n<p>i.e <code>/admin/</code> should be <code>/wp-admin/</code>.<br>\nI hope this helps.</p>\n"
},
{
"answer_id": 330890,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>You shouldn't do something like this in your JS code:</p>\n\n<pre><code>url: 'https://'+window.location.host+'/admin/admin-ajax.php',\n</code></pre>\n\n<p>You should use <a href=\"https://codex.wordpress.org/Function_Reference/wp_localize_script\" rel=\"nofollow noreferrer\"><code>wp_localize_script</code></a> and pass proper URL in there.</p>\n\n<p>Let's say your AJAX call is located in file <code>my-js-file.js</code>. Somewhere in your theme/plugin you have something like this </p>\n\n<pre><code>wp_enqueue_script( '<SOME_HANDLE>', ... . 'my-js-file.js' , ...);\n</code></pre>\n\n<p>You should add this after it:</p>\n\n<pre><code>wp_localize_script( '<SOME_HANDLE>', 'MyScriptData', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );\n</code></pre>\n\n<p>And in your JS file it should be </p>\n\n<pre><code>$.ajax({\n url: MyScriptData.ajax_url,\n type:'post',\n</code></pre>\n"
}
] | 2019/03/07 | [
"https://wordpress.stackexchange.com/questions/330943",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/162679/"
] | In my WP Plugin I have made an error handler. It works so far but I'd like to **not echo in admin\_notices**, but have that nice little message box of wordpress if sth is going wrong:
[](https://i.stack.imgur.com/lZcK8.png)
How can I do so? | You shouldn't do something like this in your JS code:
```
url: 'https://'+window.location.host+'/admin/admin-ajax.php',
```
You should use [`wp_localize_script`](https://codex.wordpress.org/Function_Reference/wp_localize_script) and pass proper URL in there.
Let's say your AJAX call is located in file `my-js-file.js`. Somewhere in your theme/plugin you have something like this
```
wp_enqueue_script( '<SOME_HANDLE>', ... . 'my-js-file.js' , ...);
```
You should add this after it:
```
wp_localize_script( '<SOME_HANDLE>', 'MyScriptData', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
```
And in your JS file it should be
```
$.ajax({
url: MyScriptData.ajax_url,
type:'post',
``` |
330,947 | <p><strong>I would like to resize the 100px x 100px store thumbnail images.</strong></p>
<p>The sizes are supposed to be set under <strong>Appearance › Customize › WooCommerce › Product Images</strong></p>
<p><strong>These size settings are missing.</strong></p>
<p>After an exhaustive search, it is obvious that the sizes only appear there if they are not set in functions.php in the theme via (for example):</p>
<pre><code>add_theme_support( 'woocommerce', array(
'thumbnail_image_width' => 200,
'gallery_thumbnail_image_width' => 100,
'single_image_width' => 500,
) );
</code></pre>
<p>However, I am using theme <strong>Twenty Fifteen</strong>, <strong>WooCommerce 3.5.5</strong>, and <strong>Elementor</strong>.</p>
<p><strong>The above code is <em>not</em> in the theme.</strong></p>
<p>I have tried disabling all plugins except WooCommerce.</p>
<p>I have tried several different themes, none of which include the add_theme_support code.</p>
<p><strong>Why are the custom images sizes not available?</strong></p>
<p>I would like to avoid having to add code… I'm a programmer but I'm going to be building a bunch of WP/WC sites in the next few months and it would be nice to avoid having to modify the theme or the WP installation for every site.</p>
| [
{
"answer_id": 330949,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>WooCommerce itself registers support for the default themes. For Twenty Fifteen it registers the following:</p>\n\n<pre><code>add_theme_support( 'wc-product-gallery-zoom' );\nadd_theme_support( 'wc-product-gallery-lightbox' );\nadd_theme_support( 'wc-product-gallery-slider' );\nadd_theme_support( 'woocommerce', array(\n 'thumbnail_image_width' => 200,\n 'single_image_width' => 350,\n) );\n</code></pre>\n\n<p>This is why those settings are not in the Customiser.</p>\n\n<p>However, regardless of what theme support is registered, the <code>gallery_thumbnail_image_width</code> size is never editable in the Customiser.</p>\n\n<p>These default settings were chosen for a reason though, so if you need to change them then that suggests you're changing the theme in some way, in which case you should be working on a child theme, rather than modifying the original theme. In that case your child theme should register its own support for WooCommerce. Then you can either omit the values so that the settings appear in the Customiser, or set your own.</p>\n"
},
{
"answer_id": 330983,
"author": "Andy Swift",
"author_id": 162680,
"author_profile": "https://wordpress.stackexchange.com/users/162680",
"pm_score": 0,
"selected": false,
"text": "<p>I found the following plugin, which worked to resize the gallery thumbnails:</p>\n\n<pre><code>custom-image-sizes-for-woocommerce.zip\n</code></pre>\n\n<p>available at <a href=\"https://cld.wthms.co/O4lsZz\" rel=\"nofollow noreferrer\">https://cld.wthms.co/O4lsZz</a></p>\n\n<p>The plugin <strong>restores the ability to change image sizes</strong> under <strong>Appearance › Customize › WooCommerce › Product Images</strong></p>\n\n<p>It was necessary to use the <strong>Regenerate Thumbnails</strong> plugin after changing the image sizes.</p>\n"
}
] | 2019/03/07 | [
"https://wordpress.stackexchange.com/questions/330947",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/162680/"
] | **I would like to resize the 100px x 100px store thumbnail images.**
The sizes are supposed to be set under **Appearance › Customize › WooCommerce › Product Images**
**These size settings are missing.**
After an exhaustive search, it is obvious that the sizes only appear there if they are not set in functions.php in the theme via (for example):
```
add_theme_support( 'woocommerce', array(
'thumbnail_image_width' => 200,
'gallery_thumbnail_image_width' => 100,
'single_image_width' => 500,
) );
```
However, I am using theme **Twenty Fifteen**, **WooCommerce 3.5.5**, and **Elementor**.
**The above code is *not* in the theme.**
I have tried disabling all plugins except WooCommerce.
I have tried several different themes, none of which include the add\_theme\_support code.
**Why are the custom images sizes not available?**
I would like to avoid having to add code… I'm a programmer but I'm going to be building a bunch of WP/WC sites in the next few months and it would be nice to avoid having to modify the theme or the WP installation for every site. | WooCommerce itself registers support for the default themes. For Twenty Fifteen it registers the following:
```
add_theme_support( 'wc-product-gallery-zoom' );
add_theme_support( 'wc-product-gallery-lightbox' );
add_theme_support( 'wc-product-gallery-slider' );
add_theme_support( 'woocommerce', array(
'thumbnail_image_width' => 200,
'single_image_width' => 350,
) );
```
This is why those settings are not in the Customiser.
However, regardless of what theme support is registered, the `gallery_thumbnail_image_width` size is never editable in the Customiser.
These default settings were chosen for a reason though, so if you need to change them then that suggests you're changing the theme in some way, in which case you should be working on a child theme, rather than modifying the original theme. In that case your child theme should register its own support for WooCommerce. Then you can either omit the values so that the settings appear in the Customiser, or set your own. |
330,962 | <p>I'm trying to send an Email before a post "type:pelicula" is submited, but it does not enter to the function <strong>post_published_notification</strong>, here is the code:</p>
<pre><code><?php
/**
* Plugin Name: VRlife Alertas Publicaciones
* Description: Avisa por el correo configurado al publicar un nuevo video
* Version: 1.0.0
* Author: José Manuel Lascasas
**/
//1
class MySettingsPage
{
/**
* Holds the values to be used in the fields callbacks
*/
private $options;
/**
* Start up
*/
public function __construct()
{
//2
add_action( 'admin_menu', array( $this, 'add_plugin_page' ) );
//6
add_action( 'admin_init', array( $this, 'page_init' ) );
add_action( 'publish_pelicula', 'post_published_notification', 10, 2 );
}
/**
* Add options page
*/
//3
public function add_plugin_page()
{
// This page will be under "Settings"
add_options_page(
'Settings Admin',
'My Settings',
'manage_options',
'my-setting-admin',
//4
array( $this, 'create_admin_page' )
);
}
/**
* Options page callback
*/
//5
public function create_admin_page()
{
// Set class property
$this->options = get_option( 'my_option_name' );
?>
<div class="wrap">
<h1>My Settings</h1>
<form method="post" action="options.php">
<?php
// This prints out all hidden setting fields
settings_fields( 'my_option_group' );
do_settings_sections( 'my-setting-admin' );
submit_button();
?>
</form>
</div>
<?php
}
/**
* Register and add settings
*/
//7
public function page_init()
{
register_setting(
'my_option_group', // Option group
'my_option_name', // Option name
//8
array( $this, 'sanitize' ) // Sanitize
);
//10
add_settings_section(
'setting_section_id', // ID
'My Custom Settings', // Title
//11
array( $this, 'print_section_info' ), // Callback
'my-setting-admin' // Page
);
//13
add_settings_field(
'title',
'Mails',
//14
array( $this, 'title_callback' ),
'my-setting-admin',
'setting_section_id'
);
}
/**
* Sanitize each setting field as needed
*
* @param array $input Contains all settings fields as array keys
*/
//9
public function sanitize( $input )
{
$new_input = array();
if( isset( $input['title'] ) )
$new_input['title'] = sanitize_text_field( $input['title'] );
return $new_input;
}
/**
* Print the Section text
*/
//12
public function print_section_info()
{
print 'Enter your settings below:';
}
/**
* Get the settings option array and print one of its values
*/
//15
public function title_callback()
{
printf(
'<input type="text" id="title" name="my_option_name[title]" value="%s" />',
isset( $this->options['title'] ) ? esc_attr( $this->options['title']) : ''
);
$maill=$this->options['title'];
//wp_mail( $maill, "wdaawddwwa", "Easy", "" );
}
public function post_published_notification( $ID, $post ) {
$author = $post->post_author; /* Post author ID. */
$name = get_the_author_meta( 'display_name', $author );
$email = get_the_author_meta( 'user_email', $author );
$title = $post->post_title;
$permalink = get_permalink( $ID );
$edit = get_edit_post_link( $ID, '' );
$to[] = $this->options['title'];
$subject = sprintf( 'Published: %s', $title );
$message = sprintf ('Congratulations, %s! Your article “%s” has been published.' . "\n\n", $name, $title );
$message .= sprintf( 'View: %s', $permalink );
$headers[] = '';
var_dump("hola");
wp_mail( $to, "wdwadwad", "dwwdawddw", "" );
}
}
//16
$my_settings_page = new MySettingsPage();
</code></pre>
| [
{
"answer_id": 330965,
"author": "tmdesigned",
"author_id": 28273,
"author_profile": "https://wordpress.stackexchange.com/users/28273",
"pm_score": 0,
"selected": false,
"text": "<p>Since you are in a class, you need to specify that the function you want (\"post_published_notification\") is a part of that class.</p>\n\n<p>You do this by specifying the class before the function as part of an array. It would look like this:</p>\n\n<p><code>add_action( 'publish_pelicula', array( $this, 'post_published_notification' ), 10, 2 );</code></p>\n"
},
{
"answer_id": 330966,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>Well let's compare the hook to one that is working:</p>\n\n<pre><code>add_action( 'admin_init', array( $this, 'page_init' ) );\nadd_action( 'publish_pelicula', 'post_published_notification', 10, 2 );\n</code></pre>\n\n<p><code>page_init()</code> and <code>post_published_notification()</code> are both methods of the <code>MySettingsPage</code> class, but you've set the action callbacks for each of them differently.</p>\n\n<p>The second argument for <code>add_action()</code> is a <a href=\"http://php.net/manual/en/language.types.callable.php\" rel=\"nofollow noreferrer\"><em>callback</em></a>. It tells WordPress/PHP which function to run when the action is fired. For an action to call a class method, you need to pass an array:</p>\n\n<blockquote>\n <p>A method of an instantiated object is passed as an array containing an\n object at index 0 and the method name at index 1.</p>\n</blockquote>\n\n<p>Since you're running <code>add_action</code> inside a class, the object in question is <code>$this</code>, and the method name is <code>post_published_notification</code>. You've done this correctly for <code>page_init</code>, so you just need to do that same for <code>post_published_notification</code>:</p>\n\n<pre><code>add_action( 'publish_pelicula', array( $this, 'post_published_notification' ), 10, 2 );\n</code></pre>\n"
}
] | 2019/03/07 | [
"https://wordpress.stackexchange.com/questions/330962",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/162285/"
] | I'm trying to send an Email before a post "type:pelicula" is submited, but it does not enter to the function **post\_published\_notification**, here is the code:
```
<?php
/**
* Plugin Name: VRlife Alertas Publicaciones
* Description: Avisa por el correo configurado al publicar un nuevo video
* Version: 1.0.0
* Author: José Manuel Lascasas
**/
//1
class MySettingsPage
{
/**
* Holds the values to be used in the fields callbacks
*/
private $options;
/**
* Start up
*/
public function __construct()
{
//2
add_action( 'admin_menu', array( $this, 'add_plugin_page' ) );
//6
add_action( 'admin_init', array( $this, 'page_init' ) );
add_action( 'publish_pelicula', 'post_published_notification', 10, 2 );
}
/**
* Add options page
*/
//3
public function add_plugin_page()
{
// This page will be under "Settings"
add_options_page(
'Settings Admin',
'My Settings',
'manage_options',
'my-setting-admin',
//4
array( $this, 'create_admin_page' )
);
}
/**
* Options page callback
*/
//5
public function create_admin_page()
{
// Set class property
$this->options = get_option( 'my_option_name' );
?>
<div class="wrap">
<h1>My Settings</h1>
<form method="post" action="options.php">
<?php
// This prints out all hidden setting fields
settings_fields( 'my_option_group' );
do_settings_sections( 'my-setting-admin' );
submit_button();
?>
</form>
</div>
<?php
}
/**
* Register and add settings
*/
//7
public function page_init()
{
register_setting(
'my_option_group', // Option group
'my_option_name', // Option name
//8
array( $this, 'sanitize' ) // Sanitize
);
//10
add_settings_section(
'setting_section_id', // ID
'My Custom Settings', // Title
//11
array( $this, 'print_section_info' ), // Callback
'my-setting-admin' // Page
);
//13
add_settings_field(
'title',
'Mails',
//14
array( $this, 'title_callback' ),
'my-setting-admin',
'setting_section_id'
);
}
/**
* Sanitize each setting field as needed
*
* @param array $input Contains all settings fields as array keys
*/
//9
public function sanitize( $input )
{
$new_input = array();
if( isset( $input['title'] ) )
$new_input['title'] = sanitize_text_field( $input['title'] );
return $new_input;
}
/**
* Print the Section text
*/
//12
public function print_section_info()
{
print 'Enter your settings below:';
}
/**
* Get the settings option array and print one of its values
*/
//15
public function title_callback()
{
printf(
'<input type="text" id="title" name="my_option_name[title]" value="%s" />',
isset( $this->options['title'] ) ? esc_attr( $this->options['title']) : ''
);
$maill=$this->options['title'];
//wp_mail( $maill, "wdaawddwwa", "Easy", "" );
}
public function post_published_notification( $ID, $post ) {
$author = $post->post_author; /* Post author ID. */
$name = get_the_author_meta( 'display_name', $author );
$email = get_the_author_meta( 'user_email', $author );
$title = $post->post_title;
$permalink = get_permalink( $ID );
$edit = get_edit_post_link( $ID, '' );
$to[] = $this->options['title'];
$subject = sprintf( 'Published: %s', $title );
$message = sprintf ('Congratulations, %s! Your article “%s” has been published.' . "\n\n", $name, $title );
$message .= sprintf( 'View: %s', $permalink );
$headers[] = '';
var_dump("hola");
wp_mail( $to, "wdwadwad", "dwwdawddw", "" );
}
}
//16
$my_settings_page = new MySettingsPage();
``` | Well let's compare the hook to one that is working:
```
add_action( 'admin_init', array( $this, 'page_init' ) );
add_action( 'publish_pelicula', 'post_published_notification', 10, 2 );
```
`page_init()` and `post_published_notification()` are both methods of the `MySettingsPage` class, but you've set the action callbacks for each of them differently.
The second argument for `add_action()` is a [*callback*](http://php.net/manual/en/language.types.callable.php). It tells WordPress/PHP which function to run when the action is fired. For an action to call a class method, you need to pass an array:
>
> A method of an instantiated object is passed as an array containing an
> object at index 0 and the method name at index 1.
>
>
>
Since you're running `add_action` inside a class, the object in question is `$this`, and the method name is `post_published_notification`. You've done this correctly for `page_init`, so you just need to do that same for `post_published_notification`:
```
add_action( 'publish_pelicula', array( $this, 'post_published_notification' ), 10, 2 );
``` |
330,974 | <p>I migrated my site to a new server. Everything seems to be fine, but the browser is redirected to the frontpage when I save configurations in either the "W3 Total Cache" plugin or in "Duplicate post" plugin.
It does save the edits, but it´s annoing with the redirect.</p>
<p>For example when I press purge all caches from W3 Cache, it is redirected to</p>
<pre><code>www.mysite.com/?w3tc_note=flush_all
</code></pre>
<p>I can´t find a solution that solves it. I tried with:</p>
<pre><code>define('WP_HOME','http://example.com');
define('WP_SITEURL','http://example.com');
</code></pre>
<p>In my wp-config.php</p>
<p>And with these google results:
<a href="https://wordpress.stackexchange.com/questions/7993/redirecting-to-home-page-when-saving-any-edited-code">Redirecting to home-page when saving any edited code</a>
<a href="https://wordpress.org/support/topic/wordpress-5-0-beta3-redirects-to-wp-admin-edit-php-after-hitting-enter-key/" rel="nofollow noreferrer">https://wordpress.org/support/topic/wordpress-5-0-beta3-redirects-to-wp-admin-edit-php-after-hitting-enter-key/</a></p>
<p>I also looked at the wp_options in the DB. But seems allright.</p>
<p>I tried to change the wp permanent link options in the admin settings too.</p>
<p>The "Duplicate post" plugin was installed after the site migration.</p>
| [
{
"answer_id": 331050,
"author": "Debbie Kurth",
"author_id": 119560,
"author_profile": "https://wordpress.stackexchange.com/users/119560",
"pm_score": 0,
"selected": false,
"text": "<p>It is a bit hard to really know what is going on. But a best \"guess\" is that you have a plugin that is redirecting and/or conflicting with the theme. By process of elimination, I would deactivate all the plugins and see if the problem still exists. If it disappears, reactivate, one by one. Somewhere there is a conflict and doing a redirect.</p>\n\n<p>A secondary effort would be, after all the plugins have been disabled and assuming it still exists, then change themes.</p>\n\n<p>You have to narrow this down to the most basic element.</p>\n"
},
{
"answer_id": 333569,
"author": "Jonas Borneland",
"author_id": 155327,
"author_profile": "https://wordpress.stackexchange.com/users/155327",
"pm_score": 1,
"selected": true,
"text": "<p>Okay, I found a solution. To anyone in the future having this problem here's what i did:</p>\n\n<ul>\n<li>I used the plugin \"Duplicator\" and made a package of the site.</li>\n<li>Then i downloaded the installer and the archive.</li>\n<li>I then deleted everything in the database and on the ftp.</li>\n<li>Then I transfered the archive and installer file to the FTP and run\nthe installer.php</li>\n</ul>\n\n<p>Now everything works again :)</p>\n"
},
{
"answer_id": 367081,
"author": "GerryM",
"author_id": 188459,
"author_profile": "https://wordpress.stackexchange.com/users/188459",
"pm_score": 2,
"selected": false,
"text": "<p>It's because you have set the Referrer Policy header incorrectly set in the W3TC page cache.</p>\n\n<pre><code>Referrer Policy\nThis header restricts the values of the referer header in outbound links.\n**Directive: same-origin**\n</code></pre>\n\n<p>...will fix it. If your overall Directive is \"same-origin\" and you set the Referrer header to something different (such as \"origin\"), this error will occur. I changed mine to same-origin and the problem was immediately fixed.</p>\n"
}
] | 2019/03/07 | [
"https://wordpress.stackexchange.com/questions/330974",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/155327/"
] | I migrated my site to a new server. Everything seems to be fine, but the browser is redirected to the frontpage when I save configurations in either the "W3 Total Cache" plugin or in "Duplicate post" plugin.
It does save the edits, but it´s annoing with the redirect.
For example when I press purge all caches from W3 Cache, it is redirected to
```
www.mysite.com/?w3tc_note=flush_all
```
I can´t find a solution that solves it. I tried with:
```
define('WP_HOME','http://example.com');
define('WP_SITEURL','http://example.com');
```
In my wp-config.php
And with these google results:
[Redirecting to home-page when saving any edited code](https://wordpress.stackexchange.com/questions/7993/redirecting-to-home-page-when-saving-any-edited-code)
<https://wordpress.org/support/topic/wordpress-5-0-beta3-redirects-to-wp-admin-edit-php-after-hitting-enter-key/>
I also looked at the wp\_options in the DB. But seems allright.
I tried to change the wp permanent link options in the admin settings too.
The "Duplicate post" plugin was installed after the site migration. | Okay, I found a solution. To anyone in the future having this problem here's what i did:
* I used the plugin "Duplicator" and made a package of the site.
* Then i downloaded the installer and the archive.
* I then deleted everything in the database and on the ftp.
* Then I transfered the archive and installer file to the FTP and run
the installer.php
Now everything works again :) |
331,002 | <p>I am trying to utilize AJAX on my WordPress site for posts as a user scrolls. I followed <a href="https://rudrastyh.com/wordpress/load-more-posts-ajax.html" rel="nofollow noreferrer">this</a> tutorial but it has no effect on my WordPress website. </p>
<p>I have used a plugin that works, but I'd much rather learn how to do this without a plugin both to learn and also to avoid using unnecessary plugins. The below code does not work, instead all of my posts show up on the page despite posts per page being set to 5. </p>
<p>Help is appreciated!</p>
<p><strong>functions.php</strong></p>
<pre><code>function misha_my_load_more_scripts() {
global $wp_query;
wp_enqueue_script('jquery');
wp_register_script( 'my_loadmore', get_stylesheet_directory_uri() . '/js/myloadmore.js', array('jquery') );
wp_localize_script( 'my_loadmore', 'misha_loadmore_params', array(
'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php',
'posts' => json_encode( $wp_query->query_vars ),
'current_page' => get_query_var( 'paged' ) ? get_query_var('paged') : 1,
'max_page' => $wp_query->max_num_pages
) );
wp_enqueue_script( 'my_loadmore' );
}
add_action( 'wp_enqueue_scripts', 'misha_my_load_more_scripts' );
function misha_loadmore_ajax_handler(){
$args = array(
'cat' => -21,
'post_type' => 'post',
'posts_per_page' => 5,
'paged' => 1,
'tax_query' => array(
array(
'taxonomy' => 'topics',
'operator' => 'NOT EXISTS'
)
)
);
$args = json_decode( stripslashes( $_POST['query'] ), true );
$args['paged'] = $_POST['page'] + 1; //need next page to be loaded
$args['post_status'] = 'publish';
$the_query = new WP_Query ( $args );
if($the_query->have_posts()) :
while($the_query->have_posts()) :
$the_query->the_post();
get_template_part( 'template-parts/post/content', get_post_format() );
endwhile;
endif;
die;
}
add_action('wp_ajax_loadmore', 'misha_loadmore_ajax_handler'); // wp_ajax_{action}
add_action('wp_ajax_nopriv_loadmore', 'misha_loadmore_ajax_handler'); // wp_ajax_nopriv_{action}
</code></pre>
<p><strong>myloadmore.js</strong></p>
<pre><code>jQuery(function($){
var canBeLoaded = true,
bottomOffset = 2000; //I've played with this number to see if it was the offset calling posts too soon but it has no effect
$(window).scroll(function(){
var data = {
'action': 'loadmore',
'query': misha_loadmore_params.posts,
'page' : misha_loadmore_params.current_page
};
if( $(document).scrollTop() > ( $(document).height() - bottomOffset ) && canBeLoaded == true ){
$.ajax({
url : misha_loadmore_params.ajaxurl,
data:data,
type:'POST',
beforeSend: function( xhr ){
canBeLoaded = false;
},
success:function(data){
if( data ) {
$('#main').find('div:last-of-type').after( data );
canBeLoaded = true;
misha_loadmore_params.current_page++;
}
}
});
}
});
});
</code></pre>
<p><strong>content.php</strong></p>
<pre><code><div class="row">
<div class="col-sm-6">
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?>
<a href="<?php the_permalink(); ?>"><img src="<?php echo $image[0]; ?>" class="img-fluid"></a>
</div>
<div class="col-sm-6">
<?php
$categories = get_the_category();
if ( $categories ) :
$deepChild = get_deep_child_category( $categories );
?>
<p><?php echo $deepChild->name; ?></p>
<?php endif; ?>
<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
</div>
</div><!-- END ROW-->
</code></pre>
<p><strong>front-page.php</strong></p>
<pre><code><div id="main" class="container-fluid">
<?php misha_loadmore_ajax_handler(); ?>
</div><!-- END CONTAINER -->
</code></pre>
<p><strong>UPDATED CODE</strong> </p>
<p>This following is updated code based on answers. I am posting this because it is still not working and I may be overlooking/misunderstanding something and I want to understand where I have gone wrong.</p>
<p><strong>functions.php</strong></p>
<pre><code>function misha_my_load_more_scripts() {
wp_register_script( 'my_loadmore', get_stylesheet_directory_uri() . '/js/myloadmore.js',
array( 'jquery' ), '', true );
wp_enqueue_script( 'my_loadmore' );
}
add_action( 'wp_enqueue_scripts', 'misha_my_load_more_scripts' );
function misha_loadmore_ajax_handler() {
$args = json_decode( wp_unslash( $_POST['query'] ), true );
$args['paged'] = $_POST['page'] + 1; // load the next page
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
get_template_part( 'template-parts/content', get_post_format() );
endwhile;
endif;
wp_die();
}
add_action( 'wp_ajax_loadmore', 'misha_loadmore_ajax_handler' ); // Authenticated users
add_action( 'wp_ajax_nopriv_loadmore', 'misha_loadmore_ajax_handler' ); // Non-authenticated users
</code></pre>
<p><strong>myloadmore.js</strong></p>
<pre><code>jQuery(function($){
var canBeLoaded = true, // this param allows to initiate the AJAX call only if necessary
// the distance (in px) from the page bottom when you want to load more posts,
bottomOffset = ( $( '#main > div.post:last' ).offset() || {} ).top;
$(window).scroll(function(){
if ( misha_loadmore_params.current_page >= misha_loadmore_params.max_page ) {
// console.log( 'max_page reached; AJAX canceled' );
return; // we've already reached the last page, so let's do no more AJAX.
}
var data = {
'action': 'loadmore',
'query': misha_loadmore_params.posts,
'page' : misha_loadmore_params.current_page
};
if( $(document).scrollTop() > ( $(document).height() - bottomOffset ) && canBeLoaded == true ){
$.ajax({
url : misha_loadmore_params.ajaxurl,
data: data,
type: 'POST',
beforeSend: function( xhr ){
// you can also add your own preloader here
// you see, the AJAX call is in process, we shouldn't run it again until complete
canBeLoaded = false;
},
success:function(data){
if( data ) {
$('#main').find('div.post:last-of-type').after( data ); // where to insert posts
canBeLoaded = true; // the ajax is completed, now we can run it again
misha_loadmore_params.current_page++;
bottomOffset = ( $( '#main > div.post:last' ).offset() || {} ).top
}
}
});
}
});
});
</code></pre>
<p><strong>content.php</strong></p>
<pre><code><div class="row post">
<div class="col-sm-6">
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?>
<a href="<?php the_permalink(); ?>"><img src="<?php echo $image[0]; ?>" class="img-fluid"></a>
</div>
<div class="col-sm-6">
<?php
$categories = get_the_category();
if ( $categories ) :
$deepChild = get_deep_child_category( $categories );
?>
<p><?php echo $deepChild->name; ?></p>
<?php endif; ?>
<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
</div>
</div><!-- END ROW-->
</code></pre>
<p><strong>front-page.php</strong></p>
<pre><code> <?php
$current_page = max( 1, get_query_var( 'paged' ) );
$the_query = new WP_Query( array(
'cat' => '-21',
'post_type' => 'post',
'posts_per_page' => 5,
'paged' => $current_page,
) );
wp_localize_script( 'my_loadmore', 'misha_loadmore_params', array(
'ajaxurl' => admin_url( 'admin-ajax.php', 'relative' ),
'posts' => json_encode( $the_query->query_vars ),
'current_page' => $current_page,
'max_page' => $the_query->max_num_pages
) );
?>
<div id="main" class="container-fluid">
<?php
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
// Should match the one in misha_loadmore_ajax_handler().
get_template_part( 'template-parts/content', get_post_format() );
endwhile;
endif;
?>
</div>
<?php wp_reset_postdata(); ?>
</div><!-- END CONTAINER -->
</code></pre>
| [
{
"answer_id": 331006,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": false,
"text": "<p>There are several issues with your code, such as:</p>\n\n<ol>\n<li><p>The original <a href=\"https://rudrastyh.com/wordpress/load-more-posts-ajax.html\" rel=\"nofollow noreferrer\">code</a> relies upon the global <code>$wp_query</code> object; see the <code>global $wp_query;</code> in the <code>misha_my_load_more_scripts()</code> function. But your code is using a custom <code>WP_Query</code> instance, which is <code>$the_query</code> and which is used in the <code>misha_loadmore_ajax_handler()</code> function.</p></li>\n<li><p>The <code>misha_loadmore_ajax_handler()</code> is an AJAX handler/callback and hence it shouldn't be called from <code>div#main</code> like so:</p>\n\n<pre><code><div id=\"main\" class=\"container-fluid\">\n <?php misha_loadmore_ajax_handler(); ?>\n</div><!-- END CONTAINER -->\n</code></pre></li>\n</ol>\n\n<p>So the original code does work; however, for custom <code>WP_Query</code> requests such as the <code>$the_query</code> in your case, you'd need to put/define the AJAX JS variables <em>after</em> you make the <code>WP_Query</code> request.</p>\n\n<p>And here's how you could do that:</p>\n\n<ol>\n<li><p>First off, I'm using the default code (JS/PHP) as provided on <a href=\"https://rudrastyh.com/wordpress/load-more-posts-ajax.html\" rel=\"nofollow noreferrer\">the page</a>, and I'm using the \"<em>load posts on scroll (lazy load)</em>\" script/option.</p></li>\n<li><p>Secondly, this is my <code>misha_my_load_more_scripts()</code> function:</p>\n\n<pre><code>function misha_my_load_more_scripts() {\n // register our main script but do not enqueue it yet\n wp_register_script( 'my_loadmore', 'URL/to/the/load-more-script', array('jquery') );\n\n wp_enqueue_script( 'my_loadmore' );\n}\nadd_action( 'wp_enqueue_scripts', 'misha_my_load_more_scripts' );\n</code></pre></li>\n<li><p>And my \"main\" <code>div</code> (the posts container):</p>\n\n<pre><code>$current_page = max( 1, get_query_var( 'paged' ) );\n$the_query = new WP_Query([\n 'posts_per_page' => 5,\n 'paged' => $current_page,\n]);\n?>\n <div id=\"main\">\n <?php while ( $the_query->have_posts() ) : $the_query->the_post();\n // This should match the one in misha_loadmore_ajax_handler().\n get_template_part( 'template-parts/post/content', get_post_format() );\n endwhile; ?>\n </div>\n <script>\n var misha_loadmore_params = {\n ajaxurl: '<?php echo admin_url( 'admin-ajax.php', 'relative' ); ?>',\n posts: '<?php echo json_encode( $the_query->query_vars ); ?>',\n current_page: <?php echo $current_page; ?>,\n max_page: <?php echo $the_query->max_num_pages; ?>\n };\n </script>\n<?php\nwp_reset_postdata();\n</code></pre></li>\n<li><p>Those are the only changes I made and the original <code>misha_loadmore_ajax_handler()</code> code (<a href=\"https://rudrastyh.com/wordpress/load-more-posts-ajax.html\" rel=\"nofollow noreferrer\">on that page</a>) can be used as it is.</p></li>\n</ol>\n\n<p>I have tried and tested the/my code, and it is working as expected. And although I didn't use your code, I believe you can easily implement my code with your code/concept.</p>\n\n<h2>UPDATE</h2>\n\n<p>If you'd like to use <code>wp_localize_script()</code> (and it might be better particularly if you wish to include translated text in the JS object/data), then you need to enqueue the load-more script in the footer:</p>\n\n<pre><code>wp_register_script( 'my_loadmore', 'URL/to/the/load-more-script', array('jquery'),\n 'version', true );\n</code></pre>\n\n<p>And then in the \"main\" <code>div</code>, remove the <code><script>...</script></code> and add this before the <code>wp_reset_postdata()</code>:</p>\n\n<pre><code>wp_localize_script( 'my_loadmore', 'misha_loadmore_params', [\n 'ajaxurl' => admin_url( 'admin-ajax.php', 'relative' ),\n 'posts' => json_encode( $the_query->query_vars ),\n 'current_page' => $current_page,\n 'max_page' => $the_query->max_num_pages,\n // These two are optional.\n 'my_text' => __( 'My text', 'text-domain' ),\n 'security' => wp_create_nonce( 'my-load-more-posts' ),\n] );\n</code></pre>\n\n<p>And as you can see, I've included one translation there: <code>My text</code> (<code>misha_loadmore_params.my_text</code>).</p>\n\n<p><strong>Using a Nonce</strong></p>\n\n<p>In the above localized data, I've also included a nonce (<code>security</code>), which is specifically useful when your AJAX PHP handler is making some write operations — e.g. updating a metadata.</p>\n\n<p>And you can send it to the PHP handler like so:</p>\n\n<pre><code>// This is set in the load-more script.\nvar data = {\n 'action': 'loadmore',\n 'query': misha_loadmore_params.posts,\n 'page' : misha_loadmore_params.current_page,\n 'security': misha_loadmore_params.security\n};\n</code></pre>\n\n<p>And then in the PHP handler, you can do so to verify the nonce:</p>\n\n<pre><code>function misha_loadmore_ajax_handler(){\n check_ajax_referer( 'my-load-more-posts', 'security' );\n\n ...\n wp_die();\n}\n</code></pre>\n\n<p><em>PS: <a href=\"https://codepen.io/anon/pen/drvaWm.js\" rel=\"nofollow noreferrer\">This</a> is my load-more script, with only one difference compared to the original one, which is the <code>misha_loadmore_params.security</code> part.</em></p>\n"
},
{
"answer_id": 332155,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": true,
"text": "<h2>Working Code Based On My Previous Answer</h2>\n\n<p><em>Without using nonce.. but you can check the previous answer on how you can implement a nonce check.</em> And the code is based on <em>your</em> code.</p>\n\n<h3><code>misha_my_load_more_scripts()</code> in <code>functions.php</code></h3>\n\n<pre><code>function misha_my_load_more_scripts() {\n wp_register_script( 'my_loadmore', get_stylesheet_directory_uri() . '/js/myloadmore.js',\n array( 'jquery' ), '', true );\n wp_enqueue_script( 'my_loadmore' );\n}\nadd_action( 'wp_enqueue_scripts', 'misha_my_load_more_scripts' );\n</code></pre>\n\n<h3><code>misha_loadmore_ajax_handler()</code> in <code>functions.php</code></h3>\n\n<pre><code>function misha_loadmore_ajax_handler() {\n $args = json_decode( wp_unslash( $_POST['query'] ), true );\n $args['paged'] = $_POST['page'] + 1; // load the next page\n\n $the_query = new WP_Query( $args );\n\n if ( $the_query->have_posts() ) :\n while ( $the_query->have_posts() ) : $the_query->the_post();\n get_template_part( 'template-parts/post/content', get_post_format() );\n endwhile;\n endif;\n\n wp_die();\n}\nadd_action( 'wp_ajax_loadmore', 'misha_loadmore_ajax_handler' ); // Authenticated users\nadd_action( 'wp_ajax_nopriv_loadmore', 'misha_loadmore_ajax_handler' ); // Non-authenticated users\n</code></pre>\n\n<h3><code>front-page.php</code> (the <code>#main</code> DIV)</h3>\n\n<pre><code>$current_page = max( 1, get_query_var( 'paged' ) );\n$the_query = new WP_Query( array(\n 'cat' => '-21',\n 'post_type' => 'post',\n 'posts_per_page' => 5,\n 'paged' => $current_page,\n) );\n\nwp_localize_script( 'my_loadmore', 'misha_loadmore_params', array(\n 'ajaxurl' => admin_url( 'admin-ajax.php', 'relative' ),\n 'posts' => json_encode( $the_query->query_vars ),\n 'current_page' => $current_page,\n 'max_page' => $the_query->max_num_pages\n) );\n?>\n <div id=\"main\" class=\"container-fluid\">\n <?php\n if ( $the_query->have_posts() ) :\n while ( $the_query->have_posts() ) : $the_query->the_post();\n // Should match the one in misha_loadmore_ajax_handler().\n get_template_part( 'template-parts/post/content', get_post_format() );\n endwhile;\n endif;\n ?>\n </div>\n<?php\nwp_reset_postdata();\n</code></pre>\n\n<h3><code>myloadmore.js</code> and <code>content.php</code></h3>\n\n<p><em>No changes.</em></p>\n\n<h2>UPDATE</h2>\n\n<p>Actually, in my code (the one I actually tested with), <strong>I don't have the <code>tax_query</code> parameter</strong>, but I mistakenly included it in the above code in the previous version of this answer (not the other one on this page).</p>\n\n<p>Because a <code>tax_query</code> like the following — which doesn't specify the required <code>terms</code> <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters\" rel=\"nofollow noreferrer\">parameter</a> — would result in an <code>0 = 1</code> in the MySQL query, and eventually leads to no results (i.e. no posts):</p>\n\n<pre><code>$the_query = new WP_Query( array(\n ...\n 'tax_query' => array(\n array(\n 'taxonomy' => 'topics',\n 'operator' => 'NOT EXISTS',\n // missing the required 'terms' parameter\n ),\n ),\n) );\n</code></pre>\n\n<p>So make certain to use <code>tax_query</code> with the proper parameters.</p>\n\n<p>And you may also want to use/check my <code>myloadmore.js</code> <a href=\"https://pastebin.com/3kYV79xJ\" rel=\"nofollow noreferrer\">script</a>?</p>\n"
}
] | 2019/03/07 | [
"https://wordpress.stackexchange.com/questions/331002",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114269/"
] | I am trying to utilize AJAX on my WordPress site for posts as a user scrolls. I followed [this](https://rudrastyh.com/wordpress/load-more-posts-ajax.html) tutorial but it has no effect on my WordPress website.
I have used a plugin that works, but I'd much rather learn how to do this without a plugin both to learn and also to avoid using unnecessary plugins. The below code does not work, instead all of my posts show up on the page despite posts per page being set to 5.
Help is appreciated!
**functions.php**
```
function misha_my_load_more_scripts() {
global $wp_query;
wp_enqueue_script('jquery');
wp_register_script( 'my_loadmore', get_stylesheet_directory_uri() . '/js/myloadmore.js', array('jquery') );
wp_localize_script( 'my_loadmore', 'misha_loadmore_params', array(
'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php',
'posts' => json_encode( $wp_query->query_vars ),
'current_page' => get_query_var( 'paged' ) ? get_query_var('paged') : 1,
'max_page' => $wp_query->max_num_pages
) );
wp_enqueue_script( 'my_loadmore' );
}
add_action( 'wp_enqueue_scripts', 'misha_my_load_more_scripts' );
function misha_loadmore_ajax_handler(){
$args = array(
'cat' => -21,
'post_type' => 'post',
'posts_per_page' => 5,
'paged' => 1,
'tax_query' => array(
array(
'taxonomy' => 'topics',
'operator' => 'NOT EXISTS'
)
)
);
$args = json_decode( stripslashes( $_POST['query'] ), true );
$args['paged'] = $_POST['page'] + 1; //need next page to be loaded
$args['post_status'] = 'publish';
$the_query = new WP_Query ( $args );
if($the_query->have_posts()) :
while($the_query->have_posts()) :
$the_query->the_post();
get_template_part( 'template-parts/post/content', get_post_format() );
endwhile;
endif;
die;
}
add_action('wp_ajax_loadmore', 'misha_loadmore_ajax_handler'); // wp_ajax_{action}
add_action('wp_ajax_nopriv_loadmore', 'misha_loadmore_ajax_handler'); // wp_ajax_nopriv_{action}
```
**myloadmore.js**
```
jQuery(function($){
var canBeLoaded = true,
bottomOffset = 2000; //I've played with this number to see if it was the offset calling posts too soon but it has no effect
$(window).scroll(function(){
var data = {
'action': 'loadmore',
'query': misha_loadmore_params.posts,
'page' : misha_loadmore_params.current_page
};
if( $(document).scrollTop() > ( $(document).height() - bottomOffset ) && canBeLoaded == true ){
$.ajax({
url : misha_loadmore_params.ajaxurl,
data:data,
type:'POST',
beforeSend: function( xhr ){
canBeLoaded = false;
},
success:function(data){
if( data ) {
$('#main').find('div:last-of-type').after( data );
canBeLoaded = true;
misha_loadmore_params.current_page++;
}
}
});
}
});
});
```
**content.php**
```
<div class="row">
<div class="col-sm-6">
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?>
<a href="<?php the_permalink(); ?>"><img src="<?php echo $image[0]; ?>" class="img-fluid"></a>
</div>
<div class="col-sm-6">
<?php
$categories = get_the_category();
if ( $categories ) :
$deepChild = get_deep_child_category( $categories );
?>
<p><?php echo $deepChild->name; ?></p>
<?php endif; ?>
<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
</div>
</div><!-- END ROW-->
```
**front-page.php**
```
<div id="main" class="container-fluid">
<?php misha_loadmore_ajax_handler(); ?>
</div><!-- END CONTAINER -->
```
**UPDATED CODE**
This following is updated code based on answers. I am posting this because it is still not working and I may be overlooking/misunderstanding something and I want to understand where I have gone wrong.
**functions.php**
```
function misha_my_load_more_scripts() {
wp_register_script( 'my_loadmore', get_stylesheet_directory_uri() . '/js/myloadmore.js',
array( 'jquery' ), '', true );
wp_enqueue_script( 'my_loadmore' );
}
add_action( 'wp_enqueue_scripts', 'misha_my_load_more_scripts' );
function misha_loadmore_ajax_handler() {
$args = json_decode( wp_unslash( $_POST['query'] ), true );
$args['paged'] = $_POST['page'] + 1; // load the next page
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
get_template_part( 'template-parts/content', get_post_format() );
endwhile;
endif;
wp_die();
}
add_action( 'wp_ajax_loadmore', 'misha_loadmore_ajax_handler' ); // Authenticated users
add_action( 'wp_ajax_nopriv_loadmore', 'misha_loadmore_ajax_handler' ); // Non-authenticated users
```
**myloadmore.js**
```
jQuery(function($){
var canBeLoaded = true, // this param allows to initiate the AJAX call only if necessary
// the distance (in px) from the page bottom when you want to load more posts,
bottomOffset = ( $( '#main > div.post:last' ).offset() || {} ).top;
$(window).scroll(function(){
if ( misha_loadmore_params.current_page >= misha_loadmore_params.max_page ) {
// console.log( 'max_page reached; AJAX canceled' );
return; // we've already reached the last page, so let's do no more AJAX.
}
var data = {
'action': 'loadmore',
'query': misha_loadmore_params.posts,
'page' : misha_loadmore_params.current_page
};
if( $(document).scrollTop() > ( $(document).height() - bottomOffset ) && canBeLoaded == true ){
$.ajax({
url : misha_loadmore_params.ajaxurl,
data: data,
type: 'POST',
beforeSend: function( xhr ){
// you can also add your own preloader here
// you see, the AJAX call is in process, we shouldn't run it again until complete
canBeLoaded = false;
},
success:function(data){
if( data ) {
$('#main').find('div.post:last-of-type').after( data ); // where to insert posts
canBeLoaded = true; // the ajax is completed, now we can run it again
misha_loadmore_params.current_page++;
bottomOffset = ( $( '#main > div.post:last' ).offset() || {} ).top
}
}
});
}
});
});
```
**content.php**
```
<div class="row post">
<div class="col-sm-6">
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?>
<a href="<?php the_permalink(); ?>"><img src="<?php echo $image[0]; ?>" class="img-fluid"></a>
</div>
<div class="col-sm-6">
<?php
$categories = get_the_category();
if ( $categories ) :
$deepChild = get_deep_child_category( $categories );
?>
<p><?php echo $deepChild->name; ?></p>
<?php endif; ?>
<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
</div>
</div><!-- END ROW-->
```
**front-page.php**
```
<?php
$current_page = max( 1, get_query_var( 'paged' ) );
$the_query = new WP_Query( array(
'cat' => '-21',
'post_type' => 'post',
'posts_per_page' => 5,
'paged' => $current_page,
) );
wp_localize_script( 'my_loadmore', 'misha_loadmore_params', array(
'ajaxurl' => admin_url( 'admin-ajax.php', 'relative' ),
'posts' => json_encode( $the_query->query_vars ),
'current_page' => $current_page,
'max_page' => $the_query->max_num_pages
) );
?>
<div id="main" class="container-fluid">
<?php
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
// Should match the one in misha_loadmore_ajax_handler().
get_template_part( 'template-parts/content', get_post_format() );
endwhile;
endif;
?>
</div>
<?php wp_reset_postdata(); ?>
</div><!-- END CONTAINER -->
``` | Working Code Based On My Previous Answer
----------------------------------------
*Without using nonce.. but you can check the previous answer on how you can implement a nonce check.* And the code is based on *your* code.
### `misha_my_load_more_scripts()` in `functions.php`
```
function misha_my_load_more_scripts() {
wp_register_script( 'my_loadmore', get_stylesheet_directory_uri() . '/js/myloadmore.js',
array( 'jquery' ), '', true );
wp_enqueue_script( 'my_loadmore' );
}
add_action( 'wp_enqueue_scripts', 'misha_my_load_more_scripts' );
```
### `misha_loadmore_ajax_handler()` in `functions.php`
```
function misha_loadmore_ajax_handler() {
$args = json_decode( wp_unslash( $_POST['query'] ), true );
$args['paged'] = $_POST['page'] + 1; // load the next page
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
get_template_part( 'template-parts/post/content', get_post_format() );
endwhile;
endif;
wp_die();
}
add_action( 'wp_ajax_loadmore', 'misha_loadmore_ajax_handler' ); // Authenticated users
add_action( 'wp_ajax_nopriv_loadmore', 'misha_loadmore_ajax_handler' ); // Non-authenticated users
```
### `front-page.php` (the `#main` DIV)
```
$current_page = max( 1, get_query_var( 'paged' ) );
$the_query = new WP_Query( array(
'cat' => '-21',
'post_type' => 'post',
'posts_per_page' => 5,
'paged' => $current_page,
) );
wp_localize_script( 'my_loadmore', 'misha_loadmore_params', array(
'ajaxurl' => admin_url( 'admin-ajax.php', 'relative' ),
'posts' => json_encode( $the_query->query_vars ),
'current_page' => $current_page,
'max_page' => $the_query->max_num_pages
) );
?>
<div id="main" class="container-fluid">
<?php
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
// Should match the one in misha_loadmore_ajax_handler().
get_template_part( 'template-parts/post/content', get_post_format() );
endwhile;
endif;
?>
</div>
<?php
wp_reset_postdata();
```
### `myloadmore.js` and `content.php`
*No changes.*
UPDATE
------
Actually, in my code (the one I actually tested with), **I don't have the `tax_query` parameter**, but I mistakenly included it in the above code in the previous version of this answer (not the other one on this page).
Because a `tax_query` like the following — which doesn't specify the required `terms` [parameter](https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters) — would result in an `0 = 1` in the MySQL query, and eventually leads to no results (i.e. no posts):
```
$the_query = new WP_Query( array(
...
'tax_query' => array(
array(
'taxonomy' => 'topics',
'operator' => 'NOT EXISTS',
// missing the required 'terms' parameter
),
),
) );
```
So make certain to use `tax_query` with the proper parameters.
And you may also want to use/check my `myloadmore.js` [script](https://pastebin.com/3kYV79xJ)? |
331,028 | <p>I have created a custom portfolio with the following code in the function.php in a custom template.</p>
<pre><code>if ( ! function_exists('custom_post_type_portafolio') ) {
// Register Custom Post Type
function custom_post_type_portafolio() {
$labels = array(
'name' => _x( 'Proyectos', 'Post Type General Name', 'text_domain' ),
'singular_name' => _x( 'Proyecto', 'Post Type Singular Name', 'text_domain' ),
'menu_name' => __( 'Portafolio', 'text_domain' ),
'name_admin_bar' => __( 'Portafolio', 'text_domain' ),
'archives' => __( 'Portafolio', 'text_domain' ),
'parent_item_colon' => __( 'Proyecto superior', 'text_domain' ),
'all_items' => __( 'Todos los proyectos', 'text_domain' ),
'add_new_item' => __( 'Añadir nuevo proyecto', 'text_domain' ),
'add_new' => __( 'Añadir nuevo Proyecto', 'text_domain' ),
'new_item' => __( 'Nuevo proyecto', 'text_domain' ),
'edit_item' => __( 'Editar proyecto', 'text_domain' ),
'update_item' => __( 'Actualizar proyecto', 'text_domain' ),
'view_item' => __( 'Ver proyecto', 'text_domain' ),
'search_items' => __( 'Buscar proyecto', 'text_domain' ),
'not_found' => __( 'Not found', 'text_domain' ),
'not_found_in_trash' => __( 'Not found in Trash', 'text_domain' ),
'featured_image' => __( 'Imagen destacada', 'text_domain' ),
'set_featured_image' => __( 'Añadir imagen destacada', 'text_domain' ),
'remove_featured_image' => __( 'Quitar Imagen destacada', 'text_domain' ),
'use_featured_image' => __( 'Usar como Imagen destacada', 'text_domain' ),
'insert_into_item' => __( 'Insert into item', 'text_domain' ),
'uploaded_to_this_item' => __( 'Uploaded to this item', 'text_domain' ),
'items_list' => __( 'Items list', 'text_domain' ),
'items_list_navigation' => __( 'Items list navigation', 'text_domain' ),
'filter_items_list' => __( 'Filter items list', 'text_domain' ),
);
$args = array(
'label' => __( 'Proyecto', 'text_domain' ),
'description' => __( 'Portafolio', 'text_domain' ),
'labels' => $labels,
'supports' => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'revisions', 'custom-fields', 'post-formats', ),
'taxonomies' => array( 'Portafolio-category', 'post_tag' ),
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'page',
);
register_post_type( 'portafolio', $args );
}
add_action( 'init', 'custom_post_type_portafolio', 0 );
}
if ( ! function_exists( 'custom_taxonomy_portafolio' ) ) {
// Register Custom Taxonomy
function custom_taxonomy_portafolio() {
$labels = array(
'name' => _x( 'Tipos de proyectos', 'Taxonomy General Name', 'text_domain' ),
'singular_name' => _x( 'Tipo Proyecto', 'Taxonomy Singular Name', 'text_domain' ),
'menu_name' => __( 'Tipos de proyectos', 'text_domain' ),
'all_items' => __( 'Todos los tipos de proyectos', 'text_domain' ),
'parent_item' => __( 'Tipo superior', 'text_domain' ),
'parent_item_colon' => __( 'Tipo superior:', 'text_domain' ),
'new_item_name' => __( 'Nuevo Tipo de proyecto', 'text_domain' ),
'add_new_item' => __( 'Añadir Nuevo Tipo de proyecto', 'text_domain' ),
'edit_item' => __( 'Editar Tipo de proyecto', 'text_domain' ),
'update_item' => __( 'Actualizar Tipo de proyecto', 'text_domain' ),
'view_item' => __( 'Ver Tipo de proyecto', 'text_domain' ),
'separate_items_with_commas' => __( 'Separar tipos con comas', 'text_domain' ),
'add_or_remove_items' => __( 'Añadir o quitar Nuevo Tipos de proyecto', 'text_domain' ),
'choose_from_most_used' => __( 'Elegir entre los más usados', 'text_domain' ),
'popular_items' => __( 'Tipos de proyecto populares', 'text_domain' ),
'search_items' => __( 'Buscar Tipos de proyecto', 'text_domain' ),
'not_found' => __( 'No se encuentra', 'text_domain' ),
'no_terms' => __( 'No hay Tipos de proyecto', 'text_domain' ),
'items_list' => __( 'Lista de Tipos de proyecto', 'text_domain' ),
'items_list_navigation' => __( 'Navegación Tipos de proyecto', 'text_domain' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_nav_menus' => true,
'show_tagcloud' => true,
);
register_taxonomy( 'tipo_proyecto', array( 'portafolio' ), $args );
}
add_action( 'init', 'custom_taxonomy_portafolio', 0 );
}
</code></pre>
<p>Print the posts correctly, do the loop of the categories for the menu well, on my portfolio.php page of my theme.
but I can not filter the projects by categories with the following code in archives.php.</p>
<pre><code> <div class="ai_section_2_2_proyectos">
<ul class="list-unstyled listado_proyectos">
<?php
$args=array(
'post_type' => 'Portafolio',
'post_status' => 'publish',
'orderby' => 'ASC',
'posts_per_page' => '-1',
'taxonomies' => array( 'tipo_proyecto', 'ecommerce' ),
);
// The Query
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
?>
<li id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<a href="<?php the_permalink();?>" title="<?php the_title();?>" class="a_hover" data-image="<?=get_the_post_thumbnail_url($post->ID, 'full')?>">
<h2><?php the_title();?></h2>
<ul class="list-unstyled list-inline post-categories">
<?
$category = get_the_category();
foreach( $category as $cat )
{
echo "<li class='categories_li'>".$cat->name."</li>";
if ($cat === end($category)) {
}
else{
echo "<li class='categories_li'>/</li>";
}
}
?>
<li class="ver_proyecto">Ver proyecto</li>
</ul>
</a>
</li>
<?php }} else {
echo 'No hay artículos';
// no se encontraron artículos
}
/* Restore original Post Data */
wp_reset_postdata();
?>
</ul>
</div>
</code></pre>
<p>I think the problem is in this part:</p>
<pre><code> $args=array(
'post_type' => 'Portafolio',
'post_status' => 'publish',
'orderby' => 'ASC',
'posts_per_page' => '-1',
'taxonomies' => $cat,
);
// The Query
$the_query = new WP_Query( $args );
</code></pre>
| [
{
"answer_id": 331030,
"author": "chrisbergr",
"author_id": 45070,
"author_profile": "https://wordpress.stackexchange.com/users/45070",
"pm_score": 0,
"selected": false,
"text": "<p>For today, Gutenberg doesn't provide <code>container blocks</code> by default. Therefore you either need a 3rd party plugin like <a href=\"https://atomicblocks.com/\" rel=\"nofollow noreferrer\">Atomic Blocks</a> or you write <a href=\"https://wordpress.stackexchange.com/questions/315941/are-there-gutenberg-container-blocks/320778#320778\">your own</a>.</p>\n\n<p>But you can do a little hack. Upload a transparent png to your media library. Then use the <code>cover block</code> for each section. Give every <code>cover block</code> the transparent png as image and write your content above. For your sections with white background just add a white overlay color in the block settings and Background Opacity of 100%. Maybe the text doesn't look like you expect it, therefore you can add a css class to the block and do it with CSS.</p>\n\n<p>I hope this helps.</p>\n"
},
{
"answer_id": 391856,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<p>Nested group and cover blocks are the solution, and since you created your question the block editor has improved enough that your design can be created with group and cover blocks, with spacing rules via global styles. No code is necessary.</p>\n<p>E.g. I was able to create this using just the editor, and no CSS or code:</p>\n<p><a href=\"https://i.stack.imgur.com/0CcLO.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/0CcLO.jpg\" alt=\"enter image description here\" /></a></p>\n<p>I used a cover block for the background, then used a group block for layout, giving it a maximum width, a white background, and black text.</p>\n<p>You could copy paste those blocks and use them to register a block pattern so that users would never have to create it themselves.</p>\n<p>Likewise you could set it as a template for the inner block, but the solution is still the same, you do what you'd do in HTML and nest tags/blocks. Having a block with more than one internal area is just as incomprehensible as having a tag that has multiple separate insides without using <code><div></code> or other tags to create them.</p>\n"
}
] | 2019/03/07 | [
"https://wordpress.stackexchange.com/questions/331028",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/162739/"
] | I have created a custom portfolio with the following code in the function.php in a custom template.
```
if ( ! function_exists('custom_post_type_portafolio') ) {
// Register Custom Post Type
function custom_post_type_portafolio() {
$labels = array(
'name' => _x( 'Proyectos', 'Post Type General Name', 'text_domain' ),
'singular_name' => _x( 'Proyecto', 'Post Type Singular Name', 'text_domain' ),
'menu_name' => __( 'Portafolio', 'text_domain' ),
'name_admin_bar' => __( 'Portafolio', 'text_domain' ),
'archives' => __( 'Portafolio', 'text_domain' ),
'parent_item_colon' => __( 'Proyecto superior', 'text_domain' ),
'all_items' => __( 'Todos los proyectos', 'text_domain' ),
'add_new_item' => __( 'Añadir nuevo proyecto', 'text_domain' ),
'add_new' => __( 'Añadir nuevo Proyecto', 'text_domain' ),
'new_item' => __( 'Nuevo proyecto', 'text_domain' ),
'edit_item' => __( 'Editar proyecto', 'text_domain' ),
'update_item' => __( 'Actualizar proyecto', 'text_domain' ),
'view_item' => __( 'Ver proyecto', 'text_domain' ),
'search_items' => __( 'Buscar proyecto', 'text_domain' ),
'not_found' => __( 'Not found', 'text_domain' ),
'not_found_in_trash' => __( 'Not found in Trash', 'text_domain' ),
'featured_image' => __( 'Imagen destacada', 'text_domain' ),
'set_featured_image' => __( 'Añadir imagen destacada', 'text_domain' ),
'remove_featured_image' => __( 'Quitar Imagen destacada', 'text_domain' ),
'use_featured_image' => __( 'Usar como Imagen destacada', 'text_domain' ),
'insert_into_item' => __( 'Insert into item', 'text_domain' ),
'uploaded_to_this_item' => __( 'Uploaded to this item', 'text_domain' ),
'items_list' => __( 'Items list', 'text_domain' ),
'items_list_navigation' => __( 'Items list navigation', 'text_domain' ),
'filter_items_list' => __( 'Filter items list', 'text_domain' ),
);
$args = array(
'label' => __( 'Proyecto', 'text_domain' ),
'description' => __( 'Portafolio', 'text_domain' ),
'labels' => $labels,
'supports' => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'revisions', 'custom-fields', 'post-formats', ),
'taxonomies' => array( 'Portafolio-category', 'post_tag' ),
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'page',
);
register_post_type( 'portafolio', $args );
}
add_action( 'init', 'custom_post_type_portafolio', 0 );
}
if ( ! function_exists( 'custom_taxonomy_portafolio' ) ) {
// Register Custom Taxonomy
function custom_taxonomy_portafolio() {
$labels = array(
'name' => _x( 'Tipos de proyectos', 'Taxonomy General Name', 'text_domain' ),
'singular_name' => _x( 'Tipo Proyecto', 'Taxonomy Singular Name', 'text_domain' ),
'menu_name' => __( 'Tipos de proyectos', 'text_domain' ),
'all_items' => __( 'Todos los tipos de proyectos', 'text_domain' ),
'parent_item' => __( 'Tipo superior', 'text_domain' ),
'parent_item_colon' => __( 'Tipo superior:', 'text_domain' ),
'new_item_name' => __( 'Nuevo Tipo de proyecto', 'text_domain' ),
'add_new_item' => __( 'Añadir Nuevo Tipo de proyecto', 'text_domain' ),
'edit_item' => __( 'Editar Tipo de proyecto', 'text_domain' ),
'update_item' => __( 'Actualizar Tipo de proyecto', 'text_domain' ),
'view_item' => __( 'Ver Tipo de proyecto', 'text_domain' ),
'separate_items_with_commas' => __( 'Separar tipos con comas', 'text_domain' ),
'add_or_remove_items' => __( 'Añadir o quitar Nuevo Tipos de proyecto', 'text_domain' ),
'choose_from_most_used' => __( 'Elegir entre los más usados', 'text_domain' ),
'popular_items' => __( 'Tipos de proyecto populares', 'text_domain' ),
'search_items' => __( 'Buscar Tipos de proyecto', 'text_domain' ),
'not_found' => __( 'No se encuentra', 'text_domain' ),
'no_terms' => __( 'No hay Tipos de proyecto', 'text_domain' ),
'items_list' => __( 'Lista de Tipos de proyecto', 'text_domain' ),
'items_list_navigation' => __( 'Navegación Tipos de proyecto', 'text_domain' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_nav_menus' => true,
'show_tagcloud' => true,
);
register_taxonomy( 'tipo_proyecto', array( 'portafolio' ), $args );
}
add_action( 'init', 'custom_taxonomy_portafolio', 0 );
}
```
Print the posts correctly, do the loop of the categories for the menu well, on my portfolio.php page of my theme.
but I can not filter the projects by categories with the following code in archives.php.
```
<div class="ai_section_2_2_proyectos">
<ul class="list-unstyled listado_proyectos">
<?php
$args=array(
'post_type' => 'Portafolio',
'post_status' => 'publish',
'orderby' => 'ASC',
'posts_per_page' => '-1',
'taxonomies' => array( 'tipo_proyecto', 'ecommerce' ),
);
// The Query
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
?>
<li id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<a href="<?php the_permalink();?>" title="<?php the_title();?>" class="a_hover" data-image="<?=get_the_post_thumbnail_url($post->ID, 'full')?>">
<h2><?php the_title();?></h2>
<ul class="list-unstyled list-inline post-categories">
<?
$category = get_the_category();
foreach( $category as $cat )
{
echo "<li class='categories_li'>".$cat->name."</li>";
if ($cat === end($category)) {
}
else{
echo "<li class='categories_li'>/</li>";
}
}
?>
<li class="ver_proyecto">Ver proyecto</li>
</ul>
</a>
</li>
<?php }} else {
echo 'No hay artículos';
// no se encontraron artículos
}
/* Restore original Post Data */
wp_reset_postdata();
?>
</ul>
</div>
```
I think the problem is in this part:
```
$args=array(
'post_type' => 'Portafolio',
'post_status' => 'publish',
'orderby' => 'ASC',
'posts_per_page' => '-1',
'taxonomies' => $cat,
);
// The Query
$the_query = new WP_Query( $args );
``` | Nested group and cover blocks are the solution, and since you created your question the block editor has improved enough that your design can be created with group and cover blocks, with spacing rules via global styles. No code is necessary.
E.g. I was able to create this using just the editor, and no CSS or code:
[](https://i.stack.imgur.com/0CcLO.jpg)
I used a cover block for the background, then used a group block for layout, giving it a maximum width, a white background, and black text.
You could copy paste those blocks and use them to register a block pattern so that users would never have to create it themselves.
Likewise you could set it as a template for the inner block, but the solution is still the same, you do what you'd do in HTML and nest tags/blocks. Having a block with more than one internal area is just as incomprehensible as having a tag that has multiple separate insides without using `<div>` or other tags to create them. |
331,078 | <p>Error log on my index file get logged in the <code>error_log.txt</code> file but the same error log is not working in the <code>functions.php</code> file. I am using the latest WordPress and <code>PHP 7.0.</code> I am not using any plugin as well.</p>
<pre><code>error_log("Hello there is an error");
</code></pre>
| [
{
"answer_id": 331082,
"author": "butlerblog",
"author_id": 38603,
"author_profile": "https://wordpress.stackexchange.com/users/38603",
"pm_score": 2,
"selected": false,
"text": "<p>In order for <code>error_log()</code> to do anything, you do need to have the <code>WP_DEBUG</code> and <code>WP_DEBUG_LOG</code> constants set to true in your wp-config.php. (See: <a href=\"https://codex.wordpress.org/Debugging_in_WordPress\" rel=\"nofollow noreferrer\">Debugging in WordPress</a> in the Codex for more information.)</p>\n\n<p>According to <a href=\"https://stackoverflow.com/questions/24330039/how-can-i-use-error-log-with-wordpress\">this answer on Stackoverflow</a>, you should also set <code>WP_DEBUG_DISPLAY</code> for <code>error_log()</code> to function. Note that you can set it to true OR false, but it evidently needs to be defined.</p>\n"
},
{
"answer_id": 338528,
"author": "Gábor Fehér",
"author_id": 168585,
"author_profile": "https://wordpress.stackexchange.com/users/168585",
"pm_score": 2,
"selected": false,
"text": "<p>I had a similar problem: calling <code>error_log()</code> from <code>wp-config.php</code> works, but calling it from <code>functions.php</code> does not work for me.</p>\n\n<p>I couldn't solve this issue but I've found a workaround that allowed me to do some sort of debugging at least. I gave up on <code>error_log()</code> and just wrote an own function that logs into a given file:</p>\n\n<pre><code>function mylog($txt) {\n file_put_contents('/home/myuser/logs/mylog.txt', $txt.PHP_EOL , FILE_APPEND | LOCK_EX);\n}\n\n</code></pre>\n"
},
{
"answer_id": 378016,
"author": "dans_art",
"author_id": 197412,
"author_profile": "https://wordpress.stackexchange.com/users/197412",
"pm_score": 2,
"selected": false,
"text": "<p>If you have this set in your wp_config;</p>\n<pre><code>define( 'WP_DEBUG_LOG', true );\n</code></pre>\n<p>it will save the logs to /wp-content/debug.log file instead of the default Apache error.log</p>\n"
}
] | 2019/03/08 | [
"https://wordpress.stackexchange.com/questions/331078",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/162761/"
] | Error log on my index file get logged in the `error_log.txt` file but the same error log is not working in the `functions.php` file. I am using the latest WordPress and `PHP 7.0.` I am not using any plugin as well.
```
error_log("Hello there is an error");
``` | In order for `error_log()` to do anything, you do need to have the `WP_DEBUG` and `WP_DEBUG_LOG` constants set to true in your wp-config.php. (See: [Debugging in WordPress](https://codex.wordpress.org/Debugging_in_WordPress) in the Codex for more information.)
According to [this answer on Stackoverflow](https://stackoverflow.com/questions/24330039/how-can-i-use-error-log-with-wordpress), you should also set `WP_DEBUG_DISPLAY` for `error_log()` to function. Note that you can set it to true OR false, but it evidently needs to be defined. |
331,086 | <p>I know that there is this option on <code>admin</code> to hide products from the entire catalog if there is no stock, but how do I hide these products only from home page and not from the entire catalog?</p>
<p>I want to be able to search the products and see it even if it has no stock.</p>
| [
{
"answer_id": 331358,
"author": "Shihab",
"author_id": 113702,
"author_profile": "https://wordpress.stackexchange.com/users/113702",
"pm_score": 1,
"selected": false,
"text": "<p>Assuming you are using storefront default homepage template. You can filter products before displaying on hompepage</p>\n\n<pre><code>function rfl_show_backorders( $is_visible, $id ) {\n $product = new wC_Product( $id );\n\n if ( ! $product->is_in_stock() && ! $product->backorders_allowed() && is_front_page() ) {\n $is_visible = false;\n }\n\n return $is_visible;\n}\nadd_filter( 'woocommerce_product_is_visible', 'rfl_show_backorders', 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 331587,
"author": "Pratik Patel",
"author_id": 143123,
"author_profile": "https://wordpress.stackexchange.com/users/143123",
"pm_score": 0,
"selected": false,
"text": "<p>You can check current page is <strong>HOME</strong> page like this:</p>\n\n<p>You can check product is <em>in stock</em> or not using <code>$product->is_in_stock()</code> in your loop.</p>\n\n<pre><code>if ( is_front_page() || is_home() ) {\n // Out of products stuff here\n}\n</code></pre>\n\n<p>Hope it will help you !</p>\n"
},
{
"answer_id": 332074,
"author": "nmr",
"author_id": 147428,
"author_profile": "https://wordpress.stackexchange.com/users/147428",
"pm_score": 0,
"selected": false,
"text": "<p>To display only <strong>in stock</strong> products you can add <code>_stock_status</code> key with the appropriate value to <strong>meta query</strong>. </p>\n\n<pre><code>add_filter('woocommerce_product_query_meta_query', 'wpse_331086_instock_homepage', 20);\n\nfunction wpse_331086_instock_homepage( $meta_query )\n{\n //\n // is_shop() - apply on shop homepage (product archive page)\n // is_front_page() - apply on site homepage\n //\n // stock status: 'instock', 'outofstock', 'onbackorder'\n if ( is_shop() ) {\n $meta_query[] = array(\n 'key' => '_stock_status',\n 'value' => 'instock',\n 'compare' => '='\n );\n }\n return $meta_query;\n}\n</code></pre>\n\n<p>Code goes in <code>functions.php</code> file of your theme .</p>\n"
},
{
"answer_id": 408267,
"author": "Iftikhar Abid",
"author_id": 224626,
"author_profile": "https://wordpress.stackexchange.com/users/224626",
"pm_score": 0,
"selected": false,
"text": "<p>Add this in function.php .. It works for me</p>\n<pre><code> <?php if( is_home() || is_front_page() ): ?>\n<script type="text/javascript" src=""></script>\n\n<script type="text/javascript">\njQuery(window).on('load', function() {\njQuery('.outofstock').parent().parent().css('display','none');\n});\n</script>\n<?php endif;\n}\nadd_action( 'wp_footer', 'add_inline_script', 0 );\n</code></pre>\n"
}
] | 2019/03/08 | [
"https://wordpress.stackexchange.com/questions/331086",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/124888/"
] | I know that there is this option on `admin` to hide products from the entire catalog if there is no stock, but how do I hide these products only from home page and not from the entire catalog?
I want to be able to search the products and see it even if it has no stock. | Assuming you are using storefront default homepage template. You can filter products before displaying on hompepage
```
function rfl_show_backorders( $is_visible, $id ) {
$product = new wC_Product( $id );
if ( ! $product->is_in_stock() && ! $product->backorders_allowed() && is_front_page() ) {
$is_visible = false;
}
return $is_visible;
}
add_filter( 'woocommerce_product_is_visible', 'rfl_show_backorders', 10, 2 );
``` |
331,103 | <p>The 'wp-admin/admin-header.php' file outputs 'viewport' meta data. It seems the value of the viewport is hard coded into the file. (See: <a href="https://github.com/WordPress/WordPress/blob/master/wp-admin/admin-header.php" rel="nofollow noreferrer">https://github.com/WordPress/WordPress/blob/master/wp-admin/admin-header.php</a> line 89).</p>
<p>I want to edit the viewport from my custom plugin. Are there any suggestions as to how this could be done?</p>
<p>Any code injected via the hooks that follow the hardcoded viewport data has no effect and I cannot see any available hooks inside the section that occur before the hardcoded data. </p>
| [
{
"answer_id": 331114,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 0,
"selected": false,
"text": "<p>As was said, <code><meta name=\"viewport\" /></code> is hardcoded, but fortunately it's done before <code>admin_head</code> hook is fired.</p>\n\n<p>It means you can override the hard-coded meta:</p>\n\n<pre><code><?php\n\nfunction my_meta_viewport() {\n echo '<meta name=\"viewport\" content=\"width=640,initial-scale=1.0\"><!-- Added -->';\n}\nadd_action( 'admin_head', 'my_meta_viewport' );\n\n?>\n</code></pre>\n\n<p>Which will result in something similar to the following HTML:</p>\n\n<pre><code><meta name=\"viewport\" content=\"width=device-width,initial-scale=1.0\">\n<meta name=\"viewport\" content=\"width=640,initial-scale=1.0\"><!-- Added -->\n</code></pre>\n\n<p>where the first (hard-coded) <code><meta name=\"viewport\" /></code> will be ignored by the browser because of the second.</p>\n"
},
{
"answer_id": 374091,
"author": "Egor Maltsev",
"author_id": 193984,
"author_profile": "https://wordpress.stackexchange.com/users/193984",
"pm_score": 1,
"selected": false,
"text": "<p>There's a new filter <code>admin_viewport_meta</code> in WordPress 5.5 - <a href=\"https://developer.wordpress.org/reference/functions/wp_admin_viewport_meta/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_admin_viewport_meta/</a></p>\n<p>Now you can change viewport:</p>\n<pre><code>function my_meta_viewport() {\n return 'width=980,initial-scale=1.0'; // your value\n}\nadd_action( 'admin_viewport_meta', 'my_meta_viewport' );\n</code></pre>\n"
}
] | 2019/03/08 | [
"https://wordpress.stackexchange.com/questions/331103",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/157032/"
] | The 'wp-admin/admin-header.php' file outputs 'viewport' meta data. It seems the value of the viewport is hard coded into the file. (See: <https://github.com/WordPress/WordPress/blob/master/wp-admin/admin-header.php> line 89).
I want to edit the viewport from my custom plugin. Are there any suggestions as to how this could be done?
Any code injected via the hooks that follow the hardcoded viewport data has no effect and I cannot see any available hooks inside the section that occur before the hardcoded data. | There's a new filter `admin_viewport_meta` in WordPress 5.5 - <https://developer.wordpress.org/reference/functions/wp_admin_viewport_meta/>
Now you can change viewport:
```
function my_meta_viewport() {
return 'width=980,initial-scale=1.0'; // your value
}
add_action( 'admin_viewport_meta', 'my_meta_viewport' );
``` |
331,117 | <p>How do we hide the admin toolbar from the back end dashboard?</p>
<p>We can hide the toolbar when viewing the website with the below code but we want to also hide it from back end?</p>
<pre><code>add_filter('show_admin_bar', '__return_false');
</code></pre>
<p>Thank you</p>
| [
{
"answer_id": 331120,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 2,
"selected": true,
"text": "<p><a href=\"https://codex.wordpress.org/Function_Reference/show_admin_bar\" rel=\"nofollow noreferrer\">WordPress page for</a> <code>show_admin_bar</code> says: </p>\n\n<blockquote>\n <p>You cannot turn off the toolbar on the WordPress dashboard</p>\n</blockquote>\n\n<p>However, this trick works </p>\n\n<pre><code> function remove_admin_bar() { ?>\n <style type=\"text/css\">\n body {\n margin-top: -28px;\n }\n\n body.admin-bar #wphead {\n padding-top: 0;\n }\n\n #wpadminbar {\n display: none;\n }\n </style>\n<?php }\n\nadd_action( 'admin_head', 'remove_admin_bar' );\n</code></pre>\n\n<p>In oreder to remove certain menus from admin bar use <code>$wp_admin_bar->remove_menu($id);</code> where <code>$id</code> of a specific menu can be found in Chrome Dev Tool. Each menus' <code><li></code> id in Dev tool is in the form of <code>wp-admin-bar-{id}</code>, for example Comments menu has id <code>wp-admin-bar-comments</code>. So to remove this menu code should be like this,</p>\n\n<pre><code>// remove links/menus from the admin bar\nfunction my_admin_bar_render() {\n global $wp_admin_bar;\n $wp_admin_bar->remove_menu('comments');\n // Code to remove other items goes here\n ....\n ....\n}\nadd_action( 'wp_before_admin_bar_render', 'my_admin_bar_render' );\n</code></pre>\n"
},
{
"answer_id": 331152,
"author": "Tanmay Patel",
"author_id": 62026,
"author_profile": "https://wordpress.stackexchange.com/users/62026",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p><strong><em>Turn Off the Admin Toolbar in Settings</em></strong>. Disable the admin toolbar in your profile settings. To remove the toolbar from your site, go to <strong>Users > Your Profile</strong>. Scroll down to “Toolbar” and check “<strong>Show Toolbar when viewing site.</strong>”</p>\n</blockquote>\n\n<p><strong><em>Reference :</em></strong> <a href=\"https://www.machothemes.com/blog/disable-wordpress-admin-bar/\" rel=\"nofollow noreferrer\">https://www.machothemes.com/blog/disable-wordpress-admin-bar/</a></p>\n"
}
] | 2019/03/08 | [
"https://wordpress.stackexchange.com/questions/331117",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/162788/"
] | How do we hide the admin toolbar from the back end dashboard?
We can hide the toolbar when viewing the website with the below code but we want to also hide it from back end?
```
add_filter('show_admin_bar', '__return_false');
```
Thank you | [WordPress page for](https://codex.wordpress.org/Function_Reference/show_admin_bar) `show_admin_bar` says:
>
> You cannot turn off the toolbar on the WordPress dashboard
>
>
>
However, this trick works
```
function remove_admin_bar() { ?>
<style type="text/css">
body {
margin-top: -28px;
}
body.admin-bar #wphead {
padding-top: 0;
}
#wpadminbar {
display: none;
}
</style>
<?php }
add_action( 'admin_head', 'remove_admin_bar' );
```
In oreder to remove certain menus from admin bar use `$wp_admin_bar->remove_menu($id);` where `$id` of a specific menu can be found in Chrome Dev Tool. Each menus' `<li>` id in Dev tool is in the form of `wp-admin-bar-{id}`, for example Comments menu has id `wp-admin-bar-comments`. So to remove this menu code should be like this,
```
// remove links/menus from the admin bar
function my_admin_bar_render() {
global $wp_admin_bar;
$wp_admin_bar->remove_menu('comments');
// Code to remove other items goes here
....
....
}
add_action( 'wp_before_admin_bar_render', 'my_admin_bar_render' );
``` |
331,121 | <p>I am facing an issue while I upload the custom HTML page into my Wordpress site.</p>
<p>The page all alone working fine as I put it in separate folder or if I change its name to <code>index.php</code> .
But then their arise a conflict between this custom page and the other WP theme pages .If I set this as a <code>index.php</code> page in theme or root WP .This page runs swiftly but other theme pages doesn’t work .Just show the same <strong>index</strong> page but with broken <em>css</em></p>
<p>So all I want is not to broke my theme page as well to set custom html page it as my default <strong>Home Page</strong>
How can I achieve this ? I am using divi them</p>
<p>HTML page that I want to set as my Default Home page : <a href="http://filmyoze.com/Default" rel="nofollow noreferrer">http://filmyoze.com/Default</a></p>
<p>Rest of site : <a href="http://filmyoze.com" rel="nofollow noreferrer">http://filmyoze.com</a></p>
| [
{
"answer_id": 331120,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 2,
"selected": true,
"text": "<p><a href=\"https://codex.wordpress.org/Function_Reference/show_admin_bar\" rel=\"nofollow noreferrer\">WordPress page for</a> <code>show_admin_bar</code> says: </p>\n\n<blockquote>\n <p>You cannot turn off the toolbar on the WordPress dashboard</p>\n</blockquote>\n\n<p>However, this trick works </p>\n\n<pre><code> function remove_admin_bar() { ?>\n <style type=\"text/css\">\n body {\n margin-top: -28px;\n }\n\n body.admin-bar #wphead {\n padding-top: 0;\n }\n\n #wpadminbar {\n display: none;\n }\n </style>\n<?php }\n\nadd_action( 'admin_head', 'remove_admin_bar' );\n</code></pre>\n\n<p>In oreder to remove certain menus from admin bar use <code>$wp_admin_bar->remove_menu($id);</code> where <code>$id</code> of a specific menu can be found in Chrome Dev Tool. Each menus' <code><li></code> id in Dev tool is in the form of <code>wp-admin-bar-{id}</code>, for example Comments menu has id <code>wp-admin-bar-comments</code>. So to remove this menu code should be like this,</p>\n\n<pre><code>// remove links/menus from the admin bar\nfunction my_admin_bar_render() {\n global $wp_admin_bar;\n $wp_admin_bar->remove_menu('comments');\n // Code to remove other items goes here\n ....\n ....\n}\nadd_action( 'wp_before_admin_bar_render', 'my_admin_bar_render' );\n</code></pre>\n"
},
{
"answer_id": 331152,
"author": "Tanmay Patel",
"author_id": 62026,
"author_profile": "https://wordpress.stackexchange.com/users/62026",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p><strong><em>Turn Off the Admin Toolbar in Settings</em></strong>. Disable the admin toolbar in your profile settings. To remove the toolbar from your site, go to <strong>Users > Your Profile</strong>. Scroll down to “Toolbar” and check “<strong>Show Toolbar when viewing site.</strong>”</p>\n</blockquote>\n\n<p><strong><em>Reference :</em></strong> <a href=\"https://www.machothemes.com/blog/disable-wordpress-admin-bar/\" rel=\"nofollow noreferrer\">https://www.machothemes.com/blog/disable-wordpress-admin-bar/</a></p>\n"
}
] | 2019/03/08 | [
"https://wordpress.stackexchange.com/questions/331121",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/150945/"
] | I am facing an issue while I upload the custom HTML page into my Wordpress site.
The page all alone working fine as I put it in separate folder or if I change its name to `index.php` .
But then their arise a conflict between this custom page and the other WP theme pages .If I set this as a `index.php` page in theme or root WP .This page runs swiftly but other theme pages doesn’t work .Just show the same **index** page but with broken *css*
So all I want is not to broke my theme page as well to set custom html page it as my default **Home Page**
How can I achieve this ? I am using divi them
HTML page that I want to set as my Default Home page : <http://filmyoze.com/Default>
Rest of site : <http://filmyoze.com> | [WordPress page for](https://codex.wordpress.org/Function_Reference/show_admin_bar) `show_admin_bar` says:
>
> You cannot turn off the toolbar on the WordPress dashboard
>
>
>
However, this trick works
```
function remove_admin_bar() { ?>
<style type="text/css">
body {
margin-top: -28px;
}
body.admin-bar #wphead {
padding-top: 0;
}
#wpadminbar {
display: none;
}
</style>
<?php }
add_action( 'admin_head', 'remove_admin_bar' );
```
In oreder to remove certain menus from admin bar use `$wp_admin_bar->remove_menu($id);` where `$id` of a specific menu can be found in Chrome Dev Tool. Each menus' `<li>` id in Dev tool is in the form of `wp-admin-bar-{id}`, for example Comments menu has id `wp-admin-bar-comments`. So to remove this menu code should be like this,
```
// remove links/menus from the admin bar
function my_admin_bar_render() {
global $wp_admin_bar;
$wp_admin_bar->remove_menu('comments');
// Code to remove other items goes here
....
....
}
add_action( 'wp_before_admin_bar_render', 'my_admin_bar_render' );
``` |
331,143 | <p>I have a custom plugin, using a custom post type for data entry capabilities in the admin section. I would like to use a textarea form, along with the checkboxes, select and text input fields I am presently using. However when I update the bost, my call back receives all the other input fields, not not the textarea field.</p>
<p>The code is rather large, covering lots of different input types, this is a refinement of that draw and save call:</p>
<pre><code>function CustomInput()
{
add_meta_box( 'List_Group1',
__( 'Lists - Card Records : Manual Input', 'myplugin_textdomain' ),
'DrawCallBack',
'customlist',
'normal',
'high',
$args
);
}
add_action( 'add_meta_boxes', 'CustomInput' );
add_action( 'save_post', 'SaveFields');
function DrawCallBack($post)
{
$Record = GetDBRecord();
echo '<textarea id="bizdesc" rows="2" cols="50">';
echo $Record['BizDescp'];
echo '</textarea>';
echo '<input type=text id="YourName" name="YourName" value="' .$Record['Name'] .'"/>'
}
function SaveFields($post_id)
{
$screen = get_current_screen();
if(strcmp($screen->post_type, 'customlist') !=0)
return;
$Desc = sanitize_text_field( $_POST[ 'bizdesc ' ] );
$Name = sanitize_text_field( $_POST[ 'YourName' ] );
}
</code></pre>
<p>The standard input field comes in nicely and correctly. The textarea field does not. Not sure why? </p>
<p>Any ideas?</p>
| [
{
"answer_id": 331144,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 3,
"selected": false,
"text": "<p>You forgot to add <code>name =\"bizdesc\"</code> to your <code>textarea</code>, so this</p>\n\n<pre><code>function DrawCallBack($post)\n{\n $Record = GetDBRecord();\n echo '<textarea id=\"bizdesc\" rows=\"2\" cols=\"50\">';\n echo $Record['BizDescp'];\n echo '</textarea>';\n\n echo '<input type=text id=\"YourName\" name=\"YourName\" value=\"' .$Record['Name'] .'\"/>'\n}\n</code></pre>\n\n<p>should be</p>\n\n<pre><code> function DrawCallBack( $post )\n {\n $Record = GetDBRecord();\n echo '<textarea name=\"bizdesc\" id=\"bizdesc\" rows=\"2\" cols=\"50\">';\n echo esc_textarea( $Record['BizDescp'] );\n echo '</textarea>';\n\n echo '<input type=\"text\" id=\"YourName\" name=\"YourName\" value=\"' .esc_attr( $Record['Name'] ) .'\"/>';\n}\n</code></pre>\n\n<p>I hope this helps.</p>\n"
},
{
"answer_id": 331244,
"author": "Debbie Kurth",
"author_id": 119560,
"author_profile": "https://wordpress.stackexchange.com/users/119560",
"pm_score": 0,
"selected": false,
"text": "<p>Problem solved. It was a field naming problem.</p>\n"
}
] | 2019/03/09 | [
"https://wordpress.stackexchange.com/questions/331143",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/119560/"
] | I have a custom plugin, using a custom post type for data entry capabilities in the admin section. I would like to use a textarea form, along with the checkboxes, select and text input fields I am presently using. However when I update the bost, my call back receives all the other input fields, not not the textarea field.
The code is rather large, covering lots of different input types, this is a refinement of that draw and save call:
```
function CustomInput()
{
add_meta_box( 'List_Group1',
__( 'Lists - Card Records : Manual Input', 'myplugin_textdomain' ),
'DrawCallBack',
'customlist',
'normal',
'high',
$args
);
}
add_action( 'add_meta_boxes', 'CustomInput' );
add_action( 'save_post', 'SaveFields');
function DrawCallBack($post)
{
$Record = GetDBRecord();
echo '<textarea id="bizdesc" rows="2" cols="50">';
echo $Record['BizDescp'];
echo '</textarea>';
echo '<input type=text id="YourName" name="YourName" value="' .$Record['Name'] .'"/>'
}
function SaveFields($post_id)
{
$screen = get_current_screen();
if(strcmp($screen->post_type, 'customlist') !=0)
return;
$Desc = sanitize_text_field( $_POST[ 'bizdesc ' ] );
$Name = sanitize_text_field( $_POST[ 'YourName' ] );
}
```
The standard input field comes in nicely and correctly. The textarea field does not. Not sure why?
Any ideas? | You forgot to add `name ="bizdesc"` to your `textarea`, so this
```
function DrawCallBack($post)
{
$Record = GetDBRecord();
echo '<textarea id="bizdesc" rows="2" cols="50">';
echo $Record['BizDescp'];
echo '</textarea>';
echo '<input type=text id="YourName" name="YourName" value="' .$Record['Name'] .'"/>'
}
```
should be
```
function DrawCallBack( $post )
{
$Record = GetDBRecord();
echo '<textarea name="bizdesc" id="bizdesc" rows="2" cols="50">';
echo esc_textarea( $Record['BizDescp'] );
echo '</textarea>';
echo '<input type="text" id="YourName" name="YourName" value="' .esc_attr( $Record['Name'] ) .'"/>';
}
```
I hope this helps. |
331,201 | <p>In the legacy (classic editor) it was possible to add buttons to the editor toolbar via tinymce API, that will add shortcode at cursor.</p>
<p>seems like this is not supported anymore from the <a href="https://go.tiny.cloud/blog/gutenberg-tinymce-faq/" rel="nofollow noreferrer">tinymce FQA</a> and this <a href="https://github.com/danielbachhuber/gutenberg-migration-guide/blob/master/tinymce-toolbar-button.md" rel="nofollow noreferrer">Gutenberg migration guide</a> </p>
<p>Seems like it would be possible with the plugin <a href="https://wordpress.org/plugins/tinymce-advanced/" rel="nofollow noreferrer">tinymce advanced</a> but I wonder what is today the best practice to add add a button to a tiny mce button to the the simple text editor of paragraph block. </p>
<p>The <a href="https://github.com/WordPress/gutenberg/tree/master/docs/designers-developers/developers/tutorials/format-api" rel="nofollow noreferrer">format API</a> allows to add a custom format with tag and class around text, but does not to support adding string after text</p>
<p>Also, seems like this in the <a href="https://github.com/WordPress/gutenberg/issues/13778" rel="nofollow noreferrer">roadmap</a> of the format API, but its not clear id its possible or not.</p>
<p>What is the best practice to add a button to tinymce editor tollbar in a simple paragraph block which will add text (shortcode for example) at cursor?</p>
<p>I added screenshot to clarify to which toolbar I refer. </p>
<p><a href="https://i.stack.imgur.com/U2V0v.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/U2V0v.png" alt="Paragraph tinymce editor toolbar"></a></p>
| [
{
"answer_id": 358854,
"author": "Didier Haller",
"author_id": 182874,
"author_profile": "https://wordpress.stackexchange.com/users/182874",
"pm_score": 0,
"selected": false,
"text": "<p>you can do this with this filter :</p>\n\n<pre><code>function do_shortcode_in_gut($block_content, $block) {\n return do_shortcode($block_content);\n}\nadd_filter( 'render_block', 'do_shortcode_in_gut', 99, 2 );\n</code></pre>\n\n<p>This filtering your block render and do shortcode.</p>\n\n<p><a href=\"https://i.stack.imgur.com/TqF3G.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/TqF3G.png\" alt=\"This is my exemple with Date shortcode\"></a></p>\n\n<p>You can see in this screenshot I use a date shortcode with attributes.\nAnd the result :\n<a href=\"https://i.stack.imgur.com/a03d9.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/a03d9.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 372598,
"author": "I'm_With_Stupid",
"author_id": 192824,
"author_profile": "https://wordpress.stackexchange.com/users/192824",
"pm_score": 2,
"selected": false,
"text": "<p>They have actually fixed it so you can just add the shortcode within the paragraph content and it works.</p>\n<p>As simple as</p>\n<pre><code>...However, when [expand tag="span" title="this trigger" targtag="span"]hidden content[/expand] is clicked…\n</code></pre>\n<p>That would be the contents of a paragraph block with inline shortcode. See <a href=\"https://github.com/WordPress/gutenberg/issues/3806\" rel=\"nofollow noreferrer\">this</a> for more information.</p>\n"
}
] | 2019/03/10 | [
"https://wordpress.stackexchange.com/questions/331201",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/62909/"
] | In the legacy (classic editor) it was possible to add buttons to the editor toolbar via tinymce API, that will add shortcode at cursor.
seems like this is not supported anymore from the [tinymce FQA](https://go.tiny.cloud/blog/gutenberg-tinymce-faq/) and this [Gutenberg migration guide](https://github.com/danielbachhuber/gutenberg-migration-guide/blob/master/tinymce-toolbar-button.md)
Seems like it would be possible with the plugin [tinymce advanced](https://wordpress.org/plugins/tinymce-advanced/) but I wonder what is today the best practice to add add a button to a tiny mce button to the the simple text editor of paragraph block.
The [format API](https://github.com/WordPress/gutenberg/tree/master/docs/designers-developers/developers/tutorials/format-api) allows to add a custom format with tag and class around text, but does not to support adding string after text
Also, seems like this in the [roadmap](https://github.com/WordPress/gutenberg/issues/13778) of the format API, but its not clear id its possible or not.
What is the best practice to add a button to tinymce editor tollbar in a simple paragraph block which will add text (shortcode for example) at cursor?
I added screenshot to clarify to which toolbar I refer.
[](https://i.stack.imgur.com/U2V0v.png) | They have actually fixed it so you can just add the shortcode within the paragraph content and it works.
As simple as
```
...However, when [expand tag="span" title="this trigger" targtag="span"]hidden content[/expand] is clicked…
```
That would be the contents of a paragraph block with inline shortcode. See [this](https://github.com/WordPress/gutenberg/issues/3806) for more information. |
331,217 | <p>I downloaded a starter theme (Underscores). I want to exclude first 3 post from my loop on index page.</p>
<p>Here is the loop;</p>
<pre><code><?php
if ( have_posts() ) :
if ( is_home() && ! is_front_page() ) :
?>
<header>
<h1 class="page-title screen-reader-text"><?php single_post_title(); ?></h1>
</header>
<?php
endif;
/* Start the Loop */
while ( have_posts() ) :
the_post();
get_template_part( 'template-parts/content', get_post_type() );
endwhile;
the_posts_navigation();
else :
get_template_part( 'template-parts/content', 'none' );
endif;
?>
</code></pre>
<p>Thanks.</p>
| [
{
"answer_id": 358854,
"author": "Didier Haller",
"author_id": 182874,
"author_profile": "https://wordpress.stackexchange.com/users/182874",
"pm_score": 0,
"selected": false,
"text": "<p>you can do this with this filter :</p>\n\n<pre><code>function do_shortcode_in_gut($block_content, $block) {\n return do_shortcode($block_content);\n}\nadd_filter( 'render_block', 'do_shortcode_in_gut', 99, 2 );\n</code></pre>\n\n<p>This filtering your block render and do shortcode.</p>\n\n<p><a href=\"https://i.stack.imgur.com/TqF3G.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/TqF3G.png\" alt=\"This is my exemple with Date shortcode\"></a></p>\n\n<p>You can see in this screenshot I use a date shortcode with attributes.\nAnd the result :\n<a href=\"https://i.stack.imgur.com/a03d9.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/a03d9.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 372598,
"author": "I'm_With_Stupid",
"author_id": 192824,
"author_profile": "https://wordpress.stackexchange.com/users/192824",
"pm_score": 2,
"selected": false,
"text": "<p>They have actually fixed it so you can just add the shortcode within the paragraph content and it works.</p>\n<p>As simple as</p>\n<pre><code>...However, when [expand tag="span" title="this trigger" targtag="span"]hidden content[/expand] is clicked…\n</code></pre>\n<p>That would be the contents of a paragraph block with inline shortcode. See <a href=\"https://github.com/WordPress/gutenberg/issues/3806\" rel=\"nofollow noreferrer\">this</a> for more information.</p>\n"
}
] | 2019/03/10 | [
"https://wordpress.stackexchange.com/questions/331217",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93501/"
] | I downloaded a starter theme (Underscores). I want to exclude first 3 post from my loop on index page.
Here is the loop;
```
<?php
if ( have_posts() ) :
if ( is_home() && ! is_front_page() ) :
?>
<header>
<h1 class="page-title screen-reader-text"><?php single_post_title(); ?></h1>
</header>
<?php
endif;
/* Start the Loop */
while ( have_posts() ) :
the_post();
get_template_part( 'template-parts/content', get_post_type() );
endwhile;
the_posts_navigation();
else :
get_template_part( 'template-parts/content', 'none' );
endif;
?>
```
Thanks. | They have actually fixed it so you can just add the shortcode within the paragraph content and it works.
As simple as
```
...However, when [expand tag="span" title="this trigger" targtag="span"]hidden content[/expand] is clicked…
```
That would be the contents of a paragraph block with inline shortcode. See [this](https://github.com/WordPress/gutenberg/issues/3806) for more information. |
331,256 | <p>I have a custom plugin that I'm trying to edit. I didn't develop the plugin. I just need to add a textarea to it and save the contents. I have the field added, but I can't get it to save. This simply needs to be on the backend in the admin. This field will not be visible anywhere but this page.</p>
<p>Here's my code: </p>
<pre><code><form method="post">
<table class="widefat">
<thead>
<tr>
<th style="width: 15%;">CHEF Account Info</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<th><label><?php echo _e( 'Status', 'chef' ); ?></label></th>
<td>
<input type="text" readonly="" onfocus="this.select()" value="<?php echo $chef_config->get_chef_status_title( $user->chef_status ); ?>" class="regular-text">
<?php if ( $user->chef_status == 'rejected' ): ?>
<br><br><textarea name="chef_status_rejection_notes" readonly="" onfocus="this.select()" class="um-forms-field um-long-field" rows="6"><?php echo $user->chef_status_rejection_notes; ?></textarea>
<?php endif; ?>
</td>
</tr>
<tr>
<th><label><?php echo _e( 'User Role', 'chef' ); ?></label></th>
<td><input type="text" readonly="" onfocus="this.select()" value="<?php echo $chef_config->get_chef_role_title( $user->roles[0] ); ?>" class="regular-text"></td>
</tr>
<tr>
<th><label><?php echo _e( 'Experience Level', 'chef' ); ?></label></th>
<td><input type="text" readonly="" onfocus="this.select()" value="<?php echo $user->chef_experience_level; ?>" class="regular-text"></td>
</tr>
<tr>
<th><label><?php echo _e( 'Registered', 'chef' ); ?></label></th>
<td><input type="text" readonly="" onfocus="this.select()" value="<?php echo date_format( date_create( $user->user_registered ), "F j\, Y @ h:i:s A" ); ?>" class="regular-text"></td>
</tr>
<tr>
<th><label><?php echo _e( 'Resources Access', 'chef' ); ?></label></th>
<td>
<?php
$terms = get_terms('resource_category');
$chef_profile_resources_access = $user->chef_profile_resources_access;
if ( empty( $chef_profile_resources_access ) ) {
$chef_profile_resources_access = [];
}
?>
<?php $terms = get_terms('resource_category'); ?>
<select name="chef_profile_resources_access[]" multiple>
<?php foreach ( $terms as $term ): ?>
<option value="<?php echo $term->term_id; ?>" <?php if ( in_array( $term->term_id, $chef_profile_resources_access ) ): echo 'selected'; endif; ?>><?php echo $term->name; ?></option>
<?php endforeach; ?>
</select>
</td>
</tr>
<tr>
<th><label><?php echo _e( 'Reporting Form', 'chef' ); ?></label></th>
<td>
<?php
$form_pages = get_pages( ['parent' => 1520 ] );
$chef_profile_reporting_form = $user->chef_profile_reporting_form;
if ( empty( $chef_profile_reporting_form ) ) {
$chef_profile_reporting_form = '';
}
?>
<select name="chef_profile_reporting_form">
<option value="">None</option>
<?php foreach ( $form_pages as $page ): ?>
<option value="<?php echo $page->ID; ?>" <?php if ( $page->ID == $chef_profile_reporting_form ): echo 'selected'; endif; ?>><?php echo $page->post_title; ?></option>
<?php endforeach; ?>
</select>
</td>
</tr>
<tr>
<th><label><?php echo _e( 'CHEF Notes', 'chef' ); ?></label></th>
<td><textarea id="chef_profile_notes" rows="5" onfocus="this.select()" value="<?php echo $user->chef_profile_notes; ?>" class="regular-text" /> </textarea></td>
</tr>
</tbody>
</table>
<div class="user-approve-reject-actions">
<input type="hidden" name="action" value="user_permissions" />
<button class="button button-primary">Save changes</button>
</div>
</form>
</code></pre>
<p>My textarea is at the bottom. What do I need to do to get it to save? </p>
| [
{
"answer_id": 331260,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 3,
"selected": true,
"text": "<p>Your <code>textarea</code> needs to have a proper <code>name</code> in order for the browser to send it to the server for processing such as be saved to a database.</p>\n\n<p>Secondly, <code>textarea</code> fields do not have a <code>value</code> and they also need a closing tag <code></textarea></code> because <code>textarea</code> is a multi-line form field.</p>\n\n<p>So the proper format is:</p>\n\n<pre><code><textarea name=\"chef_profile_notes\" id=\"chef_profile_notes\" ...other attributes...>\n <?php echo esc_textarea( $user->chef_profile_notes ): ?><!-- the field value -->\n</textarea>\n</code></pre>\n\n<p>And you can see I also use <a href=\"https://codex.wordpress.org/Function_Reference/esc_textarea\" rel=\"nofollow noreferrer\"><code>esc_textarea()</code></a> which is to secure the output sent/displayed to the user. See <a href=\"https://codex.wordpress.org/Data_Validation\" rel=\"nofollow noreferrer\">Data Validation</a> for more details.</p>\n"
},
{
"answer_id": 331265,
"author": "butalin",
"author_id": 162878,
"author_profile": "https://wordpress.stackexchange.com/users/162878",
"pm_score": 0,
"selected": false,
"text": "<p>This plugin use ajax to save data, ajax call the <code>user_permissions</code> function that is already defined in the plugin classes, if you can share this function, may you found how data is structured and saved and you could add yours.</p>\n"
}
] | 2019/03/10 | [
"https://wordpress.stackexchange.com/questions/331256",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145236/"
] | I have a custom plugin that I'm trying to edit. I didn't develop the plugin. I just need to add a textarea to it and save the contents. I have the field added, but I can't get it to save. This simply needs to be on the backend in the admin. This field will not be visible anywhere but this page.
Here's my code:
```
<form method="post">
<table class="widefat">
<thead>
<tr>
<th style="width: 15%;">CHEF Account Info</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<th><label><?php echo _e( 'Status', 'chef' ); ?></label></th>
<td>
<input type="text" readonly="" onfocus="this.select()" value="<?php echo $chef_config->get_chef_status_title( $user->chef_status ); ?>" class="regular-text">
<?php if ( $user->chef_status == 'rejected' ): ?>
<br><br><textarea name="chef_status_rejection_notes" readonly="" onfocus="this.select()" class="um-forms-field um-long-field" rows="6"><?php echo $user->chef_status_rejection_notes; ?></textarea>
<?php endif; ?>
</td>
</tr>
<tr>
<th><label><?php echo _e( 'User Role', 'chef' ); ?></label></th>
<td><input type="text" readonly="" onfocus="this.select()" value="<?php echo $chef_config->get_chef_role_title( $user->roles[0] ); ?>" class="regular-text"></td>
</tr>
<tr>
<th><label><?php echo _e( 'Experience Level', 'chef' ); ?></label></th>
<td><input type="text" readonly="" onfocus="this.select()" value="<?php echo $user->chef_experience_level; ?>" class="regular-text"></td>
</tr>
<tr>
<th><label><?php echo _e( 'Registered', 'chef' ); ?></label></th>
<td><input type="text" readonly="" onfocus="this.select()" value="<?php echo date_format( date_create( $user->user_registered ), "F j\, Y @ h:i:s A" ); ?>" class="regular-text"></td>
</tr>
<tr>
<th><label><?php echo _e( 'Resources Access', 'chef' ); ?></label></th>
<td>
<?php
$terms = get_terms('resource_category');
$chef_profile_resources_access = $user->chef_profile_resources_access;
if ( empty( $chef_profile_resources_access ) ) {
$chef_profile_resources_access = [];
}
?>
<?php $terms = get_terms('resource_category'); ?>
<select name="chef_profile_resources_access[]" multiple>
<?php foreach ( $terms as $term ): ?>
<option value="<?php echo $term->term_id; ?>" <?php if ( in_array( $term->term_id, $chef_profile_resources_access ) ): echo 'selected'; endif; ?>><?php echo $term->name; ?></option>
<?php endforeach; ?>
</select>
</td>
</tr>
<tr>
<th><label><?php echo _e( 'Reporting Form', 'chef' ); ?></label></th>
<td>
<?php
$form_pages = get_pages( ['parent' => 1520 ] );
$chef_profile_reporting_form = $user->chef_profile_reporting_form;
if ( empty( $chef_profile_reporting_form ) ) {
$chef_profile_reporting_form = '';
}
?>
<select name="chef_profile_reporting_form">
<option value="">None</option>
<?php foreach ( $form_pages as $page ): ?>
<option value="<?php echo $page->ID; ?>" <?php if ( $page->ID == $chef_profile_reporting_form ): echo 'selected'; endif; ?>><?php echo $page->post_title; ?></option>
<?php endforeach; ?>
</select>
</td>
</tr>
<tr>
<th><label><?php echo _e( 'CHEF Notes', 'chef' ); ?></label></th>
<td><textarea id="chef_profile_notes" rows="5" onfocus="this.select()" value="<?php echo $user->chef_profile_notes; ?>" class="regular-text" /> </textarea></td>
</tr>
</tbody>
</table>
<div class="user-approve-reject-actions">
<input type="hidden" name="action" value="user_permissions" />
<button class="button button-primary">Save changes</button>
</div>
</form>
```
My textarea is at the bottom. What do I need to do to get it to save? | Your `textarea` needs to have a proper `name` in order for the browser to send it to the server for processing such as be saved to a database.
Secondly, `textarea` fields do not have a `value` and they also need a closing tag `</textarea>` because `textarea` is a multi-line form field.
So the proper format is:
```
<textarea name="chef_profile_notes" id="chef_profile_notes" ...other attributes...>
<?php echo esc_textarea( $user->chef_profile_notes ): ?><!-- the field value -->
</textarea>
```
And you can see I also use [`esc_textarea()`](https://codex.wordpress.org/Function_Reference/esc_textarea) which is to secure the output sent/displayed to the user. See [Data Validation](https://codex.wordpress.org/Data_Validation) for more details. |
331,262 | <p>Trying to get this function to work.
But keep getting a <strong>jQuery not defined</strong> error.</p>
<p>I have tried many variations here to get the jQuery to work:
<a href="https://blog.templatetoaster.com/fix-jquery-is-not-defined-error/" rel="nofollow noreferrer">https://blog.templatetoaster.com/fix-jquery-is-not-defined-error/</a></p>
<pre><code>add_action( 'load-post.php', function () {
$status = "status-started";
if($status == 'status-started'):
?>
<script>
jQuery(document).ready(function($) {
/* write your JavaScript code here */
$('.btn-start').trigger('click');
console.log('Started successfully!');
});
</script>
<?php
endif;
} );
</code></pre>
| [
{
"answer_id": 331263,
"author": "butalin",
"author_id": 162878,
"author_profile": "https://wordpress.stackexchange.com/users/162878",
"pm_score": 2,
"selected": false,
"text": "<p>You must call jQuery at the end of the file, when your document is ready.</p>\n\n<p>Try to add the action to the <code>wp_footer</code> or use <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\">wp_enqueue_script</a> .</p>\n"
},
{
"answer_id": 331264,
"author": "butlerblog",
"author_id": 38603,
"author_profile": "https://wordpress.stackexchange.com/users/38603",
"pm_score": 3,
"selected": true,
"text": "<p>You have your jQuery hooked too early. The jQuery library has not yet loaded when the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow noreferrer\"><code>load-(page)</code></a> action is fired.</p>\n\n<p>Use <a href=\"https://developer.wordpress.org/reference/hooks/admin_print_scripts/\" rel=\"nofollow noreferrer\"><code>admin_print_scripts</code></a> to print inline scripts. That action comes after scripts are enqueued.</p>\n\n<p>Here's your original code using <code>admin_print_scripts</code>:</p>\n\n<pre><code>add_action( 'admin_print_scripts', function () { \n\n$status = \"status-started\";\n\nif($status == 'status-started'):\n ?>\n <script>\n jQuery(document).ready(function($) { \n /* write your JavaScript code here */\n $('.btn-start').trigger('click');\n console.log('Started successfully!');\n });\n </script>\n\n<?php \nendif;\n\n} );\n</code></pre>\n\n<p>An alternative to using <code>admin_print_scripts</code> would be to use <a href=\"https://developer.wordpress.org/reference/hooks/admin_print_footer_scripts/\" rel=\"nofollow noreferrer\"><code>admin_print_footer_scripts</code></a>, which is essentially the same thing, but in the footer instead of the header. Either is generally OK and whether you do it in the header or the footer is sometimes a matter of preference and sometimes a matter of necessity. So it will depend on the actual use case.</p>\n\n<p>For anyone wondering why I didn't suggest using another hook such as wp_head or wp_footer, there are two reasons. First, it's not what those hooks were intended for. Using them would get your scripts out of sequence with where they really should be (although in a lot of cases they would work just fine). Second, they are not admin specific hooks. The question of a <code>load-(page)</code> action indicates this is an admin side process, so use the proper admin side hooks.</p>\n\n<p>I would say similar things about the use of various \"enqueue\" hooks. First, don't use an enqueue that is not admin side specific (speaking specifically of this original post and not in generalities). Second, enqueueing is for libraries and static scripts. If you're printing out scripts (especially ones that may be dynamic), use the _print_scripts hooks instead.</p>\n"
}
] | 2019/03/10 | [
"https://wordpress.stackexchange.com/questions/331262",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/29133/"
] | Trying to get this function to work.
But keep getting a **jQuery not defined** error.
I have tried many variations here to get the jQuery to work:
<https://blog.templatetoaster.com/fix-jquery-is-not-defined-error/>
```
add_action( 'load-post.php', function () {
$status = "status-started";
if($status == 'status-started'):
?>
<script>
jQuery(document).ready(function($) {
/* write your JavaScript code here */
$('.btn-start').trigger('click');
console.log('Started successfully!');
});
</script>
<?php
endif;
} );
``` | You have your jQuery hooked too early. The jQuery library has not yet loaded when the [`load-(page)`](https://codex.wordpress.org/Plugin_API/Action_Reference) action is fired.
Use [`admin_print_scripts`](https://developer.wordpress.org/reference/hooks/admin_print_scripts/) to print inline scripts. That action comes after scripts are enqueued.
Here's your original code using `admin_print_scripts`:
```
add_action( 'admin_print_scripts', function () {
$status = "status-started";
if($status == 'status-started'):
?>
<script>
jQuery(document).ready(function($) {
/* write your JavaScript code here */
$('.btn-start').trigger('click');
console.log('Started successfully!');
});
</script>
<?php
endif;
} );
```
An alternative to using `admin_print_scripts` would be to use [`admin_print_footer_scripts`](https://developer.wordpress.org/reference/hooks/admin_print_footer_scripts/), which is essentially the same thing, but in the footer instead of the header. Either is generally OK and whether you do it in the header or the footer is sometimes a matter of preference and sometimes a matter of necessity. So it will depend on the actual use case.
For anyone wondering why I didn't suggest using another hook such as wp\_head or wp\_footer, there are two reasons. First, it's not what those hooks were intended for. Using them would get your scripts out of sequence with where they really should be (although in a lot of cases they would work just fine). Second, they are not admin specific hooks. The question of a `load-(page)` action indicates this is an admin side process, so use the proper admin side hooks.
I would say similar things about the use of various "enqueue" hooks. First, don't use an enqueue that is not admin side specific (speaking specifically of this original post and not in generalities). Second, enqueueing is for libraries and static scripts. If you're printing out scripts (especially ones that may be dynamic), use the \_print\_scripts hooks instead. |
331,309 | <p>There are <a href="https://wordpress.org/support/topic/cookie-error-site-not-letting-me-log-in/" rel="nofollow noreferrer">many</a> <a href="https://stackoverflow.com/questions/20941328/wordpress-admin-login-cookies-blocked-error-after-moving-servers">many</a> <a href="https://premium.wpmudev.org/forums/topic/error-cookies-are-blocked-or-not-supported-by-your-browser-you-must-enable-cookies-to-use-wordpres" rel="nofollow noreferrer">many</a> <a href="https://wpglorify.com/cookies-blocked-error-wordpress-admin/" rel="nofollow noreferrer">many</a> pages about this issue (and I could keep going).</p>
<h2>My question: Why does it happen?!</h2>
<p>I'm experiencing it on my local development environment, and I want to ensure that it doesn't happen on production.</p>
<p>Why does this happen?<br />
And why is it, that a simple refresh can bypass it?</p>
<hr />
<h2>The solution(s)</h2>
<p>For those who just came here for a solution, then it is:</p>
<p><strong>1)</strong> Just try and refresh the page.</p>
<p><strong>2)</strong> Try putting this in your <code>wp-config.php</code></p>
<pre><code>define('ADMIN_COOKIE_PATH', '/');
define('COOKIE_DOMAIN', '');
define('COOKIEPATH', '');
define('SITECOOKIEPATH', '');
</code></pre>
<p><strong>3)</strong> Or try putting this in your <code>wp-config.php</code></p>
<pre><code>define('COOKIE_DOMAIN', $_SERVER['HTTP_HOST'] );
</code></pre>
<p><strong>4)</strong> Or putting this in your <code>functions.php</code>:</p>
<pre><code>setcookie(TEST_COOKIE, 'WP Cookie check', 0, COOKIEPATH, COOKIE_DOMAIN);
if ( SITECOOKIEPATH != COOKIEPATH ) setcookie(TEST_COOKIE, 'WP Cookie check', 0, SITECOOKIEPATH, COOKIE_DOMAIN);
</code></pre>
<p><strong>5)</strong> Login-page cached by W3 Cache</p>
<p>If you've changed the login-url (like with <a href="https://wordpress.org/plugins/wps-hide-login/" rel="nofollow noreferrer">WPS Hide Login</a>), then remember to add the new URL as an exception. In W3 Cache it's under: Performance >> Page Cache >> Never cache the following pages. <em>This cost me half a day of my life, to figure this out!</em></p>
| [
{
"answer_id": 334134,
"author": "MikeNGarrett",
"author_id": 1670,
"author_profile": "https://wordpress.stackexchange.com/users/1670",
"pm_score": 4,
"selected": true,
"text": "<p>When you log in to the admin WordPress sets <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies\" rel=\"noreferrer\">cookies</a> (in PHP) to keep you logged in while you navigate around your site. If this fails, you get the error message, \"Cookies are blocked or not supported by your browser.\" </p>\n\n<p>This could fail in a couple different ways, but before we dig into those situations, let's take a look at the source of these error messages: </p>\n\n<blockquote>\n <p><code>wp-login.php</code> v5.1.1</p>\n</blockquote>\n\n<pre><code> if ( empty( $_COOKIE[ LOGGED_IN_COOKIE ] ) ) {\n if ( headers_sent() ) {\n $user = new WP_Error(\n 'test_cookie',\n sprintf(\n /* translators: 1: Browser cookie documentation URL, 2: Support forums URL */\n __( '<strong>ERROR</strong>: Cookies are blocked due to unexpected output. For help, please see <a href=\"%1$s\">this documentation</a> or try the <a href=\"%2$s\">support forums</a>.' ),\n __( 'https://codex.wordpress.org/Cookies' ),\n __( 'https://wordpress.org/support/' )\n )\n );\n } elseif ( isset( $_POST['testcookie'] ) && empty( $_COOKIE[ TEST_COOKIE ] ) ) {\n // If cookies are disabled we can't log in even with a valid user+pass\n $user = new WP_Error(\n 'test_cookie',\n sprintf(\n /* translators: %s: Browser cookie documentation URL */\n __( '<strong>ERROR</strong>: Cookies are blocked or not supported by your browser. You must <a href=\"%s\">enable cookies</a> to use WordPress.' ),\n __( 'https://codex.wordpress.org/Cookies' )\n )\n );\n }\n }\n</code></pre>\n\n<h1>Failure Context</h1>\n\n<h2>1. <code>LOGGED_IN_COOKIE</code> check</h2>\n\n<p>If the <code>LOGGED_IN_COOKIE</code> is missing, something has gone wrong and we cannot continue. This is the first indication there's a problem. The code then checks for 2 more specific issues to clarify the error message returned.</p>\n\n<h2>2. <code>headers_sent</code> check</h2>\n\n<p>The first test is for <code>headers_sent</code> which is a core PHP function to determine whether or not your response headers have been put together and sent back to the user making the request. They should not be sent by this point. If they are, you have a problem that needs to be resolved before a user can log in. </p>\n\n<p>This is also the least commonly addressed case for most issues raised here for this question. It also generates a slightly different error message. </p>\n\n<blockquote>\n <p>Cookies are blocked due to unexpected output.</p>\n</blockquote>\n\n<h2>3. Test Cookie status</h2>\n\n<p>In this test, WordPress tried setting a test cookie and that failed. Notice that the check is for both the <code>POST</code> request parameter <strong>and</strong> missing cookie. The <code>POST</code> parameter comes from a hidden field on the login form: <code><input type=\"hidden\" name=\"testcookie\" value=\"1\" /></code>. The cookie name default is <code>wordpress_test_cookie</code>, but can be changed via the <code>TEST_COOKIE</code> constant. More on this in a bit.</p>\n\n<p>This is the most common scenario. Something has gone wrong that prevents either the <code>POST</code> parameter from being set or the test cookie from being set. </p>\n\n<p>Let's take a look at the scenarios that could cause this to happen.</p>\n\n<h1>Common Problems and Solutions</h1>\n\n<h2>1. Your browser blocks cookies</h2>\n\n<p>This is the original intention of these checks. It's common for browsers to block \"unsafe\" cookies or common trackers. It's even pretty common for most people to block cookies altogether and only allow certain cookies to be set after they're discovered (or not at all). This is why the error message is worded this way. </p>\n\n<p><strong>Solution:</strong> <a href=\"https://www.whatismybrowser.com/guides/how-to-enable-cookies/\" rel=\"noreferrer\">enable cookies in your browser</a>.</p>\n\n<h2>2. Your site is sending headers prematurely</h2>\n\n<p>Somewhere in your code you probably have a call to send headers like this: <code>header('Location: https://google.com/');</code> (for example). Sending a header this way can kill off the process of building the entire header before sending it as a response. I'm not going to go into more detail here because you'd also get a different error message. Read more: <a href=\"https://wordpress.stackexchange.com/questions/208878/login-page-error-cookies-are-blocked-due-to-unexpected-output\">Login page error cookies are blocked due to unexpected output</a>. </p>\n\n<p><strong>Solution:</strong> check that you're not sending headers prematurely.</p>\n\n<h2>3. Cookies aren't being saved</h2>\n\n<p>This is the most common situation developers run into, especially when migrating sites. </p>\n\n<pre><code>setcookie( $name , $value, $expires ); \n</code></pre>\n\n<p><a href=\"https://www.php.net/manual/en/function.setcookie.php\" rel=\"noreferrer\">Cookies are fairly simple</a>. They typically have a name, value, and time when they expire. The rest of the parameters are usually left to the defaults. </p>\n\n<pre><code>setcookie( $name , $value, $expires, $path, $domain, $secure, $httponly );\n</code></pre>\n\n<p>WordPress explicitly sets these defaults for path, domain, and protocol. If these aren't 100% correct, the cookie just disappears. This is for security. You wouldn't want cookies you set on your site to be available to anyone else, otherwise someone could access your site admin and WordPress authentication would be worthless. </p>\n\n<blockquote>\n <p><strong>NOTE:</strong> Path is the base path the cookie is available from. If it's set to <code>/</code>, then it will be available to the entire site. If it's set to <code>/wp-admin</code>, only urls that start with <code>/wp-admin</code> will be able to access it. For example, you would not see it on your site's homepage. </p>\n</blockquote>\n\n<p><strong>Solution:</strong> This is a bit more complicated. Let's take deeper dive.</p>\n\n<h3>The test cookie</h3>\n\n<blockquote>\n <p>`wp-login.php v5.1.1</p>\n</blockquote>\n\n<pre><code>$secure = ( 'https' === parse_url( wp_login_url(), PHP_URL_SCHEME ) );\nsetcookie( TEST_COOKIE, 'WP Cookie check', 0, COOKIEPATH, COOKIE_DOMAIN, $secure );\nif ( SITECOOKIEPATH != COOKIEPATH ) {\n setcookie( TEST_COOKIE, 'WP Cookie check', 0, SITECOOKIEPATH, COOKIE_DOMAIN, $secure );\n}\n</code></pre>\n\n<p>First, WordPress is checking your login url to see if it's using https or not. <code>$secure</code> is being used to set the cookie to respond to http or https requests, <strong>not both</strong>.</p>\n\n<h3>Cookie constants</h3>\n\n<p>Next, we have to look into some of these constants that are muddying the waters. </p>\n\n<p><code>COOKIEPATH</code> and <code>SITECOOKIEPATH</code> determine the path the cookie is available from. <code>SITECOOKIEPATH</code> overrides <code>COOKIEPATH</code>. Keep this in mind. This will be important later. </p>\n\n<p><code>COOKIE_DOMAIN</code> determines the domain the cookie is available from, eg <code>yourdomains.com</code>. If it's set to false, it will use the current domain. </p>\n\n<p><code>ADMIN_COOKIE_PATH</code> isn't in the source above, but will get used later. Bear with me on this one. This is the path to your WordPress dashboard.</p>\n\n<p>These constants are set by WordPress, but can be changed. Let's take a look at the source.</p>\n\n<blockquote>\n <p><code>/wp-includes/default-constants.php</code> v5.1.1</p>\n</blockquote>\n\n<pre><code>if ( ! defined( 'COOKIEPATH' ) ) {\n define( 'COOKIEPATH', preg_replace( '|https?://[^/]+|i', '', get_option( 'home' ) . '/' ) );\n}\n\nif ( ! defined( 'SITECOOKIEPATH' ) ) {\n define( 'SITECOOKIEPATH', preg_replace( '|https?://[^/]+|i', '', get_option( 'siteurl' ) . '/' ) );\n}\n\nif ( ! defined( 'ADMIN_COOKIE_PATH' ) ) {\n define( 'ADMIN_COOKIE_PATH', SITECOOKIEPATH . 'wp-admin' );\n}\nif ( ! defined( 'TEST_COOKIE' ) ) {\n define( 'TEST_COOKIE', 'wordpress_test_cookie' );\n}\n</code></pre>\n\n<p><em>Now we're starting to get some clarity.</em></p>\n\n<p><code>COOKIEPATH</code> uses your home url stored in your database. This is typically set in your <code>wp-config.php</code> file as the constant <code>WP_HOME</code>. </p>\n\n<p><code>SITECOOKIEPATH</code> overrides <code>COOKIEPATH</code> (remember?) and that comes from your site url stored in the database. In your <code>wp-config.php</code> file this is your <code>WP_SITEURL</code> constant. </p>\n\n<p><strong>If these don't match, there's a chance you'll have a problem.</strong></p>\n\n<p>This is why you see people recommend setting these with a server parameter:</p>\n\n<pre><code>define('WP_SITEURL', 'https://' . $_SERVER['HTTP_HOST']);\ndefine('WP_HOME', 'https://' . $_SERVER['HTTP_HOST']);\n</code></pre>\n\n<p>This configuration makes sure your site responds with the correct domain. It works in most cases, but <strong>should be used cautiously.</strong></p>\n\n<blockquote>\n <p><strong>Disclaimer:</strong> You should always do a search/replace in your database for old urls and change these to your new url. Please don't think the above will fix everything. It won't.</p>\n</blockquote>\n\n<h3>Debugging cookies</h3>\n\n<p>In order to debug this issue, try outputting these constants on your <code>wp-login.php</code> page like this:</p>\n\n<pre><code>add_action( 'login_init', 'my_login_init' );\nfunction my_login_init() {\n echo '<b>Cookie path:</b> ';\n var_dump( COOKIEPATH );\n echo '<br /><b>Cookie site path:</b> ';\n var_dump( SITECOOKIEPATH );\n echo '<br /><b>Cookie domain:</b> ';\n var_dump( COOKIE_DOMAIN );\n echo '<br /><b>Admin cookie path:</b> ';\n var_dump( ADMIN_COOKIE_PATH );\n}\n</code></pre>\n\n<p>This will give you a good idea of what parameters are being used to set your cookies. If these don't match your site's settings or your expectations, you need to address it to ensure your cookie is being set correctly. </p>\n\n<p>You can set these explicitly in your <code>wp-config.php</code> file: </p>\n\n<pre><code>// False setting for the domain uses the current domain.\ndefine('COOKIE_DOMAIN', false);\n// Setting to / will only work if your site is set to the root domain.\ndefine('COOKIEPATH', '/');\ndefine('SITECOOKIEPATH', '/'); \n</code></pre>\n\n<h3>Authorization cookies</h3>\n\n<p>All the above have to do with the test cookie which is the source of the error message, but there's one more step beyond that: your authorization cookies. </p>\n\n<p>WordPress sets a bunch of cookies, depending on the context. For logging in, you'll need these: </p>\n\n<ol>\n<li><code>'wordpress_logged_in_' . COOKIEHASH</code></li>\n<li>and either <code>'wordpress_' . COOKIEHASH</code> <strong>or</strong> <code>'wordpress_sec_' . COOKIEHASH</code> </li>\n</ol>\n\n<p>These cookies need to have the right path, protocol and domain or you won't be able to log in. </p>\n\n<p>Fortunately, most of those checks are taken care of with the test cookie we already looked at. The only difference is with the admin path: </p>\n\n<pre><code>define( 'ADMIN_COOKIE_PATH', SITECOOKIEPATH . 'wp-admin' );\n</code></pre>\n\n<p>If the path to your admin is different than <code>yourdomain.com/wp-admin</code>, you need to set this in your <code>wp-config.php</code> file like this:</p>\n\n<pre><code>define( 'ADMIN_COOKIE_PATH', '/path/to/wp-admin' );\n</code></pre>\n\n<h1>Conclusion</h1>\n\n<p>This is a complicated problem. There are multiple causes for what appears to be the same issue. </p>\n\n<p>If you get this error, you will have to do some debugging to find out what's going on. Here are some suggestions:</p>\n\n<ol>\n<li>Always check your browser first. Make sure it's able to save cookies from PHP.</li>\n<li>If you recently migrated, check for old urls in your database, then check your <code>wp-config.php</code> settings.</li>\n<li>If you moved your WordPress admin, you must set your admin path cookie in <code>wp-config.php</code>.</li>\n<li>Check your cookie paths, domains, and protocols to make sure they match.</li>\n<li>Make sure you're not sending headers prematurely. </li>\n<li>Check to make sure a caching layer like Varnish or CDN like Cloudflare allows you to set cookies and bypass cache both in the admin and through the login process.</li>\n</ol>\n\n<p>Best of luck! </p>\n"
},
{
"answer_id": 350470,
"author": "user3725526",
"author_id": 176779,
"author_profile": "https://wordpress.stackexchange.com/users/176779",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks for the detailled answer. \nIf your WP site is http, the meesage can also come from a header setting in apache httpd.conf.\nIn my case, it worked after I commented the following line: </p>\n\n<pre><code>#Header edit Set-Cookie ^(.*)$ $1;HttpOnly;Secure\n</code></pre>\n\n<p>No secure on for http website!</p>\n"
},
{
"answer_id": 383564,
"author": "Sebas Rossi",
"author_id": 140364,
"author_profile": "https://wordpress.stackexchange.com/users/140364",
"pm_score": -1,
"selected": false,
"text": "<p>If you are sure your user and password are correct ones, then you can simply reload the page and you'll be loged in.</p>\n"
}
] | 2019/03/11 | [
"https://wordpress.stackexchange.com/questions/331309",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/128304/"
] | There are [many](https://wordpress.org/support/topic/cookie-error-site-not-letting-me-log-in/) [many](https://stackoverflow.com/questions/20941328/wordpress-admin-login-cookies-blocked-error-after-moving-servers) [many](https://premium.wpmudev.org/forums/topic/error-cookies-are-blocked-or-not-supported-by-your-browser-you-must-enable-cookies-to-use-wordpres) [many](https://wpglorify.com/cookies-blocked-error-wordpress-admin/) pages about this issue (and I could keep going).
My question: Why does it happen?!
---------------------------------
I'm experiencing it on my local development environment, and I want to ensure that it doesn't happen on production.
Why does this happen?
And why is it, that a simple refresh can bypass it?
---
The solution(s)
---------------
For those who just came here for a solution, then it is:
**1)** Just try and refresh the page.
**2)** Try putting this in your `wp-config.php`
```
define('ADMIN_COOKIE_PATH', '/');
define('COOKIE_DOMAIN', '');
define('COOKIEPATH', '');
define('SITECOOKIEPATH', '');
```
**3)** Or try putting this in your `wp-config.php`
```
define('COOKIE_DOMAIN', $_SERVER['HTTP_HOST'] );
```
**4)** Or putting this in your `functions.php`:
```
setcookie(TEST_COOKIE, 'WP Cookie check', 0, COOKIEPATH, COOKIE_DOMAIN);
if ( SITECOOKIEPATH != COOKIEPATH ) setcookie(TEST_COOKIE, 'WP Cookie check', 0, SITECOOKIEPATH, COOKIE_DOMAIN);
```
**5)** Login-page cached by W3 Cache
If you've changed the login-url (like with [WPS Hide Login](https://wordpress.org/plugins/wps-hide-login/)), then remember to add the new URL as an exception. In W3 Cache it's under: Performance >> Page Cache >> Never cache the following pages. *This cost me half a day of my life, to figure this out!* | When you log in to the admin WordPress sets [cookies](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies) (in PHP) to keep you logged in while you navigate around your site. If this fails, you get the error message, "Cookies are blocked or not supported by your browser."
This could fail in a couple different ways, but before we dig into those situations, let's take a look at the source of these error messages:
>
> `wp-login.php` v5.1.1
>
>
>
```
if ( empty( $_COOKIE[ LOGGED_IN_COOKIE ] ) ) {
if ( headers_sent() ) {
$user = new WP_Error(
'test_cookie',
sprintf(
/* translators: 1: Browser cookie documentation URL, 2: Support forums URL */
__( '<strong>ERROR</strong>: Cookies are blocked due to unexpected output. For help, please see <a href="%1$s">this documentation</a> or try the <a href="%2$s">support forums</a>.' ),
__( 'https://codex.wordpress.org/Cookies' ),
__( 'https://wordpress.org/support/' )
)
);
} elseif ( isset( $_POST['testcookie'] ) && empty( $_COOKIE[ TEST_COOKIE ] ) ) {
// If cookies are disabled we can't log in even with a valid user+pass
$user = new WP_Error(
'test_cookie',
sprintf(
/* translators: %s: Browser cookie documentation URL */
__( '<strong>ERROR</strong>: Cookies are blocked or not supported by your browser. You must <a href="%s">enable cookies</a> to use WordPress.' ),
__( 'https://codex.wordpress.org/Cookies' )
)
);
}
}
```
Failure Context
===============
1. `LOGGED_IN_COOKIE` check
---------------------------
If the `LOGGED_IN_COOKIE` is missing, something has gone wrong and we cannot continue. This is the first indication there's a problem. The code then checks for 2 more specific issues to clarify the error message returned.
2. `headers_sent` check
-----------------------
The first test is for `headers_sent` which is a core PHP function to determine whether or not your response headers have been put together and sent back to the user making the request. They should not be sent by this point. If they are, you have a problem that needs to be resolved before a user can log in.
This is also the least commonly addressed case for most issues raised here for this question. It also generates a slightly different error message.
>
> Cookies are blocked due to unexpected output.
>
>
>
3. Test Cookie status
---------------------
In this test, WordPress tried setting a test cookie and that failed. Notice that the check is for both the `POST` request parameter **and** missing cookie. The `POST` parameter comes from a hidden field on the login form: `<input type="hidden" name="testcookie" value="1" />`. The cookie name default is `wordpress_test_cookie`, but can be changed via the `TEST_COOKIE` constant. More on this in a bit.
This is the most common scenario. Something has gone wrong that prevents either the `POST` parameter from being set or the test cookie from being set.
Let's take a look at the scenarios that could cause this to happen.
Common Problems and Solutions
=============================
1. Your browser blocks cookies
------------------------------
This is the original intention of these checks. It's common for browsers to block "unsafe" cookies or common trackers. It's even pretty common for most people to block cookies altogether and only allow certain cookies to be set after they're discovered (or not at all). This is why the error message is worded this way.
**Solution:** [enable cookies in your browser](https://www.whatismybrowser.com/guides/how-to-enable-cookies/).
2. Your site is sending headers prematurely
-------------------------------------------
Somewhere in your code you probably have a call to send headers like this: `header('Location: https://google.com/');` (for example). Sending a header this way can kill off the process of building the entire header before sending it as a response. I'm not going to go into more detail here because you'd also get a different error message. Read more: [Login page error cookies are blocked due to unexpected output](https://wordpress.stackexchange.com/questions/208878/login-page-error-cookies-are-blocked-due-to-unexpected-output).
**Solution:** check that you're not sending headers prematurely.
3. Cookies aren't being saved
-----------------------------
This is the most common situation developers run into, especially when migrating sites.
```
setcookie( $name , $value, $expires );
```
[Cookies are fairly simple](https://www.php.net/manual/en/function.setcookie.php). They typically have a name, value, and time when they expire. The rest of the parameters are usually left to the defaults.
```
setcookie( $name , $value, $expires, $path, $domain, $secure, $httponly );
```
WordPress explicitly sets these defaults for path, domain, and protocol. If these aren't 100% correct, the cookie just disappears. This is for security. You wouldn't want cookies you set on your site to be available to anyone else, otherwise someone could access your site admin and WordPress authentication would be worthless.
>
> **NOTE:** Path is the base path the cookie is available from. If it's set to `/`, then it will be available to the entire site. If it's set to `/wp-admin`, only urls that start with `/wp-admin` will be able to access it. For example, you would not see it on your site's homepage.
>
>
>
**Solution:** This is a bit more complicated. Let's take deeper dive.
### The test cookie
>
> `wp-login.php v5.1.1
>
>
>
```
$secure = ( 'https' === parse_url( wp_login_url(), PHP_URL_SCHEME ) );
setcookie( TEST_COOKIE, 'WP Cookie check', 0, COOKIEPATH, COOKIE_DOMAIN, $secure );
if ( SITECOOKIEPATH != COOKIEPATH ) {
setcookie( TEST_COOKIE, 'WP Cookie check', 0, SITECOOKIEPATH, COOKIE_DOMAIN, $secure );
}
```
First, WordPress is checking your login url to see if it's using https or not. `$secure` is being used to set the cookie to respond to http or https requests, **not both**.
### Cookie constants
Next, we have to look into some of these constants that are muddying the waters.
`COOKIEPATH` and `SITECOOKIEPATH` determine the path the cookie is available from. `SITECOOKIEPATH` overrides `COOKIEPATH`. Keep this in mind. This will be important later.
`COOKIE_DOMAIN` determines the domain the cookie is available from, eg `yourdomains.com`. If it's set to false, it will use the current domain.
`ADMIN_COOKIE_PATH` isn't in the source above, but will get used later. Bear with me on this one. This is the path to your WordPress dashboard.
These constants are set by WordPress, but can be changed. Let's take a look at the source.
>
> `/wp-includes/default-constants.php` v5.1.1
>
>
>
```
if ( ! defined( 'COOKIEPATH' ) ) {
define( 'COOKIEPATH', preg_replace( '|https?://[^/]+|i', '', get_option( 'home' ) . '/' ) );
}
if ( ! defined( 'SITECOOKIEPATH' ) ) {
define( 'SITECOOKIEPATH', preg_replace( '|https?://[^/]+|i', '', get_option( 'siteurl' ) . '/' ) );
}
if ( ! defined( 'ADMIN_COOKIE_PATH' ) ) {
define( 'ADMIN_COOKIE_PATH', SITECOOKIEPATH . 'wp-admin' );
}
if ( ! defined( 'TEST_COOKIE' ) ) {
define( 'TEST_COOKIE', 'wordpress_test_cookie' );
}
```
*Now we're starting to get some clarity.*
`COOKIEPATH` uses your home url stored in your database. This is typically set in your `wp-config.php` file as the constant `WP_HOME`.
`SITECOOKIEPATH` overrides `COOKIEPATH` (remember?) and that comes from your site url stored in the database. In your `wp-config.php` file this is your `WP_SITEURL` constant.
**If these don't match, there's a chance you'll have a problem.**
This is why you see people recommend setting these with a server parameter:
```
define('WP_SITEURL', 'https://' . $_SERVER['HTTP_HOST']);
define('WP_HOME', 'https://' . $_SERVER['HTTP_HOST']);
```
This configuration makes sure your site responds with the correct domain. It works in most cases, but **should be used cautiously.**
>
> **Disclaimer:** You should always do a search/replace in your database for old urls and change these to your new url. Please don't think the above will fix everything. It won't.
>
>
>
### Debugging cookies
In order to debug this issue, try outputting these constants on your `wp-login.php` page like this:
```
add_action( 'login_init', 'my_login_init' );
function my_login_init() {
echo '<b>Cookie path:</b> ';
var_dump( COOKIEPATH );
echo '<br /><b>Cookie site path:</b> ';
var_dump( SITECOOKIEPATH );
echo '<br /><b>Cookie domain:</b> ';
var_dump( COOKIE_DOMAIN );
echo '<br /><b>Admin cookie path:</b> ';
var_dump( ADMIN_COOKIE_PATH );
}
```
This will give you a good idea of what parameters are being used to set your cookies. If these don't match your site's settings or your expectations, you need to address it to ensure your cookie is being set correctly.
You can set these explicitly in your `wp-config.php` file:
```
// False setting for the domain uses the current domain.
define('COOKIE_DOMAIN', false);
// Setting to / will only work if your site is set to the root domain.
define('COOKIEPATH', '/');
define('SITECOOKIEPATH', '/');
```
### Authorization cookies
All the above have to do with the test cookie which is the source of the error message, but there's one more step beyond that: your authorization cookies.
WordPress sets a bunch of cookies, depending on the context. For logging in, you'll need these:
1. `'wordpress_logged_in_' . COOKIEHASH`
2. and either `'wordpress_' . COOKIEHASH` **or** `'wordpress_sec_' . COOKIEHASH`
These cookies need to have the right path, protocol and domain or you won't be able to log in.
Fortunately, most of those checks are taken care of with the test cookie we already looked at. The only difference is with the admin path:
```
define( 'ADMIN_COOKIE_PATH', SITECOOKIEPATH . 'wp-admin' );
```
If the path to your admin is different than `yourdomain.com/wp-admin`, you need to set this in your `wp-config.php` file like this:
```
define( 'ADMIN_COOKIE_PATH', '/path/to/wp-admin' );
```
Conclusion
==========
This is a complicated problem. There are multiple causes for what appears to be the same issue.
If you get this error, you will have to do some debugging to find out what's going on. Here are some suggestions:
1. Always check your browser first. Make sure it's able to save cookies from PHP.
2. If you recently migrated, check for old urls in your database, then check your `wp-config.php` settings.
3. If you moved your WordPress admin, you must set your admin path cookie in `wp-config.php`.
4. Check your cookie paths, domains, and protocols to make sure they match.
5. Make sure you're not sending headers prematurely.
6. Check to make sure a caching layer like Varnish or CDN like Cloudflare allows you to set cookies and bypass cache both in the admin and through the login process.
Best of luck! |
331,341 | <p>I've created a child theme under <code>wp-content/themes/my-theme</code> with 5 files thus far:</p>
<pre><code>|-my-theme
|----assets
|--------css
|------------bootstrap.min.css
|--------js
|------------bootstrap.min.js
|----functions.php
|----index.php
|----style.css
</code></pre>
<p>Now the problem is within my <code>functions.php</code> file, I've tried adding my <code>.css</code> and <code>.js</code> file like this:</p>
<pre><code><?php
# functions.php
/**
* add css | js files to WP
*/
function theme_asset_setup()
{
# styles
wp_enqueue_style('bootstrap', get_template_directory_uri(). '/assets/css/bootstrap.min.css', []);
# scripts
wp_enqueue_script('bootstrap', get_template_directory_uri(). '/assets/js/bootstrap.min.js', []);
}
/** actions **/
add_action('wp_enqueue_scripts', 'theme_asset_setup');
</code></pre>
<p>This half does the job. This adds my <code>.js</code> and <code>.css</code> file with this path:</p>
<blockquote>
<p><a href="http://site.local/wp-content/themes/twentynineteen/assets/css/bootstrap.min.css?ver=5.1" rel="nofollow noreferrer">http://site.local/wp-content/themes/twentynineteen/assets/css/bootstrap.min.css?ver=5.1</a></p>
</blockquote>
<p>My parent theme is <code>twentynineteen</code> as specified in my <code>style.css</code> file:</p>
<pre><code>/*
Theme Name: My Theme
Author: treybake
Description: foobar
Requires at Least: WordPress 4.9.6
Version: 0.1
License: GNU General Public License v2 or later
Text Domain: my-theme
Template: twentynineteen
*/
</code></pre>
<p>So I'm guessing this has some sort of factor on why my <code>.css</code> and <code>.js</code> - but I'm not sure how to debug further.</p>
<p>Why is my child theme path being ignored for my css/js files?</p>
<p>Thanks</p>
| [
{
"answer_id": 331343,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 1,
"selected": false,
"text": "<p>Because this is a child theme, you should use </p>\n\n<pre><code> # styles\n wp_enqueue_style('bootstrap', get_stylesheet_directory_uri(). '/assets/css/bootstrap.min.css', []);\n\n # scripts\n wp_enqueue_script('bootstrap', get_stylesheet_directory_uri(). '/assets/js/bootstrap.min.js', []);\n</code></pre>\n\n<p><code>get_template_directory_uri()</code>\npulls from the parent theme directory</p>\n\n<p><code>get_stylesheet_directory_uri()</code>\npulls from the child theme directory</p>\n"
},
{
"answer_id": 331344,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p><code>get_template_directory_uri()</code> is explicitly for getting the URL to the parent theme, which is why your scripts and styles are being enqueued at that path (in this context the \"template\" is the parent theme). </p>\n\n<p>The equivalent function for getting the child theme path is <code>get_stylesheet_directory_uri()</code>. If you don't have a child theme then both these functions do the same thing, but when you are using a child theme the choice is important.</p>\n\n<p>However, both these functions have been superseded by much more useful functions: <a href=\"https://developer.wordpress.org/reference/functions/get_theme_file_uri/\" rel=\"nofollow noreferrer\"><code>get_theme_file_uri()</code></a> and <a href=\"https://developer.wordpress.org/reference/functions/get_parent_theme_file_uri/\" rel=\"nofollow noreferrer\"><code>get_parent_theme_file_uri()</code></a>.</p>\n\n<p><code>get_theme_file_uri()</code> will get the URL to a specific file in your theme. If your theme is a child theme it will look for the file there, but if it can't find it, it will look in the parent theme. <code>get_stylesheet_directory_uri()</code> can't do this.</p>\n\n<p>So for your use case, you should use <code>get_theme_file_uri()</code>:</p>\n\n<pre><code>wp_enqueue_style('bootstrap', get_theme_file_uri( 'assets/css/bootstrap.min.css' ), [] );\nwp_enqueue_script('bootstrap', get_theme_file_uri( 'assets/js/bootstrap.min.js' ), [] );\n</code></pre>\n\n<p>The main difference in usage is that rather than concatenating the rest of the file path to the end, you pass it as an argument. This is why it's able to check the parent theme for the file.</p>\n"
}
] | 2019/03/11 | [
"https://wordpress.stackexchange.com/questions/331341",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/155748/"
] | I've created a child theme under `wp-content/themes/my-theme` with 5 files thus far:
```
|-my-theme
|----assets
|--------css
|------------bootstrap.min.css
|--------js
|------------bootstrap.min.js
|----functions.php
|----index.php
|----style.css
```
Now the problem is within my `functions.php` file, I've tried adding my `.css` and `.js` file like this:
```
<?php
# functions.php
/**
* add css | js files to WP
*/
function theme_asset_setup()
{
# styles
wp_enqueue_style('bootstrap', get_template_directory_uri(). '/assets/css/bootstrap.min.css', []);
# scripts
wp_enqueue_script('bootstrap', get_template_directory_uri(). '/assets/js/bootstrap.min.js', []);
}
/** actions **/
add_action('wp_enqueue_scripts', 'theme_asset_setup');
```
This half does the job. This adds my `.js` and `.css` file with this path:
>
> <http://site.local/wp-content/themes/twentynineteen/assets/css/bootstrap.min.css?ver=5.1>
>
>
>
My parent theme is `twentynineteen` as specified in my `style.css` file:
```
/*
Theme Name: My Theme
Author: treybake
Description: foobar
Requires at Least: WordPress 4.9.6
Version: 0.1
License: GNU General Public License v2 or later
Text Domain: my-theme
Template: twentynineteen
*/
```
So I'm guessing this has some sort of factor on why my `.css` and `.js` - but I'm not sure how to debug further.
Why is my child theme path being ignored for my css/js files?
Thanks | `get_template_directory_uri()` is explicitly for getting the URL to the parent theme, which is why your scripts and styles are being enqueued at that path (in this context the "template" is the parent theme).
The equivalent function for getting the child theme path is `get_stylesheet_directory_uri()`. If you don't have a child theme then both these functions do the same thing, but when you are using a child theme the choice is important.
However, both these functions have been superseded by much more useful functions: [`get_theme_file_uri()`](https://developer.wordpress.org/reference/functions/get_theme_file_uri/) and [`get_parent_theme_file_uri()`](https://developer.wordpress.org/reference/functions/get_parent_theme_file_uri/).
`get_theme_file_uri()` will get the URL to a specific file in your theme. If your theme is a child theme it will look for the file there, but if it can't find it, it will look in the parent theme. `get_stylesheet_directory_uri()` can't do this.
So for your use case, you should use `get_theme_file_uri()`:
```
wp_enqueue_style('bootstrap', get_theme_file_uri( 'assets/css/bootstrap.min.css' ), [] );
wp_enqueue_script('bootstrap', get_theme_file_uri( 'assets/js/bootstrap.min.js' ), [] );
```
The main difference in usage is that rather than concatenating the rest of the file path to the end, you pass it as an argument. This is why it's able to check the parent theme for the file. |
331,349 | <p>Can anyone tell me how to change my social media links? I've tried everything on google. My wordpress was set up by a third party who is no longer able to help me. I have pretty much covered being able to keep it updated. On my website the links to the social media are at the bottom but not a menus, not a footer, or in the media link. I cannot find a plug-in used to put them there.</p>
| [
{
"answer_id": 331343,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 1,
"selected": false,
"text": "<p>Because this is a child theme, you should use </p>\n\n<pre><code> # styles\n wp_enqueue_style('bootstrap', get_stylesheet_directory_uri(). '/assets/css/bootstrap.min.css', []);\n\n # scripts\n wp_enqueue_script('bootstrap', get_stylesheet_directory_uri(). '/assets/js/bootstrap.min.js', []);\n</code></pre>\n\n<p><code>get_template_directory_uri()</code>\npulls from the parent theme directory</p>\n\n<p><code>get_stylesheet_directory_uri()</code>\npulls from the child theme directory</p>\n"
},
{
"answer_id": 331344,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p><code>get_template_directory_uri()</code> is explicitly for getting the URL to the parent theme, which is why your scripts and styles are being enqueued at that path (in this context the \"template\" is the parent theme). </p>\n\n<p>The equivalent function for getting the child theme path is <code>get_stylesheet_directory_uri()</code>. If you don't have a child theme then both these functions do the same thing, but when you are using a child theme the choice is important.</p>\n\n<p>However, both these functions have been superseded by much more useful functions: <a href=\"https://developer.wordpress.org/reference/functions/get_theme_file_uri/\" rel=\"nofollow noreferrer\"><code>get_theme_file_uri()</code></a> and <a href=\"https://developer.wordpress.org/reference/functions/get_parent_theme_file_uri/\" rel=\"nofollow noreferrer\"><code>get_parent_theme_file_uri()</code></a>.</p>\n\n<p><code>get_theme_file_uri()</code> will get the URL to a specific file in your theme. If your theme is a child theme it will look for the file there, but if it can't find it, it will look in the parent theme. <code>get_stylesheet_directory_uri()</code> can't do this.</p>\n\n<p>So for your use case, you should use <code>get_theme_file_uri()</code>:</p>\n\n<pre><code>wp_enqueue_style('bootstrap', get_theme_file_uri( 'assets/css/bootstrap.min.css' ), [] );\nwp_enqueue_script('bootstrap', get_theme_file_uri( 'assets/js/bootstrap.min.js' ), [] );\n</code></pre>\n\n<p>The main difference in usage is that rather than concatenating the rest of the file path to the end, you pass it as an argument. This is why it's able to check the parent theme for the file.</p>\n"
}
] | 2019/03/11 | [
"https://wordpress.stackexchange.com/questions/331349",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/162930/"
] | Can anyone tell me how to change my social media links? I've tried everything on google. My wordpress was set up by a third party who is no longer able to help me. I have pretty much covered being able to keep it updated. On my website the links to the social media are at the bottom but not a menus, not a footer, or in the media link. I cannot find a plug-in used to put them there. | `get_template_directory_uri()` is explicitly for getting the URL to the parent theme, which is why your scripts and styles are being enqueued at that path (in this context the "template" is the parent theme).
The equivalent function for getting the child theme path is `get_stylesheet_directory_uri()`. If you don't have a child theme then both these functions do the same thing, but when you are using a child theme the choice is important.
However, both these functions have been superseded by much more useful functions: [`get_theme_file_uri()`](https://developer.wordpress.org/reference/functions/get_theme_file_uri/) and [`get_parent_theme_file_uri()`](https://developer.wordpress.org/reference/functions/get_parent_theme_file_uri/).
`get_theme_file_uri()` will get the URL to a specific file in your theme. If your theme is a child theme it will look for the file there, but if it can't find it, it will look in the parent theme. `get_stylesheet_directory_uri()` can't do this.
So for your use case, you should use `get_theme_file_uri()`:
```
wp_enqueue_style('bootstrap', get_theme_file_uri( 'assets/css/bootstrap.min.css' ), [] );
wp_enqueue_script('bootstrap', get_theme_file_uri( 'assets/js/bootstrap.min.js' ), [] );
```
The main difference in usage is that rather than concatenating the rest of the file path to the end, you pass it as an argument. This is why it's able to check the parent theme for the file. |
331,413 | <p>We build a media (based on bootstrap 4 media object) shortcode with the following syntax:</p>
<pre><code>[media img="https://via.placeholder.com/64x64.png"]<h5>List-based media object</h5>Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.[/media]
</code></pre>
<p>The function can be found here:</p>
<pre><code>add_shortcode( 'media', 'xcore_shortcode_media' );
/**
* Media shortcode
*
* @doc https://getbootstrap.com/docs/4.3/components/media-object/
*
* @param $atts
* @param null $content
*
* @return string
*/
function xcore_shortcode_media( $atts, $content = null ) {
extract(
shortcode_atts(
array(
'style' => 'primary',
'class' => '',
'img' => '',
'align' => '',
'order' => 'left'
),
$atts
)
);
// vars
$style = ( $atts['style'] ? $atts['style'] : 'primary' );
$class = ( $atts['class'] ? $atts['class'] : '' );
$img = ( $atts['img'] ? $atts['img'] : '' );
$align = ( $atts['align'] ? $atts['align'] : '' );
$order = ( $atts['order'] ? $atts['order'] : 'left' );
$attributes = array(
'class' => array( 'xcore-media', 'media' ),
);
if ( $style ) {
$attributes['class'][] = 'media-' . $style;
}
if ( $class ) {
$attributes['class'][] = $class;
}
if ( $img ) {
$img_classes = array();
if ( $order == 'left' ) {
$img_classes[] = 'mr-3';
} else {
$img_classes[] = 'ml-3';
}
if ( $align ) {
$img_classes[] = 'align-' . $align;
}
$img_html = '<img src="' . $img . '" class="' . implode ( ' ', $img_classes ) . '"/>';
}
$output = '<div ' . xcore_attribute_array_html( $attributes ) . '>';
if ( $order == 'left' ) {
$output .= $img_html;
}
$output .= '<div class="media-body">';
$output .= do_shortcode( $content );
$output .= '</div>';
if ( $order == 'right' ) {
$output .= $img_html;
}
$output .= '</div>';
return $output;
}
</code></pre>
<p>The Problem:</p>
<p>WordPress puts an empty p-Tag right before the headline. When we start without a headline in our content, it works fine. </p>
<p>Here a example:</p>
<p><a href="https://i.stack.imgur.com/dHvpb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dHvpb.png" alt="HTML code"></a></p>
<p>Is there any way to remove this without deactivate the auto p function completely?</p>
<p>Thanks</p>
| [
{
"answer_id": 334438,
"author": "Frank P. Walentynowicz",
"author_id": 32851,
"author_profile": "https://wordpress.stackexchange.com/users/32851",
"pm_score": -1,
"selected": false,
"text": "<p>CSS <code>:first-of-type</code> selector will help to accomplish that:</p>\n\n<pre><code>.media-body p:first-of-type {\n display: none;\n}\n</code></pre>\n"
},
{
"answer_id": 334447,
"author": "Warwick",
"author_id": 19554,
"author_profile": "https://wordpress.stackexchange.com/users/19554",
"pm_score": 1,
"selected": false,
"text": "<p>The empty p tag in the developer console means that you have other HTML being outputted inside it, which shouldn't be there. i.e the H5 tag for the heading.</p>\n\n<p>This is because \"do_shortcode\" uses the <a href=\"https://codex.wordpress.org/Function_Reference/wpautop\" rel=\"nofollow noreferrer\">wpautop</a> filter which wraps everything in a p tag</p>\n\n<p>Try remove the wpautop filter, run do_shortcode, and then re add the wpautop filter (otherwise any other shortcode outputs will run without it).</p>\n\n<p>Replace</p>\n\n<pre><code>$output .= '<div class=\"media-body\">';\n $output .= do_shortcode( $content );\n$output .= '</div>';\n</code></pre>\n\n<p>With</p>\n\n<pre><code>$output .= '<div class=\"media-body\">';\n remove_filter( 'the_content', 'wpautop' );\n $output .= do_shortcode( $content );\n add_filter( 'the_content', 'wpautop' );\n$output .= '</div>';\n</code></pre>\n\n<p>You might need to add some p tags manually to your shortcode call.</p>\n\n<pre><code>[media img=\"https://via.placeholder.com/64x64.png\"]<h5>List-based media object</h5><p>Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.</p>[/media]\n</code></pre>\n"
},
{
"answer_id": 372296,
"author": "Karl Cooper",
"author_id": 192632,
"author_profile": "https://wordpress.stackexchange.com/users/192632",
"pm_score": -1,
"selected": false,
"text": "<p>I've just had this problem myself, I found the solution using the PHP trim() function. You can use the second parameter to specify what to trim, in our case, we want to trim empty <code><p></code> tags, so this is (partly) the code I used;</p>\n<pre><code>function shortcodefunction($atts,$content) {\n $content = trim($content,'<p></p>');\n return $content;\n}\nadd_shortcode('shortcode-name','shortcodefunction');\n</code></pre>\n"
}
] | 2019/03/12 | [
"https://wordpress.stackexchange.com/questions/331413",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/161828/"
] | We build a media (based on bootstrap 4 media object) shortcode with the following syntax:
```
[media img="https://via.placeholder.com/64x64.png"]<h5>List-based media object</h5>Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.[/media]
```
The function can be found here:
```
add_shortcode( 'media', 'xcore_shortcode_media' );
/**
* Media shortcode
*
* @doc https://getbootstrap.com/docs/4.3/components/media-object/
*
* @param $atts
* @param null $content
*
* @return string
*/
function xcore_shortcode_media( $atts, $content = null ) {
extract(
shortcode_atts(
array(
'style' => 'primary',
'class' => '',
'img' => '',
'align' => '',
'order' => 'left'
),
$atts
)
);
// vars
$style = ( $atts['style'] ? $atts['style'] : 'primary' );
$class = ( $atts['class'] ? $atts['class'] : '' );
$img = ( $atts['img'] ? $atts['img'] : '' );
$align = ( $atts['align'] ? $atts['align'] : '' );
$order = ( $atts['order'] ? $atts['order'] : 'left' );
$attributes = array(
'class' => array( 'xcore-media', 'media' ),
);
if ( $style ) {
$attributes['class'][] = 'media-' . $style;
}
if ( $class ) {
$attributes['class'][] = $class;
}
if ( $img ) {
$img_classes = array();
if ( $order == 'left' ) {
$img_classes[] = 'mr-3';
} else {
$img_classes[] = 'ml-3';
}
if ( $align ) {
$img_classes[] = 'align-' . $align;
}
$img_html = '<img src="' . $img . '" class="' . implode ( ' ', $img_classes ) . '"/>';
}
$output = '<div ' . xcore_attribute_array_html( $attributes ) . '>';
if ( $order == 'left' ) {
$output .= $img_html;
}
$output .= '<div class="media-body">';
$output .= do_shortcode( $content );
$output .= '</div>';
if ( $order == 'right' ) {
$output .= $img_html;
}
$output .= '</div>';
return $output;
}
```
The Problem:
WordPress puts an empty p-Tag right before the headline. When we start without a headline in our content, it works fine.
Here a example:
[](https://i.stack.imgur.com/dHvpb.png)
Is there any way to remove this without deactivate the auto p function completely?
Thanks | The empty p tag in the developer console means that you have other HTML being outputted inside it, which shouldn't be there. i.e the H5 tag for the heading.
This is because "do\_shortcode" uses the [wpautop](https://codex.wordpress.org/Function_Reference/wpautop) filter which wraps everything in a p tag
Try remove the wpautop filter, run do\_shortcode, and then re add the wpautop filter (otherwise any other shortcode outputs will run without it).
Replace
```
$output .= '<div class="media-body">';
$output .= do_shortcode( $content );
$output .= '</div>';
```
With
```
$output .= '<div class="media-body">';
remove_filter( 'the_content', 'wpautop' );
$output .= do_shortcode( $content );
add_filter( 'the_content', 'wpautop' );
$output .= '</div>';
```
You might need to add some p tags manually to your shortcode call.
```
[media img="https://via.placeholder.com/64x64.png"]<h5>List-based media object</h5><p>Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.</p>[/media]
``` |
331,416 | <p>I wan to add a responsive div to my wordpress page using bootstrap css, just when i enqueued bootstrap style it distroy themes, so i wan to make that div load using ajax call, call that enqueued style after document is ready then i will add css classes using jquery addClass( ). This way themes styles will not be afected with my custom css </p>
| [
{
"answer_id": 331481,
"author": "semperlabs",
"author_id": 163019,
"author_profile": "https://wordpress.stackexchange.com/users/163019",
"pm_score": 1,
"selected": false,
"text": "<p>Styles won't be affected if you use different selectors. Create a custom stylesheet, and enqueue it immediatelly. When the page is ready just apply the styles to the mentioned responsive div, or create some logic behind it.</p>\n\n<p>So for example if you have \n<code><div class=\"custom-sidebar\">Some content</div></code></p>\n\n<p>Enqueue custom style within functions.php</p>\n\n<pre><code>wp_enqueue_style( 'some-custom-styles', get_stylesheet_uri() . \"/custom.css\" );\n</code></pre>\n\n<p>Afterwards just assign whichever class you want</p>\n\n<pre><code>$( \".custom-sidebar\" ).addClass( \".myClassFromCustomCSS\" );\n</code></pre>\n"
},
{
"answer_id": 331494,
"author": "Loren Rosen",
"author_id": 158993,
"author_profile": "https://wordpress.stackexchange.com/users/158993",
"pm_score": 0,
"selected": false,
"text": "<p>You may be able to use a shadow DOM (see <a href=\"https://css-tricks.com/playing-shadow-dom/\" rel=\"nofollow noreferrer\">https://css-tricks.com/playing-shadow-dom/</a>), or put it an <code><iframe></code>. <br>\n(will expand soon but don't have time right now.)</p>\n"
}
] | 2019/03/12 | [
"https://wordpress.stackexchange.com/questions/331416",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/162878/"
] | I wan to add a responsive div to my wordpress page using bootstrap css, just when i enqueued bootstrap style it distroy themes, so i wan to make that div load using ajax call, call that enqueued style after document is ready then i will add css classes using jquery addClass( ). This way themes styles will not be afected with my custom css | Styles won't be affected if you use different selectors. Create a custom stylesheet, and enqueue it immediatelly. When the page is ready just apply the styles to the mentioned responsive div, or create some logic behind it.
So for example if you have
`<div class="custom-sidebar">Some content</div>`
Enqueue custom style within functions.php
```
wp_enqueue_style( 'some-custom-styles', get_stylesheet_uri() . "/custom.css" );
```
Afterwards just assign whichever class you want
```
$( ".custom-sidebar" ).addClass( ".myClassFromCustomCSS" );
``` |
331,422 | <p>I have been delving into AJAX within WordPress and have followed many tutorials on how to do so, but every single request returns a 400 error.</p>
<p>In my <strong>functions.php</strong> I have added the following:</p>
<p><strong>Step 1</strong> - Register and add scripts to WordPress</p>
<pre><code>/**
* Initialize the JavaScript we need for loading more
*
* @return void
*/
function ajax_load_more_init()
{
// Register and enqueue the script we need for load more
wp_register_script('ajax-load-more-script', get_template_directory_uri() . '/assets/scripts/ajax-load-more.js', array('jquery'));
wp_enqueue_script('ajax-load-more-script');
// Localize the script so we can access tthe variables in PHP
wp_localize_script('ajax-load-more-script', 'ajax_load_more_object', array(
'ajax_url' => admin_url('admin-ajax.php'),
));
}
</code></pre>
<p><strong>Step 2</strong> - Enqueue the actual script</p>
<pre><code>/**
* Add AJAX loader to scripts
*/
add_action('wp_enqueue_scripts', 'ajax_load_more_init');
</code></pre>
<p><strong>Step 3</strong> - Allow AJAX to be used on the frontend</p>
<pre><code>// AJAX Hook for users
add_action('wp_ajax_ajax_load_more', 'ajax_load_more');
add_action('wp_ajax_nopriv_ajax_load_more', 'ajax_load_more');
</code></pre>
<p><strong>Step 4</strong> - A dead simple function for testing</p>
<pre><code>/**
* The backend PHP to actually load more posts
*
* @return void
*/
function ajax_load_more()
{
echo "TESTING";
wp_die();
}
</code></pre>
<p>In my actual AJAX script I have the following:</p>
<pre><code>jQuery(document).ready(function ($) {
// Initialize Isotope as $grid
const $grid = $('#grid').isotope({
itemSelector: '.grid-item',
percentagePosition: true,
animationEngine: 'best-available', //CSS3 if browser supports it, jQuery otherwise
animationOptions: {
duration: 800,
},
masonry: {
columnWidth: '.grid-item',
gutter: 30,
},
})
var has_run = false;
var init_offset = 0;
// Hook into click event
$('button.load-more-posts').click(function (e) {
e.preventDefault();
var button = $(this);
var nonce = $(this).data("nonce");
console.log('Nonce is: ' + nonce);
// Disable the button
button.prop("disabled", true);
// Check the offset
if (has_run == false) {
button.data('offset', $(this).data("offset"));
init_offset = $(this).data("offset");
}
console.log('Initial offset is: ' + init_offset);
console.log('Initial offset is: ' + button.data('offset'));
// Perform AJAX request
$.ajax({
type: 'POST',
dataType: 'json',
url: ajax_load_more_object.ajax_url,
contentType: 'application/json; charset=utf-8',
data: {
action: 'ajax_load_more',
security: nonce,
init_offset: init_offset,
offset: button.data('offset'),
},
beforeSend: function (xhr) {
console.log('Loading more posts...')
button.text('Loading');
},
success: function (response) {
console.log(response);
// Undo Button Disable
button.prop("disabled", false);
// Set Offset
button.data("offset", offset + 10);
// Script has run
has_run = true;
return false;
},
error: function (xhr, status, error) {
console.log(xhr.responseText);
}
});
});
});
</code></pre>
<p>As you can see in the <code>$ajax</code> call, the url is to <code>admin-ajax</code> and the action is the trailing part of <code>wp_ajax_nopriv_ajax_load_more</code>.</p>
<p>The nonce comes from the button on the front end like so:</p>
<p><code><button class="load-more-posts" data-nonce="<?php echo wp_create_nonce('load_more_ajax'); ?>" data-offset="10">Load More Posts</button></code></p>
<p><a href="https://i.stack.imgur.com/DT6XQ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DT6XQ.jpg" alt="enter image description here"></a></p>
<p><strong>My working code</strong></p>
<p>So, thanks to everyone's shared input I was able to come up with a solution that I'll detail below:</p>
<p>In functions.php (should really be in a plugin)</p>
<pre><code>/**
* Additional thumbnail sizes
*/
add_theme_support('post-thumbnails');
add_image_size('post-thumbnail-square', 300, 300, true);
/**
* Initialize the JavaScript we need for loading more
*
* @return void
*/
function ajax_load_more_init()
{
// Register and enqueue the script we need for load more
wp_register_script('ajax-load-more-script', get_template_directory_uri() . '/assets/scripts/ajax-load-more.js', array('jquery'));
wp_enqueue_script('ajax-load-more-script');
// Localize the script so we can access tthe variables in PHP
wp_localize_script('ajax-load-more-script', 'ajax_load_more_object', array(
'ajax_url' => admin_url('admin-ajax.php'),
));
}
/**
* Add AJAX loader to scripts
*/
add_action('wp_enqueue_scripts', 'ajax_load_more_init');
/**
* Allow AJAX to be used on the front end
*/
add_action('wp_ajax_ajax_load_more_posts', 'ajax_load_more_posts_callback');
add_action('wp_ajax_nopriv_ajax_load_more_posts', 'ajax_load_more_posts_callback');
/**
* The backend PHP to actually load more posts
*
* @return void
*/
function ajax_load_more_posts_callback()
{
// First check the nonce, if it fails the function will break
check_ajax_referer('ajax_load_more_posts', 'security');
// Get the data we have from the load more button
$offset = $_POST['offset'];
$init_offset = $_POST['init_offset'];
// Get posts with given offset
if ($offset != null && absint($offset) && $init_offset != null && absint($init_offset)) {
// Finally, we'll set the query arguments and instantiate WP_Query
$args = array(
'post_type' => 'post',
'posts_per_page' => $init_offset,
'offset' => $offset
);
$post_list = array();
$query = new WP_Query($args);
if ($query->have_posts()) :
while ($query->have_posts()) : $query->the_post();
//$categories = get_the_categories();
$post_list[] = array(
'category' => get_the_category(),
'title' => get_the_title(),
'introduction' => get_field('introduction'),
'date' => get_the_date(),
'permalink' => get_permalink(),
'thumbnail' => get_the_post_thumbnail(),
);
endwhile;
endif;
echo json_encode($post_list);
wp_die();
}
}
</code></pre>
<p>In my ajax-loader script</p>
<pre><code>jQuery(document).ready(function ($) {
var has_run = false;
var init_offset = 0;
// Hook into click event
$('button.load-more-posts').click(function (e) {
var $grid = $('#grid').isotope({
itemSelector: '.grid-item',
});
e.preventDefault();
var button = $(this);
var nonce = $(this).data("nonce");
// Disable the button
button.prop("disabled", true);
// Check the offset
if (has_run == false) {
button.data('offset', $(this).data("offset"));
init_offset = $(this).data("offset");
}
// Perform AJAX request
$.ajax({
type: 'POST',
dataType: 'json',
url: ajax_load_more_object.ajax_url,
data: {
action: 'ajax_load_more_posts',
security: nonce,
init_offset: init_offset,
offset: button.data('offset'),
},
beforeSend: function (xhr) {
console.log('Loading more posts...')
button.text('Loading');
},
success: function (response) {
console.log(response);
button.text('Load more');
// An array to store new items added via AJAX
var new_items = [];
// Run through JSON
$.each(response, function (key, value) {
var $new_item = $(`<div class="grid-item article-post-card ${value.category[0]['slug']}">
<a class="article-post-card__anchor" href=" ${value.permalink}" alt="${value.title}">
<div class="article-post-card__featured-image-container">
<div class="article-post-card__overlay"></div>
<div class="article-post-card__featured-image">
${value.thumbnail}
</div>
<div class="article-post-card__category-label">
${value.category[0]['name']}
</div>
</div>
<div class="article-post-card__content-wrapper">
<div class="article-post-card__publish-date">
<time class="updated" datetime="">${value.date}</time>
</div>
<div class="article-post-card__title">
${value.title}
</div>
<div class="article-post-card__excerpt">
${value.introduction}
</div>
</div>
</a>
</div>`);
new_items.push($new_item[0]);
});
// Add the new items to the grid
$grid
.isotope('insert', new_items)
.imagesLoaded().progress(function () {
$grid.isotope('layout');
});
// Undo Button Disable
button.prop("disabled", false);
// Set Offset
var offset = button.data("offset");
button.data("offset", offset + 10);
// Script has run
has_run = true;
return false;
},
error: function (xhr, status, error) {
console.log("There was an error", error);
}
});
});
});
</code></pre>
<p>If you guys could critique I think this would be useful for others too.</p>
| [
{
"answer_id": 331432,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 4,
"selected": true,
"text": "<p>I have not tested your code, but one problem I noticed is the <code>contentType</code> property in your <code>$.ajax()</code> call:</p>\n\n<pre><code>contentType: 'application/json; charset=utf-8',\n</code></pre>\n\n<p>because that way, (from the PHP side) the action (i.e. <code>ajax_load_more</code>) is not available in <code>$_REQUEST['action']</code> which WordPress uses to determine the AJAX action being called, and when the action is not known, WordPress throws the error <code>400 Bad Request</code>, which in your case translates to \"unknown AJAX action\".</p>\n\n<p><em>You should just omit the <code>contentType</code> property, or don't set it to a JSON content type string.</em></p>\n\n<p>Also, although you're just testing in <code>ajax_load_more()</code>, make sure to return a proper JSON response/string because your <code>dataType</code> is <code>json</code>.</p>\n\n<p>I hope this helps you. :)</p>\n\n<h2>Additional Notes</h2>\n\n<p>From the <code>jQuery.ajax()</code> <a href=\"http://api.jquery.com/jquery.ajax/\" rel=\"nofollow noreferrer\">documentation</a>:</p>\n\n<ol>\n<li><p><code>dataType</code> (default: <code>Intelligent Guess (xml, json, script, or html)</code>)</p>\n\n<blockquote>\n <p>The type of data that you're <em>expecting back from the server</em>. If none\n is specified, jQuery will try to infer it based on the MIME type of\n the response</p>\n</blockquote></li>\n<li><p><code>contentType</code> (default: <code>'application/x-www-form-urlencoded; charset=UTF-8'</code>)</p>\n\n<blockquote>\n <p>When <em>sending data to the server</em>, use this content type. Default is\n \"application/x-www-form-urlencoded; charset=UTF-8\", which is fine for\n most cases. If you explicitly pass in a content-type to <code>$.ajax()</code>,\n then it is always sent to the server (even if no data is sent).</p>\n</blockquote></li>\n</ol>\n\n<p>So <code>dataType</code> is the content type (MIME) of the content from the AJAX response, whereas <code>contentType</code> is the content type of the content you are <em>sending</em> to the PHP/server-side function (which is <code>ajax_load_more()</code> in your case).</p>\n\n<h2>UPDATE</h2>\n\n<blockquote>\n <p>So by using the wrong content type the headers become unreadable?</p>\n</blockquote>\n\n<p>No it is not about the headers become unreadable - (request) headers are always readable in PHP. It's just that <strong>request <em>payload</em></strong> (in JSON) is not supported by the WordPress AJAX - only the request <em>body</em>. But you can of course, send form field data/value as JSON - for example, <code>myField: '{\"foo\":\"bar\",\"baz\":1}'</code>. Just don't set the <em>content type header</em> to JSON.</p>\n\n<p>But if you really must send a JSON request payload instead of a standard URL-encoded form data (i.e. the request body), then you can append the AJAX action to the AJAX URL - e.g. <code>/wp-admin/admin-ajax.php?action=ajax_load_more</code>. That way, you wouldn't get the error <code>400</code>; however, it's up to you to <a href=\"https://stackoverflow.com/a/9597087/9217760\">retrieve/parse</a> the JSON request payload..</p>\n\n<h3>Request Payload (JSON)</h3>\n\n<pre><code>jQuery.ajax({\n type: 'POST',\n url: '/wp-admin/admin-ajax.php?action=ajax_load_more',\n contentType: 'application/json; charset=utf-8',\n data: {\n action: 'ajax_load_more',\n foo: 'bar',\n }\n});\n</code></pre>\n\n<p><img src=\"https://i.ibb.co/mtQmx6D/image.png\"></p>\n\n<h3>Request Body (Form Data)</h3>\n\n<pre><code>jQuery.ajax({\n type: 'POST',\n url: '/wp-admin/admin-ajax.php',\n data: {\n action: 'ajax_load_more',\n foo: 'bar',\n }\n});\n</code></pre>\n\n<p><img src=\"https://i.ibb.co/MCdYJ7h/image.png\"></p>\n"
},
{
"answer_id": 331435,
"author": "butalin",
"author_id": 162878,
"author_profile": "https://wordpress.stackexchange.com/users/162878",
"pm_score": -1,
"selected": false,
"text": "<p>You haven't specify any response, functions that handle the ajax requests must return a json encoded array using wp_send_json _success() built-in function or other similar functions.</p>\n\n<p>Exemple :</p>\n\n<pre><code>function ajax_load_more(){\n\n wp_send_json_success('testing...');\n\n//Don t nee to use die() wp_send_json success will send json and die\n\n } \n</code></pre>\n\n<p>you can find out how these functions work in the <a href=\"https://codex.wordpress.org/Function_Reference/wp_send_json_success\" rel=\"nofollow noreferrer\">wordpress codex</a>, the php function can't echo anything, php send data to jquery and jquery then can echo data to html.</p>\n"
}
] | 2019/03/12 | [
"https://wordpress.stackexchange.com/questions/331422",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/146071/"
] | I have been delving into AJAX within WordPress and have followed many tutorials on how to do so, but every single request returns a 400 error.
In my **functions.php** I have added the following:
**Step 1** - Register and add scripts to WordPress
```
/**
* Initialize the JavaScript we need for loading more
*
* @return void
*/
function ajax_load_more_init()
{
// Register and enqueue the script we need for load more
wp_register_script('ajax-load-more-script', get_template_directory_uri() . '/assets/scripts/ajax-load-more.js', array('jquery'));
wp_enqueue_script('ajax-load-more-script');
// Localize the script so we can access tthe variables in PHP
wp_localize_script('ajax-load-more-script', 'ajax_load_more_object', array(
'ajax_url' => admin_url('admin-ajax.php'),
));
}
```
**Step 2** - Enqueue the actual script
```
/**
* Add AJAX loader to scripts
*/
add_action('wp_enqueue_scripts', 'ajax_load_more_init');
```
**Step 3** - Allow AJAX to be used on the frontend
```
// AJAX Hook for users
add_action('wp_ajax_ajax_load_more', 'ajax_load_more');
add_action('wp_ajax_nopriv_ajax_load_more', 'ajax_load_more');
```
**Step 4** - A dead simple function for testing
```
/**
* The backend PHP to actually load more posts
*
* @return void
*/
function ajax_load_more()
{
echo "TESTING";
wp_die();
}
```
In my actual AJAX script I have the following:
```
jQuery(document).ready(function ($) {
// Initialize Isotope as $grid
const $grid = $('#grid').isotope({
itemSelector: '.grid-item',
percentagePosition: true,
animationEngine: 'best-available', //CSS3 if browser supports it, jQuery otherwise
animationOptions: {
duration: 800,
},
masonry: {
columnWidth: '.grid-item',
gutter: 30,
},
})
var has_run = false;
var init_offset = 0;
// Hook into click event
$('button.load-more-posts').click(function (e) {
e.preventDefault();
var button = $(this);
var nonce = $(this).data("nonce");
console.log('Nonce is: ' + nonce);
// Disable the button
button.prop("disabled", true);
// Check the offset
if (has_run == false) {
button.data('offset', $(this).data("offset"));
init_offset = $(this).data("offset");
}
console.log('Initial offset is: ' + init_offset);
console.log('Initial offset is: ' + button.data('offset'));
// Perform AJAX request
$.ajax({
type: 'POST',
dataType: 'json',
url: ajax_load_more_object.ajax_url,
contentType: 'application/json; charset=utf-8',
data: {
action: 'ajax_load_more',
security: nonce,
init_offset: init_offset,
offset: button.data('offset'),
},
beforeSend: function (xhr) {
console.log('Loading more posts...')
button.text('Loading');
},
success: function (response) {
console.log(response);
// Undo Button Disable
button.prop("disabled", false);
// Set Offset
button.data("offset", offset + 10);
// Script has run
has_run = true;
return false;
},
error: function (xhr, status, error) {
console.log(xhr.responseText);
}
});
});
});
```
As you can see in the `$ajax` call, the url is to `admin-ajax` and the action is the trailing part of `wp_ajax_nopriv_ajax_load_more`.
The nonce comes from the button on the front end like so:
`<button class="load-more-posts" data-nonce="<?php echo wp_create_nonce('load_more_ajax'); ?>" data-offset="10">Load More Posts</button>`
[](https://i.stack.imgur.com/DT6XQ.jpg)
**My working code**
So, thanks to everyone's shared input I was able to come up with a solution that I'll detail below:
In functions.php (should really be in a plugin)
```
/**
* Additional thumbnail sizes
*/
add_theme_support('post-thumbnails');
add_image_size('post-thumbnail-square', 300, 300, true);
/**
* Initialize the JavaScript we need for loading more
*
* @return void
*/
function ajax_load_more_init()
{
// Register and enqueue the script we need for load more
wp_register_script('ajax-load-more-script', get_template_directory_uri() . '/assets/scripts/ajax-load-more.js', array('jquery'));
wp_enqueue_script('ajax-load-more-script');
// Localize the script so we can access tthe variables in PHP
wp_localize_script('ajax-load-more-script', 'ajax_load_more_object', array(
'ajax_url' => admin_url('admin-ajax.php'),
));
}
/**
* Add AJAX loader to scripts
*/
add_action('wp_enqueue_scripts', 'ajax_load_more_init');
/**
* Allow AJAX to be used on the front end
*/
add_action('wp_ajax_ajax_load_more_posts', 'ajax_load_more_posts_callback');
add_action('wp_ajax_nopriv_ajax_load_more_posts', 'ajax_load_more_posts_callback');
/**
* The backend PHP to actually load more posts
*
* @return void
*/
function ajax_load_more_posts_callback()
{
// First check the nonce, if it fails the function will break
check_ajax_referer('ajax_load_more_posts', 'security');
// Get the data we have from the load more button
$offset = $_POST['offset'];
$init_offset = $_POST['init_offset'];
// Get posts with given offset
if ($offset != null && absint($offset) && $init_offset != null && absint($init_offset)) {
// Finally, we'll set the query arguments and instantiate WP_Query
$args = array(
'post_type' => 'post',
'posts_per_page' => $init_offset,
'offset' => $offset
);
$post_list = array();
$query = new WP_Query($args);
if ($query->have_posts()) :
while ($query->have_posts()) : $query->the_post();
//$categories = get_the_categories();
$post_list[] = array(
'category' => get_the_category(),
'title' => get_the_title(),
'introduction' => get_field('introduction'),
'date' => get_the_date(),
'permalink' => get_permalink(),
'thumbnail' => get_the_post_thumbnail(),
);
endwhile;
endif;
echo json_encode($post_list);
wp_die();
}
}
```
In my ajax-loader script
```
jQuery(document).ready(function ($) {
var has_run = false;
var init_offset = 0;
// Hook into click event
$('button.load-more-posts').click(function (e) {
var $grid = $('#grid').isotope({
itemSelector: '.grid-item',
});
e.preventDefault();
var button = $(this);
var nonce = $(this).data("nonce");
// Disable the button
button.prop("disabled", true);
// Check the offset
if (has_run == false) {
button.data('offset', $(this).data("offset"));
init_offset = $(this).data("offset");
}
// Perform AJAX request
$.ajax({
type: 'POST',
dataType: 'json',
url: ajax_load_more_object.ajax_url,
data: {
action: 'ajax_load_more_posts',
security: nonce,
init_offset: init_offset,
offset: button.data('offset'),
},
beforeSend: function (xhr) {
console.log('Loading more posts...')
button.text('Loading');
},
success: function (response) {
console.log(response);
button.text('Load more');
// An array to store new items added via AJAX
var new_items = [];
// Run through JSON
$.each(response, function (key, value) {
var $new_item = $(`<div class="grid-item article-post-card ${value.category[0]['slug']}">
<a class="article-post-card__anchor" href=" ${value.permalink}" alt="${value.title}">
<div class="article-post-card__featured-image-container">
<div class="article-post-card__overlay"></div>
<div class="article-post-card__featured-image">
${value.thumbnail}
</div>
<div class="article-post-card__category-label">
${value.category[0]['name']}
</div>
</div>
<div class="article-post-card__content-wrapper">
<div class="article-post-card__publish-date">
<time class="updated" datetime="">${value.date}</time>
</div>
<div class="article-post-card__title">
${value.title}
</div>
<div class="article-post-card__excerpt">
${value.introduction}
</div>
</div>
</a>
</div>`);
new_items.push($new_item[0]);
});
// Add the new items to the grid
$grid
.isotope('insert', new_items)
.imagesLoaded().progress(function () {
$grid.isotope('layout');
});
// Undo Button Disable
button.prop("disabled", false);
// Set Offset
var offset = button.data("offset");
button.data("offset", offset + 10);
// Script has run
has_run = true;
return false;
},
error: function (xhr, status, error) {
console.log("There was an error", error);
}
});
});
});
```
If you guys could critique I think this would be useful for others too. | I have not tested your code, but one problem I noticed is the `contentType` property in your `$.ajax()` call:
```
contentType: 'application/json; charset=utf-8',
```
because that way, (from the PHP side) the action (i.e. `ajax_load_more`) is not available in `$_REQUEST['action']` which WordPress uses to determine the AJAX action being called, and when the action is not known, WordPress throws the error `400 Bad Request`, which in your case translates to "unknown AJAX action".
*You should just omit the `contentType` property, or don't set it to a JSON content type string.*
Also, although you're just testing in `ajax_load_more()`, make sure to return a proper JSON response/string because your `dataType` is `json`.
I hope this helps you. :)
Additional Notes
----------------
From the `jQuery.ajax()` [documentation](http://api.jquery.com/jquery.ajax/):
1. `dataType` (default: `Intelligent Guess (xml, json, script, or html)`)
>
> The type of data that you're *expecting back from the server*. If none
> is specified, jQuery will try to infer it based on the MIME type of
> the response
>
>
>
2. `contentType` (default: `'application/x-www-form-urlencoded; charset=UTF-8'`)
>
> When *sending data to the server*, use this content type. Default is
> "application/x-www-form-urlencoded; charset=UTF-8", which is fine for
> most cases. If you explicitly pass in a content-type to `$.ajax()`,
> then it is always sent to the server (even if no data is sent).
>
>
>
So `dataType` is the content type (MIME) of the content from the AJAX response, whereas `contentType` is the content type of the content you are *sending* to the PHP/server-side function (which is `ajax_load_more()` in your case).
UPDATE
------
>
> So by using the wrong content type the headers become unreadable?
>
>
>
No it is not about the headers become unreadable - (request) headers are always readable in PHP. It's just that **request *payload*** (in JSON) is not supported by the WordPress AJAX - only the request *body*. But you can of course, send form field data/value as JSON - for example, `myField: '{"foo":"bar","baz":1}'`. Just don't set the *content type header* to JSON.
But if you really must send a JSON request payload instead of a standard URL-encoded form data (i.e. the request body), then you can append the AJAX action to the AJAX URL - e.g. `/wp-admin/admin-ajax.php?action=ajax_load_more`. That way, you wouldn't get the error `400`; however, it's up to you to [retrieve/parse](https://stackoverflow.com/a/9597087/9217760) the JSON request payload..
### Request Payload (JSON)
```
jQuery.ajax({
type: 'POST',
url: '/wp-admin/admin-ajax.php?action=ajax_load_more',
contentType: 'application/json; charset=utf-8',
data: {
action: 'ajax_load_more',
foo: 'bar',
}
});
```

### Request Body (Form Data)
```
jQuery.ajax({
type: 'POST',
url: '/wp-admin/admin-ajax.php',
data: {
action: 'ajax_load_more',
foo: 'bar',
}
});
```
 |
331,425 | <p>I'm a newbie to WordPress; I just started learning WordPress. I'm trying to link style.css in functions.php but I am unable to achieve what might be the issue here. Can anyone point me the right direction?</p>
<p>index.php</p>
<pre><code><?php
get_header();
?>
<?php
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
echo 'Posts are foound';
}
} else {
echo 'No Posts are found';
}
?>
<div class="inner">
<?php bloginfo('title'); ?><br>
<?php bloginfo('description'); ?>
<?php echo "<h1>Hello world</h1>"; ?>
</div>
<?php
get_footer();
</code></pre>
<p>functions.php</p>
<pre><code> function mortal_theme() {
wp_enqueue_style( 'style', get_template_directory_uri() . '/style.css' );
}
add_action( 'wp_enqueue_scripts', 'mortal_theme' );
</code></pre>
<p>style.css</p>
<pre><code> h1 {
background-color: red;
color: yellow;
font-size: 28px;
font-weight: 700;
}
.inner {
width: 1100px;
margin: 0 auto;
}
</code></pre>
<p>header.php</p>
<pre><code><html>
<head>
<?php wp_head(); ?>
</head>
<header class="site-header">
<?php bloginfo('title'); ?>
</header>
</code></pre>
<p>footer.php</p>
<pre><code> <footer>
<p><?php bloginfo('title');?> - &copy; <?php echo date('Y');?></p>
</footer>
<?php wp_footer(); ?>
</body>
</html>
</code></pre>
| [
{
"answer_id": 331431,
"author": "Shihab",
"author_id": 113702,
"author_profile": "https://wordpress.stackexchange.com/users/113702",
"pm_score": 2,
"selected": false,
"text": "<p>Please check <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">wp_enqueue_style</a> and <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts\" rel=\"nofollow noreferrer\">wp_enqueue_scripts</a>.\nFirst of all create a function with any name you like ei: my_function and include your css file and then hook this function with <code>wp_enqueue_scripts</code>. Here is what I mean:</p>\n\n<pre><code>function my_function() {\n // This will load your default style.css\n wp_enqueue_style('main_style', get_stylesheet_uri());\n}\nadd_action('wp_enqueue_scripts', 'my_function');\n</code></pre>\n\n<p>But if you want to load another CSS file which isn't your WP style.css then you have to mention proper path. EI:</p>\n\n<pre><code>function my_function() {\n // This will load your default style.css\n wp_enqueue_style('main_style', get_stylesheet_uri());\n\n // This will load custom.css located in the css folder\n wp_enqueue_style('main_style', get_theme_file_uri('css/custom.css'));\n}\nadd_action('wp_enqueue_scripts', 'my_function');\n</code></pre>\n"
},
{
"answer_id": 331473,
"author": "semperlabs",
"author_id": 163019,
"author_profile": "https://wordpress.stackexchange.com/users/163019",
"pm_score": 0,
"selected": false,
"text": "<p>If it is child theme load stylesheet from child theme's directory as follows:</p>\n\n<pre><code>wp_enqueue_style('child-theme-styling', get_stylesheet_directory_uri() .'/style.css');\n</code></pre>\n"
},
{
"answer_id": 331538,
"author": "jsmod",
"author_id": 160457,
"author_profile": "https://wordpress.stackexchange.com/users/160457",
"pm_score": 3,
"selected": true,
"text": "<p>To get this working:</p>\n\n<p><strong>(1) Your <code>index.php</code> file should begin with:</strong></p>\n\n<pre><code><?php get_header(); ?>\n</code></pre>\n\n<p>and end with:</p>\n\n<pre><code><?php get_footer(); ?>\n</code></pre>\n\n<p><strong>(2) Your <code>header.php</code> file should have the following right <em>before</em> the closing <code></head></code> tag:</strong></p>\n\n<pre><code><?php wp_head(); ?>\n</code></pre>\n\n<p>Note: <code>header.php</code> also has other things, but I am assuming you have them set up already.</p>\n\n<p><strong>(3) Your <code>footer.php</code> file should have the following right <em>before</em> the closing <code></body></code> tag:</strong></p>\n\n<pre><code><?php wp_footer(); ?> \n</code></pre>\n\n<p><strong>(4) In your <code>functions.php</code>, modify your the second line of your wp_enqueue_style so that it looks like this:</strong></p>\n\n<pre><code>wp_enqueue_style( 'style', get_stylesheet_uri() );\n</code></pre>\n\n<p>The whole function in the end should look like this:</p>\n\n<pre><code>function mortal_theme() {\n wp_enqueue_style( 'style', get_template_directory_uri() );\n }\nadd_action( 'wp_enqueue_scripts', 'mortal_theme' );\n</code></pre>\n\n<p>This is because the <code>style.css</code> in your theme folder is the <em>main</em> stylesheet for the theme - so you don't need to tell WordPress to look for <code>style.css</code>, it will know what to look for.</p>\n\n<p><strong>Update:</strong></p>\n\n<p>I have recreated your theme using your code on a local WordPress installation to test it, and here is a screenshot of what I see when I visit the page:</p>\n\n<p><a href=\"https://i.stack.imgur.com/yAY48.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/yAY48.png\" alt=\"enter image description here\"></a></p>\n\n<p>The theme folder has the following files:</p>\n\n<ol>\n<li><code>style.css</code></li>\n<li><code>index.php</code></li>\n<li><code>header.php</code></li>\n<li><code>functions.php</code></li>\n<li><code>footer.php</code></li>\n</ol>\n\n<p>And I copied and pasted the <strong>exact</strong> code for each file from your original question, with <em>one</em> exception: for <code>functions.php</code> I added the starting <code><?php</code> tag so my final code looks like this:</p>\n\n<pre><code><?php\n function mortal_theme() {\n wp_enqueue_style( 'style', get_template_directory_uri() . '/style.css);\n }\n add_action( 'wp_enqueue_scripts', 'mortal_theme' );\n</code></pre>\n\n<p>Based on the screenshot above, everything seems to be working correctly. </p>\n\n<p>However, if I remove the <code><?php</code> that I added (to make my code match the one in your question 100%), this is what I see when I view the page:</p>\n\n<p><a href=\"https://i.stack.imgur.com/4A43n.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4A43n.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>What do you see when you view your page?</strong> If you're getting results like that in the second screenshot, then it is because you do not have the starting <code><?php</code> in the beginning of your <code>functions.php</code> file. Add that and you're good to go, insha'Allah.</p>\n"
},
{
"answer_id": 377031,
"author": "Salman.kodeforest",
"author_id": 196532,
"author_profile": "https://wordpress.stackexchange.com/users/196532",
"pm_score": 0,
"selected": false,
"text": "<p>I guess you are copy and pasting the exact function over there.</p>\n<pre><code>function mortal_theme() {\n wp_enqueue_style( 'style', get_template_directory_uri() . '/style.css);\n} \n add_action( 'wp_enqueue_scripts', 'mortal_theme');\n</code></pre>\n<p>This code will work only if you add the end tag at the end of the code. It should look like this exactly.</p>\n<p>Try putting an end tag at you end of the code '?>'\nHopefully this will work for you.</p>\n"
}
] | 2019/03/12 | [
"https://wordpress.stackexchange.com/questions/331425",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/131806/"
] | I'm a newbie to WordPress; I just started learning WordPress. I'm trying to link style.css in functions.php but I am unable to achieve what might be the issue here. Can anyone point me the right direction?
index.php
```
<?php
get_header();
?>
<?php
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
echo 'Posts are foound';
}
} else {
echo 'No Posts are found';
}
?>
<div class="inner">
<?php bloginfo('title'); ?><br>
<?php bloginfo('description'); ?>
<?php echo "<h1>Hello world</h1>"; ?>
</div>
<?php
get_footer();
```
functions.php
```
function mortal_theme() {
wp_enqueue_style( 'style', get_template_directory_uri() . '/style.css' );
}
add_action( 'wp_enqueue_scripts', 'mortal_theme' );
```
style.css
```
h1 {
background-color: red;
color: yellow;
font-size: 28px;
font-weight: 700;
}
.inner {
width: 1100px;
margin: 0 auto;
}
```
header.php
```
<html>
<head>
<?php wp_head(); ?>
</head>
<header class="site-header">
<?php bloginfo('title'); ?>
</header>
```
footer.php
```
<footer>
<p><?php bloginfo('title');?> - © <?php echo date('Y');?></p>
</footer>
<?php wp_footer(); ?>
</body>
</html>
``` | To get this working:
**(1) Your `index.php` file should begin with:**
```
<?php get_header(); ?>
```
and end with:
```
<?php get_footer(); ?>
```
**(2) Your `header.php` file should have the following right *before* the closing `</head>` tag:**
```
<?php wp_head(); ?>
```
Note: `header.php` also has other things, but I am assuming you have them set up already.
**(3) Your `footer.php` file should have the following right *before* the closing `</body>` tag:**
```
<?php wp_footer(); ?>
```
**(4) In your `functions.php`, modify your the second line of your wp\_enqueue\_style so that it looks like this:**
```
wp_enqueue_style( 'style', get_stylesheet_uri() );
```
The whole function in the end should look like this:
```
function mortal_theme() {
wp_enqueue_style( 'style', get_template_directory_uri() );
}
add_action( 'wp_enqueue_scripts', 'mortal_theme' );
```
This is because the `style.css` in your theme folder is the *main* stylesheet for the theme - so you don't need to tell WordPress to look for `style.css`, it will know what to look for.
**Update:**
I have recreated your theme using your code on a local WordPress installation to test it, and here is a screenshot of what I see when I visit the page:
[](https://i.stack.imgur.com/yAY48.png)
The theme folder has the following files:
1. `style.css`
2. `index.php`
3. `header.php`
4. `functions.php`
5. `footer.php`
And I copied and pasted the **exact** code for each file from your original question, with *one* exception: for `functions.php` I added the starting `<?php` tag so my final code looks like this:
```
<?php
function mortal_theme() {
wp_enqueue_style( 'style', get_template_directory_uri() . '/style.css);
}
add_action( 'wp_enqueue_scripts', 'mortal_theme' );
```
Based on the screenshot above, everything seems to be working correctly.
However, if I remove the `<?php` that I added (to make my code match the one in your question 100%), this is what I see when I view the page:
[](https://i.stack.imgur.com/4A43n.png)
**What do you see when you view your page?** If you're getting results like that in the second screenshot, then it is because you do not have the starting `<?php` in the beginning of your `functions.php` file. Add that and you're good to go, insha'Allah. |
331,445 | <p>probably a long shot, but here goes: for a WordPress portfolio site, I’m trying to build a project overview page with a layout similar to this: <a href="http://www.innauer-matt.com/" rel="nofollow noreferrer">http://www.innauer-matt.com/</a></p>
<p>Each row of images is centered, with a margin of 60 px between the images. The container max-width is 1400 px, so that every time the viewport width is less than that, the images are rearranged.</p>
<p>If anyone could point me to a theme that works like this, that would be greatly appreciated!</p>
<p>Thanks!</p>
| [
{
"answer_id": 331431,
"author": "Shihab",
"author_id": 113702,
"author_profile": "https://wordpress.stackexchange.com/users/113702",
"pm_score": 2,
"selected": false,
"text": "<p>Please check <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">wp_enqueue_style</a> and <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts\" rel=\"nofollow noreferrer\">wp_enqueue_scripts</a>.\nFirst of all create a function with any name you like ei: my_function and include your css file and then hook this function with <code>wp_enqueue_scripts</code>. Here is what I mean:</p>\n\n<pre><code>function my_function() {\n // This will load your default style.css\n wp_enqueue_style('main_style', get_stylesheet_uri());\n}\nadd_action('wp_enqueue_scripts', 'my_function');\n</code></pre>\n\n<p>But if you want to load another CSS file which isn't your WP style.css then you have to mention proper path. EI:</p>\n\n<pre><code>function my_function() {\n // This will load your default style.css\n wp_enqueue_style('main_style', get_stylesheet_uri());\n\n // This will load custom.css located in the css folder\n wp_enqueue_style('main_style', get_theme_file_uri('css/custom.css'));\n}\nadd_action('wp_enqueue_scripts', 'my_function');\n</code></pre>\n"
},
{
"answer_id": 331473,
"author": "semperlabs",
"author_id": 163019,
"author_profile": "https://wordpress.stackexchange.com/users/163019",
"pm_score": 0,
"selected": false,
"text": "<p>If it is child theme load stylesheet from child theme's directory as follows:</p>\n\n<pre><code>wp_enqueue_style('child-theme-styling', get_stylesheet_directory_uri() .'/style.css');\n</code></pre>\n"
},
{
"answer_id": 331538,
"author": "jsmod",
"author_id": 160457,
"author_profile": "https://wordpress.stackexchange.com/users/160457",
"pm_score": 3,
"selected": true,
"text": "<p>To get this working:</p>\n\n<p><strong>(1) Your <code>index.php</code> file should begin with:</strong></p>\n\n<pre><code><?php get_header(); ?>\n</code></pre>\n\n<p>and end with:</p>\n\n<pre><code><?php get_footer(); ?>\n</code></pre>\n\n<p><strong>(2) Your <code>header.php</code> file should have the following right <em>before</em> the closing <code></head></code> tag:</strong></p>\n\n<pre><code><?php wp_head(); ?>\n</code></pre>\n\n<p>Note: <code>header.php</code> also has other things, but I am assuming you have them set up already.</p>\n\n<p><strong>(3) Your <code>footer.php</code> file should have the following right <em>before</em> the closing <code></body></code> tag:</strong></p>\n\n<pre><code><?php wp_footer(); ?> \n</code></pre>\n\n<p><strong>(4) In your <code>functions.php</code>, modify your the second line of your wp_enqueue_style so that it looks like this:</strong></p>\n\n<pre><code>wp_enqueue_style( 'style', get_stylesheet_uri() );\n</code></pre>\n\n<p>The whole function in the end should look like this:</p>\n\n<pre><code>function mortal_theme() {\n wp_enqueue_style( 'style', get_template_directory_uri() );\n }\nadd_action( 'wp_enqueue_scripts', 'mortal_theme' );\n</code></pre>\n\n<p>This is because the <code>style.css</code> in your theme folder is the <em>main</em> stylesheet for the theme - so you don't need to tell WordPress to look for <code>style.css</code>, it will know what to look for.</p>\n\n<p><strong>Update:</strong></p>\n\n<p>I have recreated your theme using your code on a local WordPress installation to test it, and here is a screenshot of what I see when I visit the page:</p>\n\n<p><a href=\"https://i.stack.imgur.com/yAY48.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/yAY48.png\" alt=\"enter image description here\"></a></p>\n\n<p>The theme folder has the following files:</p>\n\n<ol>\n<li><code>style.css</code></li>\n<li><code>index.php</code></li>\n<li><code>header.php</code></li>\n<li><code>functions.php</code></li>\n<li><code>footer.php</code></li>\n</ol>\n\n<p>And I copied and pasted the <strong>exact</strong> code for each file from your original question, with <em>one</em> exception: for <code>functions.php</code> I added the starting <code><?php</code> tag so my final code looks like this:</p>\n\n<pre><code><?php\n function mortal_theme() {\n wp_enqueue_style( 'style', get_template_directory_uri() . '/style.css);\n }\n add_action( 'wp_enqueue_scripts', 'mortal_theme' );\n</code></pre>\n\n<p>Based on the screenshot above, everything seems to be working correctly. </p>\n\n<p>However, if I remove the <code><?php</code> that I added (to make my code match the one in your question 100%), this is what I see when I view the page:</p>\n\n<p><a href=\"https://i.stack.imgur.com/4A43n.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4A43n.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>What do you see when you view your page?</strong> If you're getting results like that in the second screenshot, then it is because you do not have the starting <code><?php</code> in the beginning of your <code>functions.php</code> file. Add that and you're good to go, insha'Allah.</p>\n"
},
{
"answer_id": 377031,
"author": "Salman.kodeforest",
"author_id": 196532,
"author_profile": "https://wordpress.stackexchange.com/users/196532",
"pm_score": 0,
"selected": false,
"text": "<p>I guess you are copy and pasting the exact function over there.</p>\n<pre><code>function mortal_theme() {\n wp_enqueue_style( 'style', get_template_directory_uri() . '/style.css);\n} \n add_action( 'wp_enqueue_scripts', 'mortal_theme');\n</code></pre>\n<p>This code will work only if you add the end tag at the end of the code. It should look like this exactly.</p>\n<p>Try putting an end tag at you end of the code '?>'\nHopefully this will work for you.</p>\n"
}
] | 2019/03/12 | [
"https://wordpress.stackexchange.com/questions/331445",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/163000/"
] | probably a long shot, but here goes: for a WordPress portfolio site, I’m trying to build a project overview page with a layout similar to this: <http://www.innauer-matt.com/>
Each row of images is centered, with a margin of 60 px between the images. The container max-width is 1400 px, so that every time the viewport width is less than that, the images are rearranged.
If anyone could point me to a theme that works like this, that would be greatly appreciated!
Thanks! | To get this working:
**(1) Your `index.php` file should begin with:**
```
<?php get_header(); ?>
```
and end with:
```
<?php get_footer(); ?>
```
**(2) Your `header.php` file should have the following right *before* the closing `</head>` tag:**
```
<?php wp_head(); ?>
```
Note: `header.php` also has other things, but I am assuming you have them set up already.
**(3) Your `footer.php` file should have the following right *before* the closing `</body>` tag:**
```
<?php wp_footer(); ?>
```
**(4) In your `functions.php`, modify your the second line of your wp\_enqueue\_style so that it looks like this:**
```
wp_enqueue_style( 'style', get_stylesheet_uri() );
```
The whole function in the end should look like this:
```
function mortal_theme() {
wp_enqueue_style( 'style', get_template_directory_uri() );
}
add_action( 'wp_enqueue_scripts', 'mortal_theme' );
```
This is because the `style.css` in your theme folder is the *main* stylesheet for the theme - so you don't need to tell WordPress to look for `style.css`, it will know what to look for.
**Update:**
I have recreated your theme using your code on a local WordPress installation to test it, and here is a screenshot of what I see when I visit the page:
[](https://i.stack.imgur.com/yAY48.png)
The theme folder has the following files:
1. `style.css`
2. `index.php`
3. `header.php`
4. `functions.php`
5. `footer.php`
And I copied and pasted the **exact** code for each file from your original question, with *one* exception: for `functions.php` I added the starting `<?php` tag so my final code looks like this:
```
<?php
function mortal_theme() {
wp_enqueue_style( 'style', get_template_directory_uri() . '/style.css);
}
add_action( 'wp_enqueue_scripts', 'mortal_theme' );
```
Based on the screenshot above, everything seems to be working correctly.
However, if I remove the `<?php` that I added (to make my code match the one in your question 100%), this is what I see when I view the page:
[](https://i.stack.imgur.com/4A43n.png)
**What do you see when you view your page?** If you're getting results like that in the second screenshot, then it is because you do not have the starting `<?php` in the beginning of your `functions.php` file. Add that and you're good to go, insha'Allah. |
331,457 | <p>I'm using an action from one plugin that needs to call a function from another plugin. That function is name spaced.</p>
<p>Typically, I would use something like:</p>
<pre><code>add_action( 'hook_name', 'function_name' );
</code></pre>
<p>But the plugin's function is Namespaced and/or object-oriented, so I'm not sure how to reference the function in that case. </p>
<p>I.e., how do I reference that specific function?</p>
| [
{
"answer_id": 331458,
"author": "Joe Fletcher",
"author_id": 7397,
"author_profile": "https://wordpress.stackexchange.com/users/7397",
"pm_score": 2,
"selected": true,
"text": "<p>Here is generic code that worked for me. If anyone wants a real-life example, please let me know. </p>\n\n<p>This creates a function that calls the plugin's function assuming the namespace is \"Custom\"</p>\n\n<pre><code>add_action( 'hook_name', 'my_custom_function_name' );\nfunction my_custom_function_name() {\n // Check if \"Custom Plugin\" installed and activated\n if ( did_action( 'plugin/loaded' ) ) {\n // call the Plugin's function (clear_cache function example here)\n \\Custom\\Plugin::instance()->files_manager->clear_cache();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 331461,
"author": "hamdirizal",
"author_id": 133145,
"author_profile": "https://wordpress.stackexchange.com/users/133145",
"pm_score": 2,
"selected": false,
"text": "<p><code>add_action</code>'s second parameter is a <code>callable</code>, it can accept a string (like what you did in the example) or an array of class-instance and function name.</p>\n\n<p>For example, if you want to call a method <code>get_age()</code> from <code>Person</code> class, you can do this:</p>\n\n<pre><code>$person = new Person();\nadd_action( 'hook_name', array($person , 'get_age') );\n</code></pre>\n"
}
] | 2019/03/12 | [
"https://wordpress.stackexchange.com/questions/331457",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/7397/"
] | I'm using an action from one plugin that needs to call a function from another plugin. That function is name spaced.
Typically, I would use something like:
```
add_action( 'hook_name', 'function_name' );
```
But the plugin's function is Namespaced and/or object-oriented, so I'm not sure how to reference the function in that case.
I.e., how do I reference that specific function? | Here is generic code that worked for me. If anyone wants a real-life example, please let me know.
This creates a function that calls the plugin's function assuming the namespace is "Custom"
```
add_action( 'hook_name', 'my_custom_function_name' );
function my_custom_function_name() {
// Check if "Custom Plugin" installed and activated
if ( did_action( 'plugin/loaded' ) ) {
// call the Plugin's function (clear_cache function example here)
\Custom\Plugin::instance()->files_manager->clear_cache();
}
}
``` |
331,474 | <p>I want to exclude two items (using their IDs) from an array that's retrieving images attached to the post: the post's thumbnail (featured image) and an image attached via Advanced Custom Fields.</p>
<p>I'm getting the first one's ID using <code>get_post_thumbnail_id()</code> and this last one's ID using <code>get_field_object('icon')</code>, where <code>'icon'</code> is the <code>$selector</code> of the custom field (essentially an image, that's being used as an icon). If you're not familiar with ACF's Documentation the relevant part about this is <a href="https://www.advancedcustomfields.com/resources/get_field_object/" rel="nofollow noreferrer">here</a>.</p>
<p>I've scrapped everything irrelevant for demonstration purposes. This is what I have and where [I believe] my problem is at:</p>
<pre><code>$var = get_children(array(
'exclude' => array(
get_post_thumbnail_id(),
get_field_object('icon')['ID'])
));
</code></pre>
<p>I'm thinking the result of <code>get_post_thumbnail_id</code> is an integer, so it works perfectly, but the result of <code>get_field_object['ID']</code> is a string and that's why it doesn't work. If I could use something like <code>echo</code> it would probably work.</p>
<p>I would love to understand where it's wrong and how to make this work, please.</p>
| [
{
"answer_id": 331458,
"author": "Joe Fletcher",
"author_id": 7397,
"author_profile": "https://wordpress.stackexchange.com/users/7397",
"pm_score": 2,
"selected": true,
"text": "<p>Here is generic code that worked for me. If anyone wants a real-life example, please let me know. </p>\n\n<p>This creates a function that calls the plugin's function assuming the namespace is \"Custom\"</p>\n\n<pre><code>add_action( 'hook_name', 'my_custom_function_name' );\nfunction my_custom_function_name() {\n // Check if \"Custom Plugin\" installed and activated\n if ( did_action( 'plugin/loaded' ) ) {\n // call the Plugin's function (clear_cache function example here)\n \\Custom\\Plugin::instance()->files_manager->clear_cache();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 331461,
"author": "hamdirizal",
"author_id": 133145,
"author_profile": "https://wordpress.stackexchange.com/users/133145",
"pm_score": 2,
"selected": false,
"text": "<p><code>add_action</code>'s second parameter is a <code>callable</code>, it can accept a string (like what you did in the example) or an array of class-instance and function name.</p>\n\n<p>For example, if you want to call a method <code>get_age()</code> from <code>Person</code> class, you can do this:</p>\n\n<pre><code>$person = new Person();\nadd_action( 'hook_name', array($person , 'get_age') );\n</code></pre>\n"
}
] | 2019/03/12 | [
"https://wordpress.stackexchange.com/questions/331474",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98727/"
] | I want to exclude two items (using their IDs) from an array that's retrieving images attached to the post: the post's thumbnail (featured image) and an image attached via Advanced Custom Fields.
I'm getting the first one's ID using `get_post_thumbnail_id()` and this last one's ID using `get_field_object('icon')`, where `'icon'` is the `$selector` of the custom field (essentially an image, that's being used as an icon). If you're not familiar with ACF's Documentation the relevant part about this is [here](https://www.advancedcustomfields.com/resources/get_field_object/).
I've scrapped everything irrelevant for demonstration purposes. This is what I have and where [I believe] my problem is at:
```
$var = get_children(array(
'exclude' => array(
get_post_thumbnail_id(),
get_field_object('icon')['ID'])
));
```
I'm thinking the result of `get_post_thumbnail_id` is an integer, so it works perfectly, but the result of `get_field_object['ID']` is a string and that's why it doesn't work. If I could use something like `echo` it would probably work.
I would love to understand where it's wrong and how to make this work, please. | Here is generic code that worked for me. If anyone wants a real-life example, please let me know.
This creates a function that calls the plugin's function assuming the namespace is "Custom"
```
add_action( 'hook_name', 'my_custom_function_name' );
function my_custom_function_name() {
// Check if "Custom Plugin" installed and activated
if ( did_action( 'plugin/loaded' ) ) {
// call the Plugin's function (clear_cache function example here)
\Custom\Plugin::instance()->files_manager->clear_cache();
}
}
``` |
331,513 | <p>How do I customize the translation of the Month name strings in WordPress?</p>
<p>example </p>
<p>"January" be "Jan11" in all of website </p>
| [
{
"answer_id": 331610,
"author": "jsmod",
"author_id": 160457,
"author_profile": "https://wordpress.stackexchange.com/users/160457",
"pm_score": 3,
"selected": true,
"text": "<p>Add the following to your existing <code>functions.php</code> file:</p>\n\n<pre><code>function ra_change_translate_text( $translated_text ) {\n if ( $translated_text == 'January' ) {\n $translated_text = 'Jan11';\n }\n return $translated_text;\n}\nadd_filter( 'gettext', 'ra_change_translate_text', 20 );\n</code></pre>\n\n<p>If you want to change multiple strings, use this function instead:</p>\n\n<pre><code>function ra_change_translate_text_multiple( $translated ) {\n $text = array(\n 'January' => 'Jan11',\n 'February' => 'Feb22',\n 'March' => 'Mar33',\n );\n $translated = str_ireplace( array_keys($text), $text, $translated );\n return $translated;\n}\nadd_filter( 'gettext', 'ra_change_translate_text_multiple', 20 );\n</code></pre>\n\n<p>You can add as many strings as you want, for example:</p>\n\n<pre><code>'April' => 'Apr44',\n</code></pre>\n\n<p>And the new translation can also be in a foreign language. Here's an example with Arabic:</p>\n\n<pre><code>'May' => 'مايو',\n</code></pre>\n\n<p>Last notes: If you use this function, keep in mind this will change the string translation <strong><em>everywhere</em></strong> in your WordPress site: front and back end. <strong>January</strong> will become <strong>Jan11</strong> <em>everywhere</em>. Try it and see.</p>\n\n<p>If that is acceptable to you then you're good to go. Otherwise, if you were looking to change the strings only on the front end (for your visitors to see), then consider making the changes to your theme or WordPress website language settings (which can be different from the admin language) - as suggested in some of the comments above.</p>\n\n<p>Also, for reference, I learned about this function here: <a href=\"https://ronangelo.com/change-or-translate-text-on-a-wordpress-theme/\" rel=\"nofollow noreferrer\">https://ronangelo.com/change-or-translate-text-on-a-wordpress-theme/</a>. It is a very good post and if you want further information on translating text or themes in WordPress I recommend reading it.</p>\n\n<p><strong>Update to the original answer:</strong></p>\n\n<p>This function can only be used with words that are translatable - meaning, those wrapped in these functions <code>( __(), _e() )</code>...</p>\n\n<p>However, your comment and the website you linked to have given me a clearer idea of what you are trying to achieve. Simply change the locale of the PHP used to show that date to <code>ar-LB.UTF-8</code>. Lebanon is one of the Arabic locales that uses أذار for March, whereas other locales use مارس. The php locale will then render the date as you want it with no need for digging into translations and strings.</p>\n\n<p>So, in your WordPress theme, use this code where you want to display the date instead of the code you are already using:</p>\n\n<pre><code><?php \n setlocale(LC_ALL, 'ar_LB.UTF-8');\n echo strftime(\"%e %B %Y\");\n?>\n</code></pre>\n\n<p>In the source code of the page you linked to, the date is displayed within these lines of code:</p>\n\n<p><a href=\"https://i.stack.imgur.com/JVdag.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/JVdag.png\" alt=\"enter image description here\"></a></p>\n\n<p>Depending on how you organized your theme, that bit could be in <code>header.php</code> or maybe even a template part. Find it and you will see that the old PHP code to echo the date will be there between the tags. Paste the snippet I gave you in its place.</p>\n\n<p>Do keep in mind that if this theme is not your own unique one and you're not using a child theme you might lose that modification if the parent theme is updated.</p>\n\n<p>I hope this helps. Please let me know if you need further assistance.</p>\n"
},
{
"answer_id": 331611,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 0,
"selected": false,
"text": "<p>The right approach is as suggested by @Jos in a comment to your question , or you can write a function where you can replace the date string extracted from WordPress functions like <code>get_the_date()</code> for desired output. </p>\n\n<p>Here is an example function that may help.</p>\n\n<pre><code>function my_custom_date($date){\n $new_date = getdate(strtotime($date));\n\n // Array that holds customized month's name\n $my_months=[\n 'January' => '1st Month',\n 'February' => '2nd Month',\n 'March' => '3rd Month',\n 'April' => '4th Month',\n 'May' => '5th Month',\n 'June' => '6th Month',\n 'July' => '7th Month',\n 'August' => '8th Month',\n 'September' => '9th Month',\n 'October' => '10th Month',\n 'November' => '11th Month',\n 'December' => '12th Month',\n ];\n\n\n\n $new_date['month']= $my_months[$new_date['month']];\n\n return $new_date['month'].' '.$new_date['mday']. ', '. $new_date['year'];\n\n }\n</code></pre>\n\n<p>Then you can use this function to display dates in your site. For example,</p>\n\n<pre><code>echo my_custom_date( get_the_date() ); // Post publish date, within a loop\n\necho my_custom_date( \"May 10, 2017\" ); // Outputs: 5th Month 10, 2017\n</code></pre>\n"
},
{
"answer_id": 405230,
"author": "maxime schoeni",
"author_id": 81094,
"author_profile": "https://wordpress.stackexchange.com/users/81094",
"pm_score": 0,
"selected": false,
"text": "<pre><code>global $wp_locale;\necho $wp_locale->get_month('01'); // string between '01' and '12'\n \n</code></pre>\n<p>Doc:\n<a href=\"https://developer.wordpress.org/reference/classes/wp_locale/get_month/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/classes/wp_locale/get_month/</a></p>\n"
}
] | 2019/03/13 | [
"https://wordpress.stackexchange.com/questions/331513",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/163057/"
] | How do I customize the translation of the Month name strings in WordPress?
example
"January" be "Jan11" in all of website | Add the following to your existing `functions.php` file:
```
function ra_change_translate_text( $translated_text ) {
if ( $translated_text == 'January' ) {
$translated_text = 'Jan11';
}
return $translated_text;
}
add_filter( 'gettext', 'ra_change_translate_text', 20 );
```
If you want to change multiple strings, use this function instead:
```
function ra_change_translate_text_multiple( $translated ) {
$text = array(
'January' => 'Jan11',
'February' => 'Feb22',
'March' => 'Mar33',
);
$translated = str_ireplace( array_keys($text), $text, $translated );
return $translated;
}
add_filter( 'gettext', 'ra_change_translate_text_multiple', 20 );
```
You can add as many strings as you want, for example:
```
'April' => 'Apr44',
```
And the new translation can also be in a foreign language. Here's an example with Arabic:
```
'May' => 'مايو',
```
Last notes: If you use this function, keep in mind this will change the string translation ***everywhere*** in your WordPress site: front and back end. **January** will become **Jan11** *everywhere*. Try it and see.
If that is acceptable to you then you're good to go. Otherwise, if you were looking to change the strings only on the front end (for your visitors to see), then consider making the changes to your theme or WordPress website language settings (which can be different from the admin language) - as suggested in some of the comments above.
Also, for reference, I learned about this function here: <https://ronangelo.com/change-or-translate-text-on-a-wordpress-theme/>. It is a very good post and if you want further information on translating text or themes in WordPress I recommend reading it.
**Update to the original answer:**
This function can only be used with words that are translatable - meaning, those wrapped in these functions `( __(), _e() )`...
However, your comment and the website you linked to have given me a clearer idea of what you are trying to achieve. Simply change the locale of the PHP used to show that date to `ar-LB.UTF-8`. Lebanon is one of the Arabic locales that uses أذار for March, whereas other locales use مارس. The php locale will then render the date as you want it with no need for digging into translations and strings.
So, in your WordPress theme, use this code where you want to display the date instead of the code you are already using:
```
<?php
setlocale(LC_ALL, 'ar_LB.UTF-8');
echo strftime("%e %B %Y");
?>
```
In the source code of the page you linked to, the date is displayed within these lines of code:
[](https://i.stack.imgur.com/JVdag.png)
Depending on how you organized your theme, that bit could be in `header.php` or maybe even a template part. Find it and you will see that the old PHP code to echo the date will be there between the tags. Paste the snippet I gave you in its place.
Do keep in mind that if this theme is not your own unique one and you're not using a child theme you might lose that modification if the parent theme is updated.
I hope this helps. Please let me know if you need further assistance. |
331,563 | <p>I want to have a small header at the top of a page showing the featured images with a link to the related custom post type.</p>
<p>This is my code:</p>
<pre><code>// Creates random image header within tax called(defaults to residential).
add_shortcode( 'rt-random-projects', 'rt_random_projects' );
function rt_random_projects($atts) {
$a = shortcode_atts( array(
'category' => 'residential',
),
$atts
);
$query = new WP_Query(
array(
'post_type' => 'jf_projects',
'posts_per_page' => '3',
'orderby' => 'RAND',
'tax_query' => array(
array(
'taxonomy' => 'project_types',
'field' => 'slug',
'terms' => $a['category'],
)
)
)
);
$count = $query->post_count;
$projects ='<div>';
while ( $query->have_posts() ) : $query->the_post();
$projects .= '<div class="projectheaderimg"><a href="'.get_the_permalink().'">'.get_the_post_thumbnail('','small').'</a></div>';
endwhile; //end while posts
$projects .='</div>';
wp_reset_postdata();
// Code
return $projects;
}
</code></pre>
<p>This brings up my images and links to the posts, but it isn't random. No matter what I do it still shows only the same 3 posts. How can I make it pull 3 random posts?</p>
| [
{
"answer_id": 331564,
"author": "mrben522",
"author_id": 84703,
"author_profile": "https://wordpress.stackexchange.com/users/84703",
"pm_score": 0,
"selected": false,
"text": "<p>More than likely this is a problem with your host. A lot of the big name managed WP hosting companies disable orderby random by default. If they are good (WPEngine) you can reach out to their support and get that enabled. If they suck (GoDaddy) you might have less luck with that request.<br>\nIf that's the case then you will need to write a function to get all the posts, assign each a random number and then order those by that number and pick the top n posts that way. Which is exactly as slow and bad as it sounds.</p>\n"
},
{
"answer_id": 331615,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 3,
"selected": true,
"text": "<p>Starting from WordPress version 4.5, you can use <code>RAND(<em>seed</em>)</code> with the <code>orderby</code> parameter.</p>\n\n<p>However, when the value is simply <code>RAND</code> (i.e. the uppercase of <code>rand</code>), <code>WP_Query</code> ignores it and defaults to the default sorting (which is by the post date).</p>\n\n<p>I've confirmed that by inspecting the <code>$query->request</code>:</p>\n\n<ol>\n<li><p>With <code>'orderby' => 'RAND'</code>, the <code>ORDER BY</code> clause is <code>ORDER BY wp_posts.post_date DESC</code>.</p></li>\n<li><p>With <code>'orderby' => 'rand'</code>, the <code>ORDER BY</code> clause is <code>ORDER BY RAND()</code>.</p></li>\n</ol>\n\n<p>So the solution is simple: <strong>Always use <code>rand</code></strong>, unless you want to use a <em>seed</em>.</p>\n"
}
] | 2019/03/13 | [
"https://wordpress.stackexchange.com/questions/331563",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77767/"
] | I want to have a small header at the top of a page showing the featured images with a link to the related custom post type.
This is my code:
```
// Creates random image header within tax called(defaults to residential).
add_shortcode( 'rt-random-projects', 'rt_random_projects' );
function rt_random_projects($atts) {
$a = shortcode_atts( array(
'category' => 'residential',
),
$atts
);
$query = new WP_Query(
array(
'post_type' => 'jf_projects',
'posts_per_page' => '3',
'orderby' => 'RAND',
'tax_query' => array(
array(
'taxonomy' => 'project_types',
'field' => 'slug',
'terms' => $a['category'],
)
)
)
);
$count = $query->post_count;
$projects ='<div>';
while ( $query->have_posts() ) : $query->the_post();
$projects .= '<div class="projectheaderimg"><a href="'.get_the_permalink().'">'.get_the_post_thumbnail('','small').'</a></div>';
endwhile; //end while posts
$projects .='</div>';
wp_reset_postdata();
// Code
return $projects;
}
```
This brings up my images and links to the posts, but it isn't random. No matter what I do it still shows only the same 3 posts. How can I make it pull 3 random posts? | Starting from WordPress version 4.5, you can use `RAND(*seed*)` with the `orderby` parameter.
However, when the value is simply `RAND` (i.e. the uppercase of `rand`), `WP_Query` ignores it and defaults to the default sorting (which is by the post date).
I've confirmed that by inspecting the `$query->request`:
1. With `'orderby' => 'RAND'`, the `ORDER BY` clause is `ORDER BY wp_posts.post_date DESC`.
2. With `'orderby' => 'rand'`, the `ORDER BY` clause is `ORDER BY RAND()`.
So the solution is simple: **Always use `rand`**, unless you want to use a *seed*. |
331,628 | <p>I have a Wordpress/WooCommerce webshop and I use WooCommerce Subscriptions. I want to disable the "Upgrade or Downgrade" button in My account > My Subsccriptions for users which have a specific user role. I found 2 pieces of php script but I don't know how to combine these two.</p>
<p>The first is to check if a user has a specific role:</p>
<pre><code>/**
* Check user has specific role
*
* @param string $role
* @param int $user_id
* @return bool
*/
function is_user_has_role( $role, $user_id = null ) {
if ( is_numeric( $user_id ) ) {
$user = get_userdata( $user_id );
}
else {
$user = wp_get_current_user();
}
if ( !empty( $user ) ) {
return in_array( $role, (array) $user->roles );
}
else
{
return false;
}
}
</code></pre>
<p>If the user has the user role 'subscriber_plus' the "Upgrade or Downgrade" button should be disabled/removed. For that I found this php script:</p>
<pre><code>/**
* Remove the "Change Payment Method" button from the My Subscriptions table.
*
* This isn't actually necessary because @see eg_subscription_payment_method_cannot_be_changed()
* will prevent the button being displayed, however, it is included here as an example of how to
* remove just the button but allow the change payment method process.
*/
function eg_remove_my_subscriptions_button( $actions, $subscription ) {
foreach ( $actions as $action_key => $action ) {
switch ( $action_key ) {
// case 'change_payment_method': // Hide "Change Payment Method" button?
// case 'change_address': // Hide "Change Address" button?
case 'switch': // Hide "Switch Subscription" button?
// case 'resubscribe': // Hide "Resubscribe" button from an expired or cancelled subscription?
// case 'pay': // Hide "Pay" button on subscriptions that are "on-hold" as they require payment?
// case 'reactivate': // Hide "Reactive" button on subscriptions that are "on-hold"?
// case 'cancel': // Hide "Cancel" button on subscriptions that are "active" or "on-hold"?
unset( $actions[ $action_key ] );
break;
default:
error_log( '-- $action = ' . print_r( $action, true ) );
break;
}
}
return $actions;
}
add_filter( 'wcs_view_subscription_actions', 'eg_remove_my_subscriptions_button', 100, 2 );
</code></pre>
<p>I can't figure it out how to combine these scripts to make this work.
Hope my question is clear.</p>
<p>My Wordpress version is: 5.1.1
WooCommerce Subscriptions version: 2.5.2</p>
| [
{
"answer_id": 332720,
"author": "Frotmans",
"author_id": 150887,
"author_profile": "https://wordpress.stackexchange.com/users/150887",
"pm_score": 1,
"selected": false,
"text": "<p>I have found/made the code that works. Maybe it helps somebody else.</p>\n\n<pre><code>/**\n* Remove the \"Upgrade or Downgrade\" button from the My Subscription table if user role is \"subscriber_plus\".\n*/\nadd_filter('woocommerce_subscriptions_switch_link', 'remove_switch_button', 10, 4);\nfunction remove_switch_button($switch_link, $item_id, $item, $subscription) {\n$user = wp_get_current_user();\nif ( in_array( 'subscriber_plus', (array) $user->roles ) ) {\n return '';\n}\nreturn $switch_link;\n</code></pre>\n"
},
{
"answer_id": 378424,
"author": "Andrew Schultz",
"author_id": 101154,
"author_profile": "https://wordpress.stackexchange.com/users/101154",
"pm_score": 0,
"selected": false,
"text": "<p>I used the following code to remove the action to prevent the code from running. I think it's cleaner than using the filter to return an empty string for the switch link.</p>\n<pre><code>remove_action('woocommerce_order_item_meta_end', array('WC_Subscriptions_Switcher', 'print_switch_link'), 10, 3);\n</code></pre>\n"
}
] | 2019/03/14 | [
"https://wordpress.stackexchange.com/questions/331628",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/150887/"
] | I have a Wordpress/WooCommerce webshop and I use WooCommerce Subscriptions. I want to disable the "Upgrade or Downgrade" button in My account > My Subsccriptions for users which have a specific user role. I found 2 pieces of php script but I don't know how to combine these two.
The first is to check if a user has a specific role:
```
/**
* Check user has specific role
*
* @param string $role
* @param int $user_id
* @return bool
*/
function is_user_has_role( $role, $user_id = null ) {
if ( is_numeric( $user_id ) ) {
$user = get_userdata( $user_id );
}
else {
$user = wp_get_current_user();
}
if ( !empty( $user ) ) {
return in_array( $role, (array) $user->roles );
}
else
{
return false;
}
}
```
If the user has the user role 'subscriber\_plus' the "Upgrade or Downgrade" button should be disabled/removed. For that I found this php script:
```
/**
* Remove the "Change Payment Method" button from the My Subscriptions table.
*
* This isn't actually necessary because @see eg_subscription_payment_method_cannot_be_changed()
* will prevent the button being displayed, however, it is included here as an example of how to
* remove just the button but allow the change payment method process.
*/
function eg_remove_my_subscriptions_button( $actions, $subscription ) {
foreach ( $actions as $action_key => $action ) {
switch ( $action_key ) {
// case 'change_payment_method': // Hide "Change Payment Method" button?
// case 'change_address': // Hide "Change Address" button?
case 'switch': // Hide "Switch Subscription" button?
// case 'resubscribe': // Hide "Resubscribe" button from an expired or cancelled subscription?
// case 'pay': // Hide "Pay" button on subscriptions that are "on-hold" as they require payment?
// case 'reactivate': // Hide "Reactive" button on subscriptions that are "on-hold"?
// case 'cancel': // Hide "Cancel" button on subscriptions that are "active" or "on-hold"?
unset( $actions[ $action_key ] );
break;
default:
error_log( '-- $action = ' . print_r( $action, true ) );
break;
}
}
return $actions;
}
add_filter( 'wcs_view_subscription_actions', 'eg_remove_my_subscriptions_button', 100, 2 );
```
I can't figure it out how to combine these scripts to make this work.
Hope my question is clear.
My Wordpress version is: 5.1.1
WooCommerce Subscriptions version: 2.5.2 | I have found/made the code that works. Maybe it helps somebody else.
```
/**
* Remove the "Upgrade or Downgrade" button from the My Subscription table if user role is "subscriber_plus".
*/
add_filter('woocommerce_subscriptions_switch_link', 'remove_switch_button', 10, 4);
function remove_switch_button($switch_link, $item_id, $item, $subscription) {
$user = wp_get_current_user();
if ( in_array( 'subscriber_plus', (array) $user->roles ) ) {
return '';
}
return $switch_link;
``` |
331,647 | <p>I have a custom post type called dogs. Within the Add Dog interface, I have a radio-button group that gives choices for color, which are added to the new dog post as meta data. There are about five color choices.</p>
<p>I also have the color field set up to be displayed as a sortable column in the admin area, when I look at all my dog posts. The sorting works as expected.</p>
<p>So now what I'd like to do is have each color value be a <strong>link</strong> which I can click, and when I click it, it filters all dog posts by that color value. So if I click "brown," I'll see a list of only brown dogs.</p>
<p>On Pages, we can click on an Author's name and see Pages filtered by that author. This is what I'd like, for color and the CPT dog.</p>
<p>I prefer to just do this in functions.php, and not use an enterprise plugin. Is there a way to do this?</p>
| [
{
"answer_id": 331655,
"author": "Jurgen Oldenburg",
"author_id": 163071,
"author_profile": "https://wordpress.stackexchange.com/users/163071",
"pm_score": 0,
"selected": false,
"text": "<p>Take a look at Admin Columns Pro plugin, it gives you complete control over all columns and fields. Even images from custom fields work perfectly.</p>\n\n<p><a href=\"https://www.admincolumns.com/\" rel=\"nofollow noreferrer\">https://www.admincolumns.com/</a></p>\n\n<p>They have a free version also:</p>\n\n<p><a href=\"https://wordpress.org/plugins/codepress-admin-columns/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/codepress-admin-columns/</a></p>\n"
},
{
"answer_id": 331668,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 2,
"selected": false,
"text": "<p>Based on @ Andy Macaulay-Brook comment on your question you can try this (it will add a dropdown next to the Filter button on top of the admin listing table):</p>\n<pre><code>add_action( 'restrict_manage_posts', 'filter_dogs_by_color' );\n\n// Filter Dogs by Color\nfunction filter_dogs_by_color( $post_type ) {\n if ( 'dog' !== $post_type ) return; // Replace 'dog' with your post_type\n\n $taxonomy = 'color'; // Replace 'color' with your taxonomy slug\n\n $info_taxonomy = get_taxonomy($taxonomy);\n $selected = isset($_GET[$info_taxonomy->query_var]) ? $_GET[$info_taxonomy->query_var] : '';\n\n wp_dropdown_categories(array(\n 'show_option_all' => __("Show All {$info_taxonomy->label}"),\n 'taxonomy' => $taxonomy,\n 'name' => $info_taxonomy->query_var,\n 'orderby' => 'name',\n 'selected' => $selected,\n 'hide_empty' => true,\n 'value_field' => 'slug'\n )\n );\n}\n</code></pre>\n"
},
{
"answer_id": 331761,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 3,
"selected": false,
"text": "<p>For comparison, I made a post type of <code>dog</code> with both a custom field <code>dog_colour</code> and a taxonomy <code>dog_colour</code>.</p>\n\n<p>With both added as admin columns, we get:</p>\n\n<p><a href=\"https://i.stack.imgur.com/WHgHE.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/WHgHE.png\" alt=\"enter image description here\"></a></p>\n\n<p>The taxonomy terms are automatically linked with a query variable, so clicking on one goes to a URL like <a href=\"http://example.com/wp-admin/edit.php?post_type=dog&dog_colour=red\" rel=\"nofollow noreferrer\">http://example.com/wp-admin/edit.php?post_type=dog&dog_colour=red</a> and only shows those dogs with the term red.</p>\n\n<p>And for <em>your</em> data, a taxonomy would seem to be the right thing to use: all dogs have a colour and colour is something you might want to list dogs by.</p>\n\n<p>But, there will be other use cases where a custom field is appropriate and where you might want to make the field clickable in the admin column to show all posts with that field value, so here goes...</p>\n\n<p>Unlike taxonomies, custom fields don't automatically get a query var, so we add one like this:</p>\n\n<pre><code>function wpse331647_custom_query_vars_filter( $vars ) {\n $vars[] .= 'dogcolour';\n $vars[] .= 'dogbreed';\n return $vars;\n}\n\nadd_filter( 'query_vars', 'wpse331647_custom_query_vars_filter' );\n</code></pre>\n\n<p>Now, calling a URL with <code>?dogcolour=red</code> will set up a variable called <code>dogcolour</code> with the value <code>red</code> within the WP query.</p>\n\n<p>We then need to modify the WP query to take account of this variable when it is present, but only in the admin and only when the query is for dogs:</p>\n\n<pre><code>add_action( 'pre_get_posts', 'wpse331647_alter_query' );\n\nfunction wpse331647_alter_query( $query ) {\n\n if ( !is_admin() || 'dog' != $query->query['post_type'] )\n return;\n\n if ( $query->query_vars['dogcolour'] ) {\n $query->set( 'meta_key', 'dog_colour' );\n $query->set( 'meta_value', $query->query_vars['dogcolour'] );\n }\n\n if ( $query->query_vars['dogbreed'] ) {\n $query->set( 'meta_key', 'dog_breed' );\n $query->set( 'meta_value', $query->query_vars['dogbreed'] );\n }\n\n}\n</code></pre>\n\n<p>And now, if we go to <a href=\"http://example.com/wp-admin/edit.php?post_type=dog&dogcolour=red\" rel=\"nofollow noreferrer\">http://example.com/wp-admin/edit.php?post_type=dog&dogcolour=red</a> we get:</p>\n\n<p><a href=\"https://i.stack.imgur.com/OxSiS.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/OxSiS.png\" alt=\"enter image description here\"></a></p>\n\n<p>The final step is for you to modify however you currently add the field to the admin column so that the field values are links with the correct value in the query string.</p>\n\n<p>Where you currently have:</p>\n\n<pre><code>echo '<a href=http://localhost/wordpress/wp-admin/edit.php? dogcolour=' . $x . '>' . $x . '</a>';\n</code></pre>\n\n<p>try this instead:</p>\n\n<pre><code>echo '<a href=\"';\necho admin_url( 'edit.php?post_type=dog&dogcolour=' . urlencode( $x ) );\necho '\">';\necho $x;\necho '</a>';\n</code></pre>\n\n<p>[only broken onto separate lines to help legibility]</p>\n\n<p>PHP's <code>urlencode()</code> handles spaces in your meta values for you, and even URLs. WP's <code>admin_url()</code> will handle the correct domain, protocol/scheme and path to admin for you.</p>\n\n<p>You could make your code more generic by using the post type query var rather than hard-coding it in, of course.</p>\n"
}
] | 2019/03/14 | [
"https://wordpress.stackexchange.com/questions/331647",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/59862/"
] | I have a custom post type called dogs. Within the Add Dog interface, I have a radio-button group that gives choices for color, which are added to the new dog post as meta data. There are about five color choices.
I also have the color field set up to be displayed as a sortable column in the admin area, when I look at all my dog posts. The sorting works as expected.
So now what I'd like to do is have each color value be a **link** which I can click, and when I click it, it filters all dog posts by that color value. So if I click "brown," I'll see a list of only brown dogs.
On Pages, we can click on an Author's name and see Pages filtered by that author. This is what I'd like, for color and the CPT dog.
I prefer to just do this in functions.php, and not use an enterprise plugin. Is there a way to do this? | For comparison, I made a post type of `dog` with both a custom field `dog_colour` and a taxonomy `dog_colour`.
With both added as admin columns, we get:
[](https://i.stack.imgur.com/WHgHE.png)
The taxonomy terms are automatically linked with a query variable, so clicking on one goes to a URL like <http://example.com/wp-admin/edit.php?post_type=dog&dog_colour=red> and only shows those dogs with the term red.
And for *your* data, a taxonomy would seem to be the right thing to use: all dogs have a colour and colour is something you might want to list dogs by.
But, there will be other use cases where a custom field is appropriate and where you might want to make the field clickable in the admin column to show all posts with that field value, so here goes...
Unlike taxonomies, custom fields don't automatically get a query var, so we add one like this:
```
function wpse331647_custom_query_vars_filter( $vars ) {
$vars[] .= 'dogcolour';
$vars[] .= 'dogbreed';
return $vars;
}
add_filter( 'query_vars', 'wpse331647_custom_query_vars_filter' );
```
Now, calling a URL with `?dogcolour=red` will set up a variable called `dogcolour` with the value `red` within the WP query.
We then need to modify the WP query to take account of this variable when it is present, but only in the admin and only when the query is for dogs:
```
add_action( 'pre_get_posts', 'wpse331647_alter_query' );
function wpse331647_alter_query( $query ) {
if ( !is_admin() || 'dog' != $query->query['post_type'] )
return;
if ( $query->query_vars['dogcolour'] ) {
$query->set( 'meta_key', 'dog_colour' );
$query->set( 'meta_value', $query->query_vars['dogcolour'] );
}
if ( $query->query_vars['dogbreed'] ) {
$query->set( 'meta_key', 'dog_breed' );
$query->set( 'meta_value', $query->query_vars['dogbreed'] );
}
}
```
And now, if we go to <http://example.com/wp-admin/edit.php?post_type=dog&dogcolour=red> we get:
[](https://i.stack.imgur.com/OxSiS.png)
The final step is for you to modify however you currently add the field to the admin column so that the field values are links with the correct value in the query string.
Where you currently have:
```
echo '<a href=http://localhost/wordpress/wp-admin/edit.php? dogcolour=' . $x . '>' . $x . '</a>';
```
try this instead:
```
echo '<a href="';
echo admin_url( 'edit.php?post_type=dog&dogcolour=' . urlencode( $x ) );
echo '">';
echo $x;
echo '</a>';
```
[only broken onto separate lines to help legibility]
PHP's `urlencode()` handles spaces in your meta values for you, and even URLs. WP's `admin_url()` will handle the correct domain, protocol/scheme and path to admin for you.
You could make your code more generic by using the post type query var rather than hard-coding it in, of course. |
331,661 | <p>I mean:</p>
<pre><code><ul>
<li>
<ul class="sub-menu">
<li>
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</li>
<li></li>
<li></li>
</ul>
</li>
<li>
<ul class="sub-menu">
<li></li>
<li></li>
<li></li>
</ul>
</li>
<li></li>
</ul>
</code></pre>
<p>I need to add an exra class to the first, big submenu. In other words, I need to style the sub-menus that contain more sub-menus in a different way mfrom sub-menusn that only contain final list items.</p>
<p>I can extend the <code>Walker_Nav_Menu</code> class, but after taking a look to it, it seems there's no way to know when an sub-menu will contain other sub-menu, because there's no data available about its children.</p>
<p>Apparently. </p>
<p>So what?</p>
| [
{
"answer_id": 331664,
"author": "Luca Reghellin",
"author_id": 10381,
"author_profile": "https://wordpress.stackexchange.com/users/10381",
"pm_score": -1,
"selected": false,
"text": "<p>Not a real answer, but a real solution at least to the primary task: style differently.</p>\n\n<p>I still don't know how to tell if a menu has other sub-menus via php, but in fact I know it because I manually built the menus with the admin editor. So when the are items that contains other deep submenus, I can add a class to them item via admin, then style accordingly.</p>\n"
},
{
"answer_id": 331785,
"author": "La Chouette Informatique",
"author_id": 155272,
"author_profile": "https://wordpress.stackexchange.com/users/155272",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>I can extend the Walker_Nav_Menu class, but after taking a look to it, it seems there's no way to know when an sub-menu will contain other sub-menu, because there's no data available about its children</p>\n</blockquote>\n\n<p>You may want to look again mate.</p>\n\n<p>The <a href=\"https://developer.wordpress.org/reference/classes/walker/display_element/\" rel=\"nofollow noreferrer\">Walker::display_element(...)</a> method take the \"List of elements to continue traversing\" (understand children list) as second parameter : array $children_elements</p>\n\n<p>If you do a</p>\n\n<pre><code>var_dump($children_elements);\n</code></pre>\n\n<p>You will see every entry of your menu.\nIn order to know if an entry got children, you can check if $children_elements[$id] is empty, with $id beeing the id of the element in question :</p>\n\n<pre><code>$this->has_children = ! empty( $children_elements[ $id ] );\n</code></pre>\n\n<p>So you could check for each entry of your menu if it has children, and if yes, check if any children have children of his own :</p>\n\n<pre><code><?php\n/**\n* menu_walker\n*\n* @since 1.0.0\n* @package My Theme Wordpress\n*/\n\nif ( ! class_exists( 'MyThemeWP_Top_Menu_Walker' ) ) {\nclass MyThemeWP_Top_Menu_Walker extends Walker_Nav_Menu {\n\n /**\n * Find menu elements with children containing children and give them the super-parent-class class\n * Then call the default display_element method\n */\n public function display_element( $element, &$children_elements, $max_depth, $depth=0, $args, &$output ){\n if ( ! $element ) {\n return;\n }\n\n $id_field = $this->db_fields['id'];\n $id = $element->$id_field; \n\n //var_dump($children_elements[ $id ]); // List the children elements of the element with $id\n\n $this->has_children = ! empty( $children_elements[ $id ] );\n if ( isset( $args[0] ) && is_array( $args[0] ) ) {\n $args[0]['has_children'] = $this->has_children; // Back-compat.\n }\n\n // If this element have children\n if ( ! empty( $children_elements[$id] ) //&& ( $depth == 0 ) // Remove this comment to apply the super-parent-class only to root elements\n //|| $element->category_post != '' && $element->object == 'category'\n ) {\n\n // var_dump($children_elements[$id]);\n\n // Loop through it's children\n foreach ($children_elements[$id] as &$child_element) {\n //var_dump($child_element->ID);\n //var_dump(! empty( $children_elements[$child_element->ID] ));\n\n // If this child has children of it's own, add super-parent-class to it's parent\n if ( ! empty( $children_elements[$child_element->ID] ) ){\n $element->classes[] = 'super-parent-class';\n }\n }\n }\n\n // Call default method from virtual parent class\n parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );\n }\n\n } // class MyThemeWP_Top_Menu_Walker END\n}\n?>\n</code></pre>\n"
}
] | 2019/03/14 | [
"https://wordpress.stackexchange.com/questions/331661",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/10381/"
] | I mean:
```
<ul>
<li>
<ul class="sub-menu">
<li>
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</li>
<li></li>
<li></li>
</ul>
</li>
<li>
<ul class="sub-menu">
<li></li>
<li></li>
<li></li>
</ul>
</li>
<li></li>
</ul>
```
I need to add an exra class to the first, big submenu. In other words, I need to style the sub-menus that contain more sub-menus in a different way mfrom sub-menusn that only contain final list items.
I can extend the `Walker_Nav_Menu` class, but after taking a look to it, it seems there's no way to know when an sub-menu will contain other sub-menu, because there's no data available about its children.
Apparently.
So what? | >
> I can extend the Walker\_Nav\_Menu class, but after taking a look to it, it seems there's no way to know when an sub-menu will contain other sub-menu, because there's no data available about its children
>
>
>
You may want to look again mate.
The [Walker::display\_element(...)](https://developer.wordpress.org/reference/classes/walker/display_element/) method take the "List of elements to continue traversing" (understand children list) as second parameter : array $children\_elements
If you do a
```
var_dump($children_elements);
```
You will see every entry of your menu.
In order to know if an entry got children, you can check if $children\_elements[$id] is empty, with $id beeing the id of the element in question :
```
$this->has_children = ! empty( $children_elements[ $id ] );
```
So you could check for each entry of your menu if it has children, and if yes, check if any children have children of his own :
```
<?php
/**
* menu_walker
*
* @since 1.0.0
* @package My Theme Wordpress
*/
if ( ! class_exists( 'MyThemeWP_Top_Menu_Walker' ) ) {
class MyThemeWP_Top_Menu_Walker extends Walker_Nav_Menu {
/**
* Find menu elements with children containing children and give them the super-parent-class class
* Then call the default display_element method
*/
public function display_element( $element, &$children_elements, $max_depth, $depth=0, $args, &$output ){
if ( ! $element ) {
return;
}
$id_field = $this->db_fields['id'];
$id = $element->$id_field;
//var_dump($children_elements[ $id ]); // List the children elements of the element with $id
$this->has_children = ! empty( $children_elements[ $id ] );
if ( isset( $args[0] ) && is_array( $args[0] ) ) {
$args[0]['has_children'] = $this->has_children; // Back-compat.
}
// If this element have children
if ( ! empty( $children_elements[$id] ) //&& ( $depth == 0 ) // Remove this comment to apply the super-parent-class only to root elements
//|| $element->category_post != '' && $element->object == 'category'
) {
// var_dump($children_elements[$id]);
// Loop through it's children
foreach ($children_elements[$id] as &$child_element) {
//var_dump($child_element->ID);
//var_dump(! empty( $children_elements[$child_element->ID] ));
// If this child has children of it's own, add super-parent-class to it's parent
if ( ! empty( $children_elements[$child_element->ID] ) ){
$element->classes[] = 'super-parent-class';
}
}
}
// Call default method from virtual parent class
parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
}
} // class MyThemeWP_Top_Menu_Walker END
}
?>
``` |
331,695 | <p>Not sure if this is the best approach - so happy to change - but I've set up a number of categories with child categories. Then on my landing page I list the parent categories - I'm using ACF to select the taxonomies I want - </p>
<pre><code> <ul>
<?php foreach( $terms as $term ): ?>
<h2><?php echo $term->name; ?></h2>
<p><?php echo $term->description; ?></p>
<a href="<?php echo get_term_link( $term ); ?>">View all '<?php echo $term->name; ?>' posts</a>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</code></pre>
<p>Each link above takes me to categories.php where I list the child categories:</p>
<pre><code> <?php
$term = get_queried_object();
$children = get_terms( $term->taxonomy, array(
'parent' => $term->term_id,
'hide_empty' => false
) );
if ( $children ) {
foreach( $children as $subcat )
{
echo '<li><a href="' . esc_url(get_term_link($subcat, $subcat->taxonomy)) . '">' . $subcat->name . '</a></li>';
}
}
?>
</code></pre>
<p>Problem is the link attached to the child categories stays on the category.php page and not the child category post. </p>
<p>How do I direct the child category link to the actual post?</p>
<p>Heres how I though it should flow:</p>
<ol>
<li>Landing page (containing list of parent categories)</li>
<li>Category.php (containing child categories)</li>
<li>Child post</li>
</ol>
| [
{
"answer_id": 331700,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 0,
"selected": false,
"text": "<p>It's normal behaviour. <code>ctaegory.php</code> is the template meant to display posts of a category (<strong>parent as well as child-categories</strong>), but you are using it to display child-categories only. Posts are not shown because there is no code to display posts.</p>\n\n<p>You can get a list of posts by appending a WP loop to the <code>category.php</code> file.</p>\n\n<pre><code>// After your current code for displaying child categories\n// Main loop\nif( have_posts() ){\n while ( have_posts() ){\n the_post();\n // Display post title, contents etc here\n\n }\n }\n</code></pre>\n\n<p>I hope this helps.</p>\n"
},
{
"answer_id": 331702,
"author": "Paul",
"author_id": 132385,
"author_profile": "https://wordpress.stackexchange.com/users/132385",
"pm_score": 1,
"selected": false,
"text": "<p>OK solved!</p>\n\n<p>I have a post called \"Cardio\" with a child category name \"Cardio\".</p>\n\n<p>I created a category-cardio.php (cardio is the child category) but the page doesn't display the post \"cardio\" same name as the category. </p>\n\n<pre><code><?php\n/**\n * Cardio category template\n *\n * @package clf\n */\n\nget_header(member);\n\n?>\n <div id=\"primary\" class=\"content-area\">\n <main id=\"main\" class=\"site-main\">\n\n<h1>category-cardio.php</h1>\n\n <?php $args = array(\n 'categroy_name' => 'cardio', \n ) ?>\n\n <?php $the_query = new WP_Query( $args ); ?>\n\n <?php if ($the_query->have_posts()) : ?>\n\n <?php while ($the_query->have_posts()) : $the_query->the_post();\n\n echo the_content();\n\n endwhile;\n\n endif;\n ?>\n\n\n </main><!-- #main -->\n </div><!-- #primary -->\n\n<?php\nget_sidebar();\nget_footer();\n</code></pre>\n"
}
] | 2019/03/15 | [
"https://wordpress.stackexchange.com/questions/331695",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132385/"
] | Not sure if this is the best approach - so happy to change - but I've set up a number of categories with child categories. Then on my landing page I list the parent categories - I'm using ACF to select the taxonomies I want -
```
<ul>
<?php foreach( $terms as $term ): ?>
<h2><?php echo $term->name; ?></h2>
<p><?php echo $term->description; ?></p>
<a href="<?php echo get_term_link( $term ); ?>">View all '<?php echo $term->name; ?>' posts</a>
<?php endforeach; ?>
</ul>
<?php endif; ?>
```
Each link above takes me to categories.php where I list the child categories:
```
<?php
$term = get_queried_object();
$children = get_terms( $term->taxonomy, array(
'parent' => $term->term_id,
'hide_empty' => false
) );
if ( $children ) {
foreach( $children as $subcat )
{
echo '<li><a href="' . esc_url(get_term_link($subcat, $subcat->taxonomy)) . '">' . $subcat->name . '</a></li>';
}
}
?>
```
Problem is the link attached to the child categories stays on the category.php page and not the child category post.
How do I direct the child category link to the actual post?
Heres how I though it should flow:
1. Landing page (containing list of parent categories)
2. Category.php (containing child categories)
3. Child post | OK solved!
I have a post called "Cardio" with a child category name "Cardio".
I created a category-cardio.php (cardio is the child category) but the page doesn't display the post "cardio" same name as the category.
```
<?php
/**
* Cardio category template
*
* @package clf
*/
get_header(member);
?>
<div id="primary" class="content-area">
<main id="main" class="site-main">
<h1>category-cardio.php</h1>
<?php $args = array(
'categroy_name' => 'cardio',
) ?>
<?php $the_query = new WP_Query( $args ); ?>
<?php if ($the_query->have_posts()) : ?>
<?php while ($the_query->have_posts()) : $the_query->the_post();
echo the_content();
endwhile;
endif;
?>
</main><!-- #main -->
</div><!-- #primary -->
<?php
get_sidebar();
get_footer();
``` |
331,708 | <p>I wanted to include some CSS rules inside of my gutenberg editor (in a way that it better reflected the frontend of the website). Yet I absolutely didn't want to see the same styles applied inside of any Tinymce instance across the backend. I found a simple CSS solution, and I would like to share!</p>
| [
{
"answer_id": 331709,
"author": "Cerere",
"author_id": 16281,
"author_profile": "https://wordpress.stackexchange.com/users/16281",
"pm_score": 2,
"selected": true,
"text": "<p><strong>SHORT VERSION</strong> </p>\n\n<p>Using css it's possible to use of the <code>:not()</code> selector to exclude Tinymce instances, e.g. <code>body:not(.mce-content-body) {...}</code></p>\n\n<p><strong>LONG VERSION</strong></p>\n\n<p>Let's assume we have declared theme support for editor styles and included an editor stylesheet somewhere in our theme (e.g functions.php) like this:</p>\n\n<pre><code>add_theme_support( 'editor-styles' );\nadd_editor_style( 'something/something/css/editor.css' );\n</code></pre>\n\n<p>For the sake of this example I would like our gutenberg background to be black. Inside of editor.css we can declare: </p>\n\n<pre><code>body { background-color: #000 }\n</code></pre>\n\n<p>Now our gutenberg background is black, but the same applies to any Tinymce instance across our site. Luckily, Tinymce instances are wrapped inside of an iframe and have more or less the following markup:</p>\n\n<pre><code><iframe>\n<html>\n<head>\n</head>\n<body id=\"tinymce\" class=\"mce-content-body acf_content post-type-page post-status-publish ...\">\n<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>\n</body>\n</html>\n</iframe>\n</code></pre>\n\n<p>Since the body tag has a few handy classes, we can go back to editor.css and change the previously declared body statement with: </p>\n\n<pre><code>body:not(.mce-content-body) { background-color: #000 }\n</code></pre>\n\n<p>Now my gutenberg editor background is back, while any instance of Tinymce retains the default background. In this example, the <code>:not(X)</code> selector applies the desired background color to any body tag, with exception of those with a <code>.mce-contnet-body</code> class. At this point we may even decide to be more specific and target <code>.post-type-page</code> to add styles only for our pages or <code>.acf_content</code> to only apply some rules to Tinymce instances created by the Advanced Custom Fields plugin.</p>\n\n<p>Furthermore if you are using Less/Scss you may be able to structure your website main stylesheet so that your \"screen.scss\" and \"editor.scss\" more or less share the same @imports and @includes, reducing duplicates and allowing for changes applied to one or more properties to be shared between \"scren.css\" and \"editor.scss\".</p>\n\n<p>Finally - sometimes changes made to your editor.css file may not show/appear in Tinymce up as the stylesheet is cached. While developing if this happens, you may find helpful to open up a tab leading to your editor.css file (e.g. \"wp-content/themes/theme-name/assets/css/editor.css\") and hit refresh. </p>\n"
},
{
"answer_id": 392160,
"author": "Azragh",
"author_id": 88089,
"author_profile": "https://wordpress.stackexchange.com/users/88089",
"pm_score": 0,
"selected": false,
"text": "<p>You could also load two different stylesheets. If you omit <code>add_theme_support('editor_stlyes')</code>, your stylesheet coming from <code>add_editor_style()</code> only applies to TinyMCE. Then enqueue your Gutenberg stylesheet with <code>enqueue_block_editor_assets()</code>. These styles only need to be prefixed with <code>.editor-styles-wrapper</code> for more specifity (which is automatically done when using <code>add_editor_style()</code>). So if you work with seperate SCSS files this is a great way to be able to use both editors and do adjustments seperately if needed.</p>\n<p>I found this while searching a solution to get HTML Block previews to work with this approach. Unfortunately they render as plain HTML when not using <code>add_editor_style()</code>, just to mention.</p>\n"
}
] | 2019/03/15 | [
"https://wordpress.stackexchange.com/questions/331708",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/16281/"
] | I wanted to include some CSS rules inside of my gutenberg editor (in a way that it better reflected the frontend of the website). Yet I absolutely didn't want to see the same styles applied inside of any Tinymce instance across the backend. I found a simple CSS solution, and I would like to share! | **SHORT VERSION**
Using css it's possible to use of the `:not()` selector to exclude Tinymce instances, e.g. `body:not(.mce-content-body) {...}`
**LONG VERSION**
Let's assume we have declared theme support for editor styles and included an editor stylesheet somewhere in our theme (e.g functions.php) like this:
```
add_theme_support( 'editor-styles' );
add_editor_style( 'something/something/css/editor.css' );
```
For the sake of this example I would like our gutenberg background to be black. Inside of editor.css we can declare:
```
body { background-color: #000 }
```
Now our gutenberg background is black, but the same applies to any Tinymce instance across our site. Luckily, Tinymce instances are wrapped inside of an iframe and have more or less the following markup:
```
<iframe>
<html>
<head>
</head>
<body id="tinymce" class="mce-content-body acf_content post-type-page post-status-publish ...">
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>
</body>
</html>
</iframe>
```
Since the body tag has a few handy classes, we can go back to editor.css and change the previously declared body statement with:
```
body:not(.mce-content-body) { background-color: #000 }
```
Now my gutenberg editor background is back, while any instance of Tinymce retains the default background. In this example, the `:not(X)` selector applies the desired background color to any body tag, with exception of those with a `.mce-contnet-body` class. At this point we may even decide to be more specific and target `.post-type-page` to add styles only for our pages or `.acf_content` to only apply some rules to Tinymce instances created by the Advanced Custom Fields plugin.
Furthermore if you are using Less/Scss you may be able to structure your website main stylesheet so that your "screen.scss" and "editor.scss" more or less share the same @imports and @includes, reducing duplicates and allowing for changes applied to one or more properties to be shared between "scren.css" and "editor.scss".
Finally - sometimes changes made to your editor.css file may not show/appear in Tinymce up as the stylesheet is cached. While developing if this happens, you may find helpful to open up a tab leading to your editor.css file (e.g. "wp-content/themes/theme-name/assets/css/editor.css") and hit refresh. |
331,727 | <p>My goal is to show an error message when i check if the user is locked or not,
the problem is that when the function ends, it redirects to the page that must appear after succesfull login.
Objectives:</p>
<ol>
<li>Check if the user is locked "solved"</li>
<li>If it is, create the error message</li>
<li>Display the error message in the page that must appear after succesfull login.</li>
</ol>
<p>Here is the relevant code i have at the moment:</p>
<pre><code>function userLockedControl($user_login, $user) {
$sitesManager = \VirtualReal\Web\SitesManager::getInstance();
$vrapi = \VirtualReal\NATS\VRAPI::getInstance();
$nats_user_locked = $vrapi->get("xxxxxxxxxxxxxxxxx");
$user_is_locked = $nats_user_locked["locked"];
//$lock_message = "<div class='natsLoginError'><span>Dear user, Your account has been blocked because an strange behaviour. Please, contact with [email protected]</span></div>";
if($user_is_locked == 0){
//Cerrar sesion del usuario y mostrar el mensaje de error
function doer_of_stuff() {
return new WP_Error( 'broke', __( "I've fallen and can't get up", "my_textdomain" ) );
}
$return = doer_of_stuff();
if( is_wp_error( $return ) ) {
echo $return->get_error_message();
}
}
}
add_action('wp_login', 'userLockedControl', 10, 2);
</code></pre>
| [
{
"answer_id": 331744,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>Main problem with your code is that you use <code>wp_login</code> action. The wp_login action hook is triggered when a user logs in by the <code>wp_signon()</code> function. It is the very last action taken in the function, immediately following the <code>wp_set_auth_cookie()</code> call.</p>\n\n<p>So first of all - the user is already authenticated and his auth cookie is already set - so he's basically logged in.</p>\n\n<p>Another problem is that your action is called before any HTML is printed - so if you echo anything in it, then this output will be printed before opening <code><html></code> tag.</p>\n\n<p>If you want to prevent user from logging in and display some errors, you should use <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/authenticate\" rel=\"nofollow noreferrer\"><code>authenticate</code></a> filter instead.</p>\n\n<p>It is called during authenticating user:</p>\n\n<pre><code>/**\n * Filters whether a set of user login credentials are valid.\n *\n * A WP_User object is returned if the credentials authenticate a user.\n * WP_Error or null otherwise.\n *\n * @since 2.8.0\n * @since 4.5.0 `$username` now accepts an email address.\n *\n * @param null|WP_User|WP_Error $user WP_User if the user is authenticated.\n * WP_Error or null otherwise.\n * @param string $username Username or email address.\n * @param string $password User password\n */\n$user = apply_filters( 'authenticate', null, $username, $password );\n</code></pre>\n\n<p>So you can use it like so:</p>\n\n<pre><code>function userLockedControl( $user, $username, $password ) {\n // ... rest of your code here\n\n if ($user_is_locked == 0 ) {\n return new WP_Error( 'broke', __( \"I've fallen and can't get up\", \"my_textdomain\" ) ); // you don't need all those functions returning errors and so one - just return an instance of the WP_Error instead of WP_User\n }\n}\nadd_filter( 'authenticate', 'userLockedControl', 10, 3 );\n</code></pre>\n"
},
{
"answer_id": 332145,
"author": "Jose Manuel Lascasas Jimenez",
"author_id": 162285,
"author_profile": "https://wordpress.stackexchange.com/users/162285",
"pm_score": 1,
"selected": true,
"text": "<p>Solved, the wp_authenticate_user filter hook instead is better, because it's used to perform additional validation/authentication any time a user logs in to WordPress.\nThat was just what i needed, because i wanted to deny from login if my condition was false adding extra validation.\nThis is the functional code:</p>\n\n<pre><code>function userLockedControl( $user, $password ) {\n require 'config.php';\n $sitesManager = \\VirtualReal\\Web\\SitesManager::getInstance();\n $vrapi = \\VirtualReal\\NATS\\VRAPI::getInstance();\n $nats_user_locked = $vrapi->get(\"xxxx\");\n $user_is_locked = $nats_user_locked[\"locked\"];\n\n $lock_message = \"Dear user, Your account has been blocked because an strange behaviour. Please, contact with [email protected]\";\n\n if ($user_is_locked == 0 ) {\n return new WP_Error( 'broke', __( $lock_message, \"my_textdomain\" ) );\n }\n\n return $user;\n}\nadd_filter( 'wp_authenticate_user', 'userLockedControl', 10, 2 );\n</code></pre>\n"
}
] | 2019/03/15 | [
"https://wordpress.stackexchange.com/questions/331727",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/162285/"
] | My goal is to show an error message when i check if the user is locked or not,
the problem is that when the function ends, it redirects to the page that must appear after succesfull login.
Objectives:
1. Check if the user is locked "solved"
2. If it is, create the error message
3. Display the error message in the page that must appear after succesfull login.
Here is the relevant code i have at the moment:
```
function userLockedControl($user_login, $user) {
$sitesManager = \VirtualReal\Web\SitesManager::getInstance();
$vrapi = \VirtualReal\NATS\VRAPI::getInstance();
$nats_user_locked = $vrapi->get("xxxxxxxxxxxxxxxxx");
$user_is_locked = $nats_user_locked["locked"];
//$lock_message = "<div class='natsLoginError'><span>Dear user, Your account has been blocked because an strange behaviour. Please, contact with [email protected]</span></div>";
if($user_is_locked == 0){
//Cerrar sesion del usuario y mostrar el mensaje de error
function doer_of_stuff() {
return new WP_Error( 'broke', __( "I've fallen and can't get up", "my_textdomain" ) );
}
$return = doer_of_stuff();
if( is_wp_error( $return ) ) {
echo $return->get_error_message();
}
}
}
add_action('wp_login', 'userLockedControl', 10, 2);
``` | Solved, the wp\_authenticate\_user filter hook instead is better, because it's used to perform additional validation/authentication any time a user logs in to WordPress.
That was just what i needed, because i wanted to deny from login if my condition was false adding extra validation.
This is the functional code:
```
function userLockedControl( $user, $password ) {
require 'config.php';
$sitesManager = \VirtualReal\Web\SitesManager::getInstance();
$vrapi = \VirtualReal\NATS\VRAPI::getInstance();
$nats_user_locked = $vrapi->get("xxxx");
$user_is_locked = $nats_user_locked["locked"];
$lock_message = "Dear user, Your account has been blocked because an strange behaviour. Please, contact with [email protected]";
if ($user_is_locked == 0 ) {
return new WP_Error( 'broke', __( $lock_message, "my_textdomain" ) );
}
return $user;
}
add_filter( 'wp_authenticate_user', 'userLockedControl', 10, 2 );
``` |
331,729 | <p>I have this sql statement: </p>
<pre><code>SELECT post_id FROM wp_postmeta WHERE meta_key = $param1 AND meta_value = $param2
</code></pre>
<p>I am facing one problem:</p>
<p>I don't know how to do that <strong>sql</strong> code with wordpress functionalities. I have read the manual to <code>get_posts()</code> etc. (though I might have missed something), but I haven't found a way to implement this yet. </p>
<p>Can you help me and show me a way or a hint.</p>
<p>Thanks in advance</p>
| [
{
"answer_id": 331732,
"author": "Prince",
"author_id": 162810,
"author_profile": "https://wordpress.stackexchange.com/users/162810",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>You can get using this using SQL</p>\n</blockquote>\n\n<pre><code>global $wpdb;\n\n// For single record\n$wpdb->get_row(\"SELECT post_id FROM $wpdb->postmeta WHERE meta_key = $param1 AND meta_value = $param2\");\n\n// For multiple records\n$wpdb->get_results(\"SELECT post_id FROM $wpdb->postmeta WHERE meta_key = $param1 AND meta_value = $param2\" );\n</code></pre>\n\n<blockquote>\n <p>Use this for query</p>\n</blockquote>\n\n<pre><code> $args = array(\n 'posts_per_page' => 10, // -1 for all posts\n 'meta_query' => array(\n array(\n 'key' => 'your_meta_key',\n 'value' => 'your_meta_value',\n 'compare' => '=',\n )\n )\n );\n $the_query = new WP_Query($args);\n\n// The Loop\nif ( $the_query->have_posts() ) {\n echo '<ul>';\n while ( $the_query->have_posts() ) {\n $the_query->the_post();\n echo '<li>' . get_the_title() . '</li>';\n }\n echo '</ul>';\n /* Restore original Post Data */\n wp_reset_postdata();\n} else {\n // no posts found\n}\n</code></pre>\n"
},
{
"answer_id": 331733,
"author": "Pratik Patel",
"author_id": 143123,
"author_profile": "https://wordpress.stackexchange.com/users/143123",
"pm_score": 0,
"selected": false,
"text": "<p>Try Like:</p>\n\n<pre><code>global $wpdb;\n\n$post = $wpdb->get_results('SELECT post_id FROM wp_postmeta WHERE meta_key = $param1 AND meta_value = $param2');\n</code></pre>\n\n<p>Using Wordpress default method:</p>\n\n<pre><code>$args = array(\n 'posts_per_page' => -1,\n 'meta_query' => array(\n array(\n 'key' => 'YOUR KEY',\n 'value' => 'YOUR VALUE',\n 'compare' => '=',\n ),\n ),\n);\n\n$posts = get_posts( $args );\n</code></pre>\n\n<p>Then print result of <code>$post</code> like <code>print_r($post)</code> and check have you get your <code>post_id</code> or not. Please let me know if any query.</p>\n\n<p>Hope it will help!</p>\n"
}
] | 2019/03/15 | [
"https://wordpress.stackexchange.com/questions/331729",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/163204/"
] | I have this sql statement:
```
SELECT post_id FROM wp_postmeta WHERE meta_key = $param1 AND meta_value = $param2
```
I am facing one problem:
I don't know how to do that **sql** code with wordpress functionalities. I have read the manual to `get_posts()` etc. (though I might have missed something), but I haven't found a way to implement this yet.
Can you help me and show me a way or a hint.
Thanks in advance | >
> You can get using this using SQL
>
>
>
```
global $wpdb;
// For single record
$wpdb->get_row("SELECT post_id FROM $wpdb->postmeta WHERE meta_key = $param1 AND meta_value = $param2");
// For multiple records
$wpdb->get_results("SELECT post_id FROM $wpdb->postmeta WHERE meta_key = $param1 AND meta_value = $param2" );
```
>
> Use this for query
>
>
>
```
$args = array(
'posts_per_page' => 10, // -1 for all posts
'meta_query' => array(
array(
'key' => 'your_meta_key',
'value' => 'your_meta_value',
'compare' => '=',
)
)
);
$the_query = new WP_Query($args);
// The Loop
if ( $the_query->have_posts() ) {
echo '<ul>';
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<li>' . get_the_title() . '</li>';
}
echo '</ul>';
/* Restore original Post Data */
wp_reset_postdata();
} else {
// no posts found
}
``` |
331,760 | <p>If you look at the 'most recent posts' on my sidebar for my posts page, you can see that the 'date' is repeating. The code and page is below. Any help would be appreciated. Thanks!</p>
<p><a href="https://cenbrandlab.org/home-blog/" rel="nofollow noreferrer">https://cenbrandlab.org/home-blog/</a></p>
<p>
</p>
<pre><code><!-- [SINGLEPOST SIDEBAR MOST POPULAR ARTICLES] [START]-->
<div class="c-singlepost__sidebar__articles">
<h3 class="c-singlepost__sidebar__articles-title"><?php the_field("side_post_list_title", "option"); ?></h3>
<?php
$args = [
"numberposts" => 5
];
$recent_posts = get_posts($args);
// echo "<pre>";
// echo var_dump($recent_posts);
// echo "</pre>";
foreach ($recent_posts as $value):
?>
<a href="<?php echo get_permalink($value->ID); ?>">
<div class="c-singlepost__sidebar__articles-item">
<div class="c-singlepost__sidebar__articles-item-image">
<img src="<?php echo get_field("thumbnail_image",$value->ID); ?>" class="responsive-image"/>
</div>
<div class="c-singlepost__sidebar__articles-item-right">
<div class="c-singlepost__sidebar__articles-item-date">
<span> <?php echo get_the_date('F j, Y'); ?> </span>
</div>
<a href="<?php echo get_permalink($value->ID); ?>" class="c-singlepost__sidebar__articles-item-post">
<?php echo $value->post_title ?>
</a>
</div>
</div>
</a>
</code></pre>
| [
{
"answer_id": 331765,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 0,
"selected": false,
"text": "<p>Replace</p>\n\n<pre><code> <span> <?php echo get_the_date('F j, Y'); ?> </span>\n</code></pre>\n\n<p>with</p>\n\n<pre><code> <span> <?php echo get_the_date('F j, Y', $value->ID); ?> </span>\n</code></pre>\n"
},
{
"answer_id": 331766,
"author": "nmr",
"author_id": 147428,
"author_profile": "https://wordpress.stackexchange.com/users/147428",
"pm_score": 1,
"selected": false,
"text": "<p>The same date is always displayed because of the use of <code>echo get_the_date('F j, Y')</code>.\nAs you can read in the <a href=\"https://codex.wordpress.org/Function_Reference/get_the_date\" rel=\"nofollow noreferrer\">documentation</a>:</p>\n\n<blockquote>\n <p>The <strong>get_the_date</strong> template tag retrieves the date the <strong>current</strong> $post was written.</p>\n</blockquote>\n\n<p>Change <code>get_the_date('F j, Y')</code> to <code>get_the_date('F j, Y', $value->ID)</code> and it should work. </p>\n\n<p>Or without additional DB queries:</p>\n\n<pre><code><div class=\"c-singlepost__sidebar__articles-item-date\">\n <span> <?php \n $date = \\DateTime::createFromFormat('Y-m-d H:i:s', $value->post_date);\n echo ($date !== FALSE) ? $date->format('F j, Y') : ''; \n ?> </span>\n</div>\n</code></pre>\n"
}
] | 2019/03/15 | [
"https://wordpress.stackexchange.com/questions/331760",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/163223/"
] | If you look at the 'most recent posts' on my sidebar for my posts page, you can see that the 'date' is repeating. The code and page is below. Any help would be appreciated. Thanks!
<https://cenbrandlab.org/home-blog/>
```
<!-- [SINGLEPOST SIDEBAR MOST POPULAR ARTICLES] [START]-->
<div class="c-singlepost__sidebar__articles">
<h3 class="c-singlepost__sidebar__articles-title"><?php the_field("side_post_list_title", "option"); ?></h3>
<?php
$args = [
"numberposts" => 5
];
$recent_posts = get_posts($args);
// echo "<pre>";
// echo var_dump($recent_posts);
// echo "</pre>";
foreach ($recent_posts as $value):
?>
<a href="<?php echo get_permalink($value->ID); ?>">
<div class="c-singlepost__sidebar__articles-item">
<div class="c-singlepost__sidebar__articles-item-image">
<img src="<?php echo get_field("thumbnail_image",$value->ID); ?>" class="responsive-image"/>
</div>
<div class="c-singlepost__sidebar__articles-item-right">
<div class="c-singlepost__sidebar__articles-item-date">
<span> <?php echo get_the_date('F j, Y'); ?> </span>
</div>
<a href="<?php echo get_permalink($value->ID); ?>" class="c-singlepost__sidebar__articles-item-post">
<?php echo $value->post_title ?>
</a>
</div>
</div>
</a>
``` | The same date is always displayed because of the use of `echo get_the_date('F j, Y')`.
As you can read in the [documentation](https://codex.wordpress.org/Function_Reference/get_the_date):
>
> The **get\_the\_date** template tag retrieves the date the **current** $post was written.
>
>
>
Change `get_the_date('F j, Y')` to `get_the_date('F j, Y', $value->ID)` and it should work.
Or without additional DB queries:
```
<div class="c-singlepost__sidebar__articles-item-date">
<span> <?php
$date = \DateTime::createFromFormat('Y-m-d H:i:s', $value->post_date);
echo ($date !== FALSE) ? $date->format('F j, Y') : '';
?> </span>
</div>
``` |
331,804 | <p>I want to run a function after the <code>wp();</code> line in the file <code>wp-blog-header.php</code>, what is the proper <code>hook</code> to use here?</p>
<pre class="lang-php prettyprint-override"><code><?php
/**
* Loads the WordPress environment and template.
*
* @package WordPress
*/
if ( !isset($wp_did_header) ) {
$wp_did_header = true;
// Load the WordPress library.
require_once( dirname(__FILE__) . '/wp-load.php' );
// Set up the WordPress query.
wp();
/********************************************
I WANT TO RUN THE FUNCTION AT THIS POINT
********************************************/
// Load the theme template.
require_once( ABSPATH . WPINC . '/template-loader.php' );
}
</code></pre>
<h3>Why do I need the hook</h3>
<p>We are migrating to a new website and we have to care about the old URLs, so what I did:</p>
<ol>
<li>Added the following <code>rewrite</code> rule to our <code>NGINX</code> config file:</li>
</ol>
<p><code>rewrite \D+(\/\d+\/\D+)$ /index.php?redirect=$1 break;</code></p>
<p>This rule will add an extra parameter <code>redirect</code> to the URL (old URL) with a value that I will be using to get the new final URL.</p>
<ol start="2">
<li>Then I will run the following code to get this value from the incoming URL and get the final URL by querying a 2-columns table that maps each value <code>redirect_from</code> with a final URL <code>redirect_to</code>:</li>
</ol>
<pre class="lang-php prettyprint-override"><code>/**
* 1. Check if the URL has a parameter [redirect]
* 2. If NO, proceed to the next step
* 3. If YES, then get that parameter value and look into [redirects] table
* 4. If you found a row that has that value, then get the [redirect_to] value
* 5. Redirect to that URL [redirect_to]
*/
if (isset($_GET['redirect'])) {
// Get the parameter value from the URL
$redirect_from = $_GET['redirect'];
// Add the table prefix to the table name
$table_name = $wpdb->prefix . 'redirects';
// The SQL query
$query = "
SELECT redirect_to
FROM $table_name
WHERE redirect_from = '$redirect_from';
";
// Run the SQL query and get the results
$result = $wpdb->get_results($query, OBJECT);
// If there was a result then do the redirection and exit
if (wp_redirect($result[0]->redirect_to)) {exit;}
}
</code></pre>
<p><strong>Note:</strong>
No way to get the new URLs from old URLs, here is an example of the old and new URLs:</p>
<p>Redirect from:</p>
<p><code>http://www.example.com/category/sub-category/post-id/slug</code></p>
<p>to:</p>
<p><code>https://www.example.com/category/sub-category/yyyy/mm/dd/slug</code></p>
| [
{
"answer_id": 331830,
"author": "Antti Koskinen",
"author_id": 144392,
"author_profile": "https://wordpress.stackexchange.com/users/144392",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps you could put your redirect function into a must-use plugin and hook the function to <code>muplugins_loaded</code>. $wpdb should be available then and I think it would minimize the amount of code loaded in the case a redirect is needed.</p>\n\n<p>You can also have a look at the action reference <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference</a> to find other hooks.</p>\n"
},
{
"answer_id": 331975,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>The appropriate hook for handling redirects would be <code>template_redirect</code>:</p>\n\n<pre><code>function wpse_331804_redirects() {\n /**\n * 1. Check if the URL has a parameter [redirect]\n * 2. If NO, proceed to the next step\n * 3. If YES, then get that parameter value and look into [redirects] table\n * 4. If you found a row that has that value, then get the [redirect_to] value\n * 5. Redirect to that URL [redirect_to]\n */\n\n if (isset($_GET['redirect'])) {\n // Get the parameter value from the URL\n $redirect_from = $_GET['redirect'];\n // Add the table prefix to the table name\n $table_name = $wpdb->prefix . 'redirects';\n // The SQL query\n $query = \"\n SELECT redirect_to\n FROM $table_name\n WHERE redirect_from = '$redirect_from';\n \";\n // Run the SQL query and get the results\n $result = $wpdb->get_results($query, OBJECT);\n\n // If there was a result then do the redirection and exit\n if (wp_redirect($result[0]->redirect_to)) {exit;}\n }\n}\nadd_action( 'template_redirect', 'wpse_331804_redirects' );\n</code></pre>\n"
}
] | 2019/03/16 | [
"https://wordpress.stackexchange.com/questions/331804",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/161580/"
] | I want to run a function after the `wp();` line in the file `wp-blog-header.php`, what is the proper `hook` to use here?
```php
<?php
/**
* Loads the WordPress environment and template.
*
* @package WordPress
*/
if ( !isset($wp_did_header) ) {
$wp_did_header = true;
// Load the WordPress library.
require_once( dirname(__FILE__) . '/wp-load.php' );
// Set up the WordPress query.
wp();
/********************************************
I WANT TO RUN THE FUNCTION AT THIS POINT
********************************************/
// Load the theme template.
require_once( ABSPATH . WPINC . '/template-loader.php' );
}
```
### Why do I need the hook
We are migrating to a new website and we have to care about the old URLs, so what I did:
1. Added the following `rewrite` rule to our `NGINX` config file:
`rewrite \D+(\/\d+\/\D+)$ /index.php?redirect=$1 break;`
This rule will add an extra parameter `redirect` to the URL (old URL) with a value that I will be using to get the new final URL.
2. Then I will run the following code to get this value from the incoming URL and get the final URL by querying a 2-columns table that maps each value `redirect_from` with a final URL `redirect_to`:
```php
/**
* 1. Check if the URL has a parameter [redirect]
* 2. If NO, proceed to the next step
* 3. If YES, then get that parameter value and look into [redirects] table
* 4. If you found a row that has that value, then get the [redirect_to] value
* 5. Redirect to that URL [redirect_to]
*/
if (isset($_GET['redirect'])) {
// Get the parameter value from the URL
$redirect_from = $_GET['redirect'];
// Add the table prefix to the table name
$table_name = $wpdb->prefix . 'redirects';
// The SQL query
$query = "
SELECT redirect_to
FROM $table_name
WHERE redirect_from = '$redirect_from';
";
// Run the SQL query and get the results
$result = $wpdb->get_results($query, OBJECT);
// If there was a result then do the redirection and exit
if (wp_redirect($result[0]->redirect_to)) {exit;}
}
```
**Note:**
No way to get the new URLs from old URLs, here is an example of the old and new URLs:
Redirect from:
`http://www.example.com/category/sub-category/post-id/slug`
to:
`https://www.example.com/category/sub-category/yyyy/mm/dd/slug` | The appropriate hook for handling redirects would be `template_redirect`:
```
function wpse_331804_redirects() {
/**
* 1. Check if the URL has a parameter [redirect]
* 2. If NO, proceed to the next step
* 3. If YES, then get that parameter value and look into [redirects] table
* 4. If you found a row that has that value, then get the [redirect_to] value
* 5. Redirect to that URL [redirect_to]
*/
if (isset($_GET['redirect'])) {
// Get the parameter value from the URL
$redirect_from = $_GET['redirect'];
// Add the table prefix to the table name
$table_name = $wpdb->prefix . 'redirects';
// The SQL query
$query = "
SELECT redirect_to
FROM $table_name
WHERE redirect_from = '$redirect_from';
";
// Run the SQL query and get the results
$result = $wpdb->get_results($query, OBJECT);
// If there was a result then do the redirection and exit
if (wp_redirect($result[0]->redirect_to)) {exit;}
}
}
add_action( 'template_redirect', 'wpse_331804_redirects' );
``` |
331,850 | <p>I am creating a website that would need to <strong><em>only allow some specific email addresses to signup</em></strong> .</p>
<p>An example of this would allowing all emails ending in "<code>@uniname.ac.uk</code>" but not allowing any "<code>@gmail.com, @hotmail.com, etc...</code>".</p>
<p>Do you guys know of <strong>any WordPress email confirmation plugins</strong> or <strong>php code</strong> that would allow me to do that?</p>
<p>Finally, I don't really know how to code php so it would be super helpful if someone could help.</p>
<p>Thank you</p>
| [
{
"answer_id": 331830,
"author": "Antti Koskinen",
"author_id": 144392,
"author_profile": "https://wordpress.stackexchange.com/users/144392",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps you could put your redirect function into a must-use plugin and hook the function to <code>muplugins_loaded</code>. $wpdb should be available then and I think it would minimize the amount of code loaded in the case a redirect is needed.</p>\n\n<p>You can also have a look at the action reference <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference</a> to find other hooks.</p>\n"
},
{
"answer_id": 331975,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>The appropriate hook for handling redirects would be <code>template_redirect</code>:</p>\n\n<pre><code>function wpse_331804_redirects() {\n /**\n * 1. Check if the URL has a parameter [redirect]\n * 2. If NO, proceed to the next step\n * 3. If YES, then get that parameter value and look into [redirects] table\n * 4. If you found a row that has that value, then get the [redirect_to] value\n * 5. Redirect to that URL [redirect_to]\n */\n\n if (isset($_GET['redirect'])) {\n // Get the parameter value from the URL\n $redirect_from = $_GET['redirect'];\n // Add the table prefix to the table name\n $table_name = $wpdb->prefix . 'redirects';\n // The SQL query\n $query = \"\n SELECT redirect_to\n FROM $table_name\n WHERE redirect_from = '$redirect_from';\n \";\n // Run the SQL query and get the results\n $result = $wpdb->get_results($query, OBJECT);\n\n // If there was a result then do the redirection and exit\n if (wp_redirect($result[0]->redirect_to)) {exit;}\n }\n}\nadd_action( 'template_redirect', 'wpse_331804_redirects' );\n</code></pre>\n"
}
] | 2019/03/17 | [
"https://wordpress.stackexchange.com/questions/331850",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/162614/"
] | I am creating a website that would need to ***only allow some specific email addresses to signup*** .
An example of this would allowing all emails ending in "`@uniname.ac.uk`" but not allowing any "`@gmail.com, @hotmail.com, etc...`".
Do you guys know of **any WordPress email confirmation plugins** or **php code** that would allow me to do that?
Finally, I don't really know how to code php so it would be super helpful if someone could help.
Thank you | The appropriate hook for handling redirects would be `template_redirect`:
```
function wpse_331804_redirects() {
/**
* 1. Check if the URL has a parameter [redirect]
* 2. If NO, proceed to the next step
* 3. If YES, then get that parameter value and look into [redirects] table
* 4. If you found a row that has that value, then get the [redirect_to] value
* 5. Redirect to that URL [redirect_to]
*/
if (isset($_GET['redirect'])) {
// Get the parameter value from the URL
$redirect_from = $_GET['redirect'];
// Add the table prefix to the table name
$table_name = $wpdb->prefix . 'redirects';
// The SQL query
$query = "
SELECT redirect_to
FROM $table_name
WHERE redirect_from = '$redirect_from';
";
// Run the SQL query and get the results
$result = $wpdb->get_results($query, OBJECT);
// If there was a result then do the redirection and exit
if (wp_redirect($result[0]->redirect_to)) {exit;}
}
}
add_action( 'template_redirect', 'wpse_331804_redirects' );
``` |
331,865 | <p>Adding Featured Image after getting inside of the post is not that hard. But some people want it to do that outside the loop. So is there a way to add a button on post columns to add a featured image in the post list without going inside the post and doing it like the old ways?? It's a simple thing but it may be hard to code. Maybe with AJAX, it can be done.</p>
| [
{
"answer_id": 331871,
"author": "Christina",
"author_id": 73071,
"author_profile": "https://wordpress.stackexchange.com/users/73071",
"pm_score": 1,
"selected": false,
"text": "<p>I've used the plugin <a href=\"https://www.admincolumns.com/\" rel=\"nofollow noreferrer\">Admin Columns Pro</a> for this — in addition to many useful & time-saving features, it allows you to add a column to the Posts list (or any post type list) showing the featured image. If you set it up to allow inline editing for that column, you can add the featured image directly from the list view. It's saved me loads of time, and clients find it easy to use too.</p>\n\n<p><a href=\"https://i.stack.imgur.com/dSSTX.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dSSTX.png\" alt=\"Screenshot of Posts view with Admin Column Pro featured image column allowing inline editing.\"></a></p>\n"
},
{
"answer_id": 331886,
"author": "jsmod",
"author_id": 160457,
"author_profile": "https://wordpress.stackexchange.com/users/160457",
"pm_score": 3,
"selected": true,
"text": "<p>Yes, it can be done very easily. There is a great tutorial by <a href=\"https://rudrastyh.com\" rel=\"nofollow noreferrer\">Misha Rudrastyh</a> on <a href=\"https://rudrastyh.com/wordpress/quick-edit-featured-image.html\" rel=\"nofollow noreferrer\">how to add Featured Images to Quick Edit</a>. I recently applied it and can confirm that it works. You will be able to see the featured images in the admin area post lists and easily change them using Quick Edit. It is a very good alternative to using a plugin.</p>\n\n<p>Copy and paste the following to your <code>functions.php</code> file:</p>\n\n<pre><code>/*\n*\n* Add Featured Image Column to Admin Area and Quick Edit menu\n* Source: https://rudrastyh.com/wordpress/quick-edit-featured-image.html\n*\n*/\n\n/*\n * This action hook allows to add a new empty column\n */\nadd_filter('manage_post_posts_columns', 'misha_featured_image_column');\nfunction misha_featured_image_column( $column_array ) {\n\n // I want to add my column at the beginning, so I use array_slice()\n // in other cases $column_array['featured_image'] = 'Featured Image' will be enough\n $column_array = array_slice( $column_array, 0, 1, true )\n + array('featured_image' => 'Featured Image') // our new column for featured images\n + array_slice( $column_array, 1, NULL, true );\n\n return $column_array;\n}\n\n/*\n * This hook will fill our column with data\n */\nadd_action('manage_posts_custom_column', 'misha_render_the_column', 10, 2);\nfunction misha_render_the_column( $column_name, $post_id ) {\n\n if( $column_name == 'featured_image' ) {\n\n // if there is no featured image for this post, print the placeholder\n if( has_post_thumbnail( $post_id ) ) {\n\n // I know about get_the_post_thumbnail() function but we need data-id attribute here\n $thumb_id = get_post_thumbnail_id( $post_id );\n echo '<img data-id=\"' . $thumb_id . '\" src=\"' . wp_get_attachment_url( $thumb_id ) . '\" />';\n\n } else {\n\n // data-id should be \"-1\" I will explain below\n echo '<img data-id=\"-1\" src=\"' . get_stylesheet_directory_uri() . '/placeholder.png\" />';\n\n }\n\n }\n\n}\n\nadd_action( 'admin_head', 'misha_custom_css' );\nfunction misha_custom_css(){\n\n echo '<style>\n #featured_image{\n width:120px;\n }\n td.featured_image.column-featured_image img{\n max-width: 100%;\n height: auto;\n }\n\n /* some styles to make Quick Edit meny beautiful */\n #misha_featured_image .title{margin-top:10px;display:block;}\n #misha_featured_image a.misha_upload_featured_image{\n display:inline-block;\n margin:10px 0 0;\n }\n #misha_featured_image img{\n display:block;\n max-width:200px !important;\n height:auto;\n }\n #misha_featured_image .misha_remove_featured_image{\n display:none;\n }\n </style>';\n\n}\n\nadd_action( 'admin_enqueue_scripts', 'misha_include_myuploadscript' );\nfunction misha_include_myuploadscript() {\n if ( ! did_action( 'wp_enqueue_media' ) ) {\n wp_enqueue_media();\n }\n}\n\nadd_action('quick_edit_custom_box', 'misha_add_featured_image_quick_edit', 10, 2);\nfunction misha_add_featured_image_quick_edit( $column_name, $post_type ) {\n\n // add it only if we have featured image column\n if ($column_name != 'featured_image') return;\n\n // we add #misha_featured_image to use it in JavaScript in CSS\n echo '<fieldset id=\"misha_featured_image\" class=\"inline-edit-col-left\">\n <div class=\"inline-edit-col\">\n <span class=\"title\">Featured Image</span>\n <div>\n <a href=\"#\" class=\"misha_upload_featured_image\">Set featured image</a>\n <input type=\"hidden\" name=\"_thumbnail_id\" value=\"\" />\n <a href=\"#\" class=\"misha_remove_featured_image\">Remove Featured Image</a>\n </div>\n </div></fieldset>';\n\n // please look at _thumbnail_id as a name attribute - I use it to skip save_post action\n\n}\n\nadd_action('admin_footer', 'misha_quick_edit_js_update');\nfunction misha_quick_edit_js_update() {\n\n global $current_screen;\n\n // add this JS function only if we are on all posts page\n if (($current_screen->id != 'edit-post') || ($current_screen->post_type != 'post'))\n return;\n\n ?><script>\n jQuery(function($){\n\n $('body').on('click', '.misha_upload_featured_image', function(e){\n e.preventDefault();\n var button = $(this),\n custom_uploader = wp.media({\n title: 'Set featured image',\n library : { type : 'image' },\n button: { text: 'Set featured image' },\n }).on('select', function() {\n var attachment = custom_uploader.state().get('selection').first().toJSON();\n $(button).html('<img src=\"' + attachment.url + '\" />').next().val(attachment.id).parent().next().show();\n }).open();\n });\n\n $('body').on('click', '.misha_remove_featured_image', function(){\n $(this).hide().prev().val('-1').prev().html('Set featured Image');\n return false;\n });\n\n var $wp_inline_edit = inlineEditPost.edit;\n inlineEditPost.edit = function( id ) {\n $wp_inline_edit.apply( this, arguments );\n var $post_id = 0;\n if ( typeof( id ) == 'object' ) { \n $post_id = parseInt( this.getId( id ) );\n }\n\n if ( $post_id > 0 ) {\n var $edit_row = $( '#edit-' + $post_id ),\n $post_row = $( '#post-' + $post_id ),\n $featured_image = $( '.column-featured_image', $post_row ).html(),\n $featured_image_id = $( '.column-featured_image', $post_row ).find('img').attr('data-id');\n\n\n if( $featured_image_id != -1 ) {\n\n $( ':input[name=\"_thumbnail_id\"]', $edit_row ).val( $featured_image_id ); // ID\n $( '.misha_upload_featured_image', $edit_row ).html( $featured_image ); // image HTML\n $( '.misha_remove_featured_image', $edit_row ).show(); // the remove link\n\n }\n }\n }\n });\n </script>\n<?php\n}\n</code></pre>\n\n<p>If you want more details on how this works and what each part of code does, <a href=\"https://rudrastyh.com/wordpress/quick-edit-featured-image.html\" rel=\"nofollow noreferrer\">refer to the tutorial by Misha Rudrastyh</a>.</p>\n"
}
] | 2019/03/17 | [
"https://wordpress.stackexchange.com/questions/331865",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/160243/"
] | Adding Featured Image after getting inside of the post is not that hard. But some people want it to do that outside the loop. So is there a way to add a button on post columns to add a featured image in the post list without going inside the post and doing it like the old ways?? It's a simple thing but it may be hard to code. Maybe with AJAX, it can be done. | Yes, it can be done very easily. There is a great tutorial by [Misha Rudrastyh](https://rudrastyh.com) on [how to add Featured Images to Quick Edit](https://rudrastyh.com/wordpress/quick-edit-featured-image.html). I recently applied it and can confirm that it works. You will be able to see the featured images in the admin area post lists and easily change them using Quick Edit. It is a very good alternative to using a plugin.
Copy and paste the following to your `functions.php` file:
```
/*
*
* Add Featured Image Column to Admin Area and Quick Edit menu
* Source: https://rudrastyh.com/wordpress/quick-edit-featured-image.html
*
*/
/*
* This action hook allows to add a new empty column
*/
add_filter('manage_post_posts_columns', 'misha_featured_image_column');
function misha_featured_image_column( $column_array ) {
// I want to add my column at the beginning, so I use array_slice()
// in other cases $column_array['featured_image'] = 'Featured Image' will be enough
$column_array = array_slice( $column_array, 0, 1, true )
+ array('featured_image' => 'Featured Image') // our new column for featured images
+ array_slice( $column_array, 1, NULL, true );
return $column_array;
}
/*
* This hook will fill our column with data
*/
add_action('manage_posts_custom_column', 'misha_render_the_column', 10, 2);
function misha_render_the_column( $column_name, $post_id ) {
if( $column_name == 'featured_image' ) {
// if there is no featured image for this post, print the placeholder
if( has_post_thumbnail( $post_id ) ) {
// I know about get_the_post_thumbnail() function but we need data-id attribute here
$thumb_id = get_post_thumbnail_id( $post_id );
echo '<img data-id="' . $thumb_id . '" src="' . wp_get_attachment_url( $thumb_id ) . '" />';
} else {
// data-id should be "-1" I will explain below
echo '<img data-id="-1" src="' . get_stylesheet_directory_uri() . '/placeholder.png" />';
}
}
}
add_action( 'admin_head', 'misha_custom_css' );
function misha_custom_css(){
echo '<style>
#featured_image{
width:120px;
}
td.featured_image.column-featured_image img{
max-width: 100%;
height: auto;
}
/* some styles to make Quick Edit meny beautiful */
#misha_featured_image .title{margin-top:10px;display:block;}
#misha_featured_image a.misha_upload_featured_image{
display:inline-block;
margin:10px 0 0;
}
#misha_featured_image img{
display:block;
max-width:200px !important;
height:auto;
}
#misha_featured_image .misha_remove_featured_image{
display:none;
}
</style>';
}
add_action( 'admin_enqueue_scripts', 'misha_include_myuploadscript' );
function misha_include_myuploadscript() {
if ( ! did_action( 'wp_enqueue_media' ) ) {
wp_enqueue_media();
}
}
add_action('quick_edit_custom_box', 'misha_add_featured_image_quick_edit', 10, 2);
function misha_add_featured_image_quick_edit( $column_name, $post_type ) {
// add it only if we have featured image column
if ($column_name != 'featured_image') return;
// we add #misha_featured_image to use it in JavaScript in CSS
echo '<fieldset id="misha_featured_image" class="inline-edit-col-left">
<div class="inline-edit-col">
<span class="title">Featured Image</span>
<div>
<a href="#" class="misha_upload_featured_image">Set featured image</a>
<input type="hidden" name="_thumbnail_id" value="" />
<a href="#" class="misha_remove_featured_image">Remove Featured Image</a>
</div>
</div></fieldset>';
// please look at _thumbnail_id as a name attribute - I use it to skip save_post action
}
add_action('admin_footer', 'misha_quick_edit_js_update');
function misha_quick_edit_js_update() {
global $current_screen;
// add this JS function only if we are on all posts page
if (($current_screen->id != 'edit-post') || ($current_screen->post_type != 'post'))
return;
?><script>
jQuery(function($){
$('body').on('click', '.misha_upload_featured_image', function(e){
e.preventDefault();
var button = $(this),
custom_uploader = wp.media({
title: 'Set featured image',
library : { type : 'image' },
button: { text: 'Set featured image' },
}).on('select', function() {
var attachment = custom_uploader.state().get('selection').first().toJSON();
$(button).html('<img src="' + attachment.url + '" />').next().val(attachment.id).parent().next().show();
}).open();
});
$('body').on('click', '.misha_remove_featured_image', function(){
$(this).hide().prev().val('-1').prev().html('Set featured Image');
return false;
});
var $wp_inline_edit = inlineEditPost.edit;
inlineEditPost.edit = function( id ) {
$wp_inline_edit.apply( this, arguments );
var $post_id = 0;
if ( typeof( id ) == 'object' ) {
$post_id = parseInt( this.getId( id ) );
}
if ( $post_id > 0 ) {
var $edit_row = $( '#edit-' + $post_id ),
$post_row = $( '#post-' + $post_id ),
$featured_image = $( '.column-featured_image', $post_row ).html(),
$featured_image_id = $( '.column-featured_image', $post_row ).find('img').attr('data-id');
if( $featured_image_id != -1 ) {
$( ':input[name="_thumbnail_id"]', $edit_row ).val( $featured_image_id ); // ID
$( '.misha_upload_featured_image', $edit_row ).html( $featured_image ); // image HTML
$( '.misha_remove_featured_image', $edit_row ).show(); // the remove link
}
}
}
});
</script>
<?php
}
```
If you want more details on how this works and what each part of code does, [refer to the tutorial by Misha Rudrastyh](https://rudrastyh.com/wordpress/quick-edit-featured-image.html). |
331,879 | <p>I use <code>get_the_category_list</code> to create a cat link in the header of my posts in the archive page, like so : </p>
<pre><code>$categories_list = get_the_category_list( esc_html__( ', ', 'mytheme' ) );
if ( $categories_list ) {
echo '<div class="cat-links">';
get_template_part('images/inline', 'picto-actu.svg');
$categories_list . '</div>';
}
</code></pre>
<p>I am trying to include the parent category to show it like so on the frontend :
parent category > the category
. But I'm probably not using the right method because whatever i try, i can't seem to get the parent, i can't even get the id of the child category from <code>$categories_list</code>, which would help me find the parent...</p>
| [
{
"answer_id": 331871,
"author": "Christina",
"author_id": 73071,
"author_profile": "https://wordpress.stackexchange.com/users/73071",
"pm_score": 1,
"selected": false,
"text": "<p>I've used the plugin <a href=\"https://www.admincolumns.com/\" rel=\"nofollow noreferrer\">Admin Columns Pro</a> for this — in addition to many useful & time-saving features, it allows you to add a column to the Posts list (or any post type list) showing the featured image. If you set it up to allow inline editing for that column, you can add the featured image directly from the list view. It's saved me loads of time, and clients find it easy to use too.</p>\n\n<p><a href=\"https://i.stack.imgur.com/dSSTX.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dSSTX.png\" alt=\"Screenshot of Posts view with Admin Column Pro featured image column allowing inline editing.\"></a></p>\n"
},
{
"answer_id": 331886,
"author": "jsmod",
"author_id": 160457,
"author_profile": "https://wordpress.stackexchange.com/users/160457",
"pm_score": 3,
"selected": true,
"text": "<p>Yes, it can be done very easily. There is a great tutorial by <a href=\"https://rudrastyh.com\" rel=\"nofollow noreferrer\">Misha Rudrastyh</a> on <a href=\"https://rudrastyh.com/wordpress/quick-edit-featured-image.html\" rel=\"nofollow noreferrer\">how to add Featured Images to Quick Edit</a>. I recently applied it and can confirm that it works. You will be able to see the featured images in the admin area post lists and easily change them using Quick Edit. It is a very good alternative to using a plugin.</p>\n\n<p>Copy and paste the following to your <code>functions.php</code> file:</p>\n\n<pre><code>/*\n*\n* Add Featured Image Column to Admin Area and Quick Edit menu\n* Source: https://rudrastyh.com/wordpress/quick-edit-featured-image.html\n*\n*/\n\n/*\n * This action hook allows to add a new empty column\n */\nadd_filter('manage_post_posts_columns', 'misha_featured_image_column');\nfunction misha_featured_image_column( $column_array ) {\n\n // I want to add my column at the beginning, so I use array_slice()\n // in other cases $column_array['featured_image'] = 'Featured Image' will be enough\n $column_array = array_slice( $column_array, 0, 1, true )\n + array('featured_image' => 'Featured Image') // our new column for featured images\n + array_slice( $column_array, 1, NULL, true );\n\n return $column_array;\n}\n\n/*\n * This hook will fill our column with data\n */\nadd_action('manage_posts_custom_column', 'misha_render_the_column', 10, 2);\nfunction misha_render_the_column( $column_name, $post_id ) {\n\n if( $column_name == 'featured_image' ) {\n\n // if there is no featured image for this post, print the placeholder\n if( has_post_thumbnail( $post_id ) ) {\n\n // I know about get_the_post_thumbnail() function but we need data-id attribute here\n $thumb_id = get_post_thumbnail_id( $post_id );\n echo '<img data-id=\"' . $thumb_id . '\" src=\"' . wp_get_attachment_url( $thumb_id ) . '\" />';\n\n } else {\n\n // data-id should be \"-1\" I will explain below\n echo '<img data-id=\"-1\" src=\"' . get_stylesheet_directory_uri() . '/placeholder.png\" />';\n\n }\n\n }\n\n}\n\nadd_action( 'admin_head', 'misha_custom_css' );\nfunction misha_custom_css(){\n\n echo '<style>\n #featured_image{\n width:120px;\n }\n td.featured_image.column-featured_image img{\n max-width: 100%;\n height: auto;\n }\n\n /* some styles to make Quick Edit meny beautiful */\n #misha_featured_image .title{margin-top:10px;display:block;}\n #misha_featured_image a.misha_upload_featured_image{\n display:inline-block;\n margin:10px 0 0;\n }\n #misha_featured_image img{\n display:block;\n max-width:200px !important;\n height:auto;\n }\n #misha_featured_image .misha_remove_featured_image{\n display:none;\n }\n </style>';\n\n}\n\nadd_action( 'admin_enqueue_scripts', 'misha_include_myuploadscript' );\nfunction misha_include_myuploadscript() {\n if ( ! did_action( 'wp_enqueue_media' ) ) {\n wp_enqueue_media();\n }\n}\n\nadd_action('quick_edit_custom_box', 'misha_add_featured_image_quick_edit', 10, 2);\nfunction misha_add_featured_image_quick_edit( $column_name, $post_type ) {\n\n // add it only if we have featured image column\n if ($column_name != 'featured_image') return;\n\n // we add #misha_featured_image to use it in JavaScript in CSS\n echo '<fieldset id=\"misha_featured_image\" class=\"inline-edit-col-left\">\n <div class=\"inline-edit-col\">\n <span class=\"title\">Featured Image</span>\n <div>\n <a href=\"#\" class=\"misha_upload_featured_image\">Set featured image</a>\n <input type=\"hidden\" name=\"_thumbnail_id\" value=\"\" />\n <a href=\"#\" class=\"misha_remove_featured_image\">Remove Featured Image</a>\n </div>\n </div></fieldset>';\n\n // please look at _thumbnail_id as a name attribute - I use it to skip save_post action\n\n}\n\nadd_action('admin_footer', 'misha_quick_edit_js_update');\nfunction misha_quick_edit_js_update() {\n\n global $current_screen;\n\n // add this JS function only if we are on all posts page\n if (($current_screen->id != 'edit-post') || ($current_screen->post_type != 'post'))\n return;\n\n ?><script>\n jQuery(function($){\n\n $('body').on('click', '.misha_upload_featured_image', function(e){\n e.preventDefault();\n var button = $(this),\n custom_uploader = wp.media({\n title: 'Set featured image',\n library : { type : 'image' },\n button: { text: 'Set featured image' },\n }).on('select', function() {\n var attachment = custom_uploader.state().get('selection').first().toJSON();\n $(button).html('<img src=\"' + attachment.url + '\" />').next().val(attachment.id).parent().next().show();\n }).open();\n });\n\n $('body').on('click', '.misha_remove_featured_image', function(){\n $(this).hide().prev().val('-1').prev().html('Set featured Image');\n return false;\n });\n\n var $wp_inline_edit = inlineEditPost.edit;\n inlineEditPost.edit = function( id ) {\n $wp_inline_edit.apply( this, arguments );\n var $post_id = 0;\n if ( typeof( id ) == 'object' ) { \n $post_id = parseInt( this.getId( id ) );\n }\n\n if ( $post_id > 0 ) {\n var $edit_row = $( '#edit-' + $post_id ),\n $post_row = $( '#post-' + $post_id ),\n $featured_image = $( '.column-featured_image', $post_row ).html(),\n $featured_image_id = $( '.column-featured_image', $post_row ).find('img').attr('data-id');\n\n\n if( $featured_image_id != -1 ) {\n\n $( ':input[name=\"_thumbnail_id\"]', $edit_row ).val( $featured_image_id ); // ID\n $( '.misha_upload_featured_image', $edit_row ).html( $featured_image ); // image HTML\n $( '.misha_remove_featured_image', $edit_row ).show(); // the remove link\n\n }\n }\n }\n });\n </script>\n<?php\n}\n</code></pre>\n\n<p>If you want more details on how this works and what each part of code does, <a href=\"https://rudrastyh.com/wordpress/quick-edit-featured-image.html\" rel=\"nofollow noreferrer\">refer to the tutorial by Misha Rudrastyh</a>.</p>\n"
}
] | 2019/03/17 | [
"https://wordpress.stackexchange.com/questions/331879",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81047/"
] | I use `get_the_category_list` to create a cat link in the header of my posts in the archive page, like so :
```
$categories_list = get_the_category_list( esc_html__( ', ', 'mytheme' ) );
if ( $categories_list ) {
echo '<div class="cat-links">';
get_template_part('images/inline', 'picto-actu.svg');
$categories_list . '</div>';
}
```
I am trying to include the parent category to show it like so on the frontend :
parent category > the category
. But I'm probably not using the right method because whatever i try, i can't seem to get the parent, i can't even get the id of the child category from `$categories_list`, which would help me find the parent... | Yes, it can be done very easily. There is a great tutorial by [Misha Rudrastyh](https://rudrastyh.com) on [how to add Featured Images to Quick Edit](https://rudrastyh.com/wordpress/quick-edit-featured-image.html). I recently applied it and can confirm that it works. You will be able to see the featured images in the admin area post lists and easily change them using Quick Edit. It is a very good alternative to using a plugin.
Copy and paste the following to your `functions.php` file:
```
/*
*
* Add Featured Image Column to Admin Area and Quick Edit menu
* Source: https://rudrastyh.com/wordpress/quick-edit-featured-image.html
*
*/
/*
* This action hook allows to add a new empty column
*/
add_filter('manage_post_posts_columns', 'misha_featured_image_column');
function misha_featured_image_column( $column_array ) {
// I want to add my column at the beginning, so I use array_slice()
// in other cases $column_array['featured_image'] = 'Featured Image' will be enough
$column_array = array_slice( $column_array, 0, 1, true )
+ array('featured_image' => 'Featured Image') // our new column for featured images
+ array_slice( $column_array, 1, NULL, true );
return $column_array;
}
/*
* This hook will fill our column with data
*/
add_action('manage_posts_custom_column', 'misha_render_the_column', 10, 2);
function misha_render_the_column( $column_name, $post_id ) {
if( $column_name == 'featured_image' ) {
// if there is no featured image for this post, print the placeholder
if( has_post_thumbnail( $post_id ) ) {
// I know about get_the_post_thumbnail() function but we need data-id attribute here
$thumb_id = get_post_thumbnail_id( $post_id );
echo '<img data-id="' . $thumb_id . '" src="' . wp_get_attachment_url( $thumb_id ) . '" />';
} else {
// data-id should be "-1" I will explain below
echo '<img data-id="-1" src="' . get_stylesheet_directory_uri() . '/placeholder.png" />';
}
}
}
add_action( 'admin_head', 'misha_custom_css' );
function misha_custom_css(){
echo '<style>
#featured_image{
width:120px;
}
td.featured_image.column-featured_image img{
max-width: 100%;
height: auto;
}
/* some styles to make Quick Edit meny beautiful */
#misha_featured_image .title{margin-top:10px;display:block;}
#misha_featured_image a.misha_upload_featured_image{
display:inline-block;
margin:10px 0 0;
}
#misha_featured_image img{
display:block;
max-width:200px !important;
height:auto;
}
#misha_featured_image .misha_remove_featured_image{
display:none;
}
</style>';
}
add_action( 'admin_enqueue_scripts', 'misha_include_myuploadscript' );
function misha_include_myuploadscript() {
if ( ! did_action( 'wp_enqueue_media' ) ) {
wp_enqueue_media();
}
}
add_action('quick_edit_custom_box', 'misha_add_featured_image_quick_edit', 10, 2);
function misha_add_featured_image_quick_edit( $column_name, $post_type ) {
// add it only if we have featured image column
if ($column_name != 'featured_image') return;
// we add #misha_featured_image to use it in JavaScript in CSS
echo '<fieldset id="misha_featured_image" class="inline-edit-col-left">
<div class="inline-edit-col">
<span class="title">Featured Image</span>
<div>
<a href="#" class="misha_upload_featured_image">Set featured image</a>
<input type="hidden" name="_thumbnail_id" value="" />
<a href="#" class="misha_remove_featured_image">Remove Featured Image</a>
</div>
</div></fieldset>';
// please look at _thumbnail_id as a name attribute - I use it to skip save_post action
}
add_action('admin_footer', 'misha_quick_edit_js_update');
function misha_quick_edit_js_update() {
global $current_screen;
// add this JS function only if we are on all posts page
if (($current_screen->id != 'edit-post') || ($current_screen->post_type != 'post'))
return;
?><script>
jQuery(function($){
$('body').on('click', '.misha_upload_featured_image', function(e){
e.preventDefault();
var button = $(this),
custom_uploader = wp.media({
title: 'Set featured image',
library : { type : 'image' },
button: { text: 'Set featured image' },
}).on('select', function() {
var attachment = custom_uploader.state().get('selection').first().toJSON();
$(button).html('<img src="' + attachment.url + '" />').next().val(attachment.id).parent().next().show();
}).open();
});
$('body').on('click', '.misha_remove_featured_image', function(){
$(this).hide().prev().val('-1').prev().html('Set featured Image');
return false;
});
var $wp_inline_edit = inlineEditPost.edit;
inlineEditPost.edit = function( id ) {
$wp_inline_edit.apply( this, arguments );
var $post_id = 0;
if ( typeof( id ) == 'object' ) {
$post_id = parseInt( this.getId( id ) );
}
if ( $post_id > 0 ) {
var $edit_row = $( '#edit-' + $post_id ),
$post_row = $( '#post-' + $post_id ),
$featured_image = $( '.column-featured_image', $post_row ).html(),
$featured_image_id = $( '.column-featured_image', $post_row ).find('img').attr('data-id');
if( $featured_image_id != -1 ) {
$( ':input[name="_thumbnail_id"]', $edit_row ).val( $featured_image_id ); // ID
$( '.misha_upload_featured_image', $edit_row ).html( $featured_image ); // image HTML
$( '.misha_remove_featured_image', $edit_row ).show(); // the remove link
}
}
}
});
</script>
<?php
}
```
If you want more details on how this works and what each part of code does, [refer to the tutorial by Misha Rudrastyh](https://rudrastyh.com/wordpress/quick-edit-featured-image.html). |
331,923 | <p>We can add some file in theme folder but it showing in the admin panel.
We can't getting the theme folder file from</p>
<pre><code>add_menu_page('Test', 'test', 'manage_options', 'test', 'test.php', null, 6);
</code></pre>
| [
{
"answer_id": 331925,
"author": "rozklad",
"author_id": 47861,
"author_profile": "https://wordpress.stackexchange.com/users/47861",
"pm_score": 1,
"selected": false,
"text": "<p>Fifth parameter of add_menu_page is of type <a href=\"http://php.net/manual/en/language.types.callable.php\" rel=\"nofollow noreferrer\">callable</a>. So you can't just give it \"test.php\" and expect it to load. But you could probably do something like:</p>\n\n<pre><code>// Include the fine with some function for example bananaMonday() declared\ninclude_once( __DIR__ . '/test.php' );\n\n// And then use it as param for add_menu_page\nadd_menu_page('Test', 'test', 'manage_options', 'test', 'bananaMonday', null, 6);\n</code></pre>\n\n<p>So in the end your full code would be something like this.</p>\n\n<p><strong>functions.php</strong></p>\n\n<pre><code>function se331925_custom_menu_page() {\n // Include the fine with some function for example bananaMonday() declared\n include_once( __DIR__ . '/test.php' );\n\n // And then use it as param for add_menu_page\n add_menu_page('Test', 'test', 'manage_options', 'test', 'bananaMonday', null, 6);\n}\n\nadd_action( 'admin_menu', 'se331925_custom_menu_page' );\n</code></pre>\n\n<p><strong>test.php</strong></p>\n\n<pre><code>function bananaMonday() {\n echo '<h1>Hello, it\\'s monday';\n}\n</code></pre>\n"
},
{
"answer_id": 381603,
"author": "Agus Syahputra",
"author_id": 124637,
"author_profile": "https://wordpress.stackexchange.com/users/124637",
"pm_score": 2,
"selected": false,
"text": "<p>This is my code to include the file in the theme folder as a page for the admin menu:</p>\n<pre class=\"lang-php prettyprint-override\"><code>// functions.php\nadd_action('admin_menu', function () {\n add_menu_page(\n 'Custom Admin Page',\n 'Custom Admin Page',\n 'manage_options',\n 'custom-admin-page',\n function () {\n include dirname(__FILE__) . '/inc/admin-settings.php';\n }\n );\n});\n</code></pre>\n"
}
] | 2019/03/18 | [
"https://wordpress.stackexchange.com/questions/331923",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/163341/"
] | We can add some file in theme folder but it showing in the admin panel.
We can't getting the theme folder file from
```
add_menu_page('Test', 'test', 'manage_options', 'test', 'test.php', null, 6);
``` | This is my code to include the file in the theme folder as a page for the admin menu:
```php
// functions.php
add_action('admin_menu', function () {
add_menu_page(
'Custom Admin Page',
'Custom Admin Page',
'manage_options',
'custom-admin-page',
function () {
include dirname(__FILE__) . '/inc/admin-settings.php';
}
);
});
``` |
331,937 | <p>Basically, we have alot of traffic coming to our site from different sources looking for slightly different things.</p>
<p>But instead of creating new pages for each slight change in heading, we were wondering if there was a way to set a custom parameter within the URL and then pull that parameter into a HTML element to display it.</p>
<p>So for example:</p>
<p>User 1 gets sent to:</p>
<blockquote>
<p>URL: www.example.com/something?title=Page_1</p>
</blockquote>
<p>Therefor the heading:</p>
<p>Heading one: Page 1</p>
<p>User 2 gets sent to the same page, but with a different parameter:</p>
<blockquote>
<p>URL: www.example.com/something?title=Page_3</p>
</blockquote>
<p>Therefore the heading:</p>
<p>Heading Two: Page 3</p>
<p>Thanks guys. I have a rough understanding of how this would be done but i'm not all too familiar with WPs Hooks.</p>
<p>But from my knowledge you'd set a custom parameter, store that parameter into a variable then display that variable. But I know it isnt that simple xD</p>
| [
{
"answer_id": 331942,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 0,
"selected": false,
"text": "<p>In <code>page.php</code> or the <code>php</code> file of currently used template replace <code>the_title()</code> or <code>echo get_the_title()</code> with this </p>\n\n<pre><code>if( isset( $_GET['title'] ) ) echo $_GET['title'];\nelse the_title();\n</code></pre>\n\n<p>or add this to <code>functions.php</code></p>\n\n<pre><code>function modified_title( $title, $id = null ) {\n\n if ( is_page( ) && isset( $_GET['title'] ) ) {\n\n return $_GET['title'];\n }\n else{\n return $title;\n }\n\n}\nadd_filter( 'the_title', 'modified_title', 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 331943,
"author": "Howard E",
"author_id": 57589,
"author_profile": "https://wordpress.stackexchange.com/users/57589",
"pm_score": 0,
"selected": false,
"text": "<p>The answer is one thing, but there isn't a specific hook for placing the title, as it's dependent upon your theme, and where it is located in the theme/page template.</p>\n\n<p>First, you'll have to find the <code>the_title()</code> tag as it's used in your template files.</p>\n\n<p>Then it's simply.</p>\n\n<pre><code><?php \n\n$title = (isset($_GET['title'])) ? $_GET['title'] : the_title();\necho '<h1>' . $title . '</h1>';\n</code></pre>\n\n<p>You will need to find the correct location in your theme though. This code will use the page title if the URL param is not set.</p>\n"
},
{
"answer_id": 331952,
"author": "tmdesigned",
"author_id": 28273,
"author_profile": "https://wordpress.stackexchange.com/users/28273",
"pm_score": 2,
"selected": true,
"text": "<p>Another approach that may be a bit more opaque to your users is to look at the referrer_url. This is a server-level variable that, while not 100% reliable, is generally a good indicator of where someone was when they clicked your link.</p>\n\n<p>It would <em>not</em> work if someone copied the link and sent it to someone else.</p>\n\n<pre><code>function wpse331937_custom_referer_title( $title ){\n\n if ( wp_get_referer() ){\n $host = parse_url( wp_get_referer(), PHP_URL_HOST );\n\n switch ( $domain ){\n case 'google.com' : \n case 'www.google.com' : \n $title = 'Hello Google Users';\n break;\n case 'cincinnati.craigslist.org' :\n $title = 'Hello, Cincinnati!';\n break;\n default :\n break;\n }\n }\n\n return $title; \n\n}\nadd_filter( 'the_title', 'wpse331937_custom_referer_title', 10, 1 );\n</code></pre>\n\n<p>So the big advantage here is that it's automatic, but like I said the referer is not going to capture every case.</p>\n\n<p>The <em>other</em> big benefit is you don't have to have the page title as part of the URL, which looks a bit awkward. </p>\n\n<p>You could get a similar benefit but without the referer piece by using the same switch structure in another way. For instance:</p>\n\n<pre><code>function wpse331937_custom_title( $title ){\n\n if ( isset( $_GET['ref'] ) && $_GET['ref'] ){\n $ref = $_GET['ref']\n\n switch ( $ref){\n case 'google' : \n $title = 'Hello Google Users';\n break;\n case 'cin-craig' :\n $title = 'Hello, Cincinnati Craigslist Users!';\n break;\n default :\n break;\n }\n }\n\n return $title; \n\n}\nadd_filter( 'the_title', 'wpse331937_custom_title', 10, 1 );\n</code></pre>\n\n<p>So now your URL looks like</p>\n\n<blockquote>\n <p>www.example.com/something?ref=cin-craig</p>\n</blockquote>\n\n<p>Instead of</p>\n\n<blockquote>\n <p>www.example.com/something?title=Hello,%20Cincinnati%20Craigslist%20Users!</p>\n</blockquote>\n"
}
] | 2019/03/18 | [
"https://wordpress.stackexchange.com/questions/331937",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/162529/"
] | Basically, we have alot of traffic coming to our site from different sources looking for slightly different things.
But instead of creating new pages for each slight change in heading, we were wondering if there was a way to set a custom parameter within the URL and then pull that parameter into a HTML element to display it.
So for example:
User 1 gets sent to:
>
> URL: www.example.com/something?title=Page\_1
>
>
>
Therefor the heading:
Heading one: Page 1
User 2 gets sent to the same page, but with a different parameter:
>
> URL: www.example.com/something?title=Page\_3
>
>
>
Therefore the heading:
Heading Two: Page 3
Thanks guys. I have a rough understanding of how this would be done but i'm not all too familiar with WPs Hooks.
But from my knowledge you'd set a custom parameter, store that parameter into a variable then display that variable. But I know it isnt that simple xD | Another approach that may be a bit more opaque to your users is to look at the referrer\_url. This is a server-level variable that, while not 100% reliable, is generally a good indicator of where someone was when they clicked your link.
It would *not* work if someone copied the link and sent it to someone else.
```
function wpse331937_custom_referer_title( $title ){
if ( wp_get_referer() ){
$host = parse_url( wp_get_referer(), PHP_URL_HOST );
switch ( $domain ){
case 'google.com' :
case 'www.google.com' :
$title = 'Hello Google Users';
break;
case 'cincinnati.craigslist.org' :
$title = 'Hello, Cincinnati!';
break;
default :
break;
}
}
return $title;
}
add_filter( 'the_title', 'wpse331937_custom_referer_title', 10, 1 );
```
So the big advantage here is that it's automatic, but like I said the referer is not going to capture every case.
The *other* big benefit is you don't have to have the page title as part of the URL, which looks a bit awkward.
You could get a similar benefit but without the referer piece by using the same switch structure in another way. For instance:
```
function wpse331937_custom_title( $title ){
if ( isset( $_GET['ref'] ) && $_GET['ref'] ){
$ref = $_GET['ref']
switch ( $ref){
case 'google' :
$title = 'Hello Google Users';
break;
case 'cin-craig' :
$title = 'Hello, Cincinnati Craigslist Users!';
break;
default :
break;
}
}
return $title;
}
add_filter( 'the_title', 'wpse331937_custom_title', 10, 1 );
```
So now your URL looks like
>
> www.example.com/something?ref=cin-craig
>
>
>
Instead of
>
> www.example.com/something?title=Hello,%20Cincinnati%20Craigslist%20Users!
>
>
> |
331,950 | <p>I am trying to display a different template depending on the post type.</p>
<p>I have registered two custom post types called <code>resource</code> and <code>contact</code>. When I try to get the post type in search.php (using <code>get_post_type()</code>), I always get back <code>resource</code> post type, even when the post is definitely <code>contact</code>.</p>
<p>Registering <code>resource</code></p>
<pre><code>function register_resource_post_type() {
$args = array(
'labels' => array('name' => __('Resources'), 'singular_name' => __('Resource'), 'add_new_item' => __('Add New Resource')),
'public' => true,
'supports' => array( 'title', 'custom-fields' ),
'show_in_rest' => true,
'rest_base' => 'resource-api'
);
register_post_type('resource', $args);
function custom_enter_resource_title( $input ) {
if ( 'resource' === get_post_type() ) {
return __( 'Enter resource title' );
}
return $input;
}
add_filter( 'enter_title_here', 'custom_enter_resource_title' );
}
add_action('init', 'register_resource_post_type');
</code></pre>
<p>Registering <code>contact</code></p>
<pre><code>function register_contact_post_type() {
$args = array(
'labels' => array('name' => __('Contacts'), 'singular_name' => __('Contact'), 'add_new_item' => __('Add New Contact')),
'public' => true,
'supports' => array( 'title', 'custom-fields' ),
'show_in_rest' => true,
'rest_base' => 'contact-api'
);
register_post_type('contact', $args);
function custom_enter_contact_title( $input ) {
if ( 'contact' === get_post_type() ) {
return __( 'Enter contact title' );
}
return $input;
}
add_filter( 'enter_title_here', 'custom_enter_contact_title' );
}
add_action('init', 'register_contact_post_type');
</code></pre>
<p>Search.php</p>
<pre><code> while ( have_posts() ) :
the_post();
$post_type = get_post_type() <---- THIS IS ALWAYS resource
endwhile;
</code></pre>
| [
{
"answer_id": 331942,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 0,
"selected": false,
"text": "<p>In <code>page.php</code> or the <code>php</code> file of currently used template replace <code>the_title()</code> or <code>echo get_the_title()</code> with this </p>\n\n<pre><code>if( isset( $_GET['title'] ) ) echo $_GET['title'];\nelse the_title();\n</code></pre>\n\n<p>or add this to <code>functions.php</code></p>\n\n<pre><code>function modified_title( $title, $id = null ) {\n\n if ( is_page( ) && isset( $_GET['title'] ) ) {\n\n return $_GET['title'];\n }\n else{\n return $title;\n }\n\n}\nadd_filter( 'the_title', 'modified_title', 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 331943,
"author": "Howard E",
"author_id": 57589,
"author_profile": "https://wordpress.stackexchange.com/users/57589",
"pm_score": 0,
"selected": false,
"text": "<p>The answer is one thing, but there isn't a specific hook for placing the title, as it's dependent upon your theme, and where it is located in the theme/page template.</p>\n\n<p>First, you'll have to find the <code>the_title()</code> tag as it's used in your template files.</p>\n\n<p>Then it's simply.</p>\n\n<pre><code><?php \n\n$title = (isset($_GET['title'])) ? $_GET['title'] : the_title();\necho '<h1>' . $title . '</h1>';\n</code></pre>\n\n<p>You will need to find the correct location in your theme though. This code will use the page title if the URL param is not set.</p>\n"
},
{
"answer_id": 331952,
"author": "tmdesigned",
"author_id": 28273,
"author_profile": "https://wordpress.stackexchange.com/users/28273",
"pm_score": 2,
"selected": true,
"text": "<p>Another approach that may be a bit more opaque to your users is to look at the referrer_url. This is a server-level variable that, while not 100% reliable, is generally a good indicator of where someone was when they clicked your link.</p>\n\n<p>It would <em>not</em> work if someone copied the link and sent it to someone else.</p>\n\n<pre><code>function wpse331937_custom_referer_title( $title ){\n\n if ( wp_get_referer() ){\n $host = parse_url( wp_get_referer(), PHP_URL_HOST );\n\n switch ( $domain ){\n case 'google.com' : \n case 'www.google.com' : \n $title = 'Hello Google Users';\n break;\n case 'cincinnati.craigslist.org' :\n $title = 'Hello, Cincinnati!';\n break;\n default :\n break;\n }\n }\n\n return $title; \n\n}\nadd_filter( 'the_title', 'wpse331937_custom_referer_title', 10, 1 );\n</code></pre>\n\n<p>So the big advantage here is that it's automatic, but like I said the referer is not going to capture every case.</p>\n\n<p>The <em>other</em> big benefit is you don't have to have the page title as part of the URL, which looks a bit awkward. </p>\n\n<p>You could get a similar benefit but without the referer piece by using the same switch structure in another way. For instance:</p>\n\n<pre><code>function wpse331937_custom_title( $title ){\n\n if ( isset( $_GET['ref'] ) && $_GET['ref'] ){\n $ref = $_GET['ref']\n\n switch ( $ref){\n case 'google' : \n $title = 'Hello Google Users';\n break;\n case 'cin-craig' :\n $title = 'Hello, Cincinnati Craigslist Users!';\n break;\n default :\n break;\n }\n }\n\n return $title; \n\n}\nadd_filter( 'the_title', 'wpse331937_custom_title', 10, 1 );\n</code></pre>\n\n<p>So now your URL looks like</p>\n\n<blockquote>\n <p>www.example.com/something?ref=cin-craig</p>\n</blockquote>\n\n<p>Instead of</p>\n\n<blockquote>\n <p>www.example.com/something?title=Hello,%20Cincinnati%20Craigslist%20Users!</p>\n</blockquote>\n"
}
] | 2019/03/18 | [
"https://wordpress.stackexchange.com/questions/331950",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/161697/"
] | I am trying to display a different template depending on the post type.
I have registered two custom post types called `resource` and `contact`. When I try to get the post type in search.php (using `get_post_type()`), I always get back `resource` post type, even when the post is definitely `contact`.
Registering `resource`
```
function register_resource_post_type() {
$args = array(
'labels' => array('name' => __('Resources'), 'singular_name' => __('Resource'), 'add_new_item' => __('Add New Resource')),
'public' => true,
'supports' => array( 'title', 'custom-fields' ),
'show_in_rest' => true,
'rest_base' => 'resource-api'
);
register_post_type('resource', $args);
function custom_enter_resource_title( $input ) {
if ( 'resource' === get_post_type() ) {
return __( 'Enter resource title' );
}
return $input;
}
add_filter( 'enter_title_here', 'custom_enter_resource_title' );
}
add_action('init', 'register_resource_post_type');
```
Registering `contact`
```
function register_contact_post_type() {
$args = array(
'labels' => array('name' => __('Contacts'), 'singular_name' => __('Contact'), 'add_new_item' => __('Add New Contact')),
'public' => true,
'supports' => array( 'title', 'custom-fields' ),
'show_in_rest' => true,
'rest_base' => 'contact-api'
);
register_post_type('contact', $args);
function custom_enter_contact_title( $input ) {
if ( 'contact' === get_post_type() ) {
return __( 'Enter contact title' );
}
return $input;
}
add_filter( 'enter_title_here', 'custom_enter_contact_title' );
}
add_action('init', 'register_contact_post_type');
```
Search.php
```
while ( have_posts() ) :
the_post();
$post_type = get_post_type() <---- THIS IS ALWAYS resource
endwhile;
``` | Another approach that may be a bit more opaque to your users is to look at the referrer\_url. This is a server-level variable that, while not 100% reliable, is generally a good indicator of where someone was when they clicked your link.
It would *not* work if someone copied the link and sent it to someone else.
```
function wpse331937_custom_referer_title( $title ){
if ( wp_get_referer() ){
$host = parse_url( wp_get_referer(), PHP_URL_HOST );
switch ( $domain ){
case 'google.com' :
case 'www.google.com' :
$title = 'Hello Google Users';
break;
case 'cincinnati.craigslist.org' :
$title = 'Hello, Cincinnati!';
break;
default :
break;
}
}
return $title;
}
add_filter( 'the_title', 'wpse331937_custom_referer_title', 10, 1 );
```
So the big advantage here is that it's automatic, but like I said the referer is not going to capture every case.
The *other* big benefit is you don't have to have the page title as part of the URL, which looks a bit awkward.
You could get a similar benefit but without the referer piece by using the same switch structure in another way. For instance:
```
function wpse331937_custom_title( $title ){
if ( isset( $_GET['ref'] ) && $_GET['ref'] ){
$ref = $_GET['ref']
switch ( $ref){
case 'google' :
$title = 'Hello Google Users';
break;
case 'cin-craig' :
$title = 'Hello, Cincinnati Craigslist Users!';
break;
default :
break;
}
}
return $title;
}
add_filter( 'the_title', 'wpse331937_custom_title', 10, 1 );
```
So now your URL looks like
>
> www.example.com/something?ref=cin-craig
>
>
>
Instead of
>
> www.example.com/something?title=Hello,%20Cincinnati%20Craigslist%20Users!
>
>
> |
331,954 | <p>I have a custom html form from which I am trying to insert records into a custom table .My problem is getting the current user name and inserting that value into the custom table. When the user clicks the Submit button the code below should fire. This is my php code:</p>
<pre><code><?php>
session_start;
require_once "wp-load.php";
require_once "dbconfig.php";
global $wpdb, $current_user;
$current_user=wp_get_current_user();
$table_name="persons";
$wpdb->insert( $table_name, array(
'first_name' => $_POST['first_name'],
'last_name' => $_POST['last_name'],
'email' => $_POST['email'],
'telephone' => $_POST['telephone'],
'user_name' => [$current_user]
)
);
?>
</code></pre>
<p>Any help is greatly appreciated. Been working on this for hours now, unable to find the solution.</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 331942,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 0,
"selected": false,
"text": "<p>In <code>page.php</code> or the <code>php</code> file of currently used template replace <code>the_title()</code> or <code>echo get_the_title()</code> with this </p>\n\n<pre><code>if( isset( $_GET['title'] ) ) echo $_GET['title'];\nelse the_title();\n</code></pre>\n\n<p>or add this to <code>functions.php</code></p>\n\n<pre><code>function modified_title( $title, $id = null ) {\n\n if ( is_page( ) && isset( $_GET['title'] ) ) {\n\n return $_GET['title'];\n }\n else{\n return $title;\n }\n\n}\nadd_filter( 'the_title', 'modified_title', 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 331943,
"author": "Howard E",
"author_id": 57589,
"author_profile": "https://wordpress.stackexchange.com/users/57589",
"pm_score": 0,
"selected": false,
"text": "<p>The answer is one thing, but there isn't a specific hook for placing the title, as it's dependent upon your theme, and where it is located in the theme/page template.</p>\n\n<p>First, you'll have to find the <code>the_title()</code> tag as it's used in your template files.</p>\n\n<p>Then it's simply.</p>\n\n<pre><code><?php \n\n$title = (isset($_GET['title'])) ? $_GET['title'] : the_title();\necho '<h1>' . $title . '</h1>';\n</code></pre>\n\n<p>You will need to find the correct location in your theme though. This code will use the page title if the URL param is not set.</p>\n"
},
{
"answer_id": 331952,
"author": "tmdesigned",
"author_id": 28273,
"author_profile": "https://wordpress.stackexchange.com/users/28273",
"pm_score": 2,
"selected": true,
"text": "<p>Another approach that may be a bit more opaque to your users is to look at the referrer_url. This is a server-level variable that, while not 100% reliable, is generally a good indicator of where someone was when they clicked your link.</p>\n\n<p>It would <em>not</em> work if someone copied the link and sent it to someone else.</p>\n\n<pre><code>function wpse331937_custom_referer_title( $title ){\n\n if ( wp_get_referer() ){\n $host = parse_url( wp_get_referer(), PHP_URL_HOST );\n\n switch ( $domain ){\n case 'google.com' : \n case 'www.google.com' : \n $title = 'Hello Google Users';\n break;\n case 'cincinnati.craigslist.org' :\n $title = 'Hello, Cincinnati!';\n break;\n default :\n break;\n }\n }\n\n return $title; \n\n}\nadd_filter( 'the_title', 'wpse331937_custom_referer_title', 10, 1 );\n</code></pre>\n\n<p>So the big advantage here is that it's automatic, but like I said the referer is not going to capture every case.</p>\n\n<p>The <em>other</em> big benefit is you don't have to have the page title as part of the URL, which looks a bit awkward. </p>\n\n<p>You could get a similar benefit but without the referer piece by using the same switch structure in another way. For instance:</p>\n\n<pre><code>function wpse331937_custom_title( $title ){\n\n if ( isset( $_GET['ref'] ) && $_GET['ref'] ){\n $ref = $_GET['ref']\n\n switch ( $ref){\n case 'google' : \n $title = 'Hello Google Users';\n break;\n case 'cin-craig' :\n $title = 'Hello, Cincinnati Craigslist Users!';\n break;\n default :\n break;\n }\n }\n\n return $title; \n\n}\nadd_filter( 'the_title', 'wpse331937_custom_title', 10, 1 );\n</code></pre>\n\n<p>So now your URL looks like</p>\n\n<blockquote>\n <p>www.example.com/something?ref=cin-craig</p>\n</blockquote>\n\n<p>Instead of</p>\n\n<blockquote>\n <p>www.example.com/something?title=Hello,%20Cincinnati%20Craigslist%20Users!</p>\n</blockquote>\n"
}
] | 2019/03/18 | [
"https://wordpress.stackexchange.com/questions/331954",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145942/"
] | I have a custom html form from which I am trying to insert records into a custom table .My problem is getting the current user name and inserting that value into the custom table. When the user clicks the Submit button the code below should fire. This is my php code:
```
<?php>
session_start;
require_once "wp-load.php";
require_once "dbconfig.php";
global $wpdb, $current_user;
$current_user=wp_get_current_user();
$table_name="persons";
$wpdb->insert( $table_name, array(
'first_name' => $_POST['first_name'],
'last_name' => $_POST['last_name'],
'email' => $_POST['email'],
'telephone' => $_POST['telephone'],
'user_name' => [$current_user]
)
);
?>
```
Any help is greatly appreciated. Been working on this for hours now, unable to find the solution.
Thanks in advance. | Another approach that may be a bit more opaque to your users is to look at the referrer\_url. This is a server-level variable that, while not 100% reliable, is generally a good indicator of where someone was when they clicked your link.
It would *not* work if someone copied the link and sent it to someone else.
```
function wpse331937_custom_referer_title( $title ){
if ( wp_get_referer() ){
$host = parse_url( wp_get_referer(), PHP_URL_HOST );
switch ( $domain ){
case 'google.com' :
case 'www.google.com' :
$title = 'Hello Google Users';
break;
case 'cincinnati.craigslist.org' :
$title = 'Hello, Cincinnati!';
break;
default :
break;
}
}
return $title;
}
add_filter( 'the_title', 'wpse331937_custom_referer_title', 10, 1 );
```
So the big advantage here is that it's automatic, but like I said the referer is not going to capture every case.
The *other* big benefit is you don't have to have the page title as part of the URL, which looks a bit awkward.
You could get a similar benefit but without the referer piece by using the same switch structure in another way. For instance:
```
function wpse331937_custom_title( $title ){
if ( isset( $_GET['ref'] ) && $_GET['ref'] ){
$ref = $_GET['ref']
switch ( $ref){
case 'google' :
$title = 'Hello Google Users';
break;
case 'cin-craig' :
$title = 'Hello, Cincinnati Craigslist Users!';
break;
default :
break;
}
}
return $title;
}
add_filter( 'the_title', 'wpse331937_custom_title', 10, 1 );
```
So now your URL looks like
>
> www.example.com/something?ref=cin-craig
>
>
>
Instead of
>
> www.example.com/something?title=Hello,%20Cincinnati%20Craigslist%20Users!
>
>
> |
331,968 | <p>I'm developing Gutenberg custom block for accodrdions on my website. My code was working with only one content field. When I have added second props it has stop worked and console says:</p>
<blockquote>
<p>Cannot read property 'content' of undefined</p>
</blockquote>
<pre><code>wp.blocks.registerBlockType('myblock/question-block', {
title: 'Blok Pytan',
icon: 'dashicons-welcome-write-blog',
category: 'common',
attributes: {
header: {type: 'string'},
content: {type: 'string'}
},
edit: function(props, propstwo) {
function updateheader(event) {
props.setAttributes({header: event.target.value})
}
function updatecontent(event) {
propstwo.setAttributes({content: event.target.value})
}
return wp.element.createElement(
"div",
null,
wp.element.createElement(
"h2",
null,
"Nagłówek tekstu"
),
wp.element.createElement("input", { type: "text", value: props.attributes.header, onChange: updateheader }),
),
wp.element.createElement(
"p",
null,
"Rozwijany tekst"
),
wp.element.createElement("input", { type: "text", value: propstwo.attributes.content, onChange: updatecontent })
},
save: function(props, propstwo) {
return wp.element.createElement(
"div",
{className: "accodrion"},
wp.element.createElement(
"h2",
{className: "accodrdion-header"},
props.attributes.header
),
wp.element.createElement(
"p",
{className: "panel"},
propstwo.attributes.content
)
)}
})
</code></pre>
| [
{
"answer_id": 331942,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 0,
"selected": false,
"text": "<p>In <code>page.php</code> or the <code>php</code> file of currently used template replace <code>the_title()</code> or <code>echo get_the_title()</code> with this </p>\n\n<pre><code>if( isset( $_GET['title'] ) ) echo $_GET['title'];\nelse the_title();\n</code></pre>\n\n<p>or add this to <code>functions.php</code></p>\n\n<pre><code>function modified_title( $title, $id = null ) {\n\n if ( is_page( ) && isset( $_GET['title'] ) ) {\n\n return $_GET['title'];\n }\n else{\n return $title;\n }\n\n}\nadd_filter( 'the_title', 'modified_title', 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 331943,
"author": "Howard E",
"author_id": 57589,
"author_profile": "https://wordpress.stackexchange.com/users/57589",
"pm_score": 0,
"selected": false,
"text": "<p>The answer is one thing, but there isn't a specific hook for placing the title, as it's dependent upon your theme, and where it is located in the theme/page template.</p>\n\n<p>First, you'll have to find the <code>the_title()</code> tag as it's used in your template files.</p>\n\n<p>Then it's simply.</p>\n\n<pre><code><?php \n\n$title = (isset($_GET['title'])) ? $_GET['title'] : the_title();\necho '<h1>' . $title . '</h1>';\n</code></pre>\n\n<p>You will need to find the correct location in your theme though. This code will use the page title if the URL param is not set.</p>\n"
},
{
"answer_id": 331952,
"author": "tmdesigned",
"author_id": 28273,
"author_profile": "https://wordpress.stackexchange.com/users/28273",
"pm_score": 2,
"selected": true,
"text": "<p>Another approach that may be a bit more opaque to your users is to look at the referrer_url. This is a server-level variable that, while not 100% reliable, is generally a good indicator of where someone was when they clicked your link.</p>\n\n<p>It would <em>not</em> work if someone copied the link and sent it to someone else.</p>\n\n<pre><code>function wpse331937_custom_referer_title( $title ){\n\n if ( wp_get_referer() ){\n $host = parse_url( wp_get_referer(), PHP_URL_HOST );\n\n switch ( $domain ){\n case 'google.com' : \n case 'www.google.com' : \n $title = 'Hello Google Users';\n break;\n case 'cincinnati.craigslist.org' :\n $title = 'Hello, Cincinnati!';\n break;\n default :\n break;\n }\n }\n\n return $title; \n\n}\nadd_filter( 'the_title', 'wpse331937_custom_referer_title', 10, 1 );\n</code></pre>\n\n<p>So the big advantage here is that it's automatic, but like I said the referer is not going to capture every case.</p>\n\n<p>The <em>other</em> big benefit is you don't have to have the page title as part of the URL, which looks a bit awkward. </p>\n\n<p>You could get a similar benefit but without the referer piece by using the same switch structure in another way. For instance:</p>\n\n<pre><code>function wpse331937_custom_title( $title ){\n\n if ( isset( $_GET['ref'] ) && $_GET['ref'] ){\n $ref = $_GET['ref']\n\n switch ( $ref){\n case 'google' : \n $title = 'Hello Google Users';\n break;\n case 'cin-craig' :\n $title = 'Hello, Cincinnati Craigslist Users!';\n break;\n default :\n break;\n }\n }\n\n return $title; \n\n}\nadd_filter( 'the_title', 'wpse331937_custom_title', 10, 1 );\n</code></pre>\n\n<p>So now your URL looks like</p>\n\n<blockquote>\n <p>www.example.com/something?ref=cin-craig</p>\n</blockquote>\n\n<p>Instead of</p>\n\n<blockquote>\n <p>www.example.com/something?title=Hello,%20Cincinnati%20Craigslist%20Users!</p>\n</blockquote>\n"
}
] | 2019/03/18 | [
"https://wordpress.stackexchange.com/questions/331968",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/136526/"
] | I'm developing Gutenberg custom block for accodrdions on my website. My code was working with only one content field. When I have added second props it has stop worked and console says:
>
> Cannot read property 'content' of undefined
>
>
>
```
wp.blocks.registerBlockType('myblock/question-block', {
title: 'Blok Pytan',
icon: 'dashicons-welcome-write-blog',
category: 'common',
attributes: {
header: {type: 'string'},
content: {type: 'string'}
},
edit: function(props, propstwo) {
function updateheader(event) {
props.setAttributes({header: event.target.value})
}
function updatecontent(event) {
propstwo.setAttributes({content: event.target.value})
}
return wp.element.createElement(
"div",
null,
wp.element.createElement(
"h2",
null,
"Nagłówek tekstu"
),
wp.element.createElement("input", { type: "text", value: props.attributes.header, onChange: updateheader }),
),
wp.element.createElement(
"p",
null,
"Rozwijany tekst"
),
wp.element.createElement("input", { type: "text", value: propstwo.attributes.content, onChange: updatecontent })
},
save: function(props, propstwo) {
return wp.element.createElement(
"div",
{className: "accodrion"},
wp.element.createElement(
"h2",
{className: "accodrdion-header"},
props.attributes.header
),
wp.element.createElement(
"p",
{className: "panel"},
propstwo.attributes.content
)
)}
})
``` | Another approach that may be a bit more opaque to your users is to look at the referrer\_url. This is a server-level variable that, while not 100% reliable, is generally a good indicator of where someone was when they clicked your link.
It would *not* work if someone copied the link and sent it to someone else.
```
function wpse331937_custom_referer_title( $title ){
if ( wp_get_referer() ){
$host = parse_url( wp_get_referer(), PHP_URL_HOST );
switch ( $domain ){
case 'google.com' :
case 'www.google.com' :
$title = 'Hello Google Users';
break;
case 'cincinnati.craigslist.org' :
$title = 'Hello, Cincinnati!';
break;
default :
break;
}
}
return $title;
}
add_filter( 'the_title', 'wpse331937_custom_referer_title', 10, 1 );
```
So the big advantage here is that it's automatic, but like I said the referer is not going to capture every case.
The *other* big benefit is you don't have to have the page title as part of the URL, which looks a bit awkward.
You could get a similar benefit but without the referer piece by using the same switch structure in another way. For instance:
```
function wpse331937_custom_title( $title ){
if ( isset( $_GET['ref'] ) && $_GET['ref'] ){
$ref = $_GET['ref']
switch ( $ref){
case 'google' :
$title = 'Hello Google Users';
break;
case 'cin-craig' :
$title = 'Hello, Cincinnati Craigslist Users!';
break;
default :
break;
}
}
return $title;
}
add_filter( 'the_title', 'wpse331937_custom_title', 10, 1 );
```
So now your URL looks like
>
> www.example.com/something?ref=cin-craig
>
>
>
Instead of
>
> www.example.com/something?title=Hello,%20Cincinnati%20Craigslist%20Users!
>
>
> |
331,981 | <p>The contents of the <code>/index.php</code> is as follows:</p>
<pre><code>/**
* 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>If I make any changes in this file, then do a Wordpress Update, will the contents of this file be replaced? I've not been able to find any references online for this file, only Wordpress' <code>/wp-includes</code> and <code>/wp-admin</code> folders.</p>
<p>I don't have access to the php.ini file and want to change the session cookie lifetime setting by adding the following code:</p>
<pre><code> $seconds = 31557600; //1 year
ini_set('session.gc_maxlifetime', $seconds);
ini_set('session.cookie_lifetime', $seconds);
</code></pre>
<p>but don't want to add it to a file that potentially could be overridden in a couple of months time.</p>
| [
{
"answer_id": 331984,
"author": "tmdesigned",
"author_id": 28273,
"author_profile": "https://wordpress.stackexchange.com/users/28273",
"pm_score": 3,
"selected": true,
"text": "<p>Yes, index.php is part of core and is liable to be overwritten. </p>\n\n<p>In fact, if you look at the <a href=\"https://codex.wordpress.org/Updating_WordPress#Manual_Update\" rel=\"nofollow noreferrer\">process to manually update WordPress</a>, step 7 is:</p>\n\n<blockquote>\n <p>Upload all new loose files from the root directory of the new version to your existing WordPress root directory</p>\n</blockquote>\n\n<p>That may include index.php.</p>\n\n<p>You can put custom PHP code in a custom plugin or theme. If using a pre-built theme, first <a href=\"https://developer.wordpress.org/themes/advanced-topics/child-themes/\" rel=\"nofollow noreferrer\">create a child theme</a> and then put your code in that child theme's functions.php. </p>\n"
},
{
"answer_id": 331992,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 1,
"selected": false,
"text": "<p>If you run PHP as Apache module you can set <code>php.ini</code> values in <code>.htaccess</code>:</p>\n\n<pre><code>AllowOverride Options\nphp_value session.gc_maxlifetime 31557600\nphp_value session.cookie_lifetime 31557600\n</code></pre>\n"
}
] | 2019/03/18 | [
"https://wordpress.stackexchange.com/questions/331981",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/9124/"
] | The contents of the `/index.php` is as follows:
```
/**
* 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' );
```
If I make any changes in this file, then do a Wordpress Update, will the contents of this file be replaced? I've not been able to find any references online for this file, only Wordpress' `/wp-includes` and `/wp-admin` folders.
I don't have access to the php.ini file and want to change the session cookie lifetime setting by adding the following code:
```
$seconds = 31557600; //1 year
ini_set('session.gc_maxlifetime', $seconds);
ini_set('session.cookie_lifetime', $seconds);
```
but don't want to add it to a file that potentially could be overridden in a couple of months time. | Yes, index.php is part of core and is liable to be overwritten.
In fact, if you look at the [process to manually update WordPress](https://codex.wordpress.org/Updating_WordPress#Manual_Update), step 7 is:
>
> Upload all new loose files from the root directory of the new version to your existing WordPress root directory
>
>
>
That may include index.php.
You can put custom PHP code in a custom plugin or theme. If using a pre-built theme, first [create a child theme](https://developer.wordpress.org/themes/advanced-topics/child-themes/) and then put your code in that child theme's functions.php. |
331,982 | <p>I am trying to replace a word only on post pages. The issue I am running into is that WordPress page content ends up blank even though this code should only run on post pages. </p>
<pre><code><?php
/**
* Plugin Name: Wordpress plugin test esmond
* Plugin URI: https://esmondmccain.com
* Description: test plugin.
* Version: 1.0
* Author: Esmond Mccain
* Author URI: https://esmondmccain.com
*/
defined('ABSPATH') or die();
function esmond_enqueue_scripts_styles() {
if(is_page()){
//Styles
wp_enqueue_style( 'bootstrap-css', 'https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css');
//Scripts
wp_enqueue_script( 'bootstrap-js', 'https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js', array('jquery'), true);
}
}
add_action('wp_enqueue_scripts','esmond_enqueue_scripts_styles');
add_filter('the_content', 'replace_word');
function replace_word($text) {
if (is_singular( 'post' )){
$text = str_replace('dog', 'cat', $text);
return $text;
}
}
</code></pre>
| [
{
"answer_id": 331987,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 2,
"selected": true,
"text": "<p>Your code is returning <code>$text</code> only for posts and nothing for other post types like pages. </p>\n\n<p>Your function should be like this</p>\n\n<pre><code>add_filter('the_content', 'replace_word');\nfunction replace_word($text) {\n if (is_singular( 'post' )){\n $text = str_replace('dog', 'cat', $text);\n\n return $text;\n }\n\n // you must return content for pages/ other post types\n return $text;\n\n}\n</code></pre>\n"
},
{
"answer_id": 331988,
"author": "MikeNGarrett",
"author_id": 1670,
"author_profile": "https://wordpress.stackexchange.com/users/1670",
"pm_score": 0,
"selected": false,
"text": "<p>You aren't returning <code>$text</code> for any other content. Filters must always return the string whether it's changed or not. </p>\n\n<pre><code>add_filter('the_content', 'replace_word');\nfunction replace_word($text) {\n if (is_singular( 'post' )){\n $text = str_replace('dog', 'cat', $text);\n\n return $text;\n }\n return $text;\n}\n</code></pre>\n"
}
] | 2019/03/18 | [
"https://wordpress.stackexchange.com/questions/331982",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/160737/"
] | I am trying to replace a word only on post pages. The issue I am running into is that WordPress page content ends up blank even though this code should only run on post pages.
```
<?php
/**
* Plugin Name: Wordpress plugin test esmond
* Plugin URI: https://esmondmccain.com
* Description: test plugin.
* Version: 1.0
* Author: Esmond Mccain
* Author URI: https://esmondmccain.com
*/
defined('ABSPATH') or die();
function esmond_enqueue_scripts_styles() {
if(is_page()){
//Styles
wp_enqueue_style( 'bootstrap-css', 'https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css');
//Scripts
wp_enqueue_script( 'bootstrap-js', 'https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js', array('jquery'), true);
}
}
add_action('wp_enqueue_scripts','esmond_enqueue_scripts_styles');
add_filter('the_content', 'replace_word');
function replace_word($text) {
if (is_singular( 'post' )){
$text = str_replace('dog', 'cat', $text);
return $text;
}
}
``` | Your code is returning `$text` only for posts and nothing for other post types like pages.
Your function should be like this
```
add_filter('the_content', 'replace_word');
function replace_word($text) {
if (is_singular( 'post' )){
$text = str_replace('dog', 'cat', $text);
return $text;
}
// you must return content for pages/ other post types
return $text;
}
``` |
331,997 | <p>I use Plugin Boilerplate for my project. I searched the internet and read all the questions but I couldn’t find what I need. I also read the WordPress Codex. I think I couldn’t get the idea.</p>
<p>I have two columns on my page. Col1 and Col2</p>
<pre><code>Inside col1: wp_list_table
Inside col2: empty
</code></pre>
<p>Page address: <code>admin.php?page=company#home</code></p>
<p>When I clicked the Add New button on <code>wp_list_table</code>, the address bar shows <code>admin.php?page=company#home&action=new</code></p>
<p>I want to get the action value from the url. I tried the code below:</p>
<pre><code>function addnew_query_vars($vars) {
$vars[] = 'action';
return $vars;
}
add_filter('query_vars', 'add_query_vars_filter');
echo $value = get_query_var('action'); // Nothing happens
</code></pre>
<p>How I can get action value? If I can get the value, I’ll show a form inside the col2 or using a switch statement for other situations.</p>
<hr>
<p><strong>UPDATE</strong> 1.1.0</p>
<p><strong>Using get_current_screen</strong></p>
<pre><code>require_once(ABSPATH . 'wp-admin/includes/screen.php');
$screen = get_current_screen();
echo $screen->action; // Null
</code></pre>
<p>I'm using query monitor plugin. I looked Admin Screen status get_current_screen() action is empty. So I need to go back.</p>
<p>In the my WP_List_Table header code, my <strong>Add New</strong> button code is like this:</p>
<pre><code><a href="<?php echo admin_url( 'admin.php?page=company#home&action=new' );?>">
php _e( 'Add New', 'ironhead' )
</a>
</code></pre>
<p>I think this code block doesn't post the action. There is set_current_screen() command. But I don't solve how to set Admin Screen action attribute. IF I can use it, I can use get_current_screen(). Anyone help me?</p>
<p><strong>ALL CODE</strong></p>
<p><strong>TAB PANE</strong></p>
<pre><code><ul class="nav nav-tabs nav-pills tab-pane" id="myTab" role="tablist">
<li class="nav-item">
<a class="nav-link active" id="home-tab" data-toggle="tab" href="#home" role="tab" aria-controls="home" aria-selected="true">Company</a>
</li>
<li class="nav-item">
<a class="nav-link" id="facility-tab" data-toggle="tab" href="#facility" role="tab" aria-controls="facility" aria-selected="false">Facility</a>
</li>
...
</ul>
</code></pre>
<p><strong>TAB CONTENT</strong></p>
<pre><code><div class="tab-content" id="myTabContent">
<div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab">
<div class="row">
<div class="col">
<?php
function wp_get_all_company( $args = array() ) {
global $wpdb;
$defaults = array(
'number' => 20,
'offset' => 0,
'orderby' => 'ID',
'order' => 'ASC',
);
$args = wp_parse_args( $args, $defaults );
$cache_key = 'company-all';
$items = wp_cache_get( $cache_key, 'ironhead' );
if ( false === $items ) {
$items = $wpdb->get_results( 'SELECT * FROM ' . $wpdb->prefix . 'ih_company ORDER BY ' . $args['orderby'] .' ' . $args['order'] .' LIMIT ' . $args['offset'] . ', ' . $args['number'] );
wp_cache_set( $cache_key, $items, 'ironhead' );
}
return $items;
}
function wp_get_company_count() {
global $wpdb;
return (int) $wpdb->get_var( 'SELECT COUNT(*) FROM ' . $wpdb->prefix . 'ih_company' );
}
function wp_get_firma( $id = 0 ) {
global $wpdb;
return $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM ' . $wpdb->prefix . 'ih_company WHERE ID = %d', $id ) );
} ?>
<h4><?php _e( 'Company List', 'ironhead' ); ?> <a href="<?php echo admin_url( 'admin.php?page=company#home&action=new' ); ?>" class="add-new-h2"><?php _e( 'Add New', 'ironhead' ); ?></a></h4>
<form method="post">
<input type="hidden" name="page" value="ttest_list_table">
<?php
$list_table = new Company_List_Table();
$list_table->prepare_items();
$list_table->search_box( 'search', 'search_id' );
$list_table->display();
?>
</form>
</div>
<div class="col">
// action=new (or action=something) if or switch statement will be here.
</div>
</div>
</code></pre>
<p>Thanks in advance</p>
| [
{
"answer_id": 331987,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 2,
"selected": true,
"text": "<p>Your code is returning <code>$text</code> only for posts and nothing for other post types like pages. </p>\n\n<p>Your function should be like this</p>\n\n<pre><code>add_filter('the_content', 'replace_word');\nfunction replace_word($text) {\n if (is_singular( 'post' )){\n $text = str_replace('dog', 'cat', $text);\n\n return $text;\n }\n\n // you must return content for pages/ other post types\n return $text;\n\n}\n</code></pre>\n"
},
{
"answer_id": 331988,
"author": "MikeNGarrett",
"author_id": 1670,
"author_profile": "https://wordpress.stackexchange.com/users/1670",
"pm_score": 0,
"selected": false,
"text": "<p>You aren't returning <code>$text</code> for any other content. Filters must always return the string whether it's changed or not. </p>\n\n<pre><code>add_filter('the_content', 'replace_word');\nfunction replace_word($text) {\n if (is_singular( 'post' )){\n $text = str_replace('dog', 'cat', $text);\n\n return $text;\n }\n return $text;\n}\n</code></pre>\n"
}
] | 2019/03/18 | [
"https://wordpress.stackexchange.com/questions/331997",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/163388/"
] | I use Plugin Boilerplate for my project. I searched the internet and read all the questions but I couldn’t find what I need. I also read the WordPress Codex. I think I couldn’t get the idea.
I have two columns on my page. Col1 and Col2
```
Inside col1: wp_list_table
Inside col2: empty
```
Page address: `admin.php?page=company#home`
When I clicked the Add New button on `wp_list_table`, the address bar shows `admin.php?page=company#home&action=new`
I want to get the action value from the url. I tried the code below:
```
function addnew_query_vars($vars) {
$vars[] = 'action';
return $vars;
}
add_filter('query_vars', 'add_query_vars_filter');
echo $value = get_query_var('action'); // Nothing happens
```
How I can get action value? If I can get the value, I’ll show a form inside the col2 or using a switch statement for other situations.
---
**UPDATE** 1.1.0
**Using get\_current\_screen**
```
require_once(ABSPATH . 'wp-admin/includes/screen.php');
$screen = get_current_screen();
echo $screen->action; // Null
```
I'm using query monitor plugin. I looked Admin Screen status get\_current\_screen() action is empty. So I need to go back.
In the my WP\_List\_Table header code, my **Add New** button code is like this:
```
<a href="<?php echo admin_url( 'admin.php?page=company#home&action=new' );?>">
php _e( 'Add New', 'ironhead' )
</a>
```
I think this code block doesn't post the action. There is set\_current\_screen() command. But I don't solve how to set Admin Screen action attribute. IF I can use it, I can use get\_current\_screen(). Anyone help me?
**ALL CODE**
**TAB PANE**
```
<ul class="nav nav-tabs nav-pills tab-pane" id="myTab" role="tablist">
<li class="nav-item">
<a class="nav-link active" id="home-tab" data-toggle="tab" href="#home" role="tab" aria-controls="home" aria-selected="true">Company</a>
</li>
<li class="nav-item">
<a class="nav-link" id="facility-tab" data-toggle="tab" href="#facility" role="tab" aria-controls="facility" aria-selected="false">Facility</a>
</li>
...
</ul>
```
**TAB CONTENT**
```
<div class="tab-content" id="myTabContent">
<div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab">
<div class="row">
<div class="col">
<?php
function wp_get_all_company( $args = array() ) {
global $wpdb;
$defaults = array(
'number' => 20,
'offset' => 0,
'orderby' => 'ID',
'order' => 'ASC',
);
$args = wp_parse_args( $args, $defaults );
$cache_key = 'company-all';
$items = wp_cache_get( $cache_key, 'ironhead' );
if ( false === $items ) {
$items = $wpdb->get_results( 'SELECT * FROM ' . $wpdb->prefix . 'ih_company ORDER BY ' . $args['orderby'] .' ' . $args['order'] .' LIMIT ' . $args['offset'] . ', ' . $args['number'] );
wp_cache_set( $cache_key, $items, 'ironhead' );
}
return $items;
}
function wp_get_company_count() {
global $wpdb;
return (int) $wpdb->get_var( 'SELECT COUNT(*) FROM ' . $wpdb->prefix . 'ih_company' );
}
function wp_get_firma( $id = 0 ) {
global $wpdb;
return $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM ' . $wpdb->prefix . 'ih_company WHERE ID = %d', $id ) );
} ?>
<h4><?php _e( 'Company List', 'ironhead' ); ?> <a href="<?php echo admin_url( 'admin.php?page=company#home&action=new' ); ?>" class="add-new-h2"><?php _e( 'Add New', 'ironhead' ); ?></a></h4>
<form method="post">
<input type="hidden" name="page" value="ttest_list_table">
<?php
$list_table = new Company_List_Table();
$list_table->prepare_items();
$list_table->search_box( 'search', 'search_id' );
$list_table->display();
?>
</form>
</div>
<div class="col">
// action=new (or action=something) if or switch statement will be here.
</div>
</div>
```
Thanks in advance | Your code is returning `$text` only for posts and nothing for other post types like pages.
Your function should be like this
```
add_filter('the_content', 'replace_word');
function replace_word($text) {
if (is_singular( 'post' )){
$text = str_replace('dog', 'cat', $text);
return $text;
}
// you must return content for pages/ other post types
return $text;
}
``` |
332,008 | <p>This is my code, where i keep getting either error: unexpected endforeach; if endforeach is used or unexpected end of file if i don't use endforeach; It's driving me crazy!!</p>
<pre><code><ul id="portfolio-filter">
<?php
$k=0;
$services = array('all', 'marketing', 'SEO', 'web-design', 'web-development', 'wordpress');
foreach($services as $key) : ?>
<li class="<?php if($k==0) { ?> active <?php { ?>"><a class="<?php echo $key; ?>" href="#"><?php echo $key; ?></a>/</li>
<?php endforeach; ?>
</ul>
</code></pre>
<p>Any help will be appreciated!</p>
| [
{
"answer_id": 331987,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 2,
"selected": true,
"text": "<p>Your code is returning <code>$text</code> only for posts and nothing for other post types like pages. </p>\n\n<p>Your function should be like this</p>\n\n<pre><code>add_filter('the_content', 'replace_word');\nfunction replace_word($text) {\n if (is_singular( 'post' )){\n $text = str_replace('dog', 'cat', $text);\n\n return $text;\n }\n\n // you must return content for pages/ other post types\n return $text;\n\n}\n</code></pre>\n"
},
{
"answer_id": 331988,
"author": "MikeNGarrett",
"author_id": 1670,
"author_profile": "https://wordpress.stackexchange.com/users/1670",
"pm_score": 0,
"selected": false,
"text": "<p>You aren't returning <code>$text</code> for any other content. Filters must always return the string whether it's changed or not. </p>\n\n<pre><code>add_filter('the_content', 'replace_word');\nfunction replace_word($text) {\n if (is_singular( 'post' )){\n $text = str_replace('dog', 'cat', $text);\n\n return $text;\n }\n return $text;\n}\n</code></pre>\n"
}
] | 2019/03/18 | [
"https://wordpress.stackexchange.com/questions/332008",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/163393/"
] | This is my code, where i keep getting either error: unexpected endforeach; if endforeach is used or unexpected end of file if i don't use endforeach; It's driving me crazy!!
```
<ul id="portfolio-filter">
<?php
$k=0;
$services = array('all', 'marketing', 'SEO', 'web-design', 'web-development', 'wordpress');
foreach($services as $key) : ?>
<li class="<?php if($k==0) { ?> active <?php { ?>"><a class="<?php echo $key; ?>" href="#"><?php echo $key; ?></a>/</li>
<?php endforeach; ?>
</ul>
```
Any help will be appreciated! | Your code is returning `$text` only for posts and nothing for other post types like pages.
Your function should be like this
```
add_filter('the_content', 'replace_word');
function replace_word($text) {
if (is_singular( 'post' )){
$text = str_replace('dog', 'cat', $text);
return $text;
}
// you must return content for pages/ other post types
return $text;
}
``` |
332,076 | <p>Heads up, I'm pretty new to Wordpress... But I need to loop through multiple posts and change all 'data-src' attributes to 'src' so my images will display. What's the way/best way to go about doing this? Would appreciate any info on this topic. Thanks. </p>
| [
{
"answer_id": 331987,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 2,
"selected": true,
"text": "<p>Your code is returning <code>$text</code> only for posts and nothing for other post types like pages. </p>\n\n<p>Your function should be like this</p>\n\n<pre><code>add_filter('the_content', 'replace_word');\nfunction replace_word($text) {\n if (is_singular( 'post' )){\n $text = str_replace('dog', 'cat', $text);\n\n return $text;\n }\n\n // you must return content for pages/ other post types\n return $text;\n\n}\n</code></pre>\n"
},
{
"answer_id": 331988,
"author": "MikeNGarrett",
"author_id": 1670,
"author_profile": "https://wordpress.stackexchange.com/users/1670",
"pm_score": 0,
"selected": false,
"text": "<p>You aren't returning <code>$text</code> for any other content. Filters must always return the string whether it's changed or not. </p>\n\n<pre><code>add_filter('the_content', 'replace_word');\nfunction replace_word($text) {\n if (is_singular( 'post' )){\n $text = str_replace('dog', 'cat', $text);\n\n return $text;\n }\n return $text;\n}\n</code></pre>\n"
}
] | 2019/03/19 | [
"https://wordpress.stackexchange.com/questions/332076",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/163457/"
] | Heads up, I'm pretty new to Wordpress... But I need to loop through multiple posts and change all 'data-src' attributes to 'src' so my images will display. What's the way/best way to go about doing this? Would appreciate any info on this topic. Thanks. | Your code is returning `$text` only for posts and nothing for other post types like pages.
Your function should be like this
```
add_filter('the_content', 'replace_word');
function replace_word($text) {
if (is_singular( 'post' )){
$text = str_replace('dog', 'cat', $text);
return $text;
}
// you must return content for pages/ other post types
return $text;
}
``` |
332,096 | <p>Today I want to ask you something which is really important what if my WordPress website <a href="https://thecodezine.com" rel="nofollow noreferrer">https://thecodezine.com</a> gets hacked or my jetpack plugin security is broken?Will I lose everything? Is there no way to get back? How can I get all my files safe and secured.</p>
| [
{
"answer_id": 331987,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 2,
"selected": true,
"text": "<p>Your code is returning <code>$text</code> only for posts and nothing for other post types like pages. </p>\n\n<p>Your function should be like this</p>\n\n<pre><code>add_filter('the_content', 'replace_word');\nfunction replace_word($text) {\n if (is_singular( 'post' )){\n $text = str_replace('dog', 'cat', $text);\n\n return $text;\n }\n\n // you must return content for pages/ other post types\n return $text;\n\n}\n</code></pre>\n"
},
{
"answer_id": 331988,
"author": "MikeNGarrett",
"author_id": 1670,
"author_profile": "https://wordpress.stackexchange.com/users/1670",
"pm_score": 0,
"selected": false,
"text": "<p>You aren't returning <code>$text</code> for any other content. Filters must always return the string whether it's changed or not. </p>\n\n<pre><code>add_filter('the_content', 'replace_word');\nfunction replace_word($text) {\n if (is_singular( 'post' )){\n $text = str_replace('dog', 'cat', $text);\n\n return $text;\n }\n return $text;\n}\n</code></pre>\n"
}
] | 2019/03/19 | [
"https://wordpress.stackexchange.com/questions/332096",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/163277/"
] | Today I want to ask you something which is really important what if my WordPress website <https://thecodezine.com> gets hacked or my jetpack plugin security is broken?Will I lose everything? Is there no way to get back? How can I get all my files safe and secured. | Your code is returning `$text` only for posts and nothing for other post types like pages.
Your function should be like this
```
add_filter('the_content', 'replace_word');
function replace_word($text) {
if (is_singular( 'post' )){
$text = str_replace('dog', 'cat', $text);
return $text;
}
// you must return content for pages/ other post types
return $text;
}
``` |
332,259 | <p>I am trying add custom taxonomy with post using cron job. The problem is since wordpress 4.7, it verify if current user have capability of assigning taxonomy. Crob job don't have the capability.</p>
<p>I am using this for registering custom taxonomoy </p>
<pre>
add_action( 'init', 'create_locations_hierarchical_taxonomy', 0 );
function create_locations_hierarchical_taxonomy() {
// Add new taxonomy, make it hierarchical like categories
//first do the translations part for GUI
$labels = array(
'name' => _x( 'Locations', 'taxonomy general name' ),
'singular_name' => _x( 'Location', 'taxonomy singular name' ),
'search_items' => __( 'Search Locations' ),
'all_items' => __( 'All Locations' ),
'parent_item' => __( 'Parent Location' ),
'parent_item_colon' => __( 'Parent Location:' ),
'edit_item' => __( 'Edit Location' ),
'update_item' => __( 'Update Location' ),
'add_new_item' => __( 'Add New Location' ),
'new_item_name' => __( 'New Location Name' ),
'menu_name' => __( 'Locations' ),
);
// Now register the taxonomy
register_taxonomy('location',array('post'), array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'location' ),
));
</pre>
<p>And this script to assign taxonomy array with $post_arr</p>
<pre>
$post_location = array_map('intval', $post_location);
if ($post_type == 'post') {
$post_arr['tax_input'] = $post_location;
}
</pre>
<p>Currently, my script can create custom taxonomy but can't assign with post..</p>
<p>Ref:
<a href="https://core.trac.wordpress.org/browser/tags/5.1/src/wp-includes/post.php#L3784" rel="nofollow noreferrer">https://core.trac.wordpress.org/browser/tags/5.1/src/wp-includes/post.php#L3784</a></p>
| [
{
"answer_id": 332167,
"author": "mrben522",
"author_id": 84703,
"author_profile": "https://wordpress.stackexchange.com/users/84703",
"pm_score": 3,
"selected": true,
"text": "<p>Some links (those built in code) will automatically change to your new domain. Others (those in post content) you will want to swap out using something like <a href=\"https://wordpress.org/plugins/better-search-replace/\" rel=\"nofollow noreferrer\">better search replace</a> to swap out localhost for your new domain. </p>\n"
},
{
"answer_id": 332168,
"author": "danhgilmore",
"author_id": 819,
"author_profile": "https://wordpress.stackexchange.com/users/819",
"pm_score": 0,
"selected": false,
"text": "<p>Those URLs are stored in your WordPress database. Once you have moved your site to your provider, you will need to update the values in your database.</p>\n\n<p>This article should point you in the right direction.</p>\n\n<p><a href=\"https://codex.wordpress.org/Moving_WordPress\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Moving_WordPress</a></p>\n"
}
] | 2019/03/21 | [
"https://wordpress.stackexchange.com/questions/332259",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/162773/"
] | I am trying add custom taxonomy with post using cron job. The problem is since wordpress 4.7, it verify if current user have capability of assigning taxonomy. Crob job don't have the capability.
I am using this for registering custom taxonomoy
```
add_action( 'init', 'create_locations_hierarchical_taxonomy', 0 );
function create_locations_hierarchical_taxonomy() {
// Add new taxonomy, make it hierarchical like categories
//first do the translations part for GUI
$labels = array(
'name' => _x( 'Locations', 'taxonomy general name' ),
'singular_name' => _x( 'Location', 'taxonomy singular name' ),
'search_items' => __( 'Search Locations' ),
'all_items' => __( 'All Locations' ),
'parent_item' => __( 'Parent Location' ),
'parent_item_colon' => __( 'Parent Location:' ),
'edit_item' => __( 'Edit Location' ),
'update_item' => __( 'Update Location' ),
'add_new_item' => __( 'Add New Location' ),
'new_item_name' => __( 'New Location Name' ),
'menu_name' => __( 'Locations' ),
);
// Now register the taxonomy
register_taxonomy('location',array('post'), array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'location' ),
));
```
And this script to assign taxonomy array with $post\_arr
```
$post_location = array_map('intval', $post_location);
if ($post_type == 'post') {
$post_arr['tax_input'] = $post_location;
}
```
Currently, my script can create custom taxonomy but can't assign with post..
Ref:
<https://core.trac.wordpress.org/browser/tags/5.1/src/wp-includes/post.php#L3784> | Some links (those built in code) will automatically change to your new domain. Others (those in post content) you will want to swap out using something like [better search replace](https://wordpress.org/plugins/better-search-replace/) to swap out localhost for your new domain. |
332,295 | <p>I am trying to collect data from a search box. Conditions; if the value exists, update the counter field based on how many times it's been searched. </p>
<p>Problem: when a duplicate value searched in the form, the counter value increases by 2 not 1. So, if its current value is 5 and the term has been searched again the value in the database updated to 7, not 6. Any idea on the cause?</p>
<pre><code>function content_filter( $where, $wp_query ){
global $wpdb;
if ( $search_term = $wp_query->get( 'search_prod_content' ) ) {
$where .= ' AND ' . $wpdb->posts . '.post_content LIKE \'%' . esc_sql( $search_term ) . '%\'';
}
// first check if data exists with select query
$datum = $wpdb->get_results("SELECT * FROM search_product WHERE TERM = '".$search_term."'");
if($wpdb->num_rows > 0) {
$sql = $wpdb->prepare(
"UPDATE search_product SET COUNTER = COUNTER + 1 WHERE TERM = '".$search_term."'");
$wpdb->query($sql);
}
// if not exist in the database then insert it
else{
$now = new DateTime();
$datesent=$now->format('Y-m-d H:i:s');
$sql = $wpdb->prepare(
"INSERT INTO `search_product` (`TERM`,`DATE`) values (%s,%s)",
$search_term, $datesent);
$wpdb->query($sql);
}
return $where;
}
</code></pre>
| [
{
"answer_id": 332167,
"author": "mrben522",
"author_id": 84703,
"author_profile": "https://wordpress.stackexchange.com/users/84703",
"pm_score": 3,
"selected": true,
"text": "<p>Some links (those built in code) will automatically change to your new domain. Others (those in post content) you will want to swap out using something like <a href=\"https://wordpress.org/plugins/better-search-replace/\" rel=\"nofollow noreferrer\">better search replace</a> to swap out localhost for your new domain. </p>\n"
},
{
"answer_id": 332168,
"author": "danhgilmore",
"author_id": 819,
"author_profile": "https://wordpress.stackexchange.com/users/819",
"pm_score": 0,
"selected": false,
"text": "<p>Those URLs are stored in your WordPress database. Once you have moved your site to your provider, you will need to update the values in your database.</p>\n\n<p>This article should point you in the right direction.</p>\n\n<p><a href=\"https://codex.wordpress.org/Moving_WordPress\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Moving_WordPress</a></p>\n"
}
] | 2019/03/21 | [
"https://wordpress.stackexchange.com/questions/332295",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/163609/"
] | I am trying to collect data from a search box. Conditions; if the value exists, update the counter field based on how many times it's been searched.
Problem: when a duplicate value searched in the form, the counter value increases by 2 not 1. So, if its current value is 5 and the term has been searched again the value in the database updated to 7, not 6. Any idea on the cause?
```
function content_filter( $where, $wp_query ){
global $wpdb;
if ( $search_term = $wp_query->get( 'search_prod_content' ) ) {
$where .= ' AND ' . $wpdb->posts . '.post_content LIKE \'%' . esc_sql( $search_term ) . '%\'';
}
// first check if data exists with select query
$datum = $wpdb->get_results("SELECT * FROM search_product WHERE TERM = '".$search_term."'");
if($wpdb->num_rows > 0) {
$sql = $wpdb->prepare(
"UPDATE search_product SET COUNTER = COUNTER + 1 WHERE TERM = '".$search_term."'");
$wpdb->query($sql);
}
// if not exist in the database then insert it
else{
$now = new DateTime();
$datesent=$now->format('Y-m-d H:i:s');
$sql = $wpdb->prepare(
"INSERT INTO `search_product` (`TERM`,`DATE`) values (%s,%s)",
$search_term, $datesent);
$wpdb->query($sql);
}
return $where;
}
``` | Some links (those built in code) will automatically change to your new domain. Others (those in post content) you will want to swap out using something like [better search replace](https://wordpress.org/plugins/better-search-replace/) to swap out localhost for your new domain. |
332,307 | <p>Is there a way in mySQL or otherwise to bulk convert all my tags into lowercase? Thanks!</p>
| [
{
"answer_id": 332311,
"author": "Uranbold",
"author_id": 140634,
"author_profile": "https://wordpress.stackexchange.com/users/140634",
"pm_score": 1,
"selected": false,
"text": "<p>Just use the Css for that. Why do you wanna change it on MySQL? I suggest <strong>text-transform: lowercase</strong> for this.</p>\n\n<p>Thanks.</p>\n"
},
{
"answer_id": 332315,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 3,
"selected": true,
"text": "<p>I would highly suggest that you use CSS to do this, as mentioned per other answer. Still, if you need to update the database due to some technical business, here's the way to go.</p>\n\n<p>First, we will try and fetch all the tags using the <a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"nofollow noreferrer\"><code>get_terms()</code></a> function, then we will update everyone of them using the <a href=\"https://codex.wordpress.org/Function_Reference/wp_update_term\" rel=\"nofollow noreferrer\"><code>wp_update_term()</code></a> function:</p>\n\n<pre><code><?php\n // Get all the tags\n $tags = get_terms(\n [\n 'taxonomy' => 'post_tag',\n 'hide_empty' => FALSE,\n ]\n );\n\n // Some basic checks\n if ( ! empty( $tags ) && ! is_wp_error( $tags ) ) {\n\n // Loop through all the tags and convert\n // them to lowercase\n foreach ( $tags as $tag ) {\n // Convert the tag to lowercase\n $lowercase_tag = strtolower( $tag->name );\n\n // Update the tag\n wp_update_term(\n $tag->term_id,\n 'post_tag',\n [\n 'name' => $lowercase_tag,\n ]\n );\n }\n\n }\n</code></pre>\n"
}
] | 2019/03/21 | [
"https://wordpress.stackexchange.com/questions/332307",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/163617/"
] | Is there a way in mySQL or otherwise to bulk convert all my tags into lowercase? Thanks! | I would highly suggest that you use CSS to do this, as mentioned per other answer. Still, if you need to update the database due to some technical business, here's the way to go.
First, we will try and fetch all the tags using the [`get_terms()`](https://developer.wordpress.org/reference/functions/get_terms/) function, then we will update everyone of them using the [`wp_update_term()`](https://codex.wordpress.org/Function_Reference/wp_update_term) function:
```
<?php
// Get all the tags
$tags = get_terms(
[
'taxonomy' => 'post_tag',
'hide_empty' => FALSE,
]
);
// Some basic checks
if ( ! empty( $tags ) && ! is_wp_error( $tags ) ) {
// Loop through all the tags and convert
// them to lowercase
foreach ( $tags as $tag ) {
// Convert the tag to lowercase
$lowercase_tag = strtolower( $tag->name );
// Update the tag
wp_update_term(
$tag->term_id,
'post_tag',
[
'name' => $lowercase_tag,
]
);
}
}
``` |
332,328 | <p>I'm implementing infinite loading using the WP API, so I pull in the new posts via an API request. Because the default API response is fine with me and I only really need to filter the posts returned, I'm not creating a custom route but rather customizing the default query: </p>
<pre><code>add_filter( 'rest_post_query', array( $this, 'get_posts' ), 10, 2 );
public function get_posts( $args, $req ) {
/*
This function is used to retrieve posts of the 'post' and 'news' type
*/
$cat = $req[ 'category' ];
$page = $req[ 'page' ];
$tag = $req[ 'tag' ];
$type = $req[ 'type' ];
$args[ 'paged' ] = isset( $page ) ? $page : 1;
$args[ 'posts_per_page' ] = 8;
$args[ 'category_name' ] = isset( $cat ) && ! empty( $cat ) ? $cat : null;
$args[ 'tag' ] = isset( $tag ) && ! empty( $tag ) ? $tag : null;
$args[ 'post_type' ] =
isset( $type ) && ! empty( $type ) ? array( $type ) : array( 'post', 'news' );
return $args;
}
</code></pre>
<p>I have a problem with pagination, though. Imagine that I have 10 pages of results and I request page 20: the API's default behavior is to throw the following error: </p>
<pre><code>{
"code": "rest_post_invalid_page_number",
"message": "The page number requested is larger than the number of pages available.",
"data": {
"status": 400
}
}
</code></pre>
<p>What I would like to do is return an empty array instead, because it would be easier and more intuitive to deal with in the frontend. So I thought I'd check the <code>max_num_pages</code> property of the query, but I don't know where to do that.</p>
<p>I tried doing this: </p>
<pre><code>add_action( 'pre_get_posts', array( $this, 'check_pagination_limit' ) );
public function check_pagination_limit( $query ) {
if( ! is_admin() ) {
$currentPage = $query->get('paged');
$lastPage = $query->max_num_pages;
if( $currentPage > $lastPage ) {
$query->set('post__in', array(0));
}
}
}
</code></pre>
<p>But <code>pre_get_posts</code> doesn't seem to work well when <code>rest_post_query</code> is being used... Is there any <code>rest_</code> filter or hook that I can use to access the query before the response is sent? </p>
| [
{
"answer_id": 332311,
"author": "Uranbold",
"author_id": 140634,
"author_profile": "https://wordpress.stackexchange.com/users/140634",
"pm_score": 1,
"selected": false,
"text": "<p>Just use the Css for that. Why do you wanna change it on MySQL? I suggest <strong>text-transform: lowercase</strong> for this.</p>\n\n<p>Thanks.</p>\n"
},
{
"answer_id": 332315,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 3,
"selected": true,
"text": "<p>I would highly suggest that you use CSS to do this, as mentioned per other answer. Still, if you need to update the database due to some technical business, here's the way to go.</p>\n\n<p>First, we will try and fetch all the tags using the <a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"nofollow noreferrer\"><code>get_terms()</code></a> function, then we will update everyone of them using the <a href=\"https://codex.wordpress.org/Function_Reference/wp_update_term\" rel=\"nofollow noreferrer\"><code>wp_update_term()</code></a> function:</p>\n\n<pre><code><?php\n // Get all the tags\n $tags = get_terms(\n [\n 'taxonomy' => 'post_tag',\n 'hide_empty' => FALSE,\n ]\n );\n\n // Some basic checks\n if ( ! empty( $tags ) && ! is_wp_error( $tags ) ) {\n\n // Loop through all the tags and convert\n // them to lowercase\n foreach ( $tags as $tag ) {\n // Convert the tag to lowercase\n $lowercase_tag = strtolower( $tag->name );\n\n // Update the tag\n wp_update_term(\n $tag->term_id,\n 'post_tag',\n [\n 'name' => $lowercase_tag,\n ]\n );\n }\n\n }\n</code></pre>\n"
}
] | 2019/03/22 | [
"https://wordpress.stackexchange.com/questions/332328",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/129417/"
] | I'm implementing infinite loading using the WP API, so I pull in the new posts via an API request. Because the default API response is fine with me and I only really need to filter the posts returned, I'm not creating a custom route but rather customizing the default query:
```
add_filter( 'rest_post_query', array( $this, 'get_posts' ), 10, 2 );
public function get_posts( $args, $req ) {
/*
This function is used to retrieve posts of the 'post' and 'news' type
*/
$cat = $req[ 'category' ];
$page = $req[ 'page' ];
$tag = $req[ 'tag' ];
$type = $req[ 'type' ];
$args[ 'paged' ] = isset( $page ) ? $page : 1;
$args[ 'posts_per_page' ] = 8;
$args[ 'category_name' ] = isset( $cat ) && ! empty( $cat ) ? $cat : null;
$args[ 'tag' ] = isset( $tag ) && ! empty( $tag ) ? $tag : null;
$args[ 'post_type' ] =
isset( $type ) && ! empty( $type ) ? array( $type ) : array( 'post', 'news' );
return $args;
}
```
I have a problem with pagination, though. Imagine that I have 10 pages of results and I request page 20: the API's default behavior is to throw the following error:
```
{
"code": "rest_post_invalid_page_number",
"message": "The page number requested is larger than the number of pages available.",
"data": {
"status": 400
}
}
```
What I would like to do is return an empty array instead, because it would be easier and more intuitive to deal with in the frontend. So I thought I'd check the `max_num_pages` property of the query, but I don't know where to do that.
I tried doing this:
```
add_action( 'pre_get_posts', array( $this, 'check_pagination_limit' ) );
public function check_pagination_limit( $query ) {
if( ! is_admin() ) {
$currentPage = $query->get('paged');
$lastPage = $query->max_num_pages;
if( $currentPage > $lastPage ) {
$query->set('post__in', array(0));
}
}
}
```
But `pre_get_posts` doesn't seem to work well when `rest_post_query` is being used... Is there any `rest_` filter or hook that I can use to access the query before the response is sent? | I would highly suggest that you use CSS to do this, as mentioned per other answer. Still, if you need to update the database due to some technical business, here's the way to go.
First, we will try and fetch all the tags using the [`get_terms()`](https://developer.wordpress.org/reference/functions/get_terms/) function, then we will update everyone of them using the [`wp_update_term()`](https://codex.wordpress.org/Function_Reference/wp_update_term) function:
```
<?php
// Get all the tags
$tags = get_terms(
[
'taxonomy' => 'post_tag',
'hide_empty' => FALSE,
]
);
// Some basic checks
if ( ! empty( $tags ) && ! is_wp_error( $tags ) ) {
// Loop through all the tags and convert
// them to lowercase
foreach ( $tags as $tag ) {
// Convert the tag to lowercase
$lowercase_tag = strtolower( $tag->name );
// Update the tag
wp_update_term(
$tag->term_id,
'post_tag',
[
'name' => $lowercase_tag,
]
);
}
}
``` |
332,340 | <p>I need an array that contains all the posts names that match with the post_type"pelicula"</p>
| [
{
"answer_id": 332311,
"author": "Uranbold",
"author_id": 140634,
"author_profile": "https://wordpress.stackexchange.com/users/140634",
"pm_score": 1,
"selected": false,
"text": "<p>Just use the Css for that. Why do you wanna change it on MySQL? I suggest <strong>text-transform: lowercase</strong> for this.</p>\n\n<p>Thanks.</p>\n"
},
{
"answer_id": 332315,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 3,
"selected": true,
"text": "<p>I would highly suggest that you use CSS to do this, as mentioned per other answer. Still, if you need to update the database due to some technical business, here's the way to go.</p>\n\n<p>First, we will try and fetch all the tags using the <a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"nofollow noreferrer\"><code>get_terms()</code></a> function, then we will update everyone of them using the <a href=\"https://codex.wordpress.org/Function_Reference/wp_update_term\" rel=\"nofollow noreferrer\"><code>wp_update_term()</code></a> function:</p>\n\n<pre><code><?php\n // Get all the tags\n $tags = get_terms(\n [\n 'taxonomy' => 'post_tag',\n 'hide_empty' => FALSE,\n ]\n );\n\n // Some basic checks\n if ( ! empty( $tags ) && ! is_wp_error( $tags ) ) {\n\n // Loop through all the tags and convert\n // them to lowercase\n foreach ( $tags as $tag ) {\n // Convert the tag to lowercase\n $lowercase_tag = strtolower( $tag->name );\n\n // Update the tag\n wp_update_term(\n $tag->term_id,\n 'post_tag',\n [\n 'name' => $lowercase_tag,\n ]\n );\n }\n\n }\n</code></pre>\n"
}
] | 2019/03/22 | [
"https://wordpress.stackexchange.com/questions/332340",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/162285/"
] | I need an array that contains all the posts names that match with the post\_type"pelicula" | I would highly suggest that you use CSS to do this, as mentioned per other answer. Still, if you need to update the database due to some technical business, here's the way to go.
First, we will try and fetch all the tags using the [`get_terms()`](https://developer.wordpress.org/reference/functions/get_terms/) function, then we will update everyone of them using the [`wp_update_term()`](https://codex.wordpress.org/Function_Reference/wp_update_term) function:
```
<?php
// Get all the tags
$tags = get_terms(
[
'taxonomy' => 'post_tag',
'hide_empty' => FALSE,
]
);
// Some basic checks
if ( ! empty( $tags ) && ! is_wp_error( $tags ) ) {
// Loop through all the tags and convert
// them to lowercase
foreach ( $tags as $tag ) {
// Convert the tag to lowercase
$lowercase_tag = strtolower( $tag->name );
// Update the tag
wp_update_term(
$tag->term_id,
'post_tag',
[
'name' => $lowercase_tag,
]
);
}
}
``` |
332,358 | <p>I need to show my client error message on all admin pages.</p>
<p>I have the following code, that adds a custom notice only on the admin dashboard page:</p>
<pre><code>add_action('admin_bar_menu', 'custom_toolbar_link2', 999);
function general_admin_notice(){
global $pagenow;
if ( $pagenow == 'index.php' ) {
echo '<div class="notice notice-error">
<h3>My custom text</h3>
</div>';
}
}
</code></pre>
<p>Is there any way to display this notice on all admin pages?</p>
| [
{
"answer_id": 332361,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 0,
"selected": false,
"text": "<p>Sure there is a method to do this. You just need to attach your function to a different hook, <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/admin_notices\" rel=\"nofollow noreferrer\"><code>admin_notices</code></a>. You can even add classes that will turn into coloured bars, telling the user how important the message is.</p>\n"
},
{
"answer_id": 332363,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 2,
"selected": true,
"text": "<pre><code>function my_admin_notice() {\n\n /*\n * The class of admin notice should be \"notice\" plus any one of\n * -\"notice-error\",\n * -\"notice-warning\",\n * -\"notice-success\"\n * -\"notice-info\".\n * Optionally use \"is-dismissible\" to apply a closing icon.\n */\n\n echo '<div class=\"notice notice-info\"><p>Custom notice text</p></div>';\n\n}\n\nadd_action( 'admin_notices', 'my_admin_notice' );\n</code></pre>\n\n<p>The only thing is, these notices does not show up on New Post, Edit Post and similar where Gutenberg reins. There must be the solution, but I can't find it right now.</p>\n"
}
] | 2019/03/22 | [
"https://wordpress.stackexchange.com/questions/332358",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/157966/"
] | I need to show my client error message on all admin pages.
I have the following code, that adds a custom notice only on the admin dashboard page:
```
add_action('admin_bar_menu', 'custom_toolbar_link2', 999);
function general_admin_notice(){
global $pagenow;
if ( $pagenow == 'index.php' ) {
echo '<div class="notice notice-error">
<h3>My custom text</h3>
</div>';
}
}
```
Is there any way to display this notice on all admin pages? | ```
function my_admin_notice() {
/*
* The class of admin notice should be "notice" plus any one of
* -"notice-error",
* -"notice-warning",
* -"notice-success"
* -"notice-info".
* Optionally use "is-dismissible" to apply a closing icon.
*/
echo '<div class="notice notice-info"><p>Custom notice text</p></div>';
}
add_action( 'admin_notices', 'my_admin_notice' );
```
The only thing is, these notices does not show up on New Post, Edit Post and similar where Gutenberg reins. There must be the solution, but I can't find it right now. |
332,383 | <p>I am using plain simple code to make a search page</p>
<pre><code>$argscontactdirectory = array(
"s" => get_search_query(),
'post_type' => array( 'expertarticle'),
'orderby' => 'title',
'order' => 'ASC',
);
</code></pre>
<p>Above is the code I am using, however, when the search query contains the "&" character it simply doesn't work, if the search query is <code>M&M</code> the URL bar will show <code>?s=M&amp;M</code></p>
<p>I tried many things, include <code>urlencode()</code>, but it doesn't work either. </p>
<p>A live example can be seen here:
<a href="http://sandbox.indiadairy.com/?s=hello&p_type=is" rel="nofollow noreferrer">http://sandbox.indiadairy.com/?s=hello&p_type=is</a></p>
<p>Any help is appreciated. </p>
| [
{
"answer_id": 332385,
"author": "czerspalace",
"author_id": 47406,
"author_profile": "https://wordpress.stackexchange.com/users/47406",
"pm_score": 2,
"selected": true,
"text": "<p><code>get_search_query</code> escapes the data for outputting to HTML. Can you try the following instead:</p>\n\n<pre><code>$argscontactdirectory = array(\n 's' => sanitize_text_field( get_search_query( false ) ),\n 'post_type' => array( 'expertarticle'),\n 'orderby' => 'title',\n 'order' => 'ASC',\n);\n</code></pre>\n"
},
{
"answer_id": 373212,
"author": "PW_NIC",
"author_id": 193283,
"author_profile": "https://wordpress.stackexchange.com/users/193283",
"pm_score": 0,
"selected": false,
"text": "<p>Like this?</p>\n<pre><code>$argscontactdirectory = urlencode(\narray(\n 's' => sanitize_text_field( get_search_query( false ) ),\n 'post_type' => array( 'expertarticle'),\n 'orderby' => 'title',\n 'order' => 'ASC',\n)\n);\n</code></pre>\n"
}
] | 2019/03/22 | [
"https://wordpress.stackexchange.com/questions/332383",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101405/"
] | I am using plain simple code to make a search page
```
$argscontactdirectory = array(
"s" => get_search_query(),
'post_type' => array( 'expertarticle'),
'orderby' => 'title',
'order' => 'ASC',
);
```
Above is the code I am using, however, when the search query contains the "&" character it simply doesn't work, if the search query is `M&M` the URL bar will show `?s=M&M`
I tried many things, include `urlencode()`, but it doesn't work either.
A live example can be seen here:
<http://sandbox.indiadairy.com/?s=hello&p_type=is>
Any help is appreciated. | `get_search_query` escapes the data for outputting to HTML. Can you try the following instead:
```
$argscontactdirectory = array(
's' => sanitize_text_field( get_search_query( false ) ),
'post_type' => array( 'expertarticle'),
'orderby' => 'title',
'order' => 'ASC',
);
``` |
332,423 | <p>i'm create custom admin page via <code>add_menu_page</code>, let's imagine that my custom page has url </p>
<blockquote>
<p>wp-admin/admin.php?page=settings_page</p>
</blockquote>
<p>then i'm checki <code>is_admin()</code> function via <code>var_dump</code> on my <code>settings_page</code> and it returns <code>true</code> - that's OK, but when i'm wrap <code>rest_api_init</code> action in <code>if is_admin()</code> statement, like this:</p>
<pre><code>if(is_admin()){
add_action('rest_api_init', [$this, 'myRegisterRoutesFunction']);
}
</code></pre>
<p>it returns me <code>404 - No route was found matching the URL and request method</code>. But if i remove <code>if</code> statement, it works fine. Can't understand why, thanks for the advices!</p>
| [
{
"answer_id": 349511,
"author": "DarkNeuron",
"author_id": 86731,
"author_profile": "https://wordpress.stackexchange.com/users/86731",
"pm_score": 1,
"selected": false,
"text": "<p>It's due to the way WP initializes the REST endpoints. It works something like this:</p>\n\n<p>Someone <code>POST</code>s to an endpoint, f.ex <code>/wp-json/my/custom/endpoint</code>. Wordpress tries to figure out if there is a route for that endpoint by calling the <code>rest_api_init</code> hook, and running any custom code that sets up that route.</p>\n\n<p>Now check out the source for <code>is_admin</code>:</p>\n\n<pre><code>function is_admin() {\n if ( isset( $GLOBALS['current_screen'] ) ) {\n return $GLOBALS['current_screen']->in_admin();\n } elseif ( defined( 'WP_ADMIN' ) ) {\n return WP_ADMIN;\n }\n\n return false;\n}\n</code></pre>\n\n<p>Nothing magical here, it just checks what screen you're currently on. However, there's no \"screen\" when a REST call comes in. So <code>is_admin</code> is always going to return false.</p>\n\n<p>So thats what happens when you wrap your REST initialization logic with <code>is_admin</code>.</p>\n"
},
{
"answer_id": 403170,
"author": "floodlitworld",
"author_id": 219726,
"author_profile": "https://wordpress.stackexchange.com/users/219726",
"pm_score": 4,
"selected": true,
"text": "<p>Essentially, you shouldn't wrap your REST route declarations inside is_admin() since Wordpress will not load them (see @DarkNueron comment).</p>\n<p>What you can do is pass a 'permission_callback' function to the <code>register_rest_route</code> function. If the function returns true, the request is allowed to continue; if false, an error is returned.</p>\n<p>So you could do:</p>\n<pre class=\"lang-php prettyprint-override\"><code>register_rest_route('your-namespace/v1', '/options/', [\n 'methods' => 'PATCH',\n 'callback' => [__CLASS__, 'update_option'],\n 'permission_callback' => function () {\n return current_user_can('manage_options');\n }\n]);\n</code></pre>\n"
}
] | 2019/03/23 | [
"https://wordpress.stackexchange.com/questions/332423",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68798/"
] | i'm create custom admin page via `add_menu_page`, let's imagine that my custom page has url
>
> wp-admin/admin.php?page=settings\_page
>
>
>
then i'm checki `is_admin()` function via `var_dump` on my `settings_page` and it returns `true` - that's OK, but when i'm wrap `rest_api_init` action in `if is_admin()` statement, like this:
```
if(is_admin()){
add_action('rest_api_init', [$this, 'myRegisterRoutesFunction']);
}
```
it returns me `404 - No route was found matching the URL and request method`. But if i remove `if` statement, it works fine. Can't understand why, thanks for the advices! | Essentially, you shouldn't wrap your REST route declarations inside is\_admin() since Wordpress will not load them (see @DarkNueron comment).
What you can do is pass a 'permission\_callback' function to the `register_rest_route` function. If the function returns true, the request is allowed to continue; if false, an error is returned.
So you could do:
```php
register_rest_route('your-namespace/v1', '/options/', [
'methods' => 'PATCH',
'callback' => [__CLASS__, 'update_option'],
'permission_callback' => function () {
return current_user_can('manage_options');
}
]);
``` |
332,429 | <p>I am coding in WordPress to make a button to toggle body class from <code>light-mode</code> to <code>dark-mode</code>. i was experimenting with trying to add a cookie so that the preference is remembered for the browser. But i receive a error <code>Cannot set property className of null at setThemeFromCookie</code>.</p>
<p>moreover clicking the button gives another error <code>(index):486 Uncaught TypeError: Cannot read property 'className' of null at togglePageContentLightDark</code></p>
<p>My url is <a href="https://milyin.com" rel="nofollow noreferrer">https://milyin.com</a>
you can see the button in blue color located in footer</p>
<p>JS follows</p>
<pre><code> function togglePageContentLightDark() {
var body = document.getElementById('body')
var currentClass = body.className
var newClass = body.className == 'dark-mode' ? 'light-mode' : 'dark-mode'
body.className = newClass
document.cookie = 'theme=' + (newClass == 'light-mode' ? 'light' : 'dark')
console.log('Cookies are now: ' + document.cookie)
}
function isDarkThemeSelected() {
return document.cookie.match(/theme=dark/i) != null
}
function setThemeFromCookie() {
var body = document.getElementById('body')
body.className = isDarkThemeSelected() ? 'dark-mode' : 'light-mode'
}
(function() {
setThemeFromCookie()
})();
</code></pre>
<p>HTML for button</p>
<pre><code><button type="button" name="dark_light" onclick="togglePageContentLightDark()" title="Toggle dark/light mode"></button>
</code></pre>
<p>i am fairly new to Java script and this code was taken from internet only. Please help me debug this code.</p>
| [
{
"answer_id": 332432,
"author": "mrben522",
"author_id": 84703,
"author_profile": "https://wordpress.stackexchange.com/users/84703",
"pm_score": 0,
"selected": false,
"text": "<p><code>var body = document.getElementById('body')</code> is your problem. The document's body is not an id, it's a tag. Use <code>var body = document.querySelector('body');</code></p>\n"
},
{
"answer_id": 332433,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 3,
"selected": true,
"text": "<h2>Using JQuery Simplifies the whole thing, using <a href=\"https://github.com/js-cookie/js-cookie\" rel=\"nofollow noreferrer\">JS Cookie</a></h2>\n\n<pre><code>$(document).ready(function(){\n\n // Check cookie and set theme\n if(Cookies.get('theme')) {\n\n $('body').removeClass('light-mode dark-mode').addClass( Cookies.get('theme') );\n\n };\n\n\n //Switch theme and create the cookie...\n\n $(\"#theme-toggler\").click(function(){\n\n if ($('body').hasClass( 'light-mode')){\n $('body').removeClass('light-mode').addClass('dark-mode');\n Cookies.set('theme', 'dark-mode');\n\n }else {\n $('body').removeClass('dark-mode').addClass('light-mode');\n Cookies.set('theme', 'light-mode');\n }\n\n });\n\n});\n</code></pre>\n\n<p>Add <code>id</code> to <code>button</code>.</p>\n\n<pre><code><button id=\"theme-toggler\" type=\"button\" name=\"dark_light\" title=\"Toggle dark/light mode\"></button>\n</code></pre>\n\n<p>Also add this script</p>\n\n<pre><code><script src=\"https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js\"></script>\n</code></pre>\n"
}
] | 2019/03/23 | [
"https://wordpress.stackexchange.com/questions/332429",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] | I am coding in WordPress to make a button to toggle body class from `light-mode` to `dark-mode`. i was experimenting with trying to add a cookie so that the preference is remembered for the browser. But i receive a error `Cannot set property className of null at setThemeFromCookie`.
moreover clicking the button gives another error `(index):486 Uncaught TypeError: Cannot read property 'className' of null at togglePageContentLightDark`
My url is <https://milyin.com>
you can see the button in blue color located in footer
JS follows
```
function togglePageContentLightDark() {
var body = document.getElementById('body')
var currentClass = body.className
var newClass = body.className == 'dark-mode' ? 'light-mode' : 'dark-mode'
body.className = newClass
document.cookie = 'theme=' + (newClass == 'light-mode' ? 'light' : 'dark')
console.log('Cookies are now: ' + document.cookie)
}
function isDarkThemeSelected() {
return document.cookie.match(/theme=dark/i) != null
}
function setThemeFromCookie() {
var body = document.getElementById('body')
body.className = isDarkThemeSelected() ? 'dark-mode' : 'light-mode'
}
(function() {
setThemeFromCookie()
})();
```
HTML for button
```
<button type="button" name="dark_light" onclick="togglePageContentLightDark()" title="Toggle dark/light mode"></button>
```
i am fairly new to Java script and this code was taken from internet only. Please help me debug this code. | Using JQuery Simplifies the whole thing, using [JS Cookie](https://github.com/js-cookie/js-cookie)
--------------------------------------------------------------------------------------------------
```
$(document).ready(function(){
// Check cookie and set theme
if(Cookies.get('theme')) {
$('body').removeClass('light-mode dark-mode').addClass( Cookies.get('theme') );
};
//Switch theme and create the cookie...
$("#theme-toggler").click(function(){
if ($('body').hasClass( 'light-mode')){
$('body').removeClass('light-mode').addClass('dark-mode');
Cookies.set('theme', 'dark-mode');
}else {
$('body').removeClass('dark-mode').addClass('light-mode');
Cookies.set('theme', 'light-mode');
}
});
});
```
Add `id` to `button`.
```
<button id="theme-toggler" type="button" name="dark_light" title="Toggle dark/light mode"></button>
```
Also add this script
```
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
``` |
332,455 | <p>I'm building a custom theme for a client's website and want to allow them to use embedded content in their posts (Youtube videos, Facebook posts, Twitter feeds, etc.) Typically, I've taken to severely limiting what kinds of blocks are available in the Gutenberg editor so this is the first time I've allowed the embed blocks -- and now I'm totally lost with how to deal with them.</p>
<p>None of the embedded iframes are responsive to window resizing or on mobile devices. Instead, they overflow off the page and mess up the page layout. I believe this has something to do with inline dimensions being declared. However, I have made sure in each block's settings that "Resize for smaller devices" is on which states: "This embed will preserve its aspect ratio when the browser is resized." I have also added the following code to my functions.php: </p>
<pre><code>function site_features() {
...
...
add_theme_support( 'responsive-embeds' );
}
add_action('after_setup_theme', 'site_features');
</code></pre>
<p>I have searched multiple forums, blog sites, and elsewhere and have not been able to find anyone having this exact issue. Any solutions I have found are outdated and don't actually solve the issue I'm having. For example, I've found this code to force iframes to respond:</p>
<pre><code>.wp-block-embed {
position: relative;
padding-bottom: 56.25%;
padding-top: 35px;
height: 0;
overflow: hidden;
}
.wp-block-embed iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
border: 0;
}
</code></pre>
<p>But this is not ideal, as I would have to manually update the aspect ratio for each individual block in my css. Can anyone shed some light on this issue?</p>
| [
{
"answer_id": 332487,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 3,
"selected": false,
"text": "<p>It may be that your theme hasn't declared support for responsive embeds. Try adding this code to your functions.php</p>\n\n<pre><code>// Add support for responsive embedded content.\nadd_theme_support( 'responsive-embeds' );\n</code></pre>\n\n<p>or your theme setup file if there is one. </p>\n"
},
{
"answer_id": 333056,
"author": "Reberg",
"author_id": 164151,
"author_profile": "https://wordpress.stackexchange.com/users/164151",
"pm_score": 2,
"selected": false,
"text": "<p>If you don't already have it, add <a href=\"https://developer.wordpress.org/reference/functions/body_class/\" rel=\"nofollow noreferrer\">body_class();</a> to the themes body tag</p>\n\n<pre><code><body <?php body_class(); ?>>\n</code></pre>\n"
}
] | 2019/03/23 | [
"https://wordpress.stackexchange.com/questions/332455",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/163716/"
] | I'm building a custom theme for a client's website and want to allow them to use embedded content in their posts (Youtube videos, Facebook posts, Twitter feeds, etc.) Typically, I've taken to severely limiting what kinds of blocks are available in the Gutenberg editor so this is the first time I've allowed the embed blocks -- and now I'm totally lost with how to deal with them.
None of the embedded iframes are responsive to window resizing or on mobile devices. Instead, they overflow off the page and mess up the page layout. I believe this has something to do with inline dimensions being declared. However, I have made sure in each block's settings that "Resize for smaller devices" is on which states: "This embed will preserve its aspect ratio when the browser is resized." I have also added the following code to my functions.php:
```
function site_features() {
...
...
add_theme_support( 'responsive-embeds' );
}
add_action('after_setup_theme', 'site_features');
```
I have searched multiple forums, blog sites, and elsewhere and have not been able to find anyone having this exact issue. Any solutions I have found are outdated and don't actually solve the issue I'm having. For example, I've found this code to force iframes to respond:
```
.wp-block-embed {
position: relative;
padding-bottom: 56.25%;
padding-top: 35px;
height: 0;
overflow: hidden;
}
.wp-block-embed iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
border: 0;
}
```
But this is not ideal, as I would have to manually update the aspect ratio for each individual block in my css. Can anyone shed some light on this issue? | It may be that your theme hasn't declared support for responsive embeds. Try adding this code to your functions.php
```
// Add support for responsive embedded content.
add_theme_support( 'responsive-embeds' );
```
or your theme setup file if there is one. |
332,457 | <p>I have a custom bootstrap 4 theme I am building out in wordpress. The drop down mobile menu does not work when the hamburger menu is pressed at smaller viewports. I am not sure if I need to add a something to the function.php file for mobile menu, or some other php/wp code for the collapsible nav? </p>
<p>The mobile menu will work when I uncomment the "collapse navbar-collapse" section, but then two menus appear. This tells me all the scripts and css are working. However, I not sure what I am missing I can't seem to figure out what I am missing. I am not using the navwalker script. I would greatly appreciate anyone's help! </p>
<p>HTML Code</p>
<pre><code><header>
<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
<img class="ml-2 NVAlogo" src="<?php bloginfo('stylesheet_directory'); ?>/img/NVAlogo.png" alt="logo"><a class="navbar-brand" href="front.html">Nuvision Alliance</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<?php
wp_nav_menu( array(
'menu' => 'primary',
'container' => 'nav',
'container_class' => 'navbar-collapse collapse',
'menu_class' => 'nav navbar-nav navbar-right'
));
?>
<div class="collapse navbar-collapse" id="navbarCollapse">
<ul class="navbar-nav mr-auto">
<!-- <li class="nav-item">
<a class="nav-link" href="mission.html">Mission</a>
</li>
<li class="nav-item">
<a class="nav-link" href="causes.html">Causes</a>
</li>
<li class="nav-item">
<a class="nav-link" href="index.html">Blog</a>
</li>
<li class="nav-item">
<a class="nav-link" href="contact.html">Contact</a>
</li>
</ul>-->
</div>
</nav>
</header>
</code></pre>
| [
{
"answer_id": 332487,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 3,
"selected": false,
"text": "<p>It may be that your theme hasn't declared support for responsive embeds. Try adding this code to your functions.php</p>\n\n<pre><code>// Add support for responsive embedded content.\nadd_theme_support( 'responsive-embeds' );\n</code></pre>\n\n<p>or your theme setup file if there is one. </p>\n"
},
{
"answer_id": 333056,
"author": "Reberg",
"author_id": 164151,
"author_profile": "https://wordpress.stackexchange.com/users/164151",
"pm_score": 2,
"selected": false,
"text": "<p>If you don't already have it, add <a href=\"https://developer.wordpress.org/reference/functions/body_class/\" rel=\"nofollow noreferrer\">body_class();</a> to the themes body tag</p>\n\n<pre><code><body <?php body_class(); ?>>\n</code></pre>\n"
}
] | 2019/03/23 | [
"https://wordpress.stackexchange.com/questions/332457",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/163720/"
] | I have a custom bootstrap 4 theme I am building out in wordpress. The drop down mobile menu does not work when the hamburger menu is pressed at smaller viewports. I am not sure if I need to add a something to the function.php file for mobile menu, or some other php/wp code for the collapsible nav?
The mobile menu will work when I uncomment the "collapse navbar-collapse" section, but then two menus appear. This tells me all the scripts and css are working. However, I not sure what I am missing I can't seem to figure out what I am missing. I am not using the navwalker script. I would greatly appreciate anyone's help!
HTML Code
```
<header>
<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
<img class="ml-2 NVAlogo" src="<?php bloginfo('stylesheet_directory'); ?>/img/NVAlogo.png" alt="logo"><a class="navbar-brand" href="front.html">Nuvision Alliance</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<?php
wp_nav_menu( array(
'menu' => 'primary',
'container' => 'nav',
'container_class' => 'navbar-collapse collapse',
'menu_class' => 'nav navbar-nav navbar-right'
));
?>
<div class="collapse navbar-collapse" id="navbarCollapse">
<ul class="navbar-nav mr-auto">
<!-- <li class="nav-item">
<a class="nav-link" href="mission.html">Mission</a>
</li>
<li class="nav-item">
<a class="nav-link" href="causes.html">Causes</a>
</li>
<li class="nav-item">
<a class="nav-link" href="index.html">Blog</a>
</li>
<li class="nav-item">
<a class="nav-link" href="contact.html">Contact</a>
</li>
</ul>-->
</div>
</nav>
</header>
``` | It may be that your theme hasn't declared support for responsive embeds. Try adding this code to your functions.php
```
// Add support for responsive embedded content.
add_theme_support( 'responsive-embeds' );
```
or your theme setup file if there is one. |
332,518 | <p>Using the call back hook, I can get the subscription information of everything EXCEPT the expiration date. Any thoughts on how to grab this. This is what I have:</p>
<pre><code>function mmd_woointerface_ProcessOrder($order_id)
{
$order = new WC_Order( $order_id );
$OrderNumber = $order->parent_id;
$ParentOrder = new WC_Order( $OrderNumber );
$TransactionId = $ParentOrder->get_transaction_id();
$DatePaid = $order->date_created;
$SubscriptionNumber = $order->get_order_number();
$PaymentDate = $order->get_date_created()->format ('Y-m-d');
$ProductId = $product->get_product_id();
$subscriptions = wcs_get_users_subscriptions( $UserId );
foreach ($subscriptions as $sub)
{
if($sub->ID == $SubscriptionNumber)
$ExpireDate = $sub->get_expiration_date( 'next_payment' ); <<NOT ACCURATE
$ExpireDate = WC_Subscriptions_Order::get_next_payment_date ( $ParentOrder, $ProductId ); << SAME PROBLEM
}
}
</code></pre>
<p>These calls:</p>
<pre><code> $ExpireDate = $sub->get_expiration_date( 'next_payment' );
$ExpireDate = WC_Subscriptions_Order::get_next_payment_date ( $ParentOrder, $ProductId );
</code></pre>
<p>are not effective when you have a user who makes a manual early payment. It just returns the next payment date, verses the actual stored expiration date </p>
| [
{
"answer_id": 332525,
"author": "Antti Koskinen",
"author_id": 144392,
"author_profile": "https://wordpress.stackexchange.com/users/144392",
"pm_score": 0,
"selected": false,
"text": "<p>Based on the documentation (<a href=\"https://docs.woocommerce.com/document/subscriptions/develop/functions/product-functions/#section-17\" rel=\"nofollow noreferrer\">product</a>, <a href=\"https://docs.woocommerce.com/document/subscriptions/develop/functions/#section-3\" rel=\"nofollow noreferrer\">subscription</a>) I would assume that either</p>\n\n<pre><code>WC_Subscriptions_Product::get_expiration_date( $ProductId );\n</code></pre>\n\n<p>or</p>\n\n<pre><code>WC_Subscription::get_date( 'end' );\n</code></pre>\n\n<p>should return the expiration date.</p>\n"
},
{
"answer_id": 343401,
"author": "bw1984",
"author_id": 172275,
"author_profile": "https://wordpress.stackexchange.com/users/172275",
"pm_score": 1,
"selected": false,
"text": "<p>I had a similar problem to the one you have described. In the end i had to hook into <code>woocommerce_subscription_status_active</code> from which you can access the related <code>$subscription</code> object as a single argument. If you need any further details from the standard <code>$order</code> object also then you can access that via <code>$subscription->get_parent()</code> within your function.</p>\n\n<p>The issue seems to be that the end date value attached to a subscription only gets set really late in the order of hooks/actions, so any of the standard hooks you would usually use post-checkout may not have access to the subscription dates yet since they are still not set. </p>\n\n<p>I tried all of the following before i got it to work for me;</p>\n\n<pre><code>woocommerce_thankyou\nwoocommerce_payment_complete\nwoocommerce_checkout_order_processed\nwoocommerce_order_status_completed\nwoocommerce_subscription_payment_complete\n</code></pre>\n\n<p>and in each case the end date (and next payment date) were both empty even though i could see them in the wordpress admin later on.</p>\n"
}
] | 2019/03/25 | [
"https://wordpress.stackexchange.com/questions/332518",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/119560/"
] | Using the call back hook, I can get the subscription information of everything EXCEPT the expiration date. Any thoughts on how to grab this. This is what I have:
```
function mmd_woointerface_ProcessOrder($order_id)
{
$order = new WC_Order( $order_id );
$OrderNumber = $order->parent_id;
$ParentOrder = new WC_Order( $OrderNumber );
$TransactionId = $ParentOrder->get_transaction_id();
$DatePaid = $order->date_created;
$SubscriptionNumber = $order->get_order_number();
$PaymentDate = $order->get_date_created()->format ('Y-m-d');
$ProductId = $product->get_product_id();
$subscriptions = wcs_get_users_subscriptions( $UserId );
foreach ($subscriptions as $sub)
{
if($sub->ID == $SubscriptionNumber)
$ExpireDate = $sub->get_expiration_date( 'next_payment' ); <<NOT ACCURATE
$ExpireDate = WC_Subscriptions_Order::get_next_payment_date ( $ParentOrder, $ProductId ); << SAME PROBLEM
}
}
```
These calls:
```
$ExpireDate = $sub->get_expiration_date( 'next_payment' );
$ExpireDate = WC_Subscriptions_Order::get_next_payment_date ( $ParentOrder, $ProductId );
```
are not effective when you have a user who makes a manual early payment. It just returns the next payment date, verses the actual stored expiration date | I had a similar problem to the one you have described. In the end i had to hook into `woocommerce_subscription_status_active` from which you can access the related `$subscription` object as a single argument. If you need any further details from the standard `$order` object also then you can access that via `$subscription->get_parent()` within your function.
The issue seems to be that the end date value attached to a subscription only gets set really late in the order of hooks/actions, so any of the standard hooks you would usually use post-checkout may not have access to the subscription dates yet since they are still not set.
I tried all of the following before i got it to work for me;
```
woocommerce_thankyou
woocommerce_payment_complete
woocommerce_checkout_order_processed
woocommerce_order_status_completed
woocommerce_subscription_payment_complete
```
and in each case the end date (and next payment date) were both empty even though i could see them in the wordpress admin later on. |
332,531 | <p>I have set some css classes for the boxes in the Gutenberg editor, and I can type it in the additional css input box, it is not a problem for me, but for the client it is not convenient, because he does not know and he forget them. There is a way to have a drop-down with all the custom classes instead of a simple input field?</p>
<p>Thank you.</p>
| [
{
"answer_id": 332547,
"author": "Botond Vajna",
"author_id": 163786,
"author_profile": "https://wordpress.stackexchange.com/users/163786",
"pm_score": 0,
"selected": false,
"text": "<p>Finally, I find an alternative solution here:\n<a href=\"https://www.billerickson.net/block-styles-in-gutenberg/\" rel=\"nofollow noreferrer\">https://www.billerickson.net/block-styles-in-gutenberg/</a></p>\n"
},
{
"answer_id": 332684,
"author": "bueltge",
"author_id": 170,
"author_profile": "https://wordpress.stackexchange.com/users/170",
"pm_score": 4,
"selected": true,
"text": "<p>You should add a custom plugin. That needs a PHP main file that includes and registers a JavaScript file. The source below should result in a plugin. You will find a usable solution also in the probs below.</p>\n<h2>PHP part</h2>\n<pre><code>add_action( 'enqueue_block_editor_assets', 'my_gutenberg_scripts' );\nfunction my_gutenberg_scripts() {\n\n wp_register_script(\n 'my-editor-enhancement',\n plugins_url( 'editor.js', __FILE__ ),\n array( 'wp-blocks' ), // Necessary script handles.\n filemtime( plugins_url( 'editor.js', __FILE__ ) ),\n true\n );\n \n wp_enqueue_script( 'my-editor-enhancement' );\n}\n</code></pre>\n<h2>JavaScript part</h2>\n<p>In our example is this the code of the <code>editor.js</code>, that we enqueue above. The example add only one paragraph and two different heading types.</p>\n<pre><code>wp.domReady( () => {\n\n wp.blocks.registerBlockStyle( 'core/paragraph', {\n name: 'blue-paragraph',\n label: 'Blue Paragraph'\n } );\n\n wp.blocks.registerBlockStyle( 'core/heading', {\n name: 'default',\n label: 'Default',\n isDefault: true,\n } );\n\n wp.blocks.registerBlockStyle( 'core/heading', {\n name: 'alt',\n label: 'Alternate',\n isDefault: false,\n } );\n\n} );\n</code></pre>\n<p>If you add <code>isDefault: true</code>, then this style will be marked as active on visible blocks that don’t already have a style specified.</p>\n<h3>core blocks</h3>\n<ul>\n<li><code>core/paragraph</code></li>\n<li><code>core/image</code></li>\n<li><code>core/heading</code></li>\n<li><code>core/gallery</code></li>\n<li><code>core/list</code></li>\n<li><code>core/quote</code></li>\n<li><code>core/audio</code></li>\n<li><code>core/cover</code></li>\n<li><code>core/file</code></li>\n<li><code>core/video</code></li>\n<li><code>core/preformatted</code></li>\n<li><code>core/code</code></li>\n<li><code>core/freeform</code></li>\n<li><code>core/html</code></li>\n<li><code>core/pullquote</code></li>\n<li><code>core/table</code></li>\n<li><code>core/verse</code></li>\n<li><code>core/button</code></li>\n<li><code>core/columns</code></li>\n<li><code>core/media-text</code></li>\n<li><code>core/more</code></li>\n<li><code>core/nextpage</code></li>\n<li><code>core/separator</code></li>\n<li><code>core/spacer</code></li>\n<li><code>core/shortcode</code></li>\n<li><code>core/archives</code></li>\n<li><code>core/categories</code></li>\n<li><code>core/latest-comments</code></li>\n<li><code>core/latest-posts</code></li>\n</ul>\n<hr/>\n<h1>Removing blocks</h1>\n<h3>JavaScript part</h3>\n<pre><code> wp.domReady( () => {\n wp.blocks.unregisterBlockStyle( 'core/button', 'default' );\n wp.blocks.unregisterBlockStyle( 'core/button', 'outline' );\n wp.blocks.unregisterBlockStyle( 'core/button', 'squared' );\n} );\n</code></pre>\n<hr/>\n<h1>Probs</h1>\n<ul>\n<li>Automattic <a href=\"https://github.com/Automattic/gutenberg-block-styles\" rel=\"nofollow noreferrer\">Block Style Examples</a></li>\n<li>Bill Eriksons <a href=\"https://www.billerickson.net/block-styles-in-gutenberg/\" rel=\"nofollow noreferrer\">great post</a>.</li>\n</ul>\n"
}
] | 2019/03/25 | [
"https://wordpress.stackexchange.com/questions/332531",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/163786/"
] | I have set some css classes for the boxes in the Gutenberg editor, and I can type it in the additional css input box, it is not a problem for me, but for the client it is not convenient, because he does not know and he forget them. There is a way to have a drop-down with all the custom classes instead of a simple input field?
Thank you. | You should add a custom plugin. That needs a PHP main file that includes and registers a JavaScript file. The source below should result in a plugin. You will find a usable solution also in the probs below.
PHP part
--------
```
add_action( 'enqueue_block_editor_assets', 'my_gutenberg_scripts' );
function my_gutenberg_scripts() {
wp_register_script(
'my-editor-enhancement',
plugins_url( 'editor.js', __FILE__ ),
array( 'wp-blocks' ), // Necessary script handles.
filemtime( plugins_url( 'editor.js', __FILE__ ) ),
true
);
wp_enqueue_script( 'my-editor-enhancement' );
}
```
JavaScript part
---------------
In our example is this the code of the `editor.js`, that we enqueue above. The example add only one paragraph and two different heading types.
```
wp.domReady( () => {
wp.blocks.registerBlockStyle( 'core/paragraph', {
name: 'blue-paragraph',
label: 'Blue Paragraph'
} );
wp.blocks.registerBlockStyle( 'core/heading', {
name: 'default',
label: 'Default',
isDefault: true,
} );
wp.blocks.registerBlockStyle( 'core/heading', {
name: 'alt',
label: 'Alternate',
isDefault: false,
} );
} );
```
If you add `isDefault: true`, then this style will be marked as active on visible blocks that don’t already have a style specified.
### core blocks
* `core/paragraph`
* `core/image`
* `core/heading`
* `core/gallery`
* `core/list`
* `core/quote`
* `core/audio`
* `core/cover`
* `core/file`
* `core/video`
* `core/preformatted`
* `core/code`
* `core/freeform`
* `core/html`
* `core/pullquote`
* `core/table`
* `core/verse`
* `core/button`
* `core/columns`
* `core/media-text`
* `core/more`
* `core/nextpage`
* `core/separator`
* `core/spacer`
* `core/shortcode`
* `core/archives`
* `core/categories`
* `core/latest-comments`
* `core/latest-posts`
---
Removing blocks
===============
### JavaScript part
```
wp.domReady( () => {
wp.blocks.unregisterBlockStyle( 'core/button', 'default' );
wp.blocks.unregisterBlockStyle( 'core/button', 'outline' );
wp.blocks.unregisterBlockStyle( 'core/button', 'squared' );
} );
```
---
Probs
=====
* Automattic [Block Style Examples](https://github.com/Automattic/gutenberg-block-styles)
* Bill Eriksons [great post](https://www.billerickson.net/block-styles-in-gutenberg/). |
332,541 | <p>I want to show an <code>iframe</code> at the top of a specific Tag page, so once I have <code>is_tag('my_tag')</code>, I will add the <code>iframe</code> before the <code>title</code> of the page.</p>
<p>I've tried this code to show the iframe before the content of the page, but it didn't work:</p>
<pre class="lang-php prettyprint-override"><code>// Show the iFrame at the beginning of the page
function show_iframe($content) {
if ( is_tag('my_tag') ) {
$before = '<iframe src="https://www.example.com" sandbox="allow-scripts allow-same-origin"></iframe>';
return $before . $content;
}
return $content;
}
add_filter('the_content', 'show_iframe');
</code></pre>
<p>Is there any hook that runs before printing the title of the page? or any way to <code>echo</code> an <code>HTML</code> code before a chosen <code>div</code> in the page?</p>
| [
{
"answer_id": 332547,
"author": "Botond Vajna",
"author_id": 163786,
"author_profile": "https://wordpress.stackexchange.com/users/163786",
"pm_score": 0,
"selected": false,
"text": "<p>Finally, I find an alternative solution here:\n<a href=\"https://www.billerickson.net/block-styles-in-gutenberg/\" rel=\"nofollow noreferrer\">https://www.billerickson.net/block-styles-in-gutenberg/</a></p>\n"
},
{
"answer_id": 332684,
"author": "bueltge",
"author_id": 170,
"author_profile": "https://wordpress.stackexchange.com/users/170",
"pm_score": 4,
"selected": true,
"text": "<p>You should add a custom plugin. That needs a PHP main file that includes and registers a JavaScript file. The source below should result in a plugin. You will find a usable solution also in the probs below.</p>\n<h2>PHP part</h2>\n<pre><code>add_action( 'enqueue_block_editor_assets', 'my_gutenberg_scripts' );\nfunction my_gutenberg_scripts() {\n\n wp_register_script(\n 'my-editor-enhancement',\n plugins_url( 'editor.js', __FILE__ ),\n array( 'wp-blocks' ), // Necessary script handles.\n filemtime( plugins_url( 'editor.js', __FILE__ ) ),\n true\n );\n \n wp_enqueue_script( 'my-editor-enhancement' );\n}\n</code></pre>\n<h2>JavaScript part</h2>\n<p>In our example is this the code of the <code>editor.js</code>, that we enqueue above. The example add only one paragraph and two different heading types.</p>\n<pre><code>wp.domReady( () => {\n\n wp.blocks.registerBlockStyle( 'core/paragraph', {\n name: 'blue-paragraph',\n label: 'Blue Paragraph'\n } );\n\n wp.blocks.registerBlockStyle( 'core/heading', {\n name: 'default',\n label: 'Default',\n isDefault: true,\n } );\n\n wp.blocks.registerBlockStyle( 'core/heading', {\n name: 'alt',\n label: 'Alternate',\n isDefault: false,\n } );\n\n} );\n</code></pre>\n<p>If you add <code>isDefault: true</code>, then this style will be marked as active on visible blocks that don’t already have a style specified.</p>\n<h3>core blocks</h3>\n<ul>\n<li><code>core/paragraph</code></li>\n<li><code>core/image</code></li>\n<li><code>core/heading</code></li>\n<li><code>core/gallery</code></li>\n<li><code>core/list</code></li>\n<li><code>core/quote</code></li>\n<li><code>core/audio</code></li>\n<li><code>core/cover</code></li>\n<li><code>core/file</code></li>\n<li><code>core/video</code></li>\n<li><code>core/preformatted</code></li>\n<li><code>core/code</code></li>\n<li><code>core/freeform</code></li>\n<li><code>core/html</code></li>\n<li><code>core/pullquote</code></li>\n<li><code>core/table</code></li>\n<li><code>core/verse</code></li>\n<li><code>core/button</code></li>\n<li><code>core/columns</code></li>\n<li><code>core/media-text</code></li>\n<li><code>core/more</code></li>\n<li><code>core/nextpage</code></li>\n<li><code>core/separator</code></li>\n<li><code>core/spacer</code></li>\n<li><code>core/shortcode</code></li>\n<li><code>core/archives</code></li>\n<li><code>core/categories</code></li>\n<li><code>core/latest-comments</code></li>\n<li><code>core/latest-posts</code></li>\n</ul>\n<hr/>\n<h1>Removing blocks</h1>\n<h3>JavaScript part</h3>\n<pre><code> wp.domReady( () => {\n wp.blocks.unregisterBlockStyle( 'core/button', 'default' );\n wp.blocks.unregisterBlockStyle( 'core/button', 'outline' );\n wp.blocks.unregisterBlockStyle( 'core/button', 'squared' );\n} );\n</code></pre>\n<hr/>\n<h1>Probs</h1>\n<ul>\n<li>Automattic <a href=\"https://github.com/Automattic/gutenberg-block-styles\" rel=\"nofollow noreferrer\">Block Style Examples</a></li>\n<li>Bill Eriksons <a href=\"https://www.billerickson.net/block-styles-in-gutenberg/\" rel=\"nofollow noreferrer\">great post</a>.</li>\n</ul>\n"
}
] | 2019/03/25 | [
"https://wordpress.stackexchange.com/questions/332541",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/161580/"
] | I want to show an `iframe` at the top of a specific Tag page, so once I have `is_tag('my_tag')`, I will add the `iframe` before the `title` of the page.
I've tried this code to show the iframe before the content of the page, but it didn't work:
```php
// Show the iFrame at the beginning of the page
function show_iframe($content) {
if ( is_tag('my_tag') ) {
$before = '<iframe src="https://www.example.com" sandbox="allow-scripts allow-same-origin"></iframe>';
return $before . $content;
}
return $content;
}
add_filter('the_content', 'show_iframe');
```
Is there any hook that runs before printing the title of the page? or any way to `echo` an `HTML` code before a chosen `div` in the page? | You should add a custom plugin. That needs a PHP main file that includes and registers a JavaScript file. The source below should result in a plugin. You will find a usable solution also in the probs below.
PHP part
--------
```
add_action( 'enqueue_block_editor_assets', 'my_gutenberg_scripts' );
function my_gutenberg_scripts() {
wp_register_script(
'my-editor-enhancement',
plugins_url( 'editor.js', __FILE__ ),
array( 'wp-blocks' ), // Necessary script handles.
filemtime( plugins_url( 'editor.js', __FILE__ ) ),
true
);
wp_enqueue_script( 'my-editor-enhancement' );
}
```
JavaScript part
---------------
In our example is this the code of the `editor.js`, that we enqueue above. The example add only one paragraph and two different heading types.
```
wp.domReady( () => {
wp.blocks.registerBlockStyle( 'core/paragraph', {
name: 'blue-paragraph',
label: 'Blue Paragraph'
} );
wp.blocks.registerBlockStyle( 'core/heading', {
name: 'default',
label: 'Default',
isDefault: true,
} );
wp.blocks.registerBlockStyle( 'core/heading', {
name: 'alt',
label: 'Alternate',
isDefault: false,
} );
} );
```
If you add `isDefault: true`, then this style will be marked as active on visible blocks that don’t already have a style specified.
### core blocks
* `core/paragraph`
* `core/image`
* `core/heading`
* `core/gallery`
* `core/list`
* `core/quote`
* `core/audio`
* `core/cover`
* `core/file`
* `core/video`
* `core/preformatted`
* `core/code`
* `core/freeform`
* `core/html`
* `core/pullquote`
* `core/table`
* `core/verse`
* `core/button`
* `core/columns`
* `core/media-text`
* `core/more`
* `core/nextpage`
* `core/separator`
* `core/spacer`
* `core/shortcode`
* `core/archives`
* `core/categories`
* `core/latest-comments`
* `core/latest-posts`
---
Removing blocks
===============
### JavaScript part
```
wp.domReady( () => {
wp.blocks.unregisterBlockStyle( 'core/button', 'default' );
wp.blocks.unregisterBlockStyle( 'core/button', 'outline' );
wp.blocks.unregisterBlockStyle( 'core/button', 'squared' );
} );
```
---
Probs
=====
* Automattic [Block Style Examples](https://github.com/Automattic/gutenberg-block-styles)
* Bill Eriksons [great post](https://www.billerickson.net/block-styles-in-gutenberg/). |
332,560 | <p>I created a function which I use to send an email when a specific button is pressed. This works great, except that it always ends up in spam instead of the inbox.</p>
<p>This is the function:</p>
<pre><code>function search_notify_email() {
// Set variables
$email = $_POST['email'];
$title = $_POST['title'];
$content = $_POST['content'];
$location = $_POST['location'];
$siteurl = $_POST['siteurl'];
$networkurl = network_site_url();
$themeurl = get_stylesheet_directory_uri();
// Call Change Email to HTML function
add_filter( 'wp_mail_content_type', 'set_email_html_content_type' );
$to = $email;
$subject = "Attention: Test!";
$message = "<html>
<body>
Testing
</body>
</html>";
$headers[] = 'From: Example <[email protected]>';
if ( wp_mail($to, $subject, $message, $headers) ) {
// Success
} else {
// Error
}
die();
// Remove filter HTML content type
remove_filter( 'wp_mail_content_type', 'set_email_html_content_type' );
}
add_action('wp_ajax_nopriv_search_notify_email', 'search_notify_email');
add_action('wp_ajax_search_notify_email', 'search_notify_email');
</code></pre>
<p>I have other emails sent on my site with the same email address used and these do not end up in the spam folder.</p>
<p>Any idea why this happens?</p>
| [
{
"answer_id": 332547,
"author": "Botond Vajna",
"author_id": 163786,
"author_profile": "https://wordpress.stackexchange.com/users/163786",
"pm_score": 0,
"selected": false,
"text": "<p>Finally, I find an alternative solution here:\n<a href=\"https://www.billerickson.net/block-styles-in-gutenberg/\" rel=\"nofollow noreferrer\">https://www.billerickson.net/block-styles-in-gutenberg/</a></p>\n"
},
{
"answer_id": 332684,
"author": "bueltge",
"author_id": 170,
"author_profile": "https://wordpress.stackexchange.com/users/170",
"pm_score": 4,
"selected": true,
"text": "<p>You should add a custom plugin. That needs a PHP main file that includes and registers a JavaScript file. The source below should result in a plugin. You will find a usable solution also in the probs below.</p>\n<h2>PHP part</h2>\n<pre><code>add_action( 'enqueue_block_editor_assets', 'my_gutenberg_scripts' );\nfunction my_gutenberg_scripts() {\n\n wp_register_script(\n 'my-editor-enhancement',\n plugins_url( 'editor.js', __FILE__ ),\n array( 'wp-blocks' ), // Necessary script handles.\n filemtime( plugins_url( 'editor.js', __FILE__ ) ),\n true\n );\n \n wp_enqueue_script( 'my-editor-enhancement' );\n}\n</code></pre>\n<h2>JavaScript part</h2>\n<p>In our example is this the code of the <code>editor.js</code>, that we enqueue above. The example add only one paragraph and two different heading types.</p>\n<pre><code>wp.domReady( () => {\n\n wp.blocks.registerBlockStyle( 'core/paragraph', {\n name: 'blue-paragraph',\n label: 'Blue Paragraph'\n } );\n\n wp.blocks.registerBlockStyle( 'core/heading', {\n name: 'default',\n label: 'Default',\n isDefault: true,\n } );\n\n wp.blocks.registerBlockStyle( 'core/heading', {\n name: 'alt',\n label: 'Alternate',\n isDefault: false,\n } );\n\n} );\n</code></pre>\n<p>If you add <code>isDefault: true</code>, then this style will be marked as active on visible blocks that don’t already have a style specified.</p>\n<h3>core blocks</h3>\n<ul>\n<li><code>core/paragraph</code></li>\n<li><code>core/image</code></li>\n<li><code>core/heading</code></li>\n<li><code>core/gallery</code></li>\n<li><code>core/list</code></li>\n<li><code>core/quote</code></li>\n<li><code>core/audio</code></li>\n<li><code>core/cover</code></li>\n<li><code>core/file</code></li>\n<li><code>core/video</code></li>\n<li><code>core/preformatted</code></li>\n<li><code>core/code</code></li>\n<li><code>core/freeform</code></li>\n<li><code>core/html</code></li>\n<li><code>core/pullquote</code></li>\n<li><code>core/table</code></li>\n<li><code>core/verse</code></li>\n<li><code>core/button</code></li>\n<li><code>core/columns</code></li>\n<li><code>core/media-text</code></li>\n<li><code>core/more</code></li>\n<li><code>core/nextpage</code></li>\n<li><code>core/separator</code></li>\n<li><code>core/spacer</code></li>\n<li><code>core/shortcode</code></li>\n<li><code>core/archives</code></li>\n<li><code>core/categories</code></li>\n<li><code>core/latest-comments</code></li>\n<li><code>core/latest-posts</code></li>\n</ul>\n<hr/>\n<h1>Removing blocks</h1>\n<h3>JavaScript part</h3>\n<pre><code> wp.domReady( () => {\n wp.blocks.unregisterBlockStyle( 'core/button', 'default' );\n wp.blocks.unregisterBlockStyle( 'core/button', 'outline' );\n wp.blocks.unregisterBlockStyle( 'core/button', 'squared' );\n} );\n</code></pre>\n<hr/>\n<h1>Probs</h1>\n<ul>\n<li>Automattic <a href=\"https://github.com/Automattic/gutenberg-block-styles\" rel=\"nofollow noreferrer\">Block Style Examples</a></li>\n<li>Bill Eriksons <a href=\"https://www.billerickson.net/block-styles-in-gutenberg/\" rel=\"nofollow noreferrer\">great post</a>.</li>\n</ul>\n"
}
] | 2019/03/25 | [
"https://wordpress.stackexchange.com/questions/332560",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/138051/"
] | I created a function which I use to send an email when a specific button is pressed. This works great, except that it always ends up in spam instead of the inbox.
This is the function:
```
function search_notify_email() {
// Set variables
$email = $_POST['email'];
$title = $_POST['title'];
$content = $_POST['content'];
$location = $_POST['location'];
$siteurl = $_POST['siteurl'];
$networkurl = network_site_url();
$themeurl = get_stylesheet_directory_uri();
// Call Change Email to HTML function
add_filter( 'wp_mail_content_type', 'set_email_html_content_type' );
$to = $email;
$subject = "Attention: Test!";
$message = "<html>
<body>
Testing
</body>
</html>";
$headers[] = 'From: Example <[email protected]>';
if ( wp_mail($to, $subject, $message, $headers) ) {
// Success
} else {
// Error
}
die();
// Remove filter HTML content type
remove_filter( 'wp_mail_content_type', 'set_email_html_content_type' );
}
add_action('wp_ajax_nopriv_search_notify_email', 'search_notify_email');
add_action('wp_ajax_search_notify_email', 'search_notify_email');
```
I have other emails sent on my site with the same email address used and these do not end up in the spam folder.
Any idea why this happens? | You should add a custom plugin. That needs a PHP main file that includes and registers a JavaScript file. The source below should result in a plugin. You will find a usable solution also in the probs below.
PHP part
--------
```
add_action( 'enqueue_block_editor_assets', 'my_gutenberg_scripts' );
function my_gutenberg_scripts() {
wp_register_script(
'my-editor-enhancement',
plugins_url( 'editor.js', __FILE__ ),
array( 'wp-blocks' ), // Necessary script handles.
filemtime( plugins_url( 'editor.js', __FILE__ ) ),
true
);
wp_enqueue_script( 'my-editor-enhancement' );
}
```
JavaScript part
---------------
In our example is this the code of the `editor.js`, that we enqueue above. The example add only one paragraph and two different heading types.
```
wp.domReady( () => {
wp.blocks.registerBlockStyle( 'core/paragraph', {
name: 'blue-paragraph',
label: 'Blue Paragraph'
} );
wp.blocks.registerBlockStyle( 'core/heading', {
name: 'default',
label: 'Default',
isDefault: true,
} );
wp.blocks.registerBlockStyle( 'core/heading', {
name: 'alt',
label: 'Alternate',
isDefault: false,
} );
} );
```
If you add `isDefault: true`, then this style will be marked as active on visible blocks that don’t already have a style specified.
### core blocks
* `core/paragraph`
* `core/image`
* `core/heading`
* `core/gallery`
* `core/list`
* `core/quote`
* `core/audio`
* `core/cover`
* `core/file`
* `core/video`
* `core/preformatted`
* `core/code`
* `core/freeform`
* `core/html`
* `core/pullquote`
* `core/table`
* `core/verse`
* `core/button`
* `core/columns`
* `core/media-text`
* `core/more`
* `core/nextpage`
* `core/separator`
* `core/spacer`
* `core/shortcode`
* `core/archives`
* `core/categories`
* `core/latest-comments`
* `core/latest-posts`
---
Removing blocks
===============
### JavaScript part
```
wp.domReady( () => {
wp.blocks.unregisterBlockStyle( 'core/button', 'default' );
wp.blocks.unregisterBlockStyle( 'core/button', 'outline' );
wp.blocks.unregisterBlockStyle( 'core/button', 'squared' );
} );
```
---
Probs
=====
* Automattic [Block Style Examples](https://github.com/Automattic/gutenberg-block-styles)
* Bill Eriksons [great post](https://www.billerickson.net/block-styles-in-gutenberg/). |
332,585 | <p>I want to redirect all 404 error pages on my WordPress site to the homepage, or to a specific page.<br>
Any advice?</p>
| [
{
"answer_id": 332595,
"author": "SherylHohman",
"author_id": 109770,
"author_profile": "https://wordpress.stackexchange.com/users/109770",
"pm_score": 2,
"selected": false,
"text": "<p>It's probably a better idea to design your 404 page to include relevant information from your homepage and/or include a link to your homepage. </p>\n\n<p>Simply redirecting all 404's to the home page can be confusing to users, and hurt your SEO / search engine ranking. It is suggested that you provide feedback to your users why a page they expected to see was not loaded. 404 error codes can serve a useful purpose. </p>\n\n<p>If you do insist on doing blanket redirections, you should, at a minimum, track these redirects, so that you can fix errors. </p>\n\n<p>This plugin that can do both <strong><a href=\"https://wordpress.org/plugins/redirection/\" rel=\"nofollow noreferrer\">Redirection</a></strong>, and more. </p>\n\n<p>A great feature of this plugin, is that if you change the URL of a page within your site, you can specify a \"permanent\" redirect to the new proper home of your page.</p>\n\n<p>If you monitor the 404's on your website, you can also identify mistakes, such as a typo in your html, that may be producing an unintended 404. You can then both fix the typo, and add a specific redirect to forward any requests for that mistyped link, to redirect to the correct url. Then visitors, whether using <em>either</em> link will arrive on the intended page. </p>\n\n<p>You can also use the log to identify spelling mistakes that originate from typos on other sites linking to yours. Again, you can add a specific redirect that intercepts the typo and forwards them to the proper page. You could even try emailing them to inform them of their typo. They may or may not fix it, but either way, you are able to automatically direct users to the correct website.</p>\n\n<p>Note, when you view the list of 404's logged by this (or any) plugin, you will see a ton of bad requests that are \"bots\" trying to find vulnerabilities in your website. These requests can either be ignored, redirected to a specific page (such as localhost, or your home page), or you can set a rule to kick them off your system after a certain number of bad requests.<br>\nFor the most part, you will want to focus on 404's that are obviously the result of typos, or urls that once existed, but have either changed, or been removed altogether.</p>\n\n<p>In the case of pages that have been deleted, then permanently redirecting those links to the home page may be the proper answer. </p>\n"
},
{
"answer_id": 351163,
"author": "Mayank Dudakiya",
"author_id": 171507,
"author_profile": "https://wordpress.stackexchange.com/users/171507",
"pm_score": 4,
"selected": true,
"text": "<blockquote>\n <p><strong><em>Note: I have read somewhere that redirecting all 404 to Homepage is</em></strong>\n <strong><em>not a good approach for SEO purposes</em></strong></p>\n</blockquote>\n\n<hr>\n\n<p>Simplest way to redirect all 404 to homepage in wordpress.</p>\n\n<pre><code>if( !function_exists('redirect_404_to_homepage') ){\n\n add_action( 'template_redirect', 'redirect_404_to_homepage' );\n\n function redirect_404_to_homepage(){\n if(is_404()):\n wp_safe_redirect( home_url('/') );\n exit;\n endif;\n }\n}\n</code></pre>\n"
}
] | 2019/03/25 | [
"https://wordpress.stackexchange.com/questions/332585",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/146130/"
] | I want to redirect all 404 error pages on my WordPress site to the homepage, or to a specific page.
Any advice? | >
> ***Note: I have read somewhere that redirecting all 404 to Homepage is***
> ***not a good approach for SEO purposes***
>
>
>
---
Simplest way to redirect all 404 to homepage in wordpress.
```
if( !function_exists('redirect_404_to_homepage') ){
add_action( 'template_redirect', 'redirect_404_to_homepage' );
function redirect_404_to_homepage(){
if(is_404()):
wp_safe_redirect( home_url('/') );
exit;
endif;
}
}
``` |
332,626 | <p>I am trying to get a list of posts if has same zipcode values. Thanks in advance for the help.</p>
<pre><code><?php
$query = new WP_Query( array(
'post_type'=> array('service'),
'posts_per_page' => -1,
'meta_query' => array( array(
'key'=> 'zipcode',
'value'=> ','.$zip.',',
'compare'=> 'LIKE'
) )
));
?>
<?php if ( $query->have_posts() ) : ?>
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
<h3><?php the_title(); ?> </h3>
<?php endwhile; // end of the loop. ?>
<?php wp_reset_query(); ?>
<?php else: ?>
No results found.
<?php endif; ?>
</code></pre>
| [
{
"answer_id": 332634,
"author": "Praveen",
"author_id": 97802,
"author_profile": "https://wordpress.stackexchange.com/users/97802",
"pm_score": 2,
"selected": false,
"text": "<p>Following code will be proper for the meta query. </p>\n\n<pre><code> $query_args = array(\n 'post_type' => 'service',\n 'posts_per_page' => -1,\n 'meta_query' => array(\n array(\n 'value' => $zip,\n 'compare' => 'LIKE',\n 'key' => 'zipcode',\n ),\n )\n );\n $query = new WP_Query($query_args);\n <?php if ( $query->have_posts() ) :while ( $query->have_posts() ) : $query->the_post(); ?>\n <h3><?php the_title(); ?></h3>\n <?php endwhile; // end of the loop. ?>\n <?php wp_reset_query(); ?>\n <?php else: ?>\n No results found.\n <?php endif; ?>\n</code></pre>\n\n<p>Hope it helps.</p>\n"
},
{
"answer_id": 332703,
"author": "Tanmay Patel",
"author_id": 62026,
"author_profile": "https://wordpress.stackexchange.com/users/62026",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>This code may help you to get perfect results.</p>\n</blockquote>\n\n<pre><code><?php\n$query_args = array(\n 'post_type' => 'service',\n 'posts_per_page' => -1,\n 'meta_query' => array(\n array(\n 'key'=> 'zipcode',\n 'value'=> $zip,\n 'type' => 'numeric',\n 'compare'=> '=',\n ),\n )\n);\n$query = new WP_Query($query_args);\nif ( $query->have_posts() ) :\n while ( $query->have_posts() ) : $query->the_post(); ?>\n <h3><?php the_title(); ?></h3>\n <?php endwhile;\n wp_reset_query();\nelse: ?>\n <h3>No results found.</h3>\n<?php endif; ?>\n</code></pre>\n"
}
] | 2019/03/26 | [
"https://wordpress.stackexchange.com/questions/332626",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97802/"
] | I am trying to get a list of posts if has same zipcode values. Thanks in advance for the help.
```
<?php
$query = new WP_Query( array(
'post_type'=> array('service'),
'posts_per_page' => -1,
'meta_query' => array( array(
'key'=> 'zipcode',
'value'=> ','.$zip.',',
'compare'=> 'LIKE'
) )
));
?>
<?php if ( $query->have_posts() ) : ?>
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
<h3><?php the_title(); ?> </h3>
<?php endwhile; // end of the loop. ?>
<?php wp_reset_query(); ?>
<?php else: ?>
No results found.
<?php endif; ?>
``` | Following code will be proper for the meta query.
```
$query_args = array(
'post_type' => 'service',
'posts_per_page' => -1,
'meta_query' => array(
array(
'value' => $zip,
'compare' => 'LIKE',
'key' => 'zipcode',
),
)
);
$query = new WP_Query($query_args);
<?php if ( $query->have_posts() ) :while ( $query->have_posts() ) : $query->the_post(); ?>
<h3><?php the_title(); ?></h3>
<?php endwhile; // end of the loop. ?>
<?php wp_reset_query(); ?>
<?php else: ?>
No results found.
<?php endif; ?>
```
Hope it helps. |
332,646 | <p>I am developing a plugin and I want to show my custom post type (<code>projects</code>) next to the standard post type <code>posts</code>. I know I can do this by adding some code to the themes functions.php. But is it possible to achieve this within my plugin? The plugin should be usable from the start without requiring the user to do some extra steps.</p>
| [
{
"answer_id": 332649,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 0,
"selected": false,
"text": "<p>The only way to do this (show CPTs every time Posts are shown) reliably across themes would be to register a new template with your plugin, and have that take over the homepage completely. This would affect styling and functionality pretty dramatically - you could certainly include the normal header and footer, but then anything in between would just be your custom code and wouldn't match the rest of the theme. It would be similar to what WooCommerce does - they create their own templates. If the end user is PHP savvy they can copy that template into the theme and customize, but most users who just want a plugin to add a custom query aren't necessarily PHP savvy.</p>\n\n<p>Themes are built in such diverse ways - from the PHP code itself to the CSS that can be dependent on a certain number of items - so unless you completely take over a template, you wouldn't have any guarantee of always safely adding the CPT query wherever posts are displayed. However, you could also set up your plugin to have an options page that covers the standard templates, and for example, have options for homepage, single, categories, archives, Pages, etc., and then in your plugin, only add the custom CPT query when it is that type of query and the option is on. So for example, for your homepage question, set up the condition as <code>if(is_home && get_option('home_cpt') == 1)</code>, and so on.</p>\n"
},
{
"answer_id": 332658,
"author": "mrben522",
"author_id": 84703,
"author_profile": "https://wordpress.stackexchange.com/users/84703",
"pm_score": 2,
"selected": false,
"text": "<p>Something like this should achieve your goal. You may need to remove the <code>is_main_query()</code> check depending on where you want this to show up though.</p>\n\n<pre><code>add_filter('pre_get_posts', 'projects_are_posts');\nfunction projects_are_posts($query) {\n if (is_admin() || !is_main_query() ) {\n return $query;\n }\n $types = $query->get('post_type');\n if (!is_array($types)) {\n $types = array($types);\n }\n if (in_array('post', $types) && !in_array('projects', $types)) {\n array_push($types, 'projects');\n $query->set('post_type', $types);\n\n }\n}\n</code></pre>\n"
}
] | 2019/03/26 | [
"https://wordpress.stackexchange.com/questions/332646",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/158872/"
] | I am developing a plugin and I want to show my custom post type (`projects`) next to the standard post type `posts`. I know I can do this by adding some code to the themes functions.php. But is it possible to achieve this within my plugin? The plugin should be usable from the start without requiring the user to do some extra steps. | Something like this should achieve your goal. You may need to remove the `is_main_query()` check depending on where you want this to show up though.
```
add_filter('pre_get_posts', 'projects_are_posts');
function projects_are_posts($query) {
if (is_admin() || !is_main_query() ) {
return $query;
}
$types = $query->get('post_type');
if (!is_array($types)) {
$types = array($types);
}
if (in_array('post', $types) && !in_array('projects', $types)) {
array_push($types, 'projects');
$query->set('post_type', $types);
}
}
``` |
332,656 | <p>I'm making a plugin for a website, which methods I'd like to use in a few different places, such as page templates, shortcodes etc.</p>
<p>I don't want to make the plugin class global or create more than one instance (I'm creating one instance of it on plugin activation).</p>
<p>What's the best approach to do it? Should I make shortcodes that use those functions? Or is there a better way?</p>
| [
{
"answer_id": 332649,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 0,
"selected": false,
"text": "<p>The only way to do this (show CPTs every time Posts are shown) reliably across themes would be to register a new template with your plugin, and have that take over the homepage completely. This would affect styling and functionality pretty dramatically - you could certainly include the normal header and footer, but then anything in between would just be your custom code and wouldn't match the rest of the theme. It would be similar to what WooCommerce does - they create their own templates. If the end user is PHP savvy they can copy that template into the theme and customize, but most users who just want a plugin to add a custom query aren't necessarily PHP savvy.</p>\n\n<p>Themes are built in such diverse ways - from the PHP code itself to the CSS that can be dependent on a certain number of items - so unless you completely take over a template, you wouldn't have any guarantee of always safely adding the CPT query wherever posts are displayed. However, you could also set up your plugin to have an options page that covers the standard templates, and for example, have options for homepage, single, categories, archives, Pages, etc., and then in your plugin, only add the custom CPT query when it is that type of query and the option is on. So for example, for your homepage question, set up the condition as <code>if(is_home && get_option('home_cpt') == 1)</code>, and so on.</p>\n"
},
{
"answer_id": 332658,
"author": "mrben522",
"author_id": 84703,
"author_profile": "https://wordpress.stackexchange.com/users/84703",
"pm_score": 2,
"selected": false,
"text": "<p>Something like this should achieve your goal. You may need to remove the <code>is_main_query()</code> check depending on where you want this to show up though.</p>\n\n<pre><code>add_filter('pre_get_posts', 'projects_are_posts');\nfunction projects_are_posts($query) {\n if (is_admin() || !is_main_query() ) {\n return $query;\n }\n $types = $query->get('post_type');\n if (!is_array($types)) {\n $types = array($types);\n }\n if (in_array('post', $types) && !in_array('projects', $types)) {\n array_push($types, 'projects');\n $query->set('post_type', $types);\n\n }\n}\n</code></pre>\n"
}
] | 2019/03/26 | [
"https://wordpress.stackexchange.com/questions/332656",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75841/"
] | I'm making a plugin for a website, which methods I'd like to use in a few different places, such as page templates, shortcodes etc.
I don't want to make the plugin class global or create more than one instance (I'm creating one instance of it on plugin activation).
What's the best approach to do it? Should I make shortcodes that use those functions? Or is there a better way? | Something like this should achieve your goal. You may need to remove the `is_main_query()` check depending on where you want this to show up though.
```
add_filter('pre_get_posts', 'projects_are_posts');
function projects_are_posts($query) {
if (is_admin() || !is_main_query() ) {
return $query;
}
$types = $query->get('post_type');
if (!is_array($types)) {
$types = array($types);
}
if (in_array('post', $types) && !in_array('projects', $types)) {
array_push($types, 'projects');
$query->set('post_type', $types);
}
}
``` |
332,661 | <p>I've this DOM here:</p>
<pre><code><ul class="sub-menu">
<li id="menu-item-1424" class="menu-item menu-item-type-taxonomy menu-item-object-product_cat">
<a href="#">Item</a>
</li>
</ul>
</code></pre>
<p>What I need to do is, to add a custom class (<code>has-ripple</code>) to only the <code>sub-menu > a</code> items:</p>
<pre><code><ul class="sub-menu">
<li id="menu-item-1424" class="menu-item menu-item-type-taxonomy menu-item-object-product_cat">
<a href="#" class="has-ripple">Item</a>
</li>
</ul>
</code></pre>
<p>This is what I've tried:</p>
<pre><code>add_filter( 'nav_menu_link_attributes', 'nav_menu_link_class', 10, 3 );
function nav_menu_link_class( $atts, $item, $args ) {
$class = 'has-ripple';
$atts['class'] = $class;
return $atts;
}
</code></pre>
<p>This works but it also add the class to non-submenu a items outside of the dropdown. So how can I do this right?</p>
| [
{
"answer_id": 332649,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 0,
"selected": false,
"text": "<p>The only way to do this (show CPTs every time Posts are shown) reliably across themes would be to register a new template with your plugin, and have that take over the homepage completely. This would affect styling and functionality pretty dramatically - you could certainly include the normal header and footer, but then anything in between would just be your custom code and wouldn't match the rest of the theme. It would be similar to what WooCommerce does - they create their own templates. If the end user is PHP savvy they can copy that template into the theme and customize, but most users who just want a plugin to add a custom query aren't necessarily PHP savvy.</p>\n\n<p>Themes are built in such diverse ways - from the PHP code itself to the CSS that can be dependent on a certain number of items - so unless you completely take over a template, you wouldn't have any guarantee of always safely adding the CPT query wherever posts are displayed. However, you could also set up your plugin to have an options page that covers the standard templates, and for example, have options for homepage, single, categories, archives, Pages, etc., and then in your plugin, only add the custom CPT query when it is that type of query and the option is on. So for example, for your homepage question, set up the condition as <code>if(is_home && get_option('home_cpt') == 1)</code>, and so on.</p>\n"
},
{
"answer_id": 332658,
"author": "mrben522",
"author_id": 84703,
"author_profile": "https://wordpress.stackexchange.com/users/84703",
"pm_score": 2,
"selected": false,
"text": "<p>Something like this should achieve your goal. You may need to remove the <code>is_main_query()</code> check depending on where you want this to show up though.</p>\n\n<pre><code>add_filter('pre_get_posts', 'projects_are_posts');\nfunction projects_are_posts($query) {\n if (is_admin() || !is_main_query() ) {\n return $query;\n }\n $types = $query->get('post_type');\n if (!is_array($types)) {\n $types = array($types);\n }\n if (in_array('post', $types) && !in_array('projects', $types)) {\n array_push($types, 'projects');\n $query->set('post_type', $types);\n\n }\n}\n</code></pre>\n"
}
] | 2019/03/26 | [
"https://wordpress.stackexchange.com/questions/332661",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/151233/"
] | I've this DOM here:
```
<ul class="sub-menu">
<li id="menu-item-1424" class="menu-item menu-item-type-taxonomy menu-item-object-product_cat">
<a href="#">Item</a>
</li>
</ul>
```
What I need to do is, to add a custom class (`has-ripple`) to only the `sub-menu > a` items:
```
<ul class="sub-menu">
<li id="menu-item-1424" class="menu-item menu-item-type-taxonomy menu-item-object-product_cat">
<a href="#" class="has-ripple">Item</a>
</li>
</ul>
```
This is what I've tried:
```
add_filter( 'nav_menu_link_attributes', 'nav_menu_link_class', 10, 3 );
function nav_menu_link_class( $atts, $item, $args ) {
$class = 'has-ripple';
$atts['class'] = $class;
return $atts;
}
```
This works but it also add the class to non-submenu a items outside of the dropdown. So how can I do this right? | Something like this should achieve your goal. You may need to remove the `is_main_query()` check depending on where you want this to show up though.
```
add_filter('pre_get_posts', 'projects_are_posts');
function projects_are_posts($query) {
if (is_admin() || !is_main_query() ) {
return $query;
}
$types = $query->get('post_type');
if (!is_array($types)) {
$types = array($types);
}
if (in_array('post', $types) && !in_array('projects', $types)) {
array_push($types, 'projects');
$query->set('post_type', $types);
}
}
``` |
332,712 | <p>we have wordpress main site on domain.com
now we did copy of the site and put in the sub-folder domain.com/blog
we did all necessary url changes.
but it seems we have issues with .htaccess file.. the domain.com/blog is redirected to domain.com</p>
<p>this is what .htaccess in root </p>
<pre><code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code></pre>
<p>this is what .htaccess in /blog folder</p>
<pre><code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /blog/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /blog/index.php [L]
</IfModule>
# END WordPress
</code></pre>
<p>whats wrong with them?
thanks a lot</p>
| [
{
"answer_id": 332728,
"author": "leymannx",
"author_id": 30597,
"author_profile": "https://wordpress.stackexchange.com/users/30597",
"pm_score": 1,
"selected": false,
"text": "<p>Your <code>.htaccess</code> looks just fine, but you need to tell WordPress itself that it got moved. Simply put the following line into your <code>wp-config.php</code>, then access your site's login page under the new URL and login. After that you can remove this line.:</p>\n\n<pre><code>define('RELOCATE', TRUE);\n</code></pre>\n\n<hr>\n\n<p>Alternatively add the following two lines to your <code>wp-config.php</code>, then navigate through the site a few pages far, then you can remove these lines. </p>\n\n<pre><code>define('WP_HOME', 'http://domain.com/blog');\ndefine('WP_SITEURL', 'http://domain.com/blog');\n</code></pre>\n\n<hr>\n\n<p>Source: <a href=\"https://codex.wordpress.org/Changing_The_Site_URL\" rel=\"nofollow noreferrer\">Changing The Site URL</a>.</p>\n"
},
{
"answer_id": 332737,
"author": "user2740846",
"author_id": 75300,
"author_profile": "https://wordpress.stackexchange.com/users/75300",
"pm_score": -1,
"selected": false,
"text": "<p>You need to Re-Check following two:</p>\n<ol>\n<li><p>SITEURL and Home in database table wp_options</p>\n</li>\n<li><p>settings in wp-config.php</p>\n<p>To learn more about check WordPress <a href=\"https://codex.wordpress.org/Giving_WordPress_Its_Own_Directory\" rel=\"nofollow noreferrer\">documentation</a></p>\n</li>\n</ol>\n"
}
] | 2019/03/27 | [
"https://wordpress.stackexchange.com/questions/332712",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] | we have wordpress main site on domain.com
now we did copy of the site and put in the sub-folder domain.com/blog
we did all necessary url changes.
but it seems we have issues with .htaccess file.. the domain.com/blog is redirected to domain.com
this is what .htaccess in root
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
```
this is what .htaccess in /blog folder
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /blog/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /blog/index.php [L]
</IfModule>
# END WordPress
```
whats wrong with them?
thanks a lot | Your `.htaccess` looks just fine, but you need to tell WordPress itself that it got moved. Simply put the following line into your `wp-config.php`, then access your site's login page under the new URL and login. After that you can remove this line.:
```
define('RELOCATE', TRUE);
```
---
Alternatively add the following two lines to your `wp-config.php`, then navigate through the site a few pages far, then you can remove these lines.
```
define('WP_HOME', 'http://domain.com/blog');
define('WP_SITEURL', 'http://domain.com/blog');
```
---
Source: [Changing The Site URL](https://codex.wordpress.org/Changing_The_Site_URL). |
332,740 | <p>The built in function <code>the_content</code> runs through several filters, but does not escape output. It would be difficult for it to do so, as HTML and even some scripts must be allowed through.</p>
<p>When outputting, the_content seems to run through these filters (as of 5.0):</p>
<pre><code>add_filter( 'the_content', 'do_blocks', 9 );
add_filter( 'the_content', 'wptexturize' );
add_filter( 'the_content', 'convert_smilies', 20 );
add_filter( 'the_content', 'wpautop' );
add_filter( 'the_content', 'shortcode_unautop' );
add_filter( 'the_content', 'prepend_attachment' );
add_filter( 'the_content', 'wp_make_content_images_responsive' );
(and)
add_filter( 'the_content', 'capital_P_dangit' );
add_filter( 'the_content', 'do_shortcode' );
</code></pre>
<p>It also does a simple string replace:</p>
<p><code>$content = str_replace( ']]>', ']]&gt;', $content );</code></p>
<p>And then get_the_content does a tiny bit of processing related to the "more" link and a bug with foreign languages.</p>
<p>None of those prevent XSS script injection, right?</p>
<p>When saving, the data <strong>is</strong> sanitized through wp_kses_post. But as this is an expensive process, I understand why it's not used on output.</p>
<p>The rule of thumb for WordPress escaping is that everything needs to be escaped, regardless of input sanitation, and as lately as possible. I've read several articles saying this, because the database is not to be considered a trusted source.</p>
<p>But for the reasons above, the_content doesn't follow that. Nor do the core themes (i.e. TwentyNineteen) add additional escaping on output.</p>
<p>So...why is it helping anything to escape elsewhere? If I were a hacker with access to the database, wouldn't I just add my code to a post's content?</p>
| [
{
"answer_id": 332741,
"author": "butlerblog",
"author_id": 38603,
"author_profile": "https://wordpress.stackexchange.com/users/38603",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>If I were a hacker with access to the database, wouldn't I just add my code to a post's content?</p>\n</blockquote>\n\n<p>I think your question answers itself. If you were a hacker with access to the db, then you've already gained the access you require. Escaping output doesn't change that at all.</p>\n\n<p>The reason for escaping output is evaluating untrusted data to avoid the hacker gaining that access in the first place.</p>\n"
},
{
"answer_id": 332742,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 4,
"selected": true,
"text": "<blockquote>\n <p>If I were a hacker with access to the database, wouldn't I just add my\n code to a post's content?</p>\n</blockquote>\n\n<p>If you've got access to the database, chances are that you've got enough access that escaping isn't going to stop you. Escaping is not going to help you if you've been hacked. It's not supposed to. There's other reasons to escape. The two main ones that I can think of are:</p>\n\n<p><strong>To deal with unsanitized input</strong></p>\n\n<p>WordPress post content is sanitized when it's saved, but not everything else is. Content passed via a query string in the URL isn't sanitized, for example. Neither is content in translation files, necessarily. Both those are sources of content that have nothing to do with the site being compromised. So translatable text and content pulled from the URL need to be escaped.</p>\n\n<p><strong>To prevent users accidentally breaking markup</strong></p>\n\n<p>Escaping isn't just for security. You also need it to prevent users accidentally breaking their site's markup. For example, if the user placing quotes or <code>></code> symbols in some content in your plugin would break the markup, then you should escape that output. You don't want to be over-aggressive in sanitising on input, because there's perfectly valid reasons a user might want to use those characters.</p>\n\n<hr>\n\n<blockquote>\n <p>“Escaping isn’t only about protecting from bad guys. It’s just making\n our software durable. Against random bad input, against malicious\n input, or against bad weather.”</p>\n</blockquote>\n\n<p>That's from the <a href=\"https://vip.wordpress.com/documentation/vip-go/validating-sanitizing-and-escaping/\" rel=\"noreferrer\">WordPress VIP guidelines on escaping</a>. It has a lot more to say on this matter, and you should give it a read.</p>\n"
},
{
"answer_id": 332743,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>The point of escaping is to generate valid HTML, the added security it provides is just a nice side effect.</p>\n\n<p>The filters applied on the content, generate a valid HTML from something that is a mix of HTML and some other text which have some other syntax like shortcodes. The fact that some of the content is already valid HTML prevents applying escaping on all of it.</p>\n\n<p>As for <code>kses</code> related functions, you can not apply them mainly because you do not have enough context to know which one to use. For example, there might be some process which uses the <code>the_content</code> filter to add JS to the post content therefor core can not guess based on things like the post author if the JS is legit or not.</p>\n\n<blockquote>\n <p>So...why is it helping anything to escape elsewhere? If I were a hacker with access to the database, wouldn't I just add my code to a post's content?</p>\n</blockquote>\n\n<p>Again, escaping is for generating valid HTML. From a security POV it is not that escaping provides security but that a code which lucks escaping should be suspicious as it might be easier to exploit.\nFor example, the way core uses <code>_e</code> and '__` for translations means that anyone that can convince you to install a non-official translation might be able to add hard to detect JS in the translation file and hack your site.\nThis is a good example of \"do what I say and not what I do\".</p>\n"
},
{
"answer_id": 332756,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": false,
"text": "<p>I'm actually an engineer at VIP who does a lot of code review :) I flag a lot of missing escaping.</p>\n\n<blockquote>\n <p>but does not escape output</p>\n</blockquote>\n\n<p>Not quite, it doesn't escape on output, which is surprising to most people. This is because if you're a super admin you have the <code>unfiltered_html</code> capability, so it can't escape on output. Instead it runs it through <code>wp_kses_post</code> on input. Ideally you would remove that capability though.</p>\n\n<p>Here is the implementation at the current time:</p>\n\n<pre><code>function the_content( $more_link_text = null, $strip_teaser = false ) {\n $content = get_the_content( $more_link_text, $strip_teaser );\n\n /**\n * Filters the post content.\n *\n * @since 0.71\n *\n * @param string $content Content of the current post.\n */\n $content = apply_filters( 'the_content', $content );\n $content = str_replace( ']]>', ']]&gt;', $content );\n echo $content;\n}\n</code></pre>\n\n<p>The ideal mechanism for escaping anything that goes through <code>the_content</code> filter on the other hand is:</p>\n\n<pre><code>echo apply_filters( 'the_content', wp_kses_post( $content ) );\n</code></pre>\n\n<p>This way we make the content safe, then run it through the filter, avoiding the embeds etc being stripped out.</p>\n\n<h3>So Why Escape</h3>\n\n<blockquote>\n <p>The point of escaping is to generate valid HTML, the added security it provides is just a nice side effect.</p>\n \n <p>To prevent users accidentally breaking markup</p>\n</blockquote>\n\n<p>There are many reasons to escape, but fundamentally, you're enforcing expectations. Take the following code:</p>\n\n<pre><code><a href=\"<?=$url?>\">\n</code></pre>\n\n<p>We expect <code>$url</code> to contain a URL suitable for a <code>href</code> attribute, but what if it isn't? Well why leave it to chance, lets enforce it:</p>\n\n<pre><code><a href=\"<?=esc_url( $url )?>\">\n</code></pre>\n\n<p>It is now always going to be a URL. It doesn't matter if a hacker puts an image in <code>$url</code>, or if a user types in the wrong field, or there's a malicious script. It will always be a valid URL because we said it's going to be a URL. Sure it might be a very strange URL, but it will always meet the expectation that a URL will be there. This is very handy, be it for markup validation, for security, etc</p>\n\n<p>Having said that, escaping is not validation, escaping is not sanitisation. Those are separate steps that happen at different points in the life cycle. Escaping forces things to meet expectations, even if it mangles them to do so.</p>\n\n<p>Sometimes I like to think of escaping as one of those Japanese gameshows with the giant foam wall with the cut out. Contestants have to fit in the dog shape or they get discarded, only for our purposes there are lasers and knives around the hole. Whatever is left at the end will be dog shaped, and it will be unforgiving and strict if you're not already dog shaped.</p>\n\n<p>Remember:</p>\n\n<ul>\n<li>sanitise early</li>\n<li>validate early</li>\n<li>escape late</li>\n<li>escape often</li>\n</ul>\n\n<p>Security is a multiple step, multiple layer onion of defences, escaping is one of the outer layers of defence on output. It can mangle attack code on a compromised site rendering it useless, thwart open exploits, and make sure your client doesn't break a site by putting tags in a field they shouldn't. It's not a substitute for the other things, and it's by far and away the most underused security tool in a developers handbook.</p>\n\n<p>As for why to escape if <code>the_content</code> doesn't? If you have a flood coming, and 5 holes in a wall, but only time to fix 3, do you shrug and fix none? Or do you mitigate the risk and reduce the attack area?</p>\n\n<p>Perhaps I can help fix those final 2 holes with this snippet:</p>\n\n<pre><code>add_filter( 'the_content' function( $content ) {\n return wp_kses_post( $content );\n}, PHP_INT_MAX + 1 );\n</code></pre>\n\n<p>Here we set the priority to the highest possible number in PHP, then add 1 so it overflows to the lowest possible number that can be represented. This way all calls to <code>the_content</code> will escape the value prior to any other filters. This way embeds etc still work, but users can't sneak in dangerous HTML via the database. Additionally, look into removing the <code>unfiltered_html</code> capability from all roles</p>\n"
}
] | 2019/03/27 | [
"https://wordpress.stackexchange.com/questions/332740",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/28273/"
] | The built in function `the_content` runs through several filters, but does not escape output. It would be difficult for it to do so, as HTML and even some scripts must be allowed through.
When outputting, the\_content seems to run through these filters (as of 5.0):
```
add_filter( 'the_content', 'do_blocks', 9 );
add_filter( 'the_content', 'wptexturize' );
add_filter( 'the_content', 'convert_smilies', 20 );
add_filter( 'the_content', 'wpautop' );
add_filter( 'the_content', 'shortcode_unautop' );
add_filter( 'the_content', 'prepend_attachment' );
add_filter( 'the_content', 'wp_make_content_images_responsive' );
(and)
add_filter( 'the_content', 'capital_P_dangit' );
add_filter( 'the_content', 'do_shortcode' );
```
It also does a simple string replace:
`$content = str_replace( ']]>', ']]>', $content );`
And then get\_the\_content does a tiny bit of processing related to the "more" link and a bug with foreign languages.
None of those prevent XSS script injection, right?
When saving, the data **is** sanitized through wp\_kses\_post. But as this is an expensive process, I understand why it's not used on output.
The rule of thumb for WordPress escaping is that everything needs to be escaped, regardless of input sanitation, and as lately as possible. I've read several articles saying this, because the database is not to be considered a trusted source.
But for the reasons above, the\_content doesn't follow that. Nor do the core themes (i.e. TwentyNineteen) add additional escaping on output.
So...why is it helping anything to escape elsewhere? If I were a hacker with access to the database, wouldn't I just add my code to a post's content? | >
> If I were a hacker with access to the database, wouldn't I just add my
> code to a post's content?
>
>
>
If you've got access to the database, chances are that you've got enough access that escaping isn't going to stop you. Escaping is not going to help you if you've been hacked. It's not supposed to. There's other reasons to escape. The two main ones that I can think of are:
**To deal with unsanitized input**
WordPress post content is sanitized when it's saved, but not everything else is. Content passed via a query string in the URL isn't sanitized, for example. Neither is content in translation files, necessarily. Both those are sources of content that have nothing to do with the site being compromised. So translatable text and content pulled from the URL need to be escaped.
**To prevent users accidentally breaking markup**
Escaping isn't just for security. You also need it to prevent users accidentally breaking their site's markup. For example, if the user placing quotes or `>` symbols in some content in your plugin would break the markup, then you should escape that output. You don't want to be over-aggressive in sanitising on input, because there's perfectly valid reasons a user might want to use those characters.
---
>
> “Escaping isn’t only about protecting from bad guys. It’s just making
> our software durable. Against random bad input, against malicious
> input, or against bad weather.”
>
>
>
That's from the [WordPress VIP guidelines on escaping](https://vip.wordpress.com/documentation/vip-go/validating-sanitizing-and-escaping/). It has a lot more to say on this matter, and you should give it a read. |
332,755 | <p>I'm currently trying to build a custom reset password form, which seems to work fine up until it needs to validate the key for the user:</p>
<pre><code>//Redirect away from default wordpress to reset password
function redirect_to_reset_password() {
if ( 'GET' == $_SERVER['REQUEST_METHOD'] ) {
// Verify key / login combo
$user = check_password_reset_key( $_REQUEST['key'], $_REQUEST['login'] );
if ( ! $user || is_wp_error( $user ) ) {
if ( $user && $user->get_error_code() === 'expired_key' ) {
wp_redirect( home_url( '/login?login=expiredkey/' ) );
} else {
wp_redirect( home_url( '/login?login=invalidkey/' ) );
}
exit;
}
$redirect_url = home_url( '/reset-password/' );
$redirect_url = add_query_arg( 'login', esc_attr( $_REQUEST['login'] ), $redirect_url );
$redirect_url = add_query_arg( 'key', esc_attr( $_REQUEST['key'] ), $redirect_url );
wp_redirect( $redirect_url );
exit;
}
}
add_action('login_form_rp', 'redirect_to_reset_password');
add_action('login_form_resetpass', 'redirect_to_reset_password');
//Make new password
function do_password_reset() {
if ( 'POST' == $_SERVER['REQUEST_METHOD'] ) {
$rp_key = $_REQUEST['rp_key'];
$rp_login = $_REQUEST['rp_login'];
$user = check_password_reset_key( $rp_key, $rp_login );
if ( ! $user || is_wp_error( $user ) ) {
if ( $user && $user->get_error_code() === 'expired_key' ) {
wp_redirect( home_url( '/login?login=expiredkey/' ) );
} else {
wp_redirect( home_url( '/login?login=invalidkey/' ) );
}
exit;
}
if ( isset( $_POST['pass1'] ) ) {
if ( $_POST['pass1'] != $_POST['pass2'] ) {
// Passwords don't match
$redirect_url = home_url( '/reset-password/' );
$redirect_url = add_query_arg( 'key', $rp_key, $redirect_url );
$redirect_url = add_query_arg( 'login', $rp_login, $redirect_url );
$redirect_url = add_query_arg( 'error', 'password_reset_mismatch', $redirect_url );
wp_redirect( $redirect_url );
exit;
}
if ( empty( $_POST['pass1'] ) ) {
// Password is empty
$redirect_url = home_url( '/reset-password/' );
$redirect_url = add_query_arg( 'key', $rp_key, $redirect_url );
$redirect_url = add_query_arg( 'login', $rp_login, $redirect_url );
$redirect_url = add_query_arg( 'error', 'password_reset_empty', $redirect_url );
wp_redirect( $redirect_url );
exit;
}
// Parameter checks OK, reset password
reset_password( $user, $_POST['pass1'] );
wp_redirect( home_url( '/login?password=changed/' ) );
} else {
echo "Invalid request.";
}
exit;
}
}
add_action( 'login_form_rp', 'do_password_reset' );
add_action( 'login_form_resetpass', 'do_password_reset' );
</code></pre>
<p>I've been snooping around trying to figure out what the cause of the issue can be, and I've found that the key under user_activation_key is not the same as the one I get in my URL when trying to reset my password. E.g:</p>
<p>DB: <code>1553346836:$P$BYEbftAGRfnhlBTeuNL4ylhsxRyhS3/</code></p>
<p>URL: <code>key=dx1GjoJnaD6Dytc5zpNq</code></p>
<p>I assume this is just wordpress' way of encrypting the key so it shouldn't cause this issue, but it is the only inconsistency I've been able to find.</p>
<p>EDIT: If I try and check what value $user is set to, I get an undefined index error regarding <code>$_REQUEST['rp_key']</code> and <code>$_REQUEST['rp_login']</code>. I then tried to var_dump $_REQUEST which gave me the following: <code>array(2) { ["login"]=> string(20) "[email protected]" ["key"]=> string(20) "nWrRCsRD4OvaROeMFErV" }</code>. Following this I changed $_REQUEST['rp_key'] to $_REQUEST['key'] and the same for login, but I still get the same undefined index error. But the value is in the $_REQUEST array, why can't it find it?</p>
<p>Could the fact that I'm using <code>check_password_reset_key</code> twice have an effect on the key being set to invalid?</p>
<p>EDIT2:
Running the code through a environment running https resulted in a "Bad Request" return. </p>
| [
{
"answer_id": 336305,
"author": "MikeNGarrett",
"author_id": 1670,
"author_profile": "https://wordpress.stackexchange.com/users/1670",
"pm_score": 0,
"selected": false,
"text": "<p>I think the problem here is the fact that you're using <code>$_REQUEST</code> instead of explicitly looking for <code>GET</code> or <code>POST</code> variables.</p>\n<p>I think you already solved the first issue which is that the first step of the process (where you request a reset) passes <code>key</code> and <code>login</code> via <code>$_GET</code> variables. This allows <code>redirect_to_reset_password()</code> to redirect appropriately.</p>\n<p>The next part is a bit different. The reset password form passes the following:</p>\n<pre><code>Array (\n [action] => resetpass\n [pass1] => [text]\n [pass1-text] => [text]\n [pass2] => [text]\n [rp_key] => [text]\n [wp-submit] => Reset Password\n)\n</code></pre>\n<p>Unless you're doing something to change these fields on a form from your <code>/reset-password/</code> page, <code>rp_login</code> will never be set. <a href=\"https://core.trac.wordpress.org/browser/tags/5.1.1/src/wp-login.php#L654\" rel=\"nofollow noreferrer\"><code>wp-login.php</code> shows a different process</a> to retrieving the necessary pieces to run <code>check_password_reset_key()</code></p>\n<pre><code>if ( isset( $_COOKIE[ $rp_cookie ] ) && 0 < strpos( $_COOKIE[ $rp_cookie ], ':' ) ) {\n list( $rp_login, $rp_key ) = explode( ':', wp_unslash( $_COOKIE[ $rp_cookie ] ), 2 );\n $user = check_password_reset_key( $rp_key, $rp_login );\n if ( isset( $_POST['pass1'] ) && ! hash_equals( $rp_key, $_POST['rp_key'] ) ) {\n $user = false;\n }\n}\n</code></pre>\n<p>You can see it's checking the <code>rp_cookie</code> that was set earlier in the process. From here it's retrieving the login and key then checking the cookie's key against the key passed via a <code>POST</code> variable.</p>\n<p>You will need to do something similar to make this work.</p>\n"
},
{
"answer_id": 358918,
"author": "Andrew",
"author_id": 182920,
"author_profile": "https://wordpress.stackexchange.com/users/182920",
"pm_score": 2,
"selected": false,
"text": "<p>I had the same issue with this, I assume you're working from this guide - <a href=\"https://code.tutsplus.com/tutorials/build-a-custom-wordpress-user-flow-part-3-password-reset--cms-23811\" rel=\"nofollow noreferrer\">https://code.tutsplus.com/tutorials/build-a-custom-wordpress-user-flow-part-3-password-reset--cms-23811</a></p>\n\n<p>Have a look at the actual reset password form where it shows pass1 and pass2. The hidden fields values are automatically set to <code>$attribute['key']</code> and <code>$attribute['login']</code>.</p>\n\n<p>Changing this to <code>$_REQUEST['key']</code> and <code>$_REQUEST['login']</code> should solve the issue.</p>\n\n<p>Hope this helps.</p>\n"
}
] | 2019/03/27 | [
"https://wordpress.stackexchange.com/questions/332755",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/163961/"
] | I'm currently trying to build a custom reset password form, which seems to work fine up until it needs to validate the key for the user:
```
//Redirect away from default wordpress to reset password
function redirect_to_reset_password() {
if ( 'GET' == $_SERVER['REQUEST_METHOD'] ) {
// Verify key / login combo
$user = check_password_reset_key( $_REQUEST['key'], $_REQUEST['login'] );
if ( ! $user || is_wp_error( $user ) ) {
if ( $user && $user->get_error_code() === 'expired_key' ) {
wp_redirect( home_url( '/login?login=expiredkey/' ) );
} else {
wp_redirect( home_url( '/login?login=invalidkey/' ) );
}
exit;
}
$redirect_url = home_url( '/reset-password/' );
$redirect_url = add_query_arg( 'login', esc_attr( $_REQUEST['login'] ), $redirect_url );
$redirect_url = add_query_arg( 'key', esc_attr( $_REQUEST['key'] ), $redirect_url );
wp_redirect( $redirect_url );
exit;
}
}
add_action('login_form_rp', 'redirect_to_reset_password');
add_action('login_form_resetpass', 'redirect_to_reset_password');
//Make new password
function do_password_reset() {
if ( 'POST' == $_SERVER['REQUEST_METHOD'] ) {
$rp_key = $_REQUEST['rp_key'];
$rp_login = $_REQUEST['rp_login'];
$user = check_password_reset_key( $rp_key, $rp_login );
if ( ! $user || is_wp_error( $user ) ) {
if ( $user && $user->get_error_code() === 'expired_key' ) {
wp_redirect( home_url( '/login?login=expiredkey/' ) );
} else {
wp_redirect( home_url( '/login?login=invalidkey/' ) );
}
exit;
}
if ( isset( $_POST['pass1'] ) ) {
if ( $_POST['pass1'] != $_POST['pass2'] ) {
// Passwords don't match
$redirect_url = home_url( '/reset-password/' );
$redirect_url = add_query_arg( 'key', $rp_key, $redirect_url );
$redirect_url = add_query_arg( 'login', $rp_login, $redirect_url );
$redirect_url = add_query_arg( 'error', 'password_reset_mismatch', $redirect_url );
wp_redirect( $redirect_url );
exit;
}
if ( empty( $_POST['pass1'] ) ) {
// Password is empty
$redirect_url = home_url( '/reset-password/' );
$redirect_url = add_query_arg( 'key', $rp_key, $redirect_url );
$redirect_url = add_query_arg( 'login', $rp_login, $redirect_url );
$redirect_url = add_query_arg( 'error', 'password_reset_empty', $redirect_url );
wp_redirect( $redirect_url );
exit;
}
// Parameter checks OK, reset password
reset_password( $user, $_POST['pass1'] );
wp_redirect( home_url( '/login?password=changed/' ) );
} else {
echo "Invalid request.";
}
exit;
}
}
add_action( 'login_form_rp', 'do_password_reset' );
add_action( 'login_form_resetpass', 'do_password_reset' );
```
I've been snooping around trying to figure out what the cause of the issue can be, and I've found that the key under user\_activation\_key is not the same as the one I get in my URL when trying to reset my password. E.g:
DB: `1553346836:$P$BYEbftAGRfnhlBTeuNL4ylhsxRyhS3/`
URL: `key=dx1GjoJnaD6Dytc5zpNq`
I assume this is just wordpress' way of encrypting the key so it shouldn't cause this issue, but it is the only inconsistency I've been able to find.
EDIT: If I try and check what value $user is set to, I get an undefined index error regarding `$_REQUEST['rp_key']` and `$_REQUEST['rp_login']`. I then tried to var\_dump $\_REQUEST which gave me the following: `array(2) { ["login"]=> string(20) "[email protected]" ["key"]=> string(20) "nWrRCsRD4OvaROeMFErV" }`. Following this I changed $\_REQUEST['rp\_key'] to $\_REQUEST['key'] and the same for login, but I still get the same undefined index error. But the value is in the $\_REQUEST array, why can't it find it?
Could the fact that I'm using `check_password_reset_key` twice have an effect on the key being set to invalid?
EDIT2:
Running the code through a environment running https resulted in a "Bad Request" return. | I had the same issue with this, I assume you're working from this guide - <https://code.tutsplus.com/tutorials/build-a-custom-wordpress-user-flow-part-3-password-reset--cms-23811>
Have a look at the actual reset password form where it shows pass1 and pass2. The hidden fields values are automatically set to `$attribute['key']` and `$attribute['login']`.
Changing this to `$_REQUEST['key']` and `$_REQUEST['login']` should solve the issue.
Hope this helps. |
332,762 | <p>I'm planning to create a wordpress plugin that will offload uploaded images to external website and show them from there.</p>
<p>What I did so far:</p>
<p>1) Whenever a images gets uploaded, my custom functions will trigger and will upload the image including its thumbnails to the external site and store the urls to database.</p>
<p>No problems here. But how do I tell wordpress instead of showing default image url show my url? I am just looking for the correct filter/hooks. I'm googling for past 12 hours still hasn't found a proper answer.</p>
<p>What I want is, whenever requests a image the filter will change:</p>
<pre><code>http://localhost/wordpress/wp-content/uploads/2019/03/dog-1200x1108.png
</code></pre>
<p>to</p>
<pre><code>http://example.com/BAHIAPJGJSHSH.png
</code></pre>
<p>There are 2 plugins which does this: <a href="https://wordpress.org/plugins/do-spaces-sync/" rel="noreferrer">DigitalOcean Spaces Sync</a> and <a href="https://wordpress.org/plugins/amazon-s3-and-cloudfront/" rel="noreferrer">WP Offload Media</a></p>
<p>This 2 plugin does this although I'm trying to do it in a different image hoster. I've tried looking out there source code, but could not figure out.</p>
<p>Can anyone please point me in the right direction?
How wordpress displays the image? and How to change the url via filter?</p>
| [
{
"answer_id": 336328,
"author": "ggedde",
"author_id": 166772,
"author_profile": "https://wordpress.stackexchange.com/users/166772",
"pm_score": 4,
"selected": true,
"text": "<p>You will most likely want to use filters. The main issue is that developers will need to make sure to use the correct functions like \"the_post_thumbnail()\" etc.\nYou can use wp_get_attachment_url\n<a href=\"https://codex.wordpress.org/Function_Reference/wp_get_attachment_url\" rel=\"noreferrer\">https://codex.wordpress.org/Function_Reference/wp_get_attachment_url</a></p>\n\n<p>I use this when doing local development, but want all my local images to load from the Production server as I don't have any images on my local machine.</p>\n\n<pre><code>if($_SERVER['REMOTE_ADDR'] === '127.0.0.1') \n{\n // Replace src paths\n add_filter('wp_get_attachment_url', function ($url) \n {\n if(file_exists($url)) \n {\n return $url;\n }\n return str_replace(WP_HOME, 'https://www.some-production-site.com', $url);\n });\n\n // Replace srcset paths\n add_filter('wp_calculate_image_srcset', function($sources)\n {\n foreach($sources as &$source) \n {\n if(!file_exists($source['url'])) \n {\n $source['url'] = str_replace(WP_HOME, 'https://www.some-production-site.com', $source['url']);\n }\n }\n return $sources;\n });\n}\n</code></pre>\n"
},
{
"answer_id": 398430,
"author": "Ionut Ardelean",
"author_id": 215138,
"author_profile": "https://wordpress.stackexchange.com/users/215138",
"pm_score": 0,
"selected": false,
"text": "<p>The srcset can't work that way.\nHere is a fix if ever needed.</p>\n<pre><code>add_filter('wp_calculate_image_srcset', function($sources)\n{\n $sr = array();\n foreach($sources as $source) \n { \n $source['url'] = str_replace('http://localhost', 'https://www.some-production-site.com', $source['url']); \n $sr[] = $source; \n } \n return $sr;\n});\n</code></pre>\n"
}
] | 2019/03/27 | [
"https://wordpress.stackexchange.com/questions/332762",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/116204/"
] | I'm planning to create a wordpress plugin that will offload uploaded images to external website and show them from there.
What I did so far:
1) Whenever a images gets uploaded, my custom functions will trigger and will upload the image including its thumbnails to the external site and store the urls to database.
No problems here. But how do I tell wordpress instead of showing default image url show my url? I am just looking for the correct filter/hooks. I'm googling for past 12 hours still hasn't found a proper answer.
What I want is, whenever requests a image the filter will change:
```
http://localhost/wordpress/wp-content/uploads/2019/03/dog-1200x1108.png
```
to
```
http://example.com/BAHIAPJGJSHSH.png
```
There are 2 plugins which does this: [DigitalOcean Spaces Sync](https://wordpress.org/plugins/do-spaces-sync/) and [WP Offload Media](https://wordpress.org/plugins/amazon-s3-and-cloudfront/)
This 2 plugin does this although I'm trying to do it in a different image hoster. I've tried looking out there source code, but could not figure out.
Can anyone please point me in the right direction?
How wordpress displays the image? and How to change the url via filter? | You will most likely want to use filters. The main issue is that developers will need to make sure to use the correct functions like "the\_post\_thumbnail()" etc.
You can use wp\_get\_attachment\_url
<https://codex.wordpress.org/Function_Reference/wp_get_attachment_url>
I use this when doing local development, but want all my local images to load from the Production server as I don't have any images on my local machine.
```
if($_SERVER['REMOTE_ADDR'] === '127.0.0.1')
{
// Replace src paths
add_filter('wp_get_attachment_url', function ($url)
{
if(file_exists($url))
{
return $url;
}
return str_replace(WP_HOME, 'https://www.some-production-site.com', $url);
});
// Replace srcset paths
add_filter('wp_calculate_image_srcset', function($sources)
{
foreach($sources as &$source)
{
if(!file_exists($source['url']))
{
$source['url'] = str_replace(WP_HOME, 'https://www.some-production-site.com', $source['url']);
}
}
return $sources;
});
}
``` |
332,771 | <p>I am trying to make a new ACF rule to display fields when parent page has a specific template name. Here's my current attempt:</p>
<pre><code>add_filter('acf/location/rule_types', 'acf_location_rules_types');
function acf_location_rules_types( $choices ) {
$choices['Parent']['parent_template'] = 'Parent Template';
return $choices;
}
add_filter('acf/location/rule_values/parent_template', 'acf_location_rules_values_parent_template');
function acf_location_rules_values_parent_template( $choices ) {
$templates = get_page_templates();
if ( $templates ) {
foreach ( $templates as $template_name => $template_filename ) {
$choices[ $template_name ] = $template_name;
}
}
return $choices;
}
add_filter('acf/location/rule_match/parent_template', 'acf_location_rules_match_parent_template', 10, 3);
function acf_location_rules_match_parent_template( $match, $rule, $options ) {
$selected_template = $rule['value'];
global $post;
$template = get_page_template_slug( $post->post_parent );
if( $rule['operator'] == "==" ) {
$match = ( $selected_template == $template );
} elseif($rule['operator'] == "!=") {
$match = ( $selected_template != $template );
}
return $match;
}
</code></pre>
<p>I think the problem is the way I am trying to get parent page template for current page. Can I even get parent page template inside a hook function inside function.php?</p>
| [
{
"answer_id": 332773,
"author": "DimChtz",
"author_id": 154572,
"author_profile": "https://wordpress.stackexchange.com/users/154572",
"pm_score": 1,
"selected": false,
"text": "<p>For anyone dealing with the same issue, I just needed to change:</p>\n\n<pre><code>$choices[ $template_name ] = $template_name;\n</code></pre>\n\n<p>with:</p>\n\n<pre><code>$choices[ $template_filename ] = $template_name;\n</code></pre>\n\n<p>Consider a page template <code>Homepage (page-home.php)</code>. This way the template name <code>Homepage</code> will appear on the custom fields page but <code>$rule['value']</code> will actually return <code>page-home.php</code> and then we can compare this with <code>get_page_template_slug( $post->post_parent )</code>.</p>\n"
},
{
"answer_id": 332774,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 0,
"selected": false,
"text": "<p>The problem is not in the way you're getting the parent page nor its template. You can do it exactly like you do.</p>\n\n<p>Problem lies in these two lines:</p>\n\n<pre><code>$choices[ $template_name ] = $template_name;\n...\n$match = ( $selected_template == $template );\n</code></pre>\n\n<p>So you're setting template name as choices, but you compare it with filename of the template.</p>\n\n<p>Change the first one to </p>\n\n<pre><code>$choices[ $template_filename ] = $template_name;\n</code></pre>\n\n<p>And it will work correctly.</p>\n"
}
] | 2019/03/27 | [
"https://wordpress.stackexchange.com/questions/332771",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/154572/"
] | I am trying to make a new ACF rule to display fields when parent page has a specific template name. Here's my current attempt:
```
add_filter('acf/location/rule_types', 'acf_location_rules_types');
function acf_location_rules_types( $choices ) {
$choices['Parent']['parent_template'] = 'Parent Template';
return $choices;
}
add_filter('acf/location/rule_values/parent_template', 'acf_location_rules_values_parent_template');
function acf_location_rules_values_parent_template( $choices ) {
$templates = get_page_templates();
if ( $templates ) {
foreach ( $templates as $template_name => $template_filename ) {
$choices[ $template_name ] = $template_name;
}
}
return $choices;
}
add_filter('acf/location/rule_match/parent_template', 'acf_location_rules_match_parent_template', 10, 3);
function acf_location_rules_match_parent_template( $match, $rule, $options ) {
$selected_template = $rule['value'];
global $post;
$template = get_page_template_slug( $post->post_parent );
if( $rule['operator'] == "==" ) {
$match = ( $selected_template == $template );
} elseif($rule['operator'] == "!=") {
$match = ( $selected_template != $template );
}
return $match;
}
```
I think the problem is the way I am trying to get parent page template for current page. Can I even get parent page template inside a hook function inside function.php? | For anyone dealing with the same issue, I just needed to change:
```
$choices[ $template_name ] = $template_name;
```
with:
```
$choices[ $template_filename ] = $template_name;
```
Consider a page template `Homepage (page-home.php)`. This way the template name `Homepage` will appear on the custom fields page but `$rule['value']` will actually return `page-home.php` and then we can compare this with `get_page_template_slug( $post->post_parent )`. |
332,828 | <p>I have been asked to do some work on a site where the old developer has written this function (create a variable that stores the users avatar into an img tag) into the functions.php:</p>
<pre><code>add_filter('get_avatar', 'lb_acf_profile_avatar', 10, 5);
function lb_acf_profile_avatar($avatar, $id_or_email, $size, $default, $alt) {
$user = '';
// Get user by id or email
if (is_numeric($id_or_email)) {
$id = (int) $id_or_email;
$user = get_user_by('id', $id);
} elseif (is_object($id_or_email)) {
if (!empty($id_or_email->user_id)) {
$id = (int) $id_or_email->user_id;
$user = get_user_by('id', $id);
}
} else {
$user = get_user_by('email', $id_or_email);
}
if (!$user) {
return $avatar;
}
// Get the user id
$user_id = $user->ID;
//$user_info = get_userdata($user_id)
// Get the file id
$avatar_url = $user->get('user_url'); //'https://dojo.nearsoft.com/wp-content/uploads/2017/02/Eric-Wroolie-per-template.jpg';
if ($avatar_url == '') {
return $avatar;
}
$avatar = '<img alt="' . $alt . '" src="' . $avatar_url . '" class="avatar avatar-' . $size . '" height="' . $size . '" width="' . $size . '"/>';
// Return our new avatar
return $avatar;
}
</code></pre>
<p>I know the function works as the app he built uses the code to generate the avatar for each user. I just don't know how to use it and cannot reach out to him to help me utilise it.</p>
<p>My efforts so far have failed, using code that looks a little like this:</p>
<pre><code><?php lb_acf_profile_avatar() ?>
<?php if ($avatar != '') : ?>
<div>Hellow World</div>
<?php endif; ?>
</code></pre>
<p>Where I have tried calling the function then assuming the returned variable (the avatar image) would be usable from that point. That doesn't appear to be the case.</p>
<p>The error message is 5 of these one for each argument:</p>
<pre><code>Warning: Missing argument 5 for lb_acf_profile_avatar(), called in /home/materialshub/public_html/development/wp-content/themes/bolt/header.php on line 238 and defined in /home/materialshub/public_html/development/wp-content/themes/bolt/functions.php on line 663
</code></pre>
<p><strong>Is there a way to tailor this so I get the avatar_url without the img tag returned, but I need the original code to function as it should as it is also used in the app and is functioning correctly.</strong></p>
<p>I don't have access to the app. Or the old developer. Any help you can provide is great. If you want further info just let me know.</p>
<p><strong>I think I want a new function that gets the avatar_url like the function above but without any of the img tag. A simple url is all I need.</strong></p>
<p>I need this to be dynamic as well so it works for all users automatically, generating the avatar_url. How can I pass the arguments in this manor?</p>
<p><strong>I cannot just use the inbuilt get_avatar() WordPress function before we try go down that route as the app has made use of an empty field in the database 'user_url'.</strong></p>
<p>I appreciate this is quite an annoying question, but I appreciate the kindness.</p>
<p><strong>EDIT:</strong> I have tried reverting back to the get_avatar() function and that then returns this warning:</p>
<pre><code>Warning: Missing argument 1 for get_avatar(), called in /home/materialshub/public_html/development/wp-content/themes/bolt/header.php on line 239 and defined in /home/materialshub/public_html/development/wp-includes/pluggable.php on line 2450
</code></pre>
<p>Thanks, Jason.</p>
| [
{
"answer_id": 332773,
"author": "DimChtz",
"author_id": 154572,
"author_profile": "https://wordpress.stackexchange.com/users/154572",
"pm_score": 1,
"selected": false,
"text": "<p>For anyone dealing with the same issue, I just needed to change:</p>\n\n<pre><code>$choices[ $template_name ] = $template_name;\n</code></pre>\n\n<p>with:</p>\n\n<pre><code>$choices[ $template_filename ] = $template_name;\n</code></pre>\n\n<p>Consider a page template <code>Homepage (page-home.php)</code>. This way the template name <code>Homepage</code> will appear on the custom fields page but <code>$rule['value']</code> will actually return <code>page-home.php</code> and then we can compare this with <code>get_page_template_slug( $post->post_parent )</code>.</p>\n"
},
{
"answer_id": 332774,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 0,
"selected": false,
"text": "<p>The problem is not in the way you're getting the parent page nor its template. You can do it exactly like you do.</p>\n\n<p>Problem lies in these two lines:</p>\n\n<pre><code>$choices[ $template_name ] = $template_name;\n...\n$match = ( $selected_template == $template );\n</code></pre>\n\n<p>So you're setting template name as choices, but you compare it with filename of the template.</p>\n\n<p>Change the first one to </p>\n\n<pre><code>$choices[ $template_filename ] = $template_name;\n</code></pre>\n\n<p>And it will work correctly.</p>\n"
}
] | 2019/03/28 | [
"https://wordpress.stackexchange.com/questions/332828",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159876/"
] | I have been asked to do some work on a site where the old developer has written this function (create a variable that stores the users avatar into an img tag) into the functions.php:
```
add_filter('get_avatar', 'lb_acf_profile_avatar', 10, 5);
function lb_acf_profile_avatar($avatar, $id_or_email, $size, $default, $alt) {
$user = '';
// Get user by id or email
if (is_numeric($id_or_email)) {
$id = (int) $id_or_email;
$user = get_user_by('id', $id);
} elseif (is_object($id_or_email)) {
if (!empty($id_or_email->user_id)) {
$id = (int) $id_or_email->user_id;
$user = get_user_by('id', $id);
}
} else {
$user = get_user_by('email', $id_or_email);
}
if (!$user) {
return $avatar;
}
// Get the user id
$user_id = $user->ID;
//$user_info = get_userdata($user_id)
// Get the file id
$avatar_url = $user->get('user_url'); //'https://dojo.nearsoft.com/wp-content/uploads/2017/02/Eric-Wroolie-per-template.jpg';
if ($avatar_url == '') {
return $avatar;
}
$avatar = '<img alt="' . $alt . '" src="' . $avatar_url . '" class="avatar avatar-' . $size . '" height="' . $size . '" width="' . $size . '"/>';
// Return our new avatar
return $avatar;
}
```
I know the function works as the app he built uses the code to generate the avatar for each user. I just don't know how to use it and cannot reach out to him to help me utilise it.
My efforts so far have failed, using code that looks a little like this:
```
<?php lb_acf_profile_avatar() ?>
<?php if ($avatar != '') : ?>
<div>Hellow World</div>
<?php endif; ?>
```
Where I have tried calling the function then assuming the returned variable (the avatar image) would be usable from that point. That doesn't appear to be the case.
The error message is 5 of these one for each argument:
```
Warning: Missing argument 5 for lb_acf_profile_avatar(), called in /home/materialshub/public_html/development/wp-content/themes/bolt/header.php on line 238 and defined in /home/materialshub/public_html/development/wp-content/themes/bolt/functions.php on line 663
```
**Is there a way to tailor this so I get the avatar\_url without the img tag returned, but I need the original code to function as it should as it is also used in the app and is functioning correctly.**
I don't have access to the app. Or the old developer. Any help you can provide is great. If you want further info just let me know.
**I think I want a new function that gets the avatar\_url like the function above but without any of the img tag. A simple url is all I need.**
I need this to be dynamic as well so it works for all users automatically, generating the avatar\_url. How can I pass the arguments in this manor?
**I cannot just use the inbuilt get\_avatar() WordPress function before we try go down that route as the app has made use of an empty field in the database 'user\_url'.**
I appreciate this is quite an annoying question, but I appreciate the kindness.
**EDIT:** I have tried reverting back to the get\_avatar() function and that then returns this warning:
```
Warning: Missing argument 1 for get_avatar(), called in /home/materialshub/public_html/development/wp-content/themes/bolt/header.php on line 239 and defined in /home/materialshub/public_html/development/wp-includes/pluggable.php on line 2450
```
Thanks, Jason. | For anyone dealing with the same issue, I just needed to change:
```
$choices[ $template_name ] = $template_name;
```
with:
```
$choices[ $template_filename ] = $template_name;
```
Consider a page template `Homepage (page-home.php)`. This way the template name `Homepage` will appear on the custom fields page but `$rule['value']` will actually return `page-home.php` and then we can compare this with `get_page_template_slug( $post->post_parent )`. |
332,856 | <p>I have a general question about functions and add_action to it.</p>
<p>I have a function and adding an action do it. But how can i define a value for the argument on this action?</p>
<pre><code>add_action( 'um_members_just_after_name', 'my_members_after_user_name', 10, 1 );
function my_members_after_user_name( $user_id ) {
// how can i set a value for $user_id ???
echo '<i class="um-verified um-icon-checkmark-circled um-tip-s"></i>';
}
</code></pre>
<p>Sorry, it may be a stupid question but i dont get the point for it... Normally in php it looks like this and i understand it here</p>
<pre><code>function Multiplication($x, $y) {
$z = $x * $y;
return $z;
}
echo "5 * 10 = " . Multiplication(5, 10) . "<br>";
echo "7 * 13 = " . Multiplication(7, 13) . "<br>";
echo "2 * 4 = " . Multiplication(2, 4);
</code></pre>
| [
{
"answer_id": 332839,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 4,
"selected": true,
"text": "<p>First of all, it is a very bad idea to modify the original theme without creating a child theme. Disabling updates of such theme is even worse idea, because without updates, your site may get infected or attacked.</p>\n\n<p>So the long-term solution would be to:</p>\n\n<ol>\n<li>Check the version of modified theme.</li>\n<li>Download that version from official repository.</li>\n<li>Compare the original files with modified ones.</li>\n<li>Create a child theme containing only necessary modifications.</li>\n</ol>\n\n<p>If you need to disable the updates for a few days, there is an easy way to do it - just change the version of your theme to 9.9.9 - WordPress will think that it is newer than the one in repository and it won't get updated. (BUT... Don't think of this hack as a solution - it's just a dirty temporary fix and you still should perform the process from points above).</p>\n"
},
{
"answer_id": 332840,
"author": "butlerblog",
"author_id": 38603,
"author_profile": "https://wordpress.stackexchange.com/users/38603",
"pm_score": 3,
"selected": false,
"text": "<p>I would agree with what Krzysiek already said - you should first be using a child theme (which is incredibly simple to set up, so there's zero reason not to do this as a best practice) and that avoiding theme updates is a recipe for eventual disaster (that goes for plugins and core, too).</p>\n\n<p>That being said, while changing the version number to a ridiculously high value is a workable and very simple solution, it doesn't really avoid updates if the developer <em>actually</em> releases something above that version - or if they change their version numbering to something non-standard.</p>\n\n<p>Here's an alternative method that handles it via the update transient. The first example would just disable all theme updates (assuming you don't have other themes installed that you DO want to allow updates for):</p>\n\n<pre><code>add_filter( 'site_transient_update_themes', 'remove_update_themes' );\nfunction remove_update_themes( $value ) {\n return null;\n}\n</code></pre>\n\n<p>If you want to do this for just a specific theme, then you need to search the response value for your theme's slug:</p>\n\n<pre><code>add_filter( 'site_transient_update_themes', 'remove_update_themes' );\nfunction remove_update_themes( $value ) {\n\n // Set your theme slug accordingly:\n $your_theme_slug = 'your-theme-slug';\n\n if ( isset( $value ) && is_object( $value ) ) {\n unset( $value->response[ $your_theme_slug ] );\n }\n\n return $value;\n}\n</code></pre>\n"
},
{
"answer_id": 332860,
"author": "Ray Mitchell",
"author_id": 2709,
"author_profile": "https://wordpress.stackexchange.com/users/2709",
"pm_score": 1,
"selected": false,
"text": "<p>If the question is to prevent editing the theme (and plugins) directly through the editor. You can make the following changes through wp-config.php</p>\n\n<ol>\n<li>Open up your wp-config.php file in a text editor. </li>\n<li><p>Anywhere above the line in that file that says </p>\n\n<p>/* That's all, stop editing! Happy\n blogging. */</p></li>\n</ol>\n\n<p>add the line <code>define( 'DISALLOW_FILE_EDIT', true );</code>.</p>\n\n<ol start=\"3\">\n<li>Save and upload the file. Check your WordPress dashboard, you should no longer\nsee (even on an Administrator account), the links at “Appearance >\nEditor” and “Plugins > Editor”.</li>\n</ol>\n"
}
] | 2019/03/28 | [
"https://wordpress.stackexchange.com/questions/332856",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/154739/"
] | I have a general question about functions and add\_action to it.
I have a function and adding an action do it. But how can i define a value for the argument on this action?
```
add_action( 'um_members_just_after_name', 'my_members_after_user_name', 10, 1 );
function my_members_after_user_name( $user_id ) {
// how can i set a value for $user_id ???
echo '<i class="um-verified um-icon-checkmark-circled um-tip-s"></i>';
}
```
Sorry, it may be a stupid question but i dont get the point for it... Normally in php it looks like this and i understand it here
```
function Multiplication($x, $y) {
$z = $x * $y;
return $z;
}
echo "5 * 10 = " . Multiplication(5, 10) . "<br>";
echo "7 * 13 = " . Multiplication(7, 13) . "<br>";
echo "2 * 4 = " . Multiplication(2, 4);
``` | First of all, it is a very bad idea to modify the original theme without creating a child theme. Disabling updates of such theme is even worse idea, because without updates, your site may get infected or attacked.
So the long-term solution would be to:
1. Check the version of modified theme.
2. Download that version from official repository.
3. Compare the original files with modified ones.
4. Create a child theme containing only necessary modifications.
If you need to disable the updates for a few days, there is an easy way to do it - just change the version of your theme to 9.9.9 - WordPress will think that it is newer than the one in repository and it won't get updated. (BUT... Don't think of this hack as a solution - it's just a dirty temporary fix and you still should perform the process from points above). |
332,857 | <p>I'm trying to run some simple javascript on a button click but I can't seem to find clear instructions on how to set up Javascript to run in wordpress.</p>
<p>The steps I've taken so far are to enqueue the script:</p>
<pre><code>function tyc_load_styles() {
wp_enqueue_style('main_font', 'https://fonts.googleapis.com/css?family=Roboto:300');
wp_enqueue_style('font_awesome', 'https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css');
wp_enqueue_style('main_styles', get_stylesheet_uri());
wp_enqueue_script( 'tyc_scripts', get_theme_file_uri('/js/tyc_scripts.js'));
};
add_action('wp_enqueue_scripts', 'tyc_load_styles');
</code></pre>
<p>Then in my js file:</p>
<pre><code>document.getElementById("navButton").addEventListener("click", function(){
document.getElementById("mobile-menu").style.display = "block";
});
</code></pre>
<p>finally in header.php</p>
<pre><code><button id="navButton" class="button icon">
<i class="fa fa-3x fa-bars mobile-nav"></i>
</button>
</code></pre>
<p>I'm getting an uncaught type error: Cannot read property 'addEventListener' of null</p>
<p>Thanks in advance!</p>
| [
{
"answer_id": 332914,
"author": "JakePowell",
"author_id": 158548,
"author_profile": "https://wordpress.stackexchange.com/users/158548",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks to WebElaine, you got it. </p>\n\n<p>I think that the type error was because the script loaded before the DOM and so there was no navButton to get, wrapping the function in a DOMcontentloaded listener did the trick. </p>\n\n<pre><code>document.addEventListener('DOMContentLoaded', function () {\n document.getElementById(\"navButton\").addEventListener('click', function() {\n alert(\"This works!\");\n });\n});\n</code></pre>\n"
},
{
"answer_id": 332918,
"author": "Rizwan Zakir",
"author_id": 67431,
"author_profile": "https://wordpress.stackexchange.com/users/67431",
"pm_score": 3,
"selected": true,
"text": "<p>Please read this documentation <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_enqueue_script/</a>\nYou need to set 5th parameter to true so the javascript is loaded in the footer.</p>\n\n<p><code>wp_enqueue_script( 'tyc_scripts', get_theme_file_uri('/js/tyc_scripts.js'), array(), false, true );</code></p>\n\n<p>if the issue still persists please add your js code inside jquery <code>document.ready()</code></p>\n"
}
] | 2019/03/28 | [
"https://wordpress.stackexchange.com/questions/332857",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/158548/"
] | I'm trying to run some simple javascript on a button click but I can't seem to find clear instructions on how to set up Javascript to run in wordpress.
The steps I've taken so far are to enqueue the script:
```
function tyc_load_styles() {
wp_enqueue_style('main_font', 'https://fonts.googleapis.com/css?family=Roboto:300');
wp_enqueue_style('font_awesome', 'https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css');
wp_enqueue_style('main_styles', get_stylesheet_uri());
wp_enqueue_script( 'tyc_scripts', get_theme_file_uri('/js/tyc_scripts.js'));
};
add_action('wp_enqueue_scripts', 'tyc_load_styles');
```
Then in my js file:
```
document.getElementById("navButton").addEventListener("click", function(){
document.getElementById("mobile-menu").style.display = "block";
});
```
finally in header.php
```
<button id="navButton" class="button icon">
<i class="fa fa-3x fa-bars mobile-nav"></i>
</button>
```
I'm getting an uncaught type error: Cannot read property 'addEventListener' of null
Thanks in advance! | Please read this documentation <https://developer.wordpress.org/reference/functions/wp_enqueue_script/>
You need to set 5th parameter to true so the javascript is loaded in the footer.
`wp_enqueue_script( 'tyc_scripts', get_theme_file_uri('/js/tyc_scripts.js'), array(), false, true );`
if the issue still persists please add your js code inside jquery `document.ready()` |
332,878 | <p>So I'm trying to set up an AJAX action for a plugin I'm building. </p>
<p>When using <code>/wp-admin/admin-ajax.php?action=beacon_podio-get_apps</code> </p>
<p>I was just getting <code>hello world0</code> and I'm not seeing <code>Request is valid</code> or the <code>Invalid request</code> so it seems like the action is not being called</p>
<p>I think I'm missing something but I'm not sure what I'm missing.</p>
<pre><code>class testClass {
public function __construct(){
echo "hello world";
add_action('wp_ajax_beacon_podio-get_apps', array($this, "get_apps"));
}
public function get_apps(){
if(isset($_POST['app_id'])){
$app_id = $_POST['app_id'];
die("Request is valid");
}else{
die("Invalid request");
}
}
}
new testClass();
</code></pre>
<p>I have been reading <a href="https://codex.wordpress.org/AJAX_in_Plugins" rel="nofollow noreferrer">https://codex.wordpress.org/AJAX_in_Plugins</a> but it's missing the URL I'm supposed to be using.</p>
<p><a href="https://i.stack.imgur.com/BiDGG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BiDGG.png" alt="Output from wordpress"></a></p>
| [
{
"answer_id": 332880,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 2,
"selected": false,
"text": "<p>OK, so you misunderstood it a little bit, I guess...</p>\n\n<p>You do the first part correctly. So yes - AJAX requests should be sent to <code>wp-admin/admin-ajax.php</code> and the should have <code>action</code> param set in the request (either as a POST or as a GET).</p>\n\n<p>But then, you do it wrong. You register your action with this code:</p>\n\n<pre><code>add_action('beacon_podio-get_apps', array($this, \"get_apps\"));\n</code></pre>\n\n<p>But id should be:</p>\n\n<pre><code>add_action('wp_ajax_beacon_podio-get_apps', array($this, \"get_apps\"));\n</code></pre>\n\n<p>or (for anonymous users)</p>\n\n<pre><code>add_action('wp_ajax_nopriv_beacon_podio-get_apps', array($this, \"get_apps\"));\n</code></pre>\n\n<p>So just to make it clear - the correct hooks are:</p>\n\n<ul>\n<li><code>wp_ajax_(action)</code></li>\n<li><code>wp_ajax_nopriv_(action)</code></li>\n</ul>\n\n<p>where (action) is the action that you sent as action parameter.</p>\n"
},
{
"answer_id": 338367,
"author": "Martin Barker",
"author_id": 39073,
"author_profile": "https://wordpress.stackexchange.com/users/39073",
"pm_score": 1,
"selected": true,
"text": "<p>This appeared to be a bug in WordPress, coming back to this and upgrading to version 5.2 the problem seems to have been fixed for some reason the has_action was failing to find the action unsure why but it seems to have been fixed.</p>\n"
}
] | 2019/03/28 | [
"https://wordpress.stackexchange.com/questions/332878",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/39073/"
] | So I'm trying to set up an AJAX action for a plugin I'm building.
When using `/wp-admin/admin-ajax.php?action=beacon_podio-get_apps`
I was just getting `hello world0` and I'm not seeing `Request is valid` or the `Invalid request` so it seems like the action is not being called
I think I'm missing something but I'm not sure what I'm missing.
```
class testClass {
public function __construct(){
echo "hello world";
add_action('wp_ajax_beacon_podio-get_apps', array($this, "get_apps"));
}
public function get_apps(){
if(isset($_POST['app_id'])){
$app_id = $_POST['app_id'];
die("Request is valid");
}else{
die("Invalid request");
}
}
}
new testClass();
```
I have been reading <https://codex.wordpress.org/AJAX_in_Plugins> but it's missing the URL I'm supposed to be using.
[](https://i.stack.imgur.com/BiDGG.png) | This appeared to be a bug in WordPress, coming back to this and upgrading to version 5.2 the problem seems to have been fixed for some reason the has\_action was failing to find the action unsure why but it seems to have been fixed. |
332,913 | <p>I am not able to get this running. What i commented out is running like it should, but i want to use the switch for specific user roles...</p>
<pre><code>add_action( 'um_members_just_after_name', 'my_members_after_user_name', 10, 1 );
function my_members_after_user_name( $user_id ) {
$user = new WP_User( $user_id );
/*
if( $user->roles[0] == 'um_musiker' ) {
// update_user_meta( $user_id, 'um_reihung', '40' );
echo '<i class="um-verified um-icon-checkmark-circled um-tip-s" title="Kein Status"></i>';
}
*/
if( $user->roles[0] == $value ) {
switch ( $value ) {
case "um_musiker":
echo '<i class="um-verified um-icon-checkmark-circled um-tip-s" title="Kein Status"></i>';
break;
case "um_musiker_bronze":
echo '<i class="um-verified um-icon-checkmark-circled um-tip-s" title="Bronze Status"></i>';
break;
case "um_musiker_silber":
echo '<i class="um-verified um-icon-checkmark-circled um-tip-s" title="Silber Status"></i>';
break;
}
}
}
</code></pre>
| [
{
"answer_id": 332915,
"author": "Tejas Gajjar",
"author_id": 155971,
"author_profile": "https://wordpress.stackexchange.com/users/155971",
"pm_score": 1,
"selected": true,
"text": "<p>You do not need to use pass the <code>$value</code> in a switch statement, Just pass there <code>$user->roles[0]</code> instead of <code>$value</code> and after that your condition.</p>\n\n<p>Add below code and let me know your answer towards it.</p>\n\n<pre><code>add_action( 'um_members_just_after_name', 'my_members_after_user_name', 10, 1 );\nfunction my_members_after_user_name( $user_id ) {\n\n $user = new WP_User( $user_id );\n /*\n if( $user->roles[0] == 'um_musiker' ) {\n // update_user_meta( $user_id, 'um_reihung', '40' );\n echo '<i class=\"um-verified um-icon-checkmark-circled um-tip-s\" title=\"Kein Status\"></i>'; \n }\n */\n\n\n switch ( $user->roles[0] ) {\n case \"um_musiker\":\n echo '<i class=\"um-verified um-icon-checkmark-circled um-tip-s\" title=\"Kein Status\"></i>';\n break;\n case \"um_musiker_bronze\":\n echo '<i class=\"um-verified um-icon-checkmark-circled um-tip-s\" title=\"Bronze Status\"></i>';\n break;\n case \"um_musiker_silber\":\n echo '<i class=\"um-verified um-icon-checkmark-circled um-tip-s\" title=\"Silber Status\"></i>';\n break;\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 332916,
"author": "Rizwan Zakir",
"author_id": 67431,
"author_profile": "https://wordpress.stackexchange.com/users/67431",
"pm_score": 0,
"selected": false,
"text": "<p>I just write new <code>$value = $user->roles[0];</code> variable and check <code>$user</code> in <code>if</code> condition. I hope it'll help you out. Thanks</p>\n\n<pre><code>add_action( 'um_members_just_after_name', 'my_members_after_user_name', 10, 1 );\nfunction my_members_after_user_name( $user_id ) {\n\n $user = new WP_User( $user_id );\n /*\n if( $user->roles[0] == 'um_musiker' ) {\n // update_user_meta( $user_id, 'um_reihung', '40' );\n echo '<i class=\"um-verified um-icon-checkmark-circled um-tip-s\" title=\"Kein Status\"></i>'; \n }\n */\n\n $value = $user->roles[0];\n\n if( $value ) {\n switch ( $value ) {\n case \"um_musiker\":\n echo '<i class=\"um-verified um-icon-checkmark-circled um-tip-s\" title=\"Kein Status\"></i>';\n break;\n case \"um_musiker_bronze\":\n echo '<i class=\"um-verified um-icon-checkmark-circled um-tip-s\" title=\"Bronze Status\"></i>';\n break;\n case \"um_musiker_silber\":\n echo '<i class=\"um-verified um-icon-checkmark-circled um-tip-s\" title=\"Silber Status\"></i>';\n break;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 332926,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>Checking <code>$user->roles[0]</code> is <em>not</em> an appropriate way to check if a user has a role. Users can have multiple roles, so this needs to be taken into account:</p>\n\n<pre><code>$user = get_userdata( $user_id );\n$roles = $user->roles;\n\nif ( in_array( 'um_musiker', $roles ) {\n echo '<i class=\"um-verified um-icon-checkmark-circled um-tip-s\" title=\"Kein Status\"></i>';\n return;\n}\n\nif ( in_array( 'um_musiker_bronze', $roles ) {\n echo '<i class=\"um-verified um-icon-checkmark-circled um-tip-s\" title=\"Bronze Status\"></i>';\n return;\n}\n\nif ( in_array( 'um_musiker_silber', $roles ) {\n echo '<i class=\"um-verified um-icon-checkmark-circled um-tip-s\" title=\"Silber Status\"></i>';\n return;\n}\n</code></pre>\n"
}
] | 2019/03/29 | [
"https://wordpress.stackexchange.com/questions/332913",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/154739/"
] | I am not able to get this running. What i commented out is running like it should, but i want to use the switch for specific user roles...
```
add_action( 'um_members_just_after_name', 'my_members_after_user_name', 10, 1 );
function my_members_after_user_name( $user_id ) {
$user = new WP_User( $user_id );
/*
if( $user->roles[0] == 'um_musiker' ) {
// update_user_meta( $user_id, 'um_reihung', '40' );
echo '<i class="um-verified um-icon-checkmark-circled um-tip-s" title="Kein Status"></i>';
}
*/
if( $user->roles[0] == $value ) {
switch ( $value ) {
case "um_musiker":
echo '<i class="um-verified um-icon-checkmark-circled um-tip-s" title="Kein Status"></i>';
break;
case "um_musiker_bronze":
echo '<i class="um-verified um-icon-checkmark-circled um-tip-s" title="Bronze Status"></i>';
break;
case "um_musiker_silber":
echo '<i class="um-verified um-icon-checkmark-circled um-tip-s" title="Silber Status"></i>';
break;
}
}
}
``` | You do not need to use pass the `$value` in a switch statement, Just pass there `$user->roles[0]` instead of `$value` and after that your condition.
Add below code and let me know your answer towards it.
```
add_action( 'um_members_just_after_name', 'my_members_after_user_name', 10, 1 );
function my_members_after_user_name( $user_id ) {
$user = new WP_User( $user_id );
/*
if( $user->roles[0] == 'um_musiker' ) {
// update_user_meta( $user_id, 'um_reihung', '40' );
echo '<i class="um-verified um-icon-checkmark-circled um-tip-s" title="Kein Status"></i>';
}
*/
switch ( $user->roles[0] ) {
case "um_musiker":
echo '<i class="um-verified um-icon-checkmark-circled um-tip-s" title="Kein Status"></i>';
break;
case "um_musiker_bronze":
echo '<i class="um-verified um-icon-checkmark-circled um-tip-s" title="Bronze Status"></i>';
break;
case "um_musiker_silber":
echo '<i class="um-verified um-icon-checkmark-circled um-tip-s" title="Silber Status"></i>';
break;
}
}
``` |
332,931 | <p>So, I am using heading tags <code>h1</code>-<code>h6</code> on my site in various places, what I'd like to do is put a <code>div</code> around those tags using a WP function. Right now I am using some jQuery to get the job done, but I'm trying to minimize the amount of jQuery on my site, so I figured it'd be better to use some kind of <code>preg_replace</code> to find any h1-h6 tags and add an outer div.</p>
<p>My current jQuery looks like this: <code>$("h6, h5, h4, h3, h2, h1").wrap('<div class="title"></div>');</code></p>
<p>I found some code that works for images, but I'm not sure how to tweak it, so I can use it for heading tags:</p>
<pre><code>function outer_img_wrap( $content ) {
$image = '/(<img([^>]*)>)/i';
$wrapper = '<span class="featured">$1</span>';
$content = preg_replace( $image, $wrapper, $content );
return $content;
}
add_filter( 'the_content', 'outer_img_wrap' );
</code></pre>
<p>Any help is appreciated. The function doesn't have to look like that, just found that for images and thought it was nice and simple.</p>
<p>Thanks,<br />
Josh</p>
| [
{
"answer_id": 332937,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 0,
"selected": false,
"text": "<p>The code you’ve posted is a great starting point. All you have to do is to change the expressions inside of it.</p>\n\n<p>It’s a little bit trickier, because you have to replace opening and closing tag. I would go for something like this:</p>\n\n<pre><code>function wrap_headers_with_div( $content ) {\n $content = preg_replace('/<h([1-6])>/', '<div class=\"title\"><h$1>', $content);\n $content = preg_replace('/<\\/h([1-6])>/', '</h$1></div>', $content);\n\n return $content;\n}\nadd_filter( 'the_content', 'wrap_headers_with_div' );\n</code></pre>\n"
},
{
"answer_id": 332940,
"author": "Rizwan Zakir",
"author_id": 67431,
"author_profile": "https://wordpress.stackexchange.com/users/67431",
"pm_score": 3,
"selected": true,
"text": "<p>Try this code</p>\n\n<pre><code>function wrap_heading_with_div( $content ) {\n $heading = '/<h\\d.*?>(.*?)<\\/h\\d>/ims';\n $wrapper = '<div class=\"title\">$0</div>';\n $content = preg_replace($heading, $wrapper, $content);\n return $content;\n}\nadd_filter( 'the_content', 'wrap_heading_with_div' );\n</code></pre>\n\n<p><a href=\"https://www.phpliveregex.com/p/rtO#tab-preg-replace\" rel=\"nofollow noreferrer\">Live Demo</a></p>\n"
}
] | 2019/03/29 | [
"https://wordpress.stackexchange.com/questions/332931",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/9820/"
] | So, I am using heading tags `h1`-`h6` on my site in various places, what I'd like to do is put a `div` around those tags using a WP function. Right now I am using some jQuery to get the job done, but I'm trying to minimize the amount of jQuery on my site, so I figured it'd be better to use some kind of `preg_replace` to find any h1-h6 tags and add an outer div.
My current jQuery looks like this: `$("h6, h5, h4, h3, h2, h1").wrap('<div class="title"></div>');`
I found some code that works for images, but I'm not sure how to tweak it, so I can use it for heading tags:
```
function outer_img_wrap( $content ) {
$image = '/(<img([^>]*)>)/i';
$wrapper = '<span class="featured">$1</span>';
$content = preg_replace( $image, $wrapper, $content );
return $content;
}
add_filter( 'the_content', 'outer_img_wrap' );
```
Any help is appreciated. The function doesn't have to look like that, just found that for images and thought it was nice and simple.
Thanks,
Josh | Try this code
```
function wrap_heading_with_div( $content ) {
$heading = '/<h\d.*?>(.*?)<\/h\d>/ims';
$wrapper = '<div class="title">$0</div>';
$content = preg_replace($heading, $wrapper, $content);
return $content;
}
add_filter( 'the_content', 'wrap_heading_with_div' );
```
[Live Demo](https://www.phpliveregex.com/p/rtO#tab-preg-replace) |
332,952 | <p>I'm getting errors, warnings and notices being displayed on a site. Those include things like filesystem paths, SQL queries and wpdb prefixes, which I don't think it's particularly good to have them being displayed to all visitors.</p>
<p><strong>I have fixed the cause of the issue,</strong> but I want to prevent these error messages from being displayed on the live site. Turning <code>WP_DEBUG_DISPLAY</code> off hides the errors, but the warnings and notices remain. How do I hide those?</p>
| [
{
"answer_id": 332953,
"author": "That Brazilian Guy",
"author_id": 22510,
"author_profile": "https://wordpress.stackexchange.com/users/22510",
"pm_score": -1,
"selected": false,
"text": "<p>As others have already said, it's very important to fix the underlying issues causing the error messages to show up.</p>\n\n<p>In my opinion, it's also important to have these errors and warnings showing up on development and homologation environments, but not on production, for a variety or reasons.</p>\n\n<p>I was able to remove notices and warnings from the production environment by placing the following line into <code>wp-config.php</code>:</p>\n\n<pre><code>ini_set('display_errors','Off');\n</code></pre>\n\n<p>Even with <code>WP_DEBUG</code> turned off, a few warnings were still being shown.</p>\n"
},
{
"answer_id": 332966,
"author": "Ted Stresen-Reuter",
"author_id": 112766,
"author_profile": "https://wordpress.stackexchange.com/users/112766",
"pm_score": 3,
"selected": false,
"text": "<p>As many have already commented, it is better to fix the source of the issue than to hide the messages. That said, these types of messages should never be displayed on production server but, since you just never know, it is also a good idea to disable them on <em>all</em> servers (local development machine, development machines, etc.).</p>\n\n<p>We use the following settings in wp-config.php to disable the display of all warnings, notices, errors, etc. and then use <code>tail -f wp-content/debug.log</code> to see the errors as we work:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>define( 'WP_DEBUG', true );\ndefine( 'WP_DEBUG_LOG', true );\ndefine( 'WP_DEBUG_DISPLAY', false );\n</code></pre>\n\n<p>Sometimes Notices don't include a backtrace so you can't see what's causing the message. Please see <a href=\"https://wordpress.stackexchange.com/questions/296194/how-to-find-cause-of-php-notices-with-no-stack-trace/332654#332654\">my answer to a similar question</a> as it includes details on how to get a backtrace for such messages.</p>\n\n<p>If you are still seeing warnings and info and such and you've followed my advice in this answer, then it is likely a plugin or the theme itself is re-enabling the display of warnings and info.</p>\n\n<p><code>WP_DEBUG_DISPLAY</code> is a constant that tells WordPress to run the following code: </p>\n\n<pre class=\"lang-php prettyprint-override\"><code>if ( WP_DEBUG_DISPLAY ) {\n ini_set( 'display_errors', 1 );\n} elseif ( null !== WP_DEBUG_DISPLAY ) {\n ini_set( 'display_errors', 0 );\n}\n</code></pre>\n\n<p>This code is in <code>wp-includes/load.php</code> and is, if not the first, one of the very first files included in the WordPress bootstrapping procedure. The function that this code appears in is called in <code>wp-settings.php</code> which is the first file included after wp-config.php. This code is called before plugins are loaded and executed.</p>\n\n<p>If a plugin producer has <code>ini_set( 'display_errors', 1 )</code> in their code, it will override what you've got in <code>wp-config.php</code> and continue showing PHP errors, warnings, info, etc. There is no way, really, to override this. Try searching your entire plugins folder for <code>ini_set</code> to see if you can spot the culprit. You should probably also check your theme while you are at it.</p>\n"
}
] | 2019/03/29 | [
"https://wordpress.stackexchange.com/questions/332952",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/22510/"
] | I'm getting errors, warnings and notices being displayed on a site. Those include things like filesystem paths, SQL queries and wpdb prefixes, which I don't think it's particularly good to have them being displayed to all visitors.
**I have fixed the cause of the issue,** but I want to prevent these error messages from being displayed on the live site. Turning `WP_DEBUG_DISPLAY` off hides the errors, but the warnings and notices remain. How do I hide those? | As many have already commented, it is better to fix the source of the issue than to hide the messages. That said, these types of messages should never be displayed on production server but, since you just never know, it is also a good idea to disable them on *all* servers (local development machine, development machines, etc.).
We use the following settings in wp-config.php to disable the display of all warnings, notices, errors, etc. and then use `tail -f wp-content/debug.log` to see the errors as we work:
```php
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
define( 'WP_DEBUG_DISPLAY', false );
```
Sometimes Notices don't include a backtrace so you can't see what's causing the message. Please see [my answer to a similar question](https://wordpress.stackexchange.com/questions/296194/how-to-find-cause-of-php-notices-with-no-stack-trace/332654#332654) as it includes details on how to get a backtrace for such messages.
If you are still seeing warnings and info and such and you've followed my advice in this answer, then it is likely a plugin or the theme itself is re-enabling the display of warnings and info.
`WP_DEBUG_DISPLAY` is a constant that tells WordPress to run the following code:
```php
if ( WP_DEBUG_DISPLAY ) {
ini_set( 'display_errors', 1 );
} elseif ( null !== WP_DEBUG_DISPLAY ) {
ini_set( 'display_errors', 0 );
}
```
This code is in `wp-includes/load.php` and is, if not the first, one of the very first files included in the WordPress bootstrapping procedure. The function that this code appears in is called in `wp-settings.php` which is the first file included after wp-config.php. This code is called before plugins are loaded and executed.
If a plugin producer has `ini_set( 'display_errors', 1 )` in their code, it will override what you've got in `wp-config.php` and continue showing PHP errors, warnings, info, etc. There is no way, really, to override this. Try searching your entire plugins folder for `ini_set` to see if you can spot the culprit. You should probably also check your theme while you are at it. |
333,009 | <p>I'm using the <code>do_shortcode</code> function to add a shortcode in a page. But I would like to check if that shortcode exists before displaying it. If the user has no gallery, I would like to display a message like this: "Sorry no gallery here".</p>
<p>This is my PHP:</p>
<pre><code><?php
/**
* galeries content
*/
function iconic_galeries_endpoint_content() {
echo /* Template Name: Client Area */
get_header();
?>
<div id="primary" class="content-area">
<main id="main" class="site-main">
<article>
<header class="entry-header">
<h1><?php _e( 'Vos galeries photos.', 'my-theme' ); ?></h1>
</header>
<div class="entry-content">
<?php
$current_user = wp_get_current_user();
if ( isset( $current_user->user_email ) ) {
echo '<p>' . sprintf( __( '%s, this is your galleries', 'my-theme' ), $current_user->display_name ) . ':</p>';
echo do_shortcode( '[picu_list_collections email="' . $current_user->user_email . '"]' );
}
else {
echo '<p>' . sprintf( __( 'Please <a href="%s">log in</a> to see this page', 'my-theme' ), wp_login_url( get_permalink() ) ) . '.</p>';
}
?>
</div>
</article>
</main>
</div>
<?php
}
</code></pre>
<p>I haven't found a way to return a message like: "Sorry no gallery here".</p>
<p>Does anyone have a solution?</p>
<hr>
<p>When client has a gallery to approve
<a href="https://i.stack.imgur.com/B7hRk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/B7hRk.png" alt="Client has no galerie to approve"></a></p>
<p>And when client has no gallery to approve or he has already approve his photos
<a href="https://i.stack.imgur.com/5XUkz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5XUkz.png" alt="Client has a gallery to approve"></a></p>
| [
{
"answer_id": 333004,
"author": "selidamou.gr",
"author_id": 126844,
"author_profile": "https://wordpress.stackexchange.com/users/126844",
"pm_score": -1,
"selected": false,
"text": "<p>you can certainly alter the <code>wp-content/uploads</code> and make it to appear as <code>/uploads</code> or media by adding the following code in your <code>wp-config.php</code>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>require_once(ABSPATH.’wp-settings.php’);\ndefine( ‘UPLOADS’, ”.’media’ );\n</code></pre>\n"
},
{
"answer_id": 333024,
"author": "Arvind Singh",
"author_id": 113501,
"author_profile": "https://wordpress.stackexchange.com/users/113501",
"pm_score": 0,
"selected": false,
"text": "<p>You can try this code <code>define('UPLOADS','')</code>and also unclick Organize my uploads into month- and year-based folders from media settings.</p>\n"
}
] | 2019/03/30 | [
"https://wordpress.stackexchange.com/questions/333009",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/164119/"
] | I'm using the `do_shortcode` function to add a shortcode in a page. But I would like to check if that shortcode exists before displaying it. If the user has no gallery, I would like to display a message like this: "Sorry no gallery here".
This is my PHP:
```
<?php
/**
* galeries content
*/
function iconic_galeries_endpoint_content() {
echo /* Template Name: Client Area */
get_header();
?>
<div id="primary" class="content-area">
<main id="main" class="site-main">
<article>
<header class="entry-header">
<h1><?php _e( 'Vos galeries photos.', 'my-theme' ); ?></h1>
</header>
<div class="entry-content">
<?php
$current_user = wp_get_current_user();
if ( isset( $current_user->user_email ) ) {
echo '<p>' . sprintf( __( '%s, this is your galleries', 'my-theme' ), $current_user->display_name ) . ':</p>';
echo do_shortcode( '[picu_list_collections email="' . $current_user->user_email . '"]' );
}
else {
echo '<p>' . sprintf( __( 'Please <a href="%s">log in</a> to see this page', 'my-theme' ), wp_login_url( get_permalink() ) ) . '.</p>';
}
?>
</div>
</article>
</main>
</div>
<?php
}
```
I haven't found a way to return a message like: "Sorry no gallery here".
Does anyone have a solution?
---
When client has a gallery to approve
[](https://i.stack.imgur.com/B7hRk.png)
And when client has no gallery to approve or he has already approve his photos
[](https://i.stack.imgur.com/5XUkz.png) | You can try this code `define('UPLOADS','')`and also unclick Organize my uploads into month- and year-based folders from media settings. |
333,016 | <p>I have a custom Gutenberg block which is attempting to take an array of strings and save them as <code><li></code> elements. Everything works as expected and displays correctly to the end user, but I'm getting validation errors after reloading the editor.</p>
<p>Here is the validation error:</p>
<pre><code>Expected:
<div class="wp-block-ggcn-blocks-query-string-content"><span class="data-drop" newtab=""></span><ul class="tabs"><li class="tab"><li class="tab">Tab1</li></li><li class="tab"><li class="tab">Tab2</li></li></ul><p class="custom-content"></p></div>
Actual:
<div class="wp-block-ggcn-blocks-query-string-content"><span class="data-drop" newtab=""></span><ul class="tabs"><li class="tab">Tab1</li><li class="tab">Tab2</li></ul><p class="custom-content"></p></div>
</code></pre>
<p>Here is my save function:</p>
<pre><code>save({attributes, className}) {
const { tabs, newTab, content } = attributes;
return (
<div className={className}>
<span className="data-drop" newtab={newTab}></span>
<ul className="tabs">
{tabs.map(tab => {
return <li className="tab">{tab}</li>;
})}
</ul>
</div>
);
}
</code></pre>
<p>Here is how I'm parsing the attributes:</p>
<pre><code>attributes: {
tabs: {
type: 'array',
source: 'children',
selector: 'ul.tabs',
default: []
}
}
</code></pre>
<p>Obviously I'm parsing out the entire HTML list elements, when I only want the text. But when I change the selector to be <code>ul.tabs > li</code>, I get only the text for a single element, and lists of more than 1 item fail validation.</p>
<p>Can someone help me understand how to get an array of text values?</p>
| [
{
"answer_id": 333047,
"author": "tmdesigned",
"author_id": 28273,
"author_profile": "https://wordpress.stackexchange.com/users/28273",
"pm_score": 2,
"selected": false,
"text": "<p>When you set the attribute's source to children, it gives you DOM elements, i.e. including the wrapping HTML and not just the inner text. </p>\n\n<p>So the behavior you're seeing, which you probably already know, is the HTML elements getting nested inside of themselves. You're wrapping the contents in <code><li></code>, which gets wrapped in <code><li></code>, which could get wrapped in <code><li></code> again, and so on.</p>\n\n<p>That part I'm pretty sure about. The solution below is my <em>understanding</em> of how to do it, but having not yet done this type of attribute selector, <em>I haven't fully tested this</em>. That being said, I think what you are looking for is closer to:</p>\n\n<pre><code>attributes: {\n tabs: { \n type: 'array',\n source: 'query',\n selector: 'ul.tabs',\n default: [],\n query: {\n val: {\n type: 'string',\n selector: 'li',\n source: 'text',\n },\n }\n}\n</code></pre>\n\n<p>So we're creating an array of objects with one property, which comes from each children's text. Then in your save function, you have to specifically pull that new <code>val</code> property we just specified as coming from the inner text of the <code>li</code> selector:</p>\n\n<pre><code>save({attributes, className}) {\n const { tabs, newTab, content } = attributes;\n\n return (\n <div className={className}>\n <span className=\"data-drop\" newtab={newTab}></span>\n <ul className=\"tabs\">\n {tabs.map(tab => {\n return <li className=\"tab\">{tab.val}</li>;\n })}\n </ul> \n </div>\n );\n}\n</code></pre>\n"
},
{
"answer_id": 333103,
"author": "Sam Schneider",
"author_id": 137195,
"author_profile": "https://wordpress.stackexchange.com/users/137195",
"pm_score": 2,
"selected": false,
"text": "<p>I found a workaround, sparked by @tmdesigned's answer, which I'm going to post as an answer. It is not pretty and I don't think it can be the \"canonical\" answer, but hopefully it helps us get there.</p>\n\n<p>So first, I kept the attributes using a <code>source: children</code>:</p>\n\n<pre><code>tabs: { \n type: 'array',\n source: 'children',\n selector: 'ul.tabs',\n default: []\n}\n</code></pre>\n\n<p>This meant that on initial save, I was dealing with an array of strings, but on subsequent loads in the editor, I was dealing with an array of objects, since my source type of children was pulling in the <code><li></code> elements themselves in the list, instead of the text values of the elements.</p>\n\n<p>My solution was to map over these elements and convert them back into an array of strings. This had to be done in both the <code>edit</code> function and the <code>save</code> function.</p>\n\n<pre><code>const tabValues = tabs.map(tab => {\n if (typeof(tab) === 'object')\n return tab.props.children[0];\n\n return tab;\n});\n</code></pre>\n\n<p>Then later in the output, I was able to output like this:</p>\n\n<pre><code>{tabValues.map(tab => <li key={tab} className=\"tab\">{tab}</li>)}\n</code></pre>\n\n<p>If anyone has a solution that relies exclusively on the data parse and doesn't require this workaround, I will mark that as the answer.</p>\n"
}
] | 2019/03/30 | [
"https://wordpress.stackexchange.com/questions/333016",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/137195/"
] | I have a custom Gutenberg block which is attempting to take an array of strings and save them as `<li>` elements. Everything works as expected and displays correctly to the end user, but I'm getting validation errors after reloading the editor.
Here is the validation error:
```
Expected:
<div class="wp-block-ggcn-blocks-query-string-content"><span class="data-drop" newtab=""></span><ul class="tabs"><li class="tab"><li class="tab">Tab1</li></li><li class="tab"><li class="tab">Tab2</li></li></ul><p class="custom-content"></p></div>
Actual:
<div class="wp-block-ggcn-blocks-query-string-content"><span class="data-drop" newtab=""></span><ul class="tabs"><li class="tab">Tab1</li><li class="tab">Tab2</li></ul><p class="custom-content"></p></div>
```
Here is my save function:
```
save({attributes, className}) {
const { tabs, newTab, content } = attributes;
return (
<div className={className}>
<span className="data-drop" newtab={newTab}></span>
<ul className="tabs">
{tabs.map(tab => {
return <li className="tab">{tab}</li>;
})}
</ul>
</div>
);
}
```
Here is how I'm parsing the attributes:
```
attributes: {
tabs: {
type: 'array',
source: 'children',
selector: 'ul.tabs',
default: []
}
}
```
Obviously I'm parsing out the entire HTML list elements, when I only want the text. But when I change the selector to be `ul.tabs > li`, I get only the text for a single element, and lists of more than 1 item fail validation.
Can someone help me understand how to get an array of text values? | When you set the attribute's source to children, it gives you DOM elements, i.e. including the wrapping HTML and not just the inner text.
So the behavior you're seeing, which you probably already know, is the HTML elements getting nested inside of themselves. You're wrapping the contents in `<li>`, which gets wrapped in `<li>`, which could get wrapped in `<li>` again, and so on.
That part I'm pretty sure about. The solution below is my *understanding* of how to do it, but having not yet done this type of attribute selector, *I haven't fully tested this*. That being said, I think what you are looking for is closer to:
```
attributes: {
tabs: {
type: 'array',
source: 'query',
selector: 'ul.tabs',
default: [],
query: {
val: {
type: 'string',
selector: 'li',
source: 'text',
},
}
}
```
So we're creating an array of objects with one property, which comes from each children's text. Then in your save function, you have to specifically pull that new `val` property we just specified as coming from the inner text of the `li` selector:
```
save({attributes, className}) {
const { tabs, newTab, content } = attributes;
return (
<div className={className}>
<span className="data-drop" newtab={newTab}></span>
<ul className="tabs">
{tabs.map(tab => {
return <li className="tab">{tab.val}</li>;
})}
</ul>
</div>
);
}
``` |
333,071 | <p>I am working on a wordpress shortcodes in which I want to the limit the content coming from a xml.</p>
<p>The code which I have used for wordpress shortcodes is:</p>
<pre><code>function podcast_func( $content = null ){
ob_start();
?>
<script src="https://content.jwplatform.com/libraries/FZ8yNTef.js"></script>
<center><div id="podcast" align="center"></div></center>
<script>
var PodcastplayerInstance = jwplayer("podcast");
PodcastplayerInstance.setup({
playlist: "http://www.cpac.ca/tip-podcast/jwplayer.xml",
androidhls: true,
preload: "auto",
height: 200,
width: 400,
visualplaylist:false,
stretching: "fill",
"plugins": {
"http://www.cpac.ca/tip-podcast/listy.js":{},
'viral-2': {'oncomplete':'False','onpause':'False','functions':'All'}
}
});
</script>
<?PHP
return ob_get_clean();
}
add_shortcode( 'podcast', 'podcast_func' );
</code></pre>
<p>On using this <code><div class="today-podcast" style="text-align: center;">[podcast]</div></code>, it displays the entire content from here <a href="http://www.cpac.ca/tip-podcast/jwplayer.xml" rel="nofollow noreferrer">http://www.cpac.ca/tip-podcast/jwplayer.xml</a></p>
<p><strong>Problem Statement:</strong> I am wondering what changes I should make in the wordpress shortcode above so that it displays only 1st two items from here <a href="http://www.cpac.ca/tip-podcast/jwplayer.xml" rel="nofollow noreferrer">http://www.cpac.ca/tip-podcast/jwplayer.xml</a></p>
| [
{
"answer_id": 333521,
"author": "Serkan Algur",
"author_id": 23042,
"author_profile": "https://wordpress.stackexchange.com/users/23042",
"pm_score": 2,
"selected": false,
"text": "<p>You need to parse your XML file for creating a playlist for jwplayer according to this <a href=\"https://developer.jwplayer.com/jw-player/docs/developer-guide/customization/configuration-reference/#playlist\" rel=\"nofollow noreferrer\"><strong>page</strong></a>. But there is a problem. <code>jwplayer:image</code> and <code>jwplayer:source</code> strings cant resolve with <code>simple_xml_load()</code> for parsing.</p>\n\n<p>I create a code for you. Code needs <code>file_get_contens()</code> function enabled by the server (because we must change remote XML and resolve the <code>jwplayer:image</code> problem).</p>\n\n<p>Here is the code;</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$source_xml = 'http://www.cpac.ca/tip-podcast/jwplayer.xml';\n$fileContents = file_get_contents( $source_xml );\n$fileContents = str_replace( array( 'jwplayer:image', 'jwplayer:source', ' file=\"', '\" />' ), array( 'image', 'file', '>', '</file>' ), $fileContents );\n$fileContents = trim( str_replace( '\"', \"'\", $fileContents ) );\n$simpleXml = simplexml_load_string( $fileContents );\n$json = json_encode( array( $simpleXml->channel->item[0], $simpleXml->channel->item[1] ) );\n\nprint( $json );\n</code></pre>\n\n<p>This code resolves your XML file and parses only first two sources for creating playlist items. You can test with your localhost. The result should be like this;</p>\n\n<pre><code>[\n {\n \"title\": \"April 4, 2019\",\n \"description\": \"The Prime Minister defends the removal of two former cabinet ministers from the Liberal caucus. Jane Philpott and Jody Wilson-Raybould speak out about the Prime Ministers' decision. Members of the \\\"Daughters of the Vote\\\" turn their backs on the Prime Minister, and walk out on Andrew Scheer.\",\n \"image\": \"http://media.cpac.ca/_app_images/tip_player_poster.png\",\n \"file\": \"http://www.cpac.ca/tip-podcast/1554372812.mp3\"\n },\n {\n \"title\": \"April 3, 2019\",\n \"description\": \"Jody Wilson-Raybould and Jane Philpott are removed from the Liberal Caucus. Gerald Butts submits text messages, and other evidence, to the justice committee. The Environment Commissioner says Canada isn't doing enough to fight climate change. \",\n \"image\": \"http://media.cpac.ca/_app_images/tip_player_poster.png\",\n \"file\": \"http://www.cpac.ca/tip-podcast/1554286033.mp3\"\n }\n]\n</code></pre>\n\n<p>Best regards</p>\n"
},
{
"answer_id": 333541,
"author": "Karun",
"author_id": 63470,
"author_profile": "https://wordpress.stackexchange.com/users/63470",
"pm_score": 2,
"selected": true,
"text": "<p>It's better to 1st save the returned XML to a file and then loop back to unset. </p>\n\n<pre><code><?php\n $curl = curl_init();\n\n curl_setopt_array($curl, array(\n CURLOPT_URL => \"http://www.cpac.ca/tip-podcast/jwplayer.xml\",\n CURLOPT_RETURNTRANSFER => true,\n CURLOPT_ENCODING => \"\",\n CURLOPT_MAXREDIRS => 10,\n CURLOPT_TIMEOUT => 30,\n CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n CURLOPT_CUSTOMREQUEST => \"GET\",\n CURLOPT_HTTPHEADER => array(\n \"cache-control: no-cache\",\n \"postman-token: 28025ee8-1e82-ce60-f6ae-f401118baa1c\"\n ),\n ));\n\n $response = curl_exec($curl);\n $err = curl_error($curl);\n\n curl_close($curl);\n\n if ($err) {\n echo \"cURL Error #:\" . $err;\n } else {\n $fp = fopen(ABSPATH.'jwp.xml', 'w');\n fwrite($fp, $response);\n fclose($fp);\n }\n\n $xml = simplexml_load_file(ABSPATH.'jwp.xml');\n\n for($i = count($xml->channel->item); $i >= 2; $i--){\n unset($xml->channel->item[$i]);\n }\n\n $xml->saveXML(ABSPATH.'jwp.xml');\n\n ?>\n <script src=\"https://content.jwplatform.com/libraries/FZ8yNTef.js\"></script>\n <center><div id=\"podcast\" align=\"center\"></div></center> \n <script> \n var PodcastplayerInstance = jwplayer(\"podcast\"); \n PodcastplayerInstance.setup({ \n playlist: \"<?php echo site_url(); ?>/jwp.xml\", \n androidhls: true, \n preload: \"auto\", \n height: 200, \n width: 400,\n visualplaylist:false,\n stretching: \"fill\",\n \"plugins\": {\n \"http://www.cpac.ca/tip-podcast/listy.js\":{},\n 'viral-2': {'oncomplete':'False','onpause':'False','functions':'All'}\n }\n });\n </script> \n</code></pre>\n\n<p>In case you want the 2nd or 3rd element only, update the above code with the following</p>\n\n<pre><code>for($i = count($xml->channel->item); $i >= 3; $i--){\n unset($xml->channel->item[$i]);\n}\n\nfor($i = 0; $i < count($xml->channel->item); $i++){\n unset($xml->channel->item[0]);\n}\n</code></pre>\n"
}
] | 2019/03/31 | [
"https://wordpress.stackexchange.com/questions/333071",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143115/"
] | I am working on a wordpress shortcodes in which I want to the limit the content coming from a xml.
The code which I have used for wordpress shortcodes is:
```
function podcast_func( $content = null ){
ob_start();
?>
<script src="https://content.jwplatform.com/libraries/FZ8yNTef.js"></script>
<center><div id="podcast" align="center"></div></center>
<script>
var PodcastplayerInstance = jwplayer("podcast");
PodcastplayerInstance.setup({
playlist: "http://www.cpac.ca/tip-podcast/jwplayer.xml",
androidhls: true,
preload: "auto",
height: 200,
width: 400,
visualplaylist:false,
stretching: "fill",
"plugins": {
"http://www.cpac.ca/tip-podcast/listy.js":{},
'viral-2': {'oncomplete':'False','onpause':'False','functions':'All'}
}
});
</script>
<?PHP
return ob_get_clean();
}
add_shortcode( 'podcast', 'podcast_func' );
```
On using this `<div class="today-podcast" style="text-align: center;">[podcast]</div>`, it displays the entire content from here <http://www.cpac.ca/tip-podcast/jwplayer.xml>
**Problem Statement:** I am wondering what changes I should make in the wordpress shortcode above so that it displays only 1st two items from here <http://www.cpac.ca/tip-podcast/jwplayer.xml> | It's better to 1st save the returned XML to a file and then loop back to unset.
```
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://www.cpac.ca/tip-podcast/jwplayer.xml",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"postman-token: 28025ee8-1e82-ce60-f6ae-f401118baa1c"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
$fp = fopen(ABSPATH.'jwp.xml', 'w');
fwrite($fp, $response);
fclose($fp);
}
$xml = simplexml_load_file(ABSPATH.'jwp.xml');
for($i = count($xml->channel->item); $i >= 2; $i--){
unset($xml->channel->item[$i]);
}
$xml->saveXML(ABSPATH.'jwp.xml');
?>
<script src="https://content.jwplatform.com/libraries/FZ8yNTef.js"></script>
<center><div id="podcast" align="center"></div></center>
<script>
var PodcastplayerInstance = jwplayer("podcast");
PodcastplayerInstance.setup({
playlist: "<?php echo site_url(); ?>/jwp.xml",
androidhls: true,
preload: "auto",
height: 200,
width: 400,
visualplaylist:false,
stretching: "fill",
"plugins": {
"http://www.cpac.ca/tip-podcast/listy.js":{},
'viral-2': {'oncomplete':'False','onpause':'False','functions':'All'}
}
});
</script>
```
In case you want the 2nd or 3rd element only, update the above code with the following
```
for($i = count($xml->channel->item); $i >= 3; $i--){
unset($xml->channel->item[$i]);
}
for($i = 0; $i < count($xml->channel->item); $i++){
unset($xml->channel->item[0]);
}
``` |
333,090 | <p>I have 16 published posts of type "portfolio".
With the query below, "found_posts" is 16. Correct so far.</p>
<p>I've set "posts_per_page" to -1 to see all of them. But only 8 of them get rendered. The wordpress setting posts per page is 10, so this cant be the issues. There is also no multilingual plugin like WPML working.</p>
<p>What am i doing wrong?</p>
<pre><code>function portfolio_filter(){
$query = new WP_Query( array( 'posts_per_page' => -1,'post_status' => 'publish', 'post_type' => 'portfolio') );
$output = $query->found_posts; // Returns 16
if ( $query->have_posts() ) :
while ( $query->have_posts() ) {
$query->the_post();
$output.='<div class="entry filter_product">';
$output.=get_the_post_thumbnail($query->the_post()->ID,'medium');
$output.='<h3 class="title">'.get_the_title().'</h3>';
$output.='</div>';
}
wp_reset_postdata();
else :
//show 404 error here -->
endif;
return $output;
</code></pre>
<p>}</p>
| [
{
"answer_id": 333091,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 2,
"selected": true,
"text": "<p>But all of them get obtained from the database.</p>\n\n<p>The problem is that you’re ignoring half of them. Or rather merging two of them and displaying as one.</p>\n\n<p>Let’s take a look at your code:</p>\n\n<pre><code>while ( $query->have_posts() ) { \n $query->the_post(); // <- here you call the_post() first time\n\n $output.='<div class=\"entry filter_product\">';\n // and in the next line you call the_post second time\n $output.=get_the_post_thumbnail($query->the_post()->ID,'medium');\n $output.='<h3 class=\"title\">'.get_the_title().'</h3>';\n $output.='</div>';\n}\n</code></pre>\n\n<p>Every time you call the_post method, you tell the loop to go to the next post. So if you call the_post twice in one loop, then you’ll be skipping by two posts, not by one.</p>\n\n<p>You should change this line:</p>\n\n<pre><code>$output.=get_the_post_thumbnail($query->the_post()->ID,'medium');\n</code></pre>\n\n<p>To this:</p>\n\n<pre><code>$output.=get_the_post_thumbnail(get_the_ID(),'medium');\n</code></pre>\n"
},
{
"answer_id": 333092,
"author": "Tanmay Patel",
"author_id": 62026,
"author_profile": "https://wordpress.stackexchange.com/users/62026",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>Hope this code may help you.</p>\n</blockquote>\n\n<pre><code><?php\nfunction portfolio_filter(){\n$args = array(\n 'post_type' => 'portfolio',\n 'post_status' => 'publish',\n 'posts_per_page' => -1,\n);\n$query = new WP_Query( $args );\nif ( $query->have_posts() ) :\nwhile($query->have_posts()) : $query->the_post(); ?>\n <div class=\"entry filter_product\">\n <?php the_post_thumbnail( 'medium' ); ?>\n <h3 class=\"title\"><?php echo get_the_title(); ?></h3>\n </div>\n<?php endwhile;\nwp_reset_postdata();\nelse : ?>\n <p>No Posts Found.</p>\n<?php endif;\n}\n?>\n</code></pre>\n"
}
] | 2019/04/01 | [
"https://wordpress.stackexchange.com/questions/333090",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/134335/"
] | I have 16 published posts of type "portfolio".
With the query below, "found\_posts" is 16. Correct so far.
I've set "posts\_per\_page" to -1 to see all of them. But only 8 of them get rendered. The wordpress setting posts per page is 10, so this cant be the issues. There is also no multilingual plugin like WPML working.
What am i doing wrong?
```
function portfolio_filter(){
$query = new WP_Query( array( 'posts_per_page' => -1,'post_status' => 'publish', 'post_type' => 'portfolio') );
$output = $query->found_posts; // Returns 16
if ( $query->have_posts() ) :
while ( $query->have_posts() ) {
$query->the_post();
$output.='<div class="entry filter_product">';
$output.=get_the_post_thumbnail($query->the_post()->ID,'medium');
$output.='<h3 class="title">'.get_the_title().'</h3>';
$output.='</div>';
}
wp_reset_postdata();
else :
//show 404 error here -->
endif;
return $output;
```
} | But all of them get obtained from the database.
The problem is that you’re ignoring half of them. Or rather merging two of them and displaying as one.
Let’s take a look at your code:
```
while ( $query->have_posts() ) {
$query->the_post(); // <- here you call the_post() first time
$output.='<div class="entry filter_product">';
// and in the next line you call the_post second time
$output.=get_the_post_thumbnail($query->the_post()->ID,'medium');
$output.='<h3 class="title">'.get_the_title().'</h3>';
$output.='</div>';
}
```
Every time you call the\_post method, you tell the loop to go to the next post. So if you call the\_post twice in one loop, then you’ll be skipping by two posts, not by one.
You should change this line:
```
$output.=get_the_post_thumbnail($query->the_post()->ID,'medium');
```
To this:
```
$output.=get_the_post_thumbnail(get_the_ID(),'medium');
``` |
333,130 | <p>i called wordpress function between the shorcodes as a input. </p>
<pre><code><?php echo do_shortcode('[shortcode]'.$var.'[/shortcode]');?>
</code></pre>
<p>how to add div class for the $var here?</p>
<p>I tried few combination but it works for the full shortcode. i just want to use the div only for $var.</p>
<p>I tried like,</p>
<pre><code><?php echo '<div class="own">', do_shortcode( '[shortcode]'.$var.'[/shortcode]'), '</div>' ; ?>
</code></pre>
<p>How to add div class only for $var here?</p>
| [
{
"answer_id": 333131,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>How to add div class <strong>only for $var</strong> here?</p>\n</blockquote>\n\n<p>Try this</p>\n\n<pre><code><?php \n echo do_shortcode( '[shortcode]<div class=\"own\">'.$var.'</div>[/shortcode]'), ; \n?>\n</code></pre>\n"
},
{
"answer_id": 333135,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 3,
"selected": true,
"text": "<p>It's a bit difficult to understand or provide an accurate answer as we don't know what the shortcode is executing. Is it stripping html or any other parsing? </p>\n\n<p>If this is your own code, then you could add it in the function the shortcode is calling.</p>\n\n<p>If its not you could try a couple options:</p>\n\n<p>1: (adding the div directly into the shortcode call)</p>\n\n<pre><code><?php echo do_shortcode( '[shortcode]<div>'.$var.'</div>[/shortcode]'), ; ?>\n</code></pre>\n\n<p>2: add it to the <code>$var</code> first:</p>\n\n<pre><code><?php \n $dvar = '<div class=\"own\">'.$var.'</div>';\n echo do_shortcode('[shortcode]'.$dvar.'[/shortcode]');\n?>\n</code></pre>\n\n<p>Again, the ideal solution would be to see that function and then put the div directly in before the shortcode is executed.</p>\n"
}
] | 2019/04/01 | [
"https://wordpress.stackexchange.com/questions/333130",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/5669/"
] | i called wordpress function between the shorcodes as a input.
```
<?php echo do_shortcode('[shortcode]'.$var.'[/shortcode]');?>
```
how to add div class for the $var here?
I tried few combination but it works for the full shortcode. i just want to use the div only for $var.
I tried like,
```
<?php echo '<div class="own">', do_shortcode( '[shortcode]'.$var.'[/shortcode]'), '</div>' ; ?>
```
How to add div class only for $var here? | It's a bit difficult to understand or provide an accurate answer as we don't know what the shortcode is executing. Is it stripping html or any other parsing?
If this is your own code, then you could add it in the function the shortcode is calling.
If its not you could try a couple options:
1: (adding the div directly into the shortcode call)
```
<?php echo do_shortcode( '[shortcode]<div>'.$var.'</div>[/shortcode]'), ; ?>
```
2: add it to the `$var` first:
```
<?php
$dvar = '<div class="own">'.$var.'</div>';
echo do_shortcode('[shortcode]'.$dvar.'[/shortcode]');
?>
```
Again, the ideal solution would be to see that function and then put the div directly in before the shortcode is executed. |
333,138 | <p>I'm trying to remove the infinite-wrap class jetpack adds to posts with infinite scroll turned on because I want to add infinitely loaded posts to a gridded layout.</p>
<p>I found the article here that says to add the theme support stuff to the functions.php :<a href="https://trickspanda.com/customize-jetpack-infinite-scroll/" rel="nofollow noreferrer">https://trickspanda.com/customize-jetpack-infinite-scroll/</a></p>
<p>I ended up adding</p>
<pre><code>add_theme_support( 'infinite-scroll', array(
'wrapper' => false,
) );
</code></pre>
<p>The weird thing is this has no effect. I have jetpack installed as a plugin and turned on infinite scroll the the settings in the dashboard. Am I doing something wrong? This seems like it should be easy...</p>
| [
{
"answer_id": 333210,
"author": "Tiago Hillebrandt",
"author_id": 44840,
"author_profile": "https://wordpress.stackexchange.com/users/44840",
"pm_score": 1,
"selected": false,
"text": "<p>What if you remove the existing infinite-scroll before re-add it?</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>remove_theme_support( 'infinite-scroll' );\n\nadd_theme_support(\n 'infinite-scroll',\n array(\n 'wrapper' => false,\n )\n);\n</code></pre>\n"
},
{
"answer_id": 333260,
"author": "Garrett Scafani",
"author_id": 103174,
"author_profile": "https://wordpress.stackexchange.com/users/103174",
"pm_score": 1,
"selected": true,
"text": "<p>Since I was using the underscores.me theme, I had to look in the 'inc' folder for the jetpack.php file. There is where I had to change the options to get the desired effect.</p>\n"
}
] | 2019/04/01 | [
"https://wordpress.stackexchange.com/questions/333138",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103174/"
] | I'm trying to remove the infinite-wrap class jetpack adds to posts with infinite scroll turned on because I want to add infinitely loaded posts to a gridded layout.
I found the article here that says to add the theme support stuff to the functions.php :<https://trickspanda.com/customize-jetpack-infinite-scroll/>
I ended up adding
```
add_theme_support( 'infinite-scroll', array(
'wrapper' => false,
) );
```
The weird thing is this has no effect. I have jetpack installed as a plugin and turned on infinite scroll the the settings in the dashboard. Am I doing something wrong? This seems like it should be easy... | Since I was using the underscores.me theme, I had to look in the 'inc' folder for the jetpack.php file. There is where I had to change the options to get the desired effect. |
333,149 | <p>in my <code>functions.php</code> I have</p>
<pre><code>require 'autoloader.php';
add_action('init', 'MyClass::make');
</code></pre>
<p>and in my <code>MyClass</code> class I have</p>
<pre class="lang-php prettyprint-override"><code>class MyClass {
public static function make($type) {
var_dump($type);die;
}
}
</code></pre>
<p>but the output of <code>var_dump</code> is <code>string(0) ""</code>. What I want is to pass the argument to this class as <code>$type</code>. What I tried was to pass it through <code>do_action</code> however I think it is not best practice.</p>
<p>How can I pass argument to a method which is inside a class for <code>add_action</code>?</p>
| [
{
"answer_id": 333160,
"author": "phatskat",
"author_id": 20143,
"author_profile": "https://wordpress.stackexchange.com/users/20143",
"pm_score": 0,
"selected": false,
"text": "<p>The <code>init</code> hook doesn't pass any parameters - when you call <code>add_action</code>, <code>init</code> isn't passing anything to <code>make</code>.</p>\n\n<p>You could just call <code>make</code> outright:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>require 'autoloader.php';\nMyClass::make( <whatever );\n</code></pre>\n\n<p>If you need to do this on <code>init</code>, set up a callback function:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>\nfunction add_my_type() {\n MyClass::make( <foo> );\n}\n\nadd_action( 'init', 'add_my_type' );\n</code></pre>\n"
},
{
"answer_id": 333208,
"author": "Tiago Hillebrandt",
"author_id": 44840,
"author_profile": "https://wordpress.stackexchange.com/users/44840",
"pm_score": 1,
"selected": false,
"text": "<p>Here's another example on how you could implement the <code>add_action</code>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$type = 'my_sample_type';\n\nadd_action(\n 'init',\n function() use ( $type ) {\n MyClass::make( $type );\n }\n);\n</code></pre>\n"
}
] | 2019/04/01 | [
"https://wordpress.stackexchange.com/questions/333149",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/164241/"
] | in my `functions.php` I have
```
require 'autoloader.php';
add_action('init', 'MyClass::make');
```
and in my `MyClass` class I have
```php
class MyClass {
public static function make($type) {
var_dump($type);die;
}
}
```
but the output of `var_dump` is `string(0) ""`. What I want is to pass the argument to this class as `$type`. What I tried was to pass it through `do_action` however I think it is not best practice.
How can I pass argument to a method which is inside a class for `add_action`? | Here's another example on how you could implement the `add_action`:
```php
$type = 'my_sample_type';
add_action(
'init',
function() use ( $type ) {
MyClass::make( $type );
}
);
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.