qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
264,446 | <p>I use TinyMce on my customizer (for obv reasons).
But i encounter a problem that i do not seem to have the answer to.
Let me first share you my code that are crucial:</p>
<p><strong>Functions.php</strong></p>
<pre><code>// text editor
if ( ! class_exists( 'WP_Customize_Control' ) )
return NULL;
/**
* Class to create a custom tags control
*/
class Text_Editor_Custom_Control extends WP_Customize_Control
{
/**
* Render the content on the theme customizer page
*/
public function render_content()
{
?>
<label>
<span class="customize-text_editor"><?php echo esc_html( $this->label ); ?></span>
<input class="wp-editor-area" type="hidden" <?php $this->link(); ?> value="<?php echo esc_textarea( $this->value() ); ?>">
<?php
$settings = array(
'textarea_name' => $this->id,
'media_buttons' => false,
'drag_drop_upload' => false,
'teeny' => true,
'quicktags' => false,
'textarea_rows' => 5,
);
$this->filter_editor_setting_link();
wp_editor($this->value(), $this->id, $settings );
?>
</label>
<?php
do_action('admin_footer');
do_action('admin_print_footer_scripts');
}
private function filter_editor_setting_link() {
add_filter( 'the_editor', function( $output ) { return preg_replace( '/<textarea/', '<textarea ' . $this->get_link(), $output, 1 ); } );
}
}
function editor_customizer_script() {
wp_enqueue_script( 'wp-editor-customizer', get_template_directory_uri() . '/inc/customizer.js', array( 'jquery' ), rand(), true );
}
add_action( 'customize_controls_enqueue_scripts', 'editor_customizer_script' );
</code></pre>
<p><strong>Customizer.php</strong></p>
<pre><code> // content 1 text
$wp_customize->add_setting('home_content1_text', array(
'default' => 'Here goes an awesome title!',
'transport' => 'postMessage',
));
$wp_customize->add_control(new Text_Editor_Custom_Control( $wp_customize, 'home_content1_text', array(
'label' => __('Text content 1', 'DesignitMultistore'),
'section' => 'home_content_1',
'description' => __('Here you can add a title for your content', 'DesignitMultistore'),
'priority' => 5,
)));
//slider text 1 control
$wp_customize->add_setting('slider_text_1', array(
'default' => _x('Welcome to the Designit Multistore theme for Wordpress', 'DesignitMultistore'),
'transport' => 'postMessage',
));
$wp_customize->add_control(new Text_Editor_Custom_Control( $wp_customize, 'slider_text_1', array(
'description' => __('The text for first image for the slider', 'DesignitMultistore'),
'label' => __('Slider Text 1', 'DesignitMultistore'),
'section' => 'Designit_slider_slide1',
'priority' => 3,
)));
</code></pre>
<p><strong>Customizer.JS</strong></p>
<pre><code> ( function( $ ) {
wp.customizerCtrlEditor = {
init: function() {
$(window).load(function(){
var adjustArea = $('textarea.wp-editor-area');
adjustArea.each(function(){
var tArea = $(this),
id = tArea.attr('id'),
input = $('input[data-customize-setting-link="'+ id +'"]'),
editor = tinyMCE.get(id),
setChange,
content;
if(editor){
editor.onChange.add(function (ed, e) {
ed.save();
content = editor.getContent();
clearTimeout(setChange);
setChange = setTimeout(function(){
input.val(content).trigger('change');
},500);
});
}
if(editor){
editor.onChange.add(function (ed, e) {
ed.save();
content = editor.getContent();
clearTimeout(setChange);
setChange = setTimeout(function(){
input.val(content).trigger('change');
},500);
});
}
tArea.css({
visibility: 'visible'
}).on('keyup', function(){
content = tArea.val();
clearTimeout(setChange);
setChange = setTimeout(function(){
input.val(content).trigger('change');
},500);
});
});
});
}
};
wp.customizerCtrlEditor.init();
} )( jQuery );
</code></pre>
<p><strong>Now the problem</strong></p>
<p>Everything seems to work fine. I do have an TinyMce editor.
Its not registering that something has been changed. And when i change something else and save it along with the changes is not saved either.</p>
<p>Does someone have a working example of a RTE or TinyMce editor that replaces the textarea's on the customizer?</p>
<p><strong>Update</strong></p>
<p>Only the last instance that i define in my customizer.php works. By now i have 14 textarea's. The text area works fine on the 14th but not on 1-13th</p>
<p><strong>UPDATE 2</strong></p>
<p>It seems that for each area that remains he creates that number of tinymce's within that area. So the first area has 14 tinymce's overlapping eachother. The second 13 ; the thirth 14 etc etc. Until the last has only 1 and therefor working</p>
| [
{
"answer_id": 264636,
"author": "CompactCode",
"author_id": 118063,
"author_profile": "https://wordpress.stackexchange.com/users/118063",
"pm_score": 3,
"selected": true,
"text": "<p>My problem has been \"solved\" by doing the following :</p>\n\n<p>The problem is that do_action is getting called each time that i have a new class. But it needs to be called only in the last. Otherwise this creates a bunch of admin_print_footer_scripts.</p>\n\n<p>Since i'm writing the code myself and i don't intend on selling this for now i can just count the number of new class instances i create. Which is 14 at this point.</p>\n\n<p>So i altered it like this :</p>\n\n<p><strong>Functions.php</strong></p>\n\n<pre><code>class Text_Editor_Custom_Control extends WP_Customize_Control\n{\n\n /**\n * Render the content on the theme customizer page\n */\n public function render_content()\n {\n static $i = 1;\n ?>\n <label>\n <span class=\"customize-text_editor\"><?php echo esc_html( $this->label ); ?></span>\n <input class=\"wp-editor-area\" type=\"hidden\" <?php $this->link(); ?> value=\"<?php echo esc_textarea( $this->value() ); ?>\">\n <?php\n $content = $this->value();\n $editor_id = $this->id;\n $settings = array(\n 'textarea_name' => $this->id,\n 'media_buttons' => false,\n 'drag_drop_upload' => false,\n 'teeny' => true,\n 'quicktags' => false,\n 'textarea_rows' => 5,\n );\n wp_editor($content, $editor_id, $settings );\n\n\n if( $i == 14) {\n do_action('admin_print_footer_scripts');\n }\n $i++;\n\n ?>\n </label>\n <?php\n }\n};\n\nfunction editor_customizer_script() {\n wp_enqueue_script( 'wp-editor-customizer', get_template_directory_uri() . '/inc/customizer.js', array( 'jquery' ), false, true );\n}\nadd_action( 'customize_controls_enqueue_scripts', 'editor_customizer_script' );\n</code></pre>\n\n<p>If someone knows how i can count the times i call that new class in my customizer and use it in my functions.php to know when the last time its called i can call the do_action... It would help a lot</p>\n"
},
{
"answer_id": 265359,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 0,
"selected": false,
"text": "<p>Looks like I'm a bit too late for the answer, but as far as the count you could use this: (add the counter and __construct() to the top of your class for actual use) NOT tested but should be good to go.</p>\n\n<pre><code><?php\nclass Text_Editor_Custom_Control {\n public static $counter = 0;\n\n function __construct() {\n self::$counter++;\n self::$lastcall= date('Y-m-d H:i:s');\n }\n}\n\nnew Text_Editor_Custom_Control();\nnew Text_Editor_Custom_Control();\nnew Text_Editor_Custom_Control();\n\necho Text_Editor_Custom_Control::$counter; //would be 3\n\necho Text_Editor_Custom_Control::$counter; //shows datetime of last call\n?>\n</code></pre>\n"
},
{
"answer_id": 265592,
"author": "Tom Groot",
"author_id": 118863,
"author_profile": "https://wordpress.stackexchange.com/users/118863",
"pm_score": 0,
"selected": false,
"text": "<p>The problem lies inside <code>customizer.js</code> where you try to select the <code>.wp-editor-area</code>. However the <code>input[data-customize-setting-link=\"'+ id +'\"]</code> does not select this input because the <code>id</code> returns the <code>control</code> instead of the <code>setting</code>.</p>\n\n<p><strong>To fix this</strong> </p>\n\n<p>give the input <code>.wp-editor-area</code> an id <code>id=\"tinymce-input\"</code> </p>\n\n<p>and use it to select this input in your <code>customizer.js</code> by changing <code>input = $('input[data-customize-setting-link=\"'+ id +'\"]')</code> into <code>input = $('#tinymce-input')</code></p>\n"
},
{
"answer_id": 274333,
"author": "ips",
"author_id": 124419,
"author_profile": "https://wordpress.stackexchange.com/users/124419",
"pm_score": 2,
"selected": false,
"text": "<p>SwAt.Be, your own answer helped me a bunch and I've nailed the problem of printing admin scripts after the last rendition of wp_editor. Also see how I pass JS setup function as tinymce option to sync the editor changes with WP customizer to make it work properly.</p>\n\n\n\n<pre class=\"lang-php prettyprint-override\"><code>if (class_exists('WP_Customize_Control')) {\n class WP_Customize_Teeny_Control extends WP_Customize_Control {\n function __construct($manager, $id, $options) {\n parent::__construct($manager, $id, $options);\n\n global $num_customizer_teenies_initiated;\n $num_customizer_teenies_initiated = empty($num_customizer_teenies_initiated)\n ? 1\n : $num_customizer_teenies_initiated + 1;\n }\n function render_content() {\n global $num_customizer_teenies_initiated, $num_customizer_teenies_rendered;\n $num_customizer_teenies_rendered = empty($num_customizer_teenies_rendered)\n ? 1\n : $num_customizer_teenies_rendered + 1;\n\n $value = $this->value();\n ?>\n <label>\n <span class=\"customize-text_editor\"><?php echo esc_html($this->label); ?></span>\n <input id=\"<?php echo $this->id ?>-link\" class=\"wp-editor-area\" type=\"hidden\" <?php $this->link(); ?> value=\"<?php echo esc_textarea($value); ?>\">\n <?php\n wp_editor($value, $this->id, [\n 'textarea_name' => $this->id,\n 'media_buttons' => false,\n 'drag_drop_upload' => false,\n 'teeny' => true,\n 'quicktags' => false,\n 'textarea_rows' => 5,\n // MAKE SURE TINYMCE CHANGES ARE LINKED TO CUSTOMIZER\n 'tinymce' => [\n 'setup' => \"function (editor) {\n var cb = function () {\n var linkInput = document.getElementById('$this->id-link')\n linkInput.value = editor.getContent()\n linkInput.dispatchEvent(new Event('change'))\n }\n editor.on('Change', cb)\n editor.on('Undo', cb)\n editor.on('Redo', cb)\n editor.on('KeyUp', cb) // Remove this if it seems like an overkill\n }\"\n ]\n ]);\n ?>\n </label>\n <?php\n // PRINT THEM ADMIN SCRIPTS AFTER LAST EDITOR\n if ($num_customizer_teenies_rendered == $num_customizer_teenies_initiated)\n do_action('admin_print_footer_scripts');\n }\n }\n}\n\n// TRY IT\nadd_action('customize_register', function ($wp_customize) {\n $wp_customize->add_section('footer_section' , [\n 'title' => __('Footer', 'musiccase'),\n 'priority' => 100\n ]);\n\n // 1st EDITOR\n $wp_customize->add_setting('footer_contact', [\n 'type' => 'option'\n ]);\n $wp_customize->add_control(new WP_Customize_Teeny_Control($wp_customize, 'footer_contact', [\n 'label' => __('Contact Info', 'musiccase'),\n 'section' => 'footer_section'\n ]));\n\n // 2nd EDITOR\n $wp_customize->add_setting('footer_contact_2', [\n 'type' => 'option'\n ]);\n $wp_customize->add_control(new WP_Customize_Teeny_Control($wp_customize, 'footer_contact_2', [\n 'label' => __('Contact Info 2', 'musiccase'),\n 'section' => 'footer_section'\n ]));\n}, 20);\n</code></pre>\n"
}
]
| 2017/04/21 | [
"https://wordpress.stackexchange.com/questions/264446",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118063/"
]
| I use TinyMce on my customizer (for obv reasons).
But i encounter a problem that i do not seem to have the answer to.
Let me first share you my code that are crucial:
**Functions.php**
```
// text editor
if ( ! class_exists( 'WP_Customize_Control' ) )
return NULL;
/**
* Class to create a custom tags control
*/
class Text_Editor_Custom_Control extends WP_Customize_Control
{
/**
* Render the content on the theme customizer page
*/
public function render_content()
{
?>
<label>
<span class="customize-text_editor"><?php echo esc_html( $this->label ); ?></span>
<input class="wp-editor-area" type="hidden" <?php $this->link(); ?> value="<?php echo esc_textarea( $this->value() ); ?>">
<?php
$settings = array(
'textarea_name' => $this->id,
'media_buttons' => false,
'drag_drop_upload' => false,
'teeny' => true,
'quicktags' => false,
'textarea_rows' => 5,
);
$this->filter_editor_setting_link();
wp_editor($this->value(), $this->id, $settings );
?>
</label>
<?php
do_action('admin_footer');
do_action('admin_print_footer_scripts');
}
private function filter_editor_setting_link() {
add_filter( 'the_editor', function( $output ) { return preg_replace( '/<textarea/', '<textarea ' . $this->get_link(), $output, 1 ); } );
}
}
function editor_customizer_script() {
wp_enqueue_script( 'wp-editor-customizer', get_template_directory_uri() . '/inc/customizer.js', array( 'jquery' ), rand(), true );
}
add_action( 'customize_controls_enqueue_scripts', 'editor_customizer_script' );
```
**Customizer.php**
```
// content 1 text
$wp_customize->add_setting('home_content1_text', array(
'default' => 'Here goes an awesome title!',
'transport' => 'postMessage',
));
$wp_customize->add_control(new Text_Editor_Custom_Control( $wp_customize, 'home_content1_text', array(
'label' => __('Text content 1', 'DesignitMultistore'),
'section' => 'home_content_1',
'description' => __('Here you can add a title for your content', 'DesignitMultistore'),
'priority' => 5,
)));
//slider text 1 control
$wp_customize->add_setting('slider_text_1', array(
'default' => _x('Welcome to the Designit Multistore theme for Wordpress', 'DesignitMultistore'),
'transport' => 'postMessage',
));
$wp_customize->add_control(new Text_Editor_Custom_Control( $wp_customize, 'slider_text_1', array(
'description' => __('The text for first image for the slider', 'DesignitMultistore'),
'label' => __('Slider Text 1', 'DesignitMultistore'),
'section' => 'Designit_slider_slide1',
'priority' => 3,
)));
```
**Customizer.JS**
```
( function( $ ) {
wp.customizerCtrlEditor = {
init: function() {
$(window).load(function(){
var adjustArea = $('textarea.wp-editor-area');
adjustArea.each(function(){
var tArea = $(this),
id = tArea.attr('id'),
input = $('input[data-customize-setting-link="'+ id +'"]'),
editor = tinyMCE.get(id),
setChange,
content;
if(editor){
editor.onChange.add(function (ed, e) {
ed.save();
content = editor.getContent();
clearTimeout(setChange);
setChange = setTimeout(function(){
input.val(content).trigger('change');
},500);
});
}
if(editor){
editor.onChange.add(function (ed, e) {
ed.save();
content = editor.getContent();
clearTimeout(setChange);
setChange = setTimeout(function(){
input.val(content).trigger('change');
},500);
});
}
tArea.css({
visibility: 'visible'
}).on('keyup', function(){
content = tArea.val();
clearTimeout(setChange);
setChange = setTimeout(function(){
input.val(content).trigger('change');
},500);
});
});
});
}
};
wp.customizerCtrlEditor.init();
} )( jQuery );
```
**Now the problem**
Everything seems to work fine. I do have an TinyMce editor.
Its not registering that something has been changed. And when i change something else and save it along with the changes is not saved either.
Does someone have a working example of a RTE or TinyMce editor that replaces the textarea's on the customizer?
**Update**
Only the last instance that i define in my customizer.php works. By now i have 14 textarea's. The text area works fine on the 14th but not on 1-13th
**UPDATE 2**
It seems that for each area that remains he creates that number of tinymce's within that area. So the first area has 14 tinymce's overlapping eachother. The second 13 ; the thirth 14 etc etc. Until the last has only 1 and therefor working | My problem has been "solved" by doing the following :
The problem is that do\_action is getting called each time that i have a new class. But it needs to be called only in the last. Otherwise this creates a bunch of admin\_print\_footer\_scripts.
Since i'm writing the code myself and i don't intend on selling this for now i can just count the number of new class instances i create. Which is 14 at this point.
So i altered it like this :
**Functions.php**
```
class Text_Editor_Custom_Control extends WP_Customize_Control
{
/**
* Render the content on the theme customizer page
*/
public function render_content()
{
static $i = 1;
?>
<label>
<span class="customize-text_editor"><?php echo esc_html( $this->label ); ?></span>
<input class="wp-editor-area" type="hidden" <?php $this->link(); ?> value="<?php echo esc_textarea( $this->value() ); ?>">
<?php
$content = $this->value();
$editor_id = $this->id;
$settings = array(
'textarea_name' => $this->id,
'media_buttons' => false,
'drag_drop_upload' => false,
'teeny' => true,
'quicktags' => false,
'textarea_rows' => 5,
);
wp_editor($content, $editor_id, $settings );
if( $i == 14) {
do_action('admin_print_footer_scripts');
}
$i++;
?>
</label>
<?php
}
};
function editor_customizer_script() {
wp_enqueue_script( 'wp-editor-customizer', get_template_directory_uri() . '/inc/customizer.js', array( 'jquery' ), false, true );
}
add_action( 'customize_controls_enqueue_scripts', 'editor_customizer_script' );
```
If someone knows how i can count the times i call that new class in my customizer and use it in my functions.php to know when the last time its called i can call the do\_action... It would help a lot |
264,479 | <p>I want to remove the page name from displaying in my browser's tab. How do I hide the page name and only show the name of my website?</p>
<p><a href="https://i.stack.imgur.com/EFpCB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EFpCB.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 264480,
"author": "JItendra Rana",
"author_id": 87433,
"author_profile": "https://wordpress.stackexchange.com/users/87433",
"pm_score": 2,
"selected": true,
"text": "<p>You can either use this code in your function.php </p>\n\n<pre><code>remove_all_filters( 'wp_title' );\nadd_filter('wp_title', 'filter_pagetitle', 99,1);\nfunction filter_pagetitle($title) {\n $title = get_bloginfo('name');\n return $title;\n}\n</code></pre>\n\n<p>Or install plugin like <a href=\"https://wordpress.org/plugins/wordpress-seo/\" rel=\"nofollow noreferrer\">Yoast SEO</a>.</p>\n\n<hr>\n\n<p>EDIT : Screenshot </p>\n\n<p><a href=\"https://i.stack.imgur.com/omFm7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/omFm7.png\" alt=\"enter image description here\"></a></p>\n\n<hr>\n\n<p>UPDATE : Change header.php in your theme folder if above solution doesn't work for you. </p>\n\n<p><code><title><?php get_bloginfo('name'); ?></title></code></p>\n"
},
{
"answer_id": 311682,
"author": "Dave Sieving",
"author_id": 148883,
"author_profile": "https://wordpress.stackexchange.com/users/148883",
"pm_score": 0,
"selected": false,
"text": "<ul>\n<li>Setting Site Title in Wordpress: failed</li>\n<li>Editing function.php: not found</li>\n<li>Using All-in-one SEO plugin: failed</li>\n<li>Editing header.php: Worked!</li>\n</ul>\n\n<p>This is what worked for me. Your mileage may vary.</p>\n\n<p>Please understand that this site does not support HTML, so I've substituted square brackets for angle brackets and '(amp)' for ampersand.</p>\n\n<ol>\n<li>Edit the following file:</li>\n</ol>\n\n<pre>\n\n (your_blog)/wp-content/themes/(your_theme)/header.php\n\n</pre>\n\n<ol start=\"2\">\n<li>Find the line:</li>\n</ol>\n\n<pre>\n\n [meta http-equiv=\"Content-Type\" content=\"[?php bloginfo('html_type'); ?]; charset=[?php bloginfo('charset'); ?]\" /]\n\n</pre>\n\n<ol start=\"3\">\n<li>Add the following line after the line shown above. I copied mine from my other WordPress blog that didn't have this problem - (the advantages of dual redundancy).</li>\n</ol>\n\n<pre>\n\n [title][?php wp_title('(amp)laquo;', true, 'right'); ?] [?php bloginfo('name'); ?][/title]\n\n</pre>\n\n<ol start=\"4\">\n<li><p>Save the file and upload it to the same place on your website.</p></li>\n<li><p>Reload your blog site and hope something else isn't overwriting your site name.</p></li>\n</ol>\n"
}
]
| 2017/04/22 | [
"https://wordpress.stackexchange.com/questions/264479",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108734/"
]
| I want to remove the page name from displaying in my browser's tab. How do I hide the page name and only show the name of my website?
[](https://i.stack.imgur.com/EFpCB.png) | You can either use this code in your function.php
```
remove_all_filters( 'wp_title' );
add_filter('wp_title', 'filter_pagetitle', 99,1);
function filter_pagetitle($title) {
$title = get_bloginfo('name');
return $title;
}
```
Or install plugin like [Yoast SEO](https://wordpress.org/plugins/wordpress-seo/).
---
EDIT : Screenshot
[](https://i.stack.imgur.com/omFm7.png)
---
UPDATE : Change header.php in your theme folder if above solution doesn't work for you.
`<title><?php get_bloginfo('name'); ?></title>` |
264,483 | <p>I am doing the code work for a website that someone else will be managing. I'm worried that just telling them not to use the code editor for appearance or plugins won't be enough to stop them from doing so.</p>
<p>I've tried the standard WordPress <code>add_role( $role, $title, $capability )</code> but I can't figure out what combination of terms will allow them to edit pages, posts, post types, add or remove plugins, add and remove users, AND edit the WordPress customizer. I also want to make sure this user role can't delete users with the administrator role.</p>
<p>This didn't do the job: </p>
<pre><code>add_role( 'sub_admin_role', 'Sub-Admin', array( 'level_7' => true ) );
</code></pre>
| [
{
"answer_id": 264480,
"author": "JItendra Rana",
"author_id": 87433,
"author_profile": "https://wordpress.stackexchange.com/users/87433",
"pm_score": 2,
"selected": true,
"text": "<p>You can either use this code in your function.php </p>\n\n<pre><code>remove_all_filters( 'wp_title' );\nadd_filter('wp_title', 'filter_pagetitle', 99,1);\nfunction filter_pagetitle($title) {\n $title = get_bloginfo('name');\n return $title;\n}\n</code></pre>\n\n<p>Or install plugin like <a href=\"https://wordpress.org/plugins/wordpress-seo/\" rel=\"nofollow noreferrer\">Yoast SEO</a>.</p>\n\n<hr>\n\n<p>EDIT : Screenshot </p>\n\n<p><a href=\"https://i.stack.imgur.com/omFm7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/omFm7.png\" alt=\"enter image description here\"></a></p>\n\n<hr>\n\n<p>UPDATE : Change header.php in your theme folder if above solution doesn't work for you. </p>\n\n<p><code><title><?php get_bloginfo('name'); ?></title></code></p>\n"
},
{
"answer_id": 311682,
"author": "Dave Sieving",
"author_id": 148883,
"author_profile": "https://wordpress.stackexchange.com/users/148883",
"pm_score": 0,
"selected": false,
"text": "<ul>\n<li>Setting Site Title in Wordpress: failed</li>\n<li>Editing function.php: not found</li>\n<li>Using All-in-one SEO plugin: failed</li>\n<li>Editing header.php: Worked!</li>\n</ul>\n\n<p>This is what worked for me. Your mileage may vary.</p>\n\n<p>Please understand that this site does not support HTML, so I've substituted square brackets for angle brackets and '(amp)' for ampersand.</p>\n\n<ol>\n<li>Edit the following file:</li>\n</ol>\n\n<pre>\n\n (your_blog)/wp-content/themes/(your_theme)/header.php\n\n</pre>\n\n<ol start=\"2\">\n<li>Find the line:</li>\n</ol>\n\n<pre>\n\n [meta http-equiv=\"Content-Type\" content=\"[?php bloginfo('html_type'); ?]; charset=[?php bloginfo('charset'); ?]\" /]\n\n</pre>\n\n<ol start=\"3\">\n<li>Add the following line after the line shown above. I copied mine from my other WordPress blog that didn't have this problem - (the advantages of dual redundancy).</li>\n</ol>\n\n<pre>\n\n [title][?php wp_title('(amp)laquo;', true, 'right'); ?] [?php bloginfo('name'); ?][/title]\n\n</pre>\n\n<ol start=\"4\">\n<li><p>Save the file and upload it to the same place on your website.</p></li>\n<li><p>Reload your blog site and hope something else isn't overwriting your site name.</p></li>\n</ol>\n"
}
]
| 2017/04/22 | [
"https://wordpress.stackexchange.com/questions/264483",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118207/"
]
| I am doing the code work for a website that someone else will be managing. I'm worried that just telling them not to use the code editor for appearance or plugins won't be enough to stop them from doing so.
I've tried the standard WordPress `add_role( $role, $title, $capability )` but I can't figure out what combination of terms will allow them to edit pages, posts, post types, add or remove plugins, add and remove users, AND edit the WordPress customizer. I also want to make sure this user role can't delete users with the administrator role.
This didn't do the job:
```
add_role( 'sub_admin_role', 'Sub-Admin', array( 'level_7' => true ) );
``` | You can either use this code in your function.php
```
remove_all_filters( 'wp_title' );
add_filter('wp_title', 'filter_pagetitle', 99,1);
function filter_pagetitle($title) {
$title = get_bloginfo('name');
return $title;
}
```
Or install plugin like [Yoast SEO](https://wordpress.org/plugins/wordpress-seo/).
---
EDIT : Screenshot
[](https://i.stack.imgur.com/omFm7.png)
---
UPDATE : Change header.php in your theme folder if above solution doesn't work for you.
`<title><?php get_bloginfo('name'); ?></title>` |
264,488 | <p>I want to write update query to expire transients . I will upadte their time to 1 in wordpress option table. </p>
<p>My query for update is </p>
<pre><code>$wpdb->update(
'options',
array(
'option_value' => '1', // string
),
array( 'option_name' => '%re_compare%' )
);
</code></pre>
<p>Its not working .
Basically I want to remove / Expire already existing transients. </p>
<p>But if I delete transients from options table they still show in transient manager plugin. So thought to set their expire time to 1 second.</p>
| [
{
"answer_id": 264492,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 1,
"selected": false,
"text": "<p>Transients are not guaranteed to use database at all. They will use object cache if it is enabled.</p>\n\n<p>And since there is no bulk delete in object cache API, effectively there is no reliable way to clear out transients across all possible environments.</p>\n\n<p>There are some <em>performance</em> reasons to clear them out of database (which core is now doing on upgrades), but your program <em>logic</em> should stay away from it.</p>\n\n<p>As for why specifically it fails in your case it is hard to say. You would need to determine what storage is being used and resulting raw SQL query to test.</p>\n"
},
{
"answer_id": 264493,
"author": "JItendra Rana",
"author_id": 87433,
"author_profile": "https://wordpress.stackexchange.com/users/87433",
"pm_score": 0,
"selected": false,
"text": "<p>Try deleting transients following way. It should work. </p>\n\n<pre><code>global $wpdb; \n$sql = 'DELETE FROM ' . $wpdb->options . ' WHERE option_name LIKE \"_transient_%\"'; \n$wpdb->query($sql); \n</code></pre>\n\n<p>Or you can try this plugin to delete expired transients </p>\n\n<p><a href=\"https://wordpress.org/plugins/delete-expired-transients/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/delete-expired-transients/</a></p>\n\n<p><strong>Edit</strong> : To update transient value to 1 use following Query </p>\n\n<pre><code>$sql = 'UPDATE ' . $wpdb->options . ' SET option_value = 1 WHERE option_name LIKE \"_transient_%\"'; \n</code></pre>\n\n<p>I just tried deleting transient data using above query and it deleted 1500+ rows from options table. So quoery should work. May be your site is using object cache to store transient data as pointed out by @Rarst.</p>\n"
}
]
| 2017/04/22 | [
"https://wordpress.stackexchange.com/questions/264488",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105243/"
]
| I want to write update query to expire transients . I will upadte their time to 1 in wordpress option table.
My query for update is
```
$wpdb->update(
'options',
array(
'option_value' => '1', // string
),
array( 'option_name' => '%re_compare%' )
);
```
Its not working .
Basically I want to remove / Expire already existing transients.
But if I delete transients from options table they still show in transient manager plugin. So thought to set their expire time to 1 second. | Transients are not guaranteed to use database at all. They will use object cache if it is enabled.
And since there is no bulk delete in object cache API, effectively there is no reliable way to clear out transients across all possible environments.
There are some *performance* reasons to clear them out of database (which core is now doing on upgrades), but your program *logic* should stay away from it.
As for why specifically it fails in your case it is hard to say. You would need to determine what storage is being used and resulting raw SQL query to test. |
264,498 | <p>I have 2 plugins</p>
<p>1) FAT Gallery</p>
<p>2) Salon Booking</p>
<p>So FAT Gallery has a certain js lib (select2) which conflicts with Salon Booking Settings page.</p>
<p>In this URL</p>
<pre><code>example.com/wp-admin/post-new.php?post_type=sln_booking
</code></pre>
<p>I'm trying to <code>DISABLE</code> the FAT Gallery because it causes js error and i cant do my job.</p>
<p>Any idea of how to block it ONLY on the certain page?</p>
<p>Thanks a lot!</p>
| [
{
"answer_id": 264501,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 3,
"selected": true,
"text": "<p>That's pretty easy.</p>\n\n<p>Remember, I don't know exactly what's the plugin's file name and directory, and the following code was not tested.</p>\n\n<p>Put this to the <code>functions.php</code> or create a small plugin.</p>\n\n<pre><code><?php\nadd_filter( 'option_active_plugins', 'wpse264498_deactivate_fat_gallery' );\n\nfunction wpse264498_deactivate_fat_gallery($plugins){\n\n // check if you are on the certain page\n global $pagenow;\n if( $pagenow == 'post-new.php' ) {\n\n // check if it's right CPT\n if( isset($_GET['post_type']) && $_GET['post_type'] == 'sln_booking') {\n\n // search the plugin to disable among active plugins\n // Warning! Check the plugin directory and name\n $key = array_search( 'fat-gallery/fat-gallery.php' , $plugins );\n\n // if found, unset it from the active plugins array\n if ( false !== $key ) {\n unset( $plugins[$key] );\n }\n }\n }\n\n return $plugins;\n}\n</code></pre>\n\n<p>Also, you can try <a href=\"https://wordpress.org/plugins/plugin-organizer/\" rel=\"nofollow noreferrer\">Plugin Organizer</a>.</p>\n"
},
{
"answer_id": 264502,
"author": "am_",
"author_id": 118059,
"author_profile": "https://wordpress.stackexchange.com/users/118059",
"pm_score": 0,
"selected": false,
"text": "<p>Try something like this.\nThis does not deactivate the whole plugin but just remove the script that causes problems.\nNot tested, look the functions up if you don´t know how to use them and what parameters to use.</p>\n\n<pre><code>// add this hook if in admin area\nif (is_admin()) add_action(\"wp_enqueue_scripts\", \"my_dequeue_script\", 99);\nfunction my_jquery_enqueue() {\n // don´t do it if it´s not the page you want to remove the script\n if (get_current_screen() != \"yourpage\") return;\n // deregister the script\n // find the exact name of the script in the plugin where it is registered\n wp_deregister_script('fatgalleryScript');\n\n}\n</code></pre>\n"
},
{
"answer_id": 398636,
"author": "bvsmith",
"author_id": 98712,
"author_profile": "https://wordpress.stackexchange.com/users/98712",
"pm_score": 1,
"selected": false,
"text": "<p>I have tested <a href=\"https://wordpress.org/plugins/plugin-organizer/\" rel=\"nofollow noreferrer\">Plugin Organizer</a> but I found it difficult to use.</p>\n<p>In replacement I found <a href=\"https://wordpress.org/plugins/freesoul-deactivate-plugins/\" rel=\"nofollow noreferrer\">Freesoul Deactivate Plugins</a> which have a really nice and simple UI and works perfectly well.</p>\n"
}
]
| 2017/04/22 | [
"https://wordpress.stackexchange.com/questions/264498",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82936/"
]
| I have 2 plugins
1) FAT Gallery
2) Salon Booking
So FAT Gallery has a certain js lib (select2) which conflicts with Salon Booking Settings page.
In this URL
```
example.com/wp-admin/post-new.php?post_type=sln_booking
```
I'm trying to `DISABLE` the FAT Gallery because it causes js error and i cant do my job.
Any idea of how to block it ONLY on the certain page?
Thanks a lot! | That's pretty easy.
Remember, I don't know exactly what's the plugin's file name and directory, and the following code was not tested.
Put this to the `functions.php` or create a small plugin.
```
<?php
add_filter( 'option_active_plugins', 'wpse264498_deactivate_fat_gallery' );
function wpse264498_deactivate_fat_gallery($plugins){
// check if you are on the certain page
global $pagenow;
if( $pagenow == 'post-new.php' ) {
// check if it's right CPT
if( isset($_GET['post_type']) && $_GET['post_type'] == 'sln_booking') {
// search the plugin to disable among active plugins
// Warning! Check the plugin directory and name
$key = array_search( 'fat-gallery/fat-gallery.php' , $plugins );
// if found, unset it from the active plugins array
if ( false !== $key ) {
unset( $plugins[$key] );
}
}
}
return $plugins;
}
```
Also, you can try [Plugin Organizer](https://wordpress.org/plugins/plugin-organizer/). |
264,505 | <p>I use the following method to add a $_GET Variable to my custom post type in wordpress.</p>
<pre><code> add_filter('query_vars', 'add_type2_var', 0, 1);
function add_type2_var($vars){ $vars[] = 'type2'; return $vars; }
add_rewrite_rule('/?c/(.[^/])/(.[^/])/(.*)$',"/c/$1/$2?type2=$3",'top');
</code></pre>
<p>My custom post type is non-hierarchical post. The links to the posts works without a problem but when I try to add something at the end after the slash the links stop working.</p>
<p>If I add <code>show</code> at the end of <code>http://127.0.0.1/wp/c/default/dd</code> <code>http://127.0.0.1/wp/c/default/dd/show</code> the link gives a 404 error. Though it works perfectly fine when I add numbers at the end like <code>http://127.0.0.1/wp/c/default/dd/123456</code> and I could also get the <code>123456</code> using <code>$_GET</code> in php.</p>
<p>I am not sure where the problem is but my guess is that wordpress gives an 404 error before my function. I have a function using <code>single_template</code> filter.</p>
<p><strong>UPDATE:</strong></p>
<p>I have added a function to `template_redirect.</p>
<pre><code>function CPTTest()
{
if ( is_singular('cpt') )
{
echo 'cpt';
}
elseif ( is_singular() ) {
echo 'post';
}
else
{
echo 'none';
}
var_dump($_GET);
die();
}
</code></pre>
<p>This works fine when I use the url <code>http://127.0.0.1/wp/c/default/dd/show</code>. Only problem is that it doesn't recognize it as a cpt post. But it does recognize <code>http://127.0.0.1/wp/c/default/dd/123456</code> as a cpt post. Same result when I used <code>wp</code> action instead of <code>template_redirect</code>. </p>
| [
{
"answer_id": 264501,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 3,
"selected": true,
"text": "<p>That's pretty easy.</p>\n\n<p>Remember, I don't know exactly what's the plugin's file name and directory, and the following code was not tested.</p>\n\n<p>Put this to the <code>functions.php</code> or create a small plugin.</p>\n\n<pre><code><?php\nadd_filter( 'option_active_plugins', 'wpse264498_deactivate_fat_gallery' );\n\nfunction wpse264498_deactivate_fat_gallery($plugins){\n\n // check if you are on the certain page\n global $pagenow;\n if( $pagenow == 'post-new.php' ) {\n\n // check if it's right CPT\n if( isset($_GET['post_type']) && $_GET['post_type'] == 'sln_booking') {\n\n // search the plugin to disable among active plugins\n // Warning! Check the plugin directory and name\n $key = array_search( 'fat-gallery/fat-gallery.php' , $plugins );\n\n // if found, unset it from the active plugins array\n if ( false !== $key ) {\n unset( $plugins[$key] );\n }\n }\n }\n\n return $plugins;\n}\n</code></pre>\n\n<p>Also, you can try <a href=\"https://wordpress.org/plugins/plugin-organizer/\" rel=\"nofollow noreferrer\">Plugin Organizer</a>.</p>\n"
},
{
"answer_id": 264502,
"author": "am_",
"author_id": 118059,
"author_profile": "https://wordpress.stackexchange.com/users/118059",
"pm_score": 0,
"selected": false,
"text": "<p>Try something like this.\nThis does not deactivate the whole plugin but just remove the script that causes problems.\nNot tested, look the functions up if you don´t know how to use them and what parameters to use.</p>\n\n<pre><code>// add this hook if in admin area\nif (is_admin()) add_action(\"wp_enqueue_scripts\", \"my_dequeue_script\", 99);\nfunction my_jquery_enqueue() {\n // don´t do it if it´s not the page you want to remove the script\n if (get_current_screen() != \"yourpage\") return;\n // deregister the script\n // find the exact name of the script in the plugin where it is registered\n wp_deregister_script('fatgalleryScript');\n\n}\n</code></pre>\n"
},
{
"answer_id": 398636,
"author": "bvsmith",
"author_id": 98712,
"author_profile": "https://wordpress.stackexchange.com/users/98712",
"pm_score": 1,
"selected": false,
"text": "<p>I have tested <a href=\"https://wordpress.org/plugins/plugin-organizer/\" rel=\"nofollow noreferrer\">Plugin Organizer</a> but I found it difficult to use.</p>\n<p>In replacement I found <a href=\"https://wordpress.org/plugins/freesoul-deactivate-plugins/\" rel=\"nofollow noreferrer\">Freesoul Deactivate Plugins</a> which have a really nice and simple UI and works perfectly well.</p>\n"
}
]
| 2017/04/22 | [
"https://wordpress.stackexchange.com/questions/264505",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68381/"
]
| I use the following method to add a $\_GET Variable to my custom post type in wordpress.
```
add_filter('query_vars', 'add_type2_var', 0, 1);
function add_type2_var($vars){ $vars[] = 'type2'; return $vars; }
add_rewrite_rule('/?c/(.[^/])/(.[^/])/(.*)$',"/c/$1/$2?type2=$3",'top');
```
My custom post type is non-hierarchical post. The links to the posts works without a problem but when I try to add something at the end after the slash the links stop working.
If I add `show` at the end of `http://127.0.0.1/wp/c/default/dd` `http://127.0.0.1/wp/c/default/dd/show` the link gives a 404 error. Though it works perfectly fine when I add numbers at the end like `http://127.0.0.1/wp/c/default/dd/123456` and I could also get the `123456` using `$_GET` in php.
I am not sure where the problem is but my guess is that wordpress gives an 404 error before my function. I have a function using `single_template` filter.
**UPDATE:**
I have added a function to `template\_redirect.
```
function CPTTest()
{
if ( is_singular('cpt') )
{
echo 'cpt';
}
elseif ( is_singular() ) {
echo 'post';
}
else
{
echo 'none';
}
var_dump($_GET);
die();
}
```
This works fine when I use the url `http://127.0.0.1/wp/c/default/dd/show`. Only problem is that it doesn't recognize it as a cpt post. But it does recognize `http://127.0.0.1/wp/c/default/dd/123456` as a cpt post. Same result when I used `wp` action instead of `template_redirect`. | That's pretty easy.
Remember, I don't know exactly what's the plugin's file name and directory, and the following code was not tested.
Put this to the `functions.php` or create a small plugin.
```
<?php
add_filter( 'option_active_plugins', 'wpse264498_deactivate_fat_gallery' );
function wpse264498_deactivate_fat_gallery($plugins){
// check if you are on the certain page
global $pagenow;
if( $pagenow == 'post-new.php' ) {
// check if it's right CPT
if( isset($_GET['post_type']) && $_GET['post_type'] == 'sln_booking') {
// search the plugin to disable among active plugins
// Warning! Check the plugin directory and name
$key = array_search( 'fat-gallery/fat-gallery.php' , $plugins );
// if found, unset it from the active plugins array
if ( false !== $key ) {
unset( $plugins[$key] );
}
}
}
return $plugins;
}
```
Also, you can try [Plugin Organizer](https://wordpress.org/plugins/plugin-organizer/). |
264,509 | <p>I'm attempting to display a specific taxonomy (channel) in the archive.php page. I want to display the taxonomy's URL, name, post count, and taxonomy image.</p>
<p>This is what I have that's working so far:</p>
<pre><code><?php
$taxonomy = 'channel';
$tax_terms = get_terms($taxonomy);
$image_url = print apply_filters( 'taxonomy-images-queried-term-image', '' );
?>
<ul>
<?php
foreach ($tax_terms as $tax_term) { ?>
<li>
<?php echo esc_attr(get_term_link($tax_term, $taxonomy)); ?>
<?php echo $tax_term->name; ?>
<?php echo $tax_term->count; ?>
<?php echo $image_url->image_id; ?>
</li>
<?php } ?>
</ul>
</code></pre>
<p>I've gotten URL, name and post count working, the part that's not working is the taxonomy image provided by the Taxonomy Images plugin. (in the snippet, it's $image_url)</p>
<p><a href="https://wordpress.org/plugins/taxonomy-images/" rel="nofollow noreferrer">https://wordpress.org/plugins/taxonomy-images/</a></p>
<p>The plugin provides a image_id for an image added to a taxonomy, the plugin has a ton of ways to get the ID and display the image but I just can't seem to find the correct combination to work with my snippet with my level of skill.</p>
<p>Need some help, thanks.</p>
| [
{
"answer_id": 264501,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 3,
"selected": true,
"text": "<p>That's pretty easy.</p>\n\n<p>Remember, I don't know exactly what's the plugin's file name and directory, and the following code was not tested.</p>\n\n<p>Put this to the <code>functions.php</code> or create a small plugin.</p>\n\n<pre><code><?php\nadd_filter( 'option_active_plugins', 'wpse264498_deactivate_fat_gallery' );\n\nfunction wpse264498_deactivate_fat_gallery($plugins){\n\n // check if you are on the certain page\n global $pagenow;\n if( $pagenow == 'post-new.php' ) {\n\n // check if it's right CPT\n if( isset($_GET['post_type']) && $_GET['post_type'] == 'sln_booking') {\n\n // search the plugin to disable among active plugins\n // Warning! Check the plugin directory and name\n $key = array_search( 'fat-gallery/fat-gallery.php' , $plugins );\n\n // if found, unset it from the active plugins array\n if ( false !== $key ) {\n unset( $plugins[$key] );\n }\n }\n }\n\n return $plugins;\n}\n</code></pre>\n\n<p>Also, you can try <a href=\"https://wordpress.org/plugins/plugin-organizer/\" rel=\"nofollow noreferrer\">Plugin Organizer</a>.</p>\n"
},
{
"answer_id": 264502,
"author": "am_",
"author_id": 118059,
"author_profile": "https://wordpress.stackexchange.com/users/118059",
"pm_score": 0,
"selected": false,
"text": "<p>Try something like this.\nThis does not deactivate the whole plugin but just remove the script that causes problems.\nNot tested, look the functions up if you don´t know how to use them and what parameters to use.</p>\n\n<pre><code>// add this hook if in admin area\nif (is_admin()) add_action(\"wp_enqueue_scripts\", \"my_dequeue_script\", 99);\nfunction my_jquery_enqueue() {\n // don´t do it if it´s not the page you want to remove the script\n if (get_current_screen() != \"yourpage\") return;\n // deregister the script\n // find the exact name of the script in the plugin where it is registered\n wp_deregister_script('fatgalleryScript');\n\n}\n</code></pre>\n"
},
{
"answer_id": 398636,
"author": "bvsmith",
"author_id": 98712,
"author_profile": "https://wordpress.stackexchange.com/users/98712",
"pm_score": 1,
"selected": false,
"text": "<p>I have tested <a href=\"https://wordpress.org/plugins/plugin-organizer/\" rel=\"nofollow noreferrer\">Plugin Organizer</a> but I found it difficult to use.</p>\n<p>In replacement I found <a href=\"https://wordpress.org/plugins/freesoul-deactivate-plugins/\" rel=\"nofollow noreferrer\">Freesoul Deactivate Plugins</a> which have a really nice and simple UI and works perfectly well.</p>\n"
}
]
| 2017/04/22 | [
"https://wordpress.stackexchange.com/questions/264509",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/35798/"
]
| I'm attempting to display a specific taxonomy (channel) in the archive.php page. I want to display the taxonomy's URL, name, post count, and taxonomy image.
This is what I have that's working so far:
```
<?php
$taxonomy = 'channel';
$tax_terms = get_terms($taxonomy);
$image_url = print apply_filters( 'taxonomy-images-queried-term-image', '' );
?>
<ul>
<?php
foreach ($tax_terms as $tax_term) { ?>
<li>
<?php echo esc_attr(get_term_link($tax_term, $taxonomy)); ?>
<?php echo $tax_term->name; ?>
<?php echo $tax_term->count; ?>
<?php echo $image_url->image_id; ?>
</li>
<?php } ?>
</ul>
```
I've gotten URL, name and post count working, the part that's not working is the taxonomy image provided by the Taxonomy Images plugin. (in the snippet, it's $image\_url)
<https://wordpress.org/plugins/taxonomy-images/>
The plugin provides a image\_id for an image added to a taxonomy, the plugin has a ton of ways to get the ID and display the image but I just can't seem to find the correct combination to work with my snippet with my level of skill.
Need some help, thanks. | That's pretty easy.
Remember, I don't know exactly what's the plugin's file name and directory, and the following code was not tested.
Put this to the `functions.php` or create a small plugin.
```
<?php
add_filter( 'option_active_plugins', 'wpse264498_deactivate_fat_gallery' );
function wpse264498_deactivate_fat_gallery($plugins){
// check if you are on the certain page
global $pagenow;
if( $pagenow == 'post-new.php' ) {
// check if it's right CPT
if( isset($_GET['post_type']) && $_GET['post_type'] == 'sln_booking') {
// search the plugin to disable among active plugins
// Warning! Check the plugin directory and name
$key = array_search( 'fat-gallery/fat-gallery.php' , $plugins );
// if found, unset it from the active plugins array
if ( false !== $key ) {
unset( $plugins[$key] );
}
}
}
return $plugins;
}
```
Also, you can try [Plugin Organizer](https://wordpress.org/plugins/plugin-organizer/). |
264,511 | <p>At this moment I use functions as described in the "Theme handbook" from the WordPress site. The problem is that the stylesheet is loading on the backend pages too and it affects the layout of the backend pages. This behavior is not wanted.</p>
<p>The code I use to load the stylesheet -> <a href="https://pastebin.com/rAMZSu3u" rel="nofollow noreferrer">https://pastebin.com/rAMZSu3u</a></p>
<p>Does anyone know a way/method to load the stylesheet only on the frontend so the wp-admin backend does not get affected?</p>
<p>Note: The CSS is compiled with scssphp when the $dev variable is set to true.</p>
| [
{
"answer_id": 264514,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 1,
"selected": true,
"text": "<p>There is a conditional tag <code>is_admin()</code> which checks are you in the Administration Panel or Frontend. So, </p>\n\n<pre><code>if( !is_admin() ) {\n wp_enqueue_style(\n 'css-minified',\n get_stylesheet_directory_uri() . DIRECTORY_SEPARATOR . 'style.css',\n [],\n null,\n 'all'\n );\n wp_enqueue_style(\n 'font-awesome',\n 'https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css',\n [],\n null,\n 'all'\n );\n}\n</code></pre>\n\n<p>See <a href=\"https://codex.wordpress.org/Function_Reference/is_admin\" rel=\"nofollow noreferrer\">is_admin()</a>.</p>\n"
},
{
"answer_id": 264515,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 2,
"selected": false,
"text": "<p>Your styles should be enqueued on the <code>wp_enqueue_scripts</code> hook for the public side or <code>admin_enqueue_scripts</code> for the admin side.</p>\n\n<pre><code>//* Enqueue public scripts and style\nfunction wpse_264511_wp_enqueue_scripts {\n wp_enqueue_style( $handle, $src = '', $deps = array(), $ver = false, $media = 'all' );\n}\nadd_action( 'wp_enqueue_scripts', 'wpse_264511_wp_enqueue_scripts' );\n\n//* Enqueue admin scripts and style\nfunction wpse_264511_admin_enqueue_scripts {\n wp_enqueue_style( $handle, $src = '', $deps = array(), $ver = false, $media = 'all' );\n}\nadd_action( 'admin_enqueue_scripts', 'wpse_264511_admin_enqueue_scripts' );\n</code></pre>\n"
}
]
| 2017/04/22 | [
"https://wordpress.stackexchange.com/questions/264511",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118223/"
]
| At this moment I use functions as described in the "Theme handbook" from the WordPress site. The problem is that the stylesheet is loading on the backend pages too and it affects the layout of the backend pages. This behavior is not wanted.
The code I use to load the stylesheet -> <https://pastebin.com/rAMZSu3u>
Does anyone know a way/method to load the stylesheet only on the frontend so the wp-admin backend does not get affected?
Note: The CSS is compiled with scssphp when the $dev variable is set to true. | There is a conditional tag `is_admin()` which checks are you in the Administration Panel or Frontend. So,
```
if( !is_admin() ) {
wp_enqueue_style(
'css-minified',
get_stylesheet_directory_uri() . DIRECTORY_SEPARATOR . 'style.css',
[],
null,
'all'
);
wp_enqueue_style(
'font-awesome',
'https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css',
[],
null,
'all'
);
}
```
See [is\_admin()](https://codex.wordpress.org/Function_Reference/is_admin). |
264,527 | <p>I'm currently trying to build a wordpress plugin. I'd like its users to be able to add an upload file to the settings field menu of my plugin and then to be registered into the wordpress database, is there some way to do that?</p>
| [
{
"answer_id": 264579,
"author": "Nate",
"author_id": 87380,
"author_profile": "https://wordpress.stackexchange.com/users/87380",
"pm_score": 0,
"selected": false,
"text": "<p>The media manager is loaded using jQuery.<br>\nHere is a sample JS file that I've found. I hope it helps.</p>\n\n<pre><code>(function($) {\n\n$(document).ready( function() {\n var file_frame; // variable for the wp.media file_frame\n\n // attach a click event (or whatever you want) to some element on your page\n $( '#frontend-button' ).on( 'click', function( event ) {\n event.preventDefault();\n\n // if the file_frame has already been created, just reuse it\n if ( file_frame ) {\n file_frame.open();\n return;\n } \n\n file_frame = wp.media.frames.file_frame = wp.media({\n title: $( this ).data( 'uploader_title' ),\n button: {\n text: $( this ).data( 'uploader_button_text' ),\n },\n multiple: false // set this to true for multiple file selection\n });\n\n file_frame.on( 'select', function() {\n attachment = file_frame.state().get('selection').first().toJSON();\n\n // do something with the file here\n $( '#frontend-button' ).hide();\n $( '#frontend-image' ).attr('src', attachment.url);\n });\n\n file_frame.open();\n });\n});\n\n})(jQuery);\n</code></pre>\n"
},
{
"answer_id": 264589,
"author": "user118266",
"author_id": 118266,
"author_profile": "https://wordpress.stackexchange.com/users/118266",
"pm_score": 2,
"selected": true,
"text": "<p>I think I've been down that road. Take a look at <code>wp_handle_upload</code>, which will upload your file to the /uploads directory and then <code>wp_insert_attachment</code> and <code>wp_generate_attachment_metadata</code> to list said upload in the media library as an attachment which will 'register it in the wordpress database'. Then you can query attachments like this:</p>\n\n<pre><code>$attachments = get_posts( array( 'post_type' => 'attachment') );\n</code></pre>\n"
}
]
| 2017/04/22 | [
"https://wordpress.stackexchange.com/questions/264527",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118080/"
]
| I'm currently trying to build a wordpress plugin. I'd like its users to be able to add an upload file to the settings field menu of my plugin and then to be registered into the wordpress database, is there some way to do that? | I think I've been down that road. Take a look at `wp_handle_upload`, which will upload your file to the /uploads directory and then `wp_insert_attachment` and `wp_generate_attachment_metadata` to list said upload in the media library as an attachment which will 'register it in the wordpress database'. Then you can query attachments like this:
```
$attachments = get_posts( array( 'post_type' => 'attachment') );
``` |
264,531 | <p>I have 20,000 fake subscribers I'd like to get rid of. The admin panel only lets you delete 200 at a time.</p>
<p>How can I bulk delete all Wordpress subscribers via MySQL?</p>
| [
{
"answer_id": 264579,
"author": "Nate",
"author_id": 87380,
"author_profile": "https://wordpress.stackexchange.com/users/87380",
"pm_score": 0,
"selected": false,
"text": "<p>The media manager is loaded using jQuery.<br>\nHere is a sample JS file that I've found. I hope it helps.</p>\n\n<pre><code>(function($) {\n\n$(document).ready( function() {\n var file_frame; // variable for the wp.media file_frame\n\n // attach a click event (or whatever you want) to some element on your page\n $( '#frontend-button' ).on( 'click', function( event ) {\n event.preventDefault();\n\n // if the file_frame has already been created, just reuse it\n if ( file_frame ) {\n file_frame.open();\n return;\n } \n\n file_frame = wp.media.frames.file_frame = wp.media({\n title: $( this ).data( 'uploader_title' ),\n button: {\n text: $( this ).data( 'uploader_button_text' ),\n },\n multiple: false // set this to true for multiple file selection\n });\n\n file_frame.on( 'select', function() {\n attachment = file_frame.state().get('selection').first().toJSON();\n\n // do something with the file here\n $( '#frontend-button' ).hide();\n $( '#frontend-image' ).attr('src', attachment.url);\n });\n\n file_frame.open();\n });\n});\n\n})(jQuery);\n</code></pre>\n"
},
{
"answer_id": 264589,
"author": "user118266",
"author_id": 118266,
"author_profile": "https://wordpress.stackexchange.com/users/118266",
"pm_score": 2,
"selected": true,
"text": "<p>I think I've been down that road. Take a look at <code>wp_handle_upload</code>, which will upload your file to the /uploads directory and then <code>wp_insert_attachment</code> and <code>wp_generate_attachment_metadata</code> to list said upload in the media library as an attachment which will 'register it in the wordpress database'. Then you can query attachments like this:</p>\n\n<pre><code>$attachments = get_posts( array( 'post_type' => 'attachment') );\n</code></pre>\n"
}
]
| 2017/04/22 | [
"https://wordpress.stackexchange.com/questions/264531",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/34762/"
]
| I have 20,000 fake subscribers I'd like to get rid of. The admin panel only lets you delete 200 at a time.
How can I bulk delete all Wordpress subscribers via MySQL? | I think I've been down that road. Take a look at `wp_handle_upload`, which will upload your file to the /uploads directory and then `wp_insert_attachment` and `wp_generate_attachment_metadata` to list said upload in the media library as an attachment which will 'register it in the wordpress database'. Then you can query attachments like this:
```
$attachments = get_posts( array( 'post_type' => 'attachment') );
``` |
264,548 | <p>The WordPress editor keeps adding “amp;” after every “&”.</p>
<p>This effectively breaks all my custom links. How can i stop this?
I don’t mind all the others things the editor does to the formatting i just need it to stop adding “amp;”. Is there a filter i can use?</p>
| [
{
"answer_id": 264996,
"author": "Christine Cooper",
"author_id": 24875,
"author_profile": "https://wordpress.stackexchange.com/users/24875",
"pm_score": 2,
"selected": true,
"text": "<p>One solution is to hook into <code>wp_insert_post_data</code> and do some regex magic to replace all instances of <code>&amp;</code> with <code>&</code>:</p>\n\n<pre><code>// when saving posts, replace &amp; with &\nfunction cc_wpse_264548_unamp( $data ) {\n\n $data['post_content'] = preg_replace(\n \"/&amp;/\", // find '&amp;'\n \"&\", // replace with '&'\n $data['post_content'] // target the 'post_content'\n );\n\n return $data;\n}\nadd_filter( 'wp_insert_post_data', 'cc_wpse_264548_unamp', 20 );\n</code></pre>\n\n<p>You will obviously only see changes when a post is saved/updated.</p>\n"
},
{
"answer_id": 307225,
"author": "user4438328",
"author_id": 146022,
"author_profile": "https://wordpress.stackexchange.com/users/146022",
"pm_score": 0,
"selected": false,
"text": "<p>You can edit the TinyMCE Config as i did. I just add entity_encoding = \"raw\"</p>\n\n<pre><code><script>\ntinymce.init({\n selector: 'textarea',\n entity_encoding : \"raw\" \n});\n</script>\n</code></pre>\n"
}
]
| 2017/04/23 | [
"https://wordpress.stackexchange.com/questions/264548",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77283/"
]
| The WordPress editor keeps adding “amp;” after every “&”.
This effectively breaks all my custom links. How can i stop this?
I don’t mind all the others things the editor does to the formatting i just need it to stop adding “amp;”. Is there a filter i can use? | One solution is to hook into `wp_insert_post_data` and do some regex magic to replace all instances of `&` with `&`:
```
// when saving posts, replace & with &
function cc_wpse_264548_unamp( $data ) {
$data['post_content'] = preg_replace(
"/&/", // find '&'
"&", // replace with '&'
$data['post_content'] // target the 'post_content'
);
return $data;
}
add_filter( 'wp_insert_post_data', 'cc_wpse_264548_unamp', 20 );
```
You will obviously only see changes when a post is saved/updated. |
264,565 | <p>i would want to customize the navigation menu so that its dropdown-menu stays active all the time, i don't want it to appear on hover, but when the page of the active main menu item has loaded and the submenu should remain visible. So when the home page loads it's submenu should be visible just like at www.dailymail.co.uk</p>
<p>could anyone assist with the custom css that i can use</p>
| [
{
"answer_id": 264570,
"author": "Mervan Agency",
"author_id": 118206,
"author_profile": "https://wordpress.stackexchange.com/users/118206",
"pm_score": 1,
"selected": false,
"text": "<p>We have created a CodePen to demonstrate how you can achieve that using HTML/CSS/JS. Hope that will help you.</p>\n\n<p><a href=\"https://codepen.io/mervanagency/pen/XRKxwr\" rel=\"nofollow noreferrer\">https://codepen.io/mervanagency/pen/XRKxwr</a></p>\n"
},
{
"answer_id": 264571,
"author": "Nate",
"author_id": 87380,
"author_profile": "https://wordpress.stackexchange.com/users/87380",
"pm_score": 1,
"selected": true,
"text": "<p>WordPress automatically generates \"current-menu-item\" class to the menu of the current page you visit. So in this case, you can do something like-</p>\n\n<pre><code>.current-menu-item ul.sub-menu { display: block !important; }\n</code></pre>\n"
}
]
| 2017/04/23 | [
"https://wordpress.stackexchange.com/questions/264565",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118256/"
]
| i would want to customize the navigation menu so that its dropdown-menu stays active all the time, i don't want it to appear on hover, but when the page of the active main menu item has loaded and the submenu should remain visible. So when the home page loads it's submenu should be visible just like at www.dailymail.co.uk
could anyone assist with the custom css that i can use | WordPress automatically generates "current-menu-item" class to the menu of the current page you visit. So in this case, you can do something like-
```
.current-menu-item ul.sub-menu { display: block !important; }
``` |
264,606 | <p>I have a website with two user role named “A” and “B” when anyone doing registration with "A" then i want to send a welcome email and when with “B” wanna send different welcome email, is it possible?
Thanks in advance</p>
| [
{
"answer_id": 264609,
"author": "Jared Cobb",
"author_id": 6737,
"author_profile": "https://wordpress.stackexchange.com/users/6737",
"pm_score": 1,
"selected": false,
"text": "<p>Yes, this is possible. WordPress defines a function named <a href=\"https://developer.wordpress.org/reference/functions/wp_new_user_notification/\" rel=\"nofollow noreferrer\"><code>wp_new_user_notification</code></a>. You can override this function by creating your own version (also named <code>wp_new_user_notification</code>) in your own theme or plugin.</p>\n\n<p>You may wish to start by copying the <a href=\"https://github.com/WordPress/WordPress/blob/2e6e53d26f69c1c486bd021710c61d02dd9e144e/wp-includes/pluggable.php#L1770\" rel=\"nofollow noreferrer\">contents of the existing core version</a> into your own copy. You can now customize the logic for your own needs.</p>\n\n<p>Since this function passes the <code>$user_id</code> as the first argument, you can use <a href=\"https://codex.wordpress.org/Function_Reference/get_userdata\" rel=\"nofollow noreferrer\"><code>get_userdata</code></a> to obtain more information about the user (for example that user's roles) and then send different content depending on their role.</p>\n\n<pre><code>$user_data = get_userdata( $user_id );\nif ( ! empty( $user_data->roles ) ) {\n if ( in_array( 'role_a', $user_data->roles, true ) {\n // custom content for role a\n } elseif ( in_array( 'role_b', $user_data->roles, true ) {\n // custom content for role b\n }\n}\n</code></pre>\n"
},
{
"answer_id": 264789,
"author": "rasel mahmud",
"author_id": 96944,
"author_profile": "https://wordpress.stackexchange.com/users/96944",
"pm_score": 0,
"selected": false,
"text": "<p>i have solved the issue. Thanks for your great help @jared-cobb</p>\n\n<pre><code> function send_welcome_email_to_new_user($user_id) {\n $user = get_userdata($user_id);\n $user_email = $user->user_email;\n\n // email will send only for \"A\" registers\n if ( in_array( 'A', $user->roles )) {\n $to = $user_email;\n $subject = \"Hi A, welcome to our site!\";\n $body = '\n <h1>Dear A,</h1></br>\n <p>Thank you for joining our site. Your account is now active.</p>\n ';\n $headers = array('Content-Type: text/html; charset=UTF-8');\n if (wp_mail($to, $subject, $body, $headers)) {\n error_log(\"email has been successfully sent to user whose email is \" . $user_email);\n }\n }\n\n // email will send only for \"B\" registers\n if ( in_array( 'B', $user->roles )) {\n $to = $user_email;\n $subject = \"Hi B, welcome to our site!\";\n $body = '\n <h1>Dear B,</h1></br>\n <p>Thank you for joining our site. Your account is now active.</p>\n ';\n $headers = array('Content-Type: text/html; charset=UTF-8');\n if (wp_mail($to, $subject, $body, $headers)) {\n error_log(\"email has been successfully sent to user whose email is \" . $user_email);\n }\n }\n\n }\n add_action('user_register', 'send_welcome_email_to_new_user');\n</code></pre>\n"
}
]
| 2017/04/23 | [
"https://wordpress.stackexchange.com/questions/264606",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96944/"
]
| I have a website with two user role named “A” and “B” when anyone doing registration with "A" then i want to send a welcome email and when with “B” wanna send different welcome email, is it possible?
Thanks in advance | Yes, this is possible. WordPress defines a function named [`wp_new_user_notification`](https://developer.wordpress.org/reference/functions/wp_new_user_notification/). You can override this function by creating your own version (also named `wp_new_user_notification`) in your own theme or plugin.
You may wish to start by copying the [contents of the existing core version](https://github.com/WordPress/WordPress/blob/2e6e53d26f69c1c486bd021710c61d02dd9e144e/wp-includes/pluggable.php#L1770) into your own copy. You can now customize the logic for your own needs.
Since this function passes the `$user_id` as the first argument, you can use [`get_userdata`](https://codex.wordpress.org/Function_Reference/get_userdata) to obtain more information about the user (for example that user's roles) and then send different content depending on their role.
```
$user_data = get_userdata( $user_id );
if ( ! empty( $user_data->roles ) ) {
if ( in_array( 'role_a', $user_data->roles, true ) {
// custom content for role a
} elseif ( in_array( 'role_b', $user_data->roles, true ) {
// custom content for role b
}
}
``` |
264,608 | <p>I've searched multiple forums, and not finding anything quite like this...
On a site I manage, there are several parent pages with links to child pages embedded in images. Each image links to the corresponding child page without a problem. ONE of the parents pages, however, when I click on any of the images (or even try to manually direct to one of the child pages), it redirects to the homepage. I've read through the code several times and can't find the problem. I know it's not a problem with any of the shortcode, because all the other parent pages using the same shortcode are working perfectly. Anyone have any suggestions on where to look to possibly track down this problem?</p>
| [
{
"answer_id": 264609,
"author": "Jared Cobb",
"author_id": 6737,
"author_profile": "https://wordpress.stackexchange.com/users/6737",
"pm_score": 1,
"selected": false,
"text": "<p>Yes, this is possible. WordPress defines a function named <a href=\"https://developer.wordpress.org/reference/functions/wp_new_user_notification/\" rel=\"nofollow noreferrer\"><code>wp_new_user_notification</code></a>. You can override this function by creating your own version (also named <code>wp_new_user_notification</code>) in your own theme or plugin.</p>\n\n<p>You may wish to start by copying the <a href=\"https://github.com/WordPress/WordPress/blob/2e6e53d26f69c1c486bd021710c61d02dd9e144e/wp-includes/pluggable.php#L1770\" rel=\"nofollow noreferrer\">contents of the existing core version</a> into your own copy. You can now customize the logic for your own needs.</p>\n\n<p>Since this function passes the <code>$user_id</code> as the first argument, you can use <a href=\"https://codex.wordpress.org/Function_Reference/get_userdata\" rel=\"nofollow noreferrer\"><code>get_userdata</code></a> to obtain more information about the user (for example that user's roles) and then send different content depending on their role.</p>\n\n<pre><code>$user_data = get_userdata( $user_id );\nif ( ! empty( $user_data->roles ) ) {\n if ( in_array( 'role_a', $user_data->roles, true ) {\n // custom content for role a\n } elseif ( in_array( 'role_b', $user_data->roles, true ) {\n // custom content for role b\n }\n}\n</code></pre>\n"
},
{
"answer_id": 264789,
"author": "rasel mahmud",
"author_id": 96944,
"author_profile": "https://wordpress.stackexchange.com/users/96944",
"pm_score": 0,
"selected": false,
"text": "<p>i have solved the issue. Thanks for your great help @jared-cobb</p>\n\n<pre><code> function send_welcome_email_to_new_user($user_id) {\n $user = get_userdata($user_id);\n $user_email = $user->user_email;\n\n // email will send only for \"A\" registers\n if ( in_array( 'A', $user->roles )) {\n $to = $user_email;\n $subject = \"Hi A, welcome to our site!\";\n $body = '\n <h1>Dear A,</h1></br>\n <p>Thank you for joining our site. Your account is now active.</p>\n ';\n $headers = array('Content-Type: text/html; charset=UTF-8');\n if (wp_mail($to, $subject, $body, $headers)) {\n error_log(\"email has been successfully sent to user whose email is \" . $user_email);\n }\n }\n\n // email will send only for \"B\" registers\n if ( in_array( 'B', $user->roles )) {\n $to = $user_email;\n $subject = \"Hi B, welcome to our site!\";\n $body = '\n <h1>Dear B,</h1></br>\n <p>Thank you for joining our site. Your account is now active.</p>\n ';\n $headers = array('Content-Type: text/html; charset=UTF-8');\n if (wp_mail($to, $subject, $body, $headers)) {\n error_log(\"email has been successfully sent to user whose email is \" . $user_email);\n }\n }\n\n }\n add_action('user_register', 'send_welcome_email_to_new_user');\n</code></pre>\n"
}
]
| 2017/04/23 | [
"https://wordpress.stackexchange.com/questions/264608",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118239/"
]
| I've searched multiple forums, and not finding anything quite like this...
On a site I manage, there are several parent pages with links to child pages embedded in images. Each image links to the corresponding child page without a problem. ONE of the parents pages, however, when I click on any of the images (or even try to manually direct to one of the child pages), it redirects to the homepage. I've read through the code several times and can't find the problem. I know it's not a problem with any of the shortcode, because all the other parent pages using the same shortcode are working perfectly. Anyone have any suggestions on where to look to possibly track down this problem? | Yes, this is possible. WordPress defines a function named [`wp_new_user_notification`](https://developer.wordpress.org/reference/functions/wp_new_user_notification/). You can override this function by creating your own version (also named `wp_new_user_notification`) in your own theme or plugin.
You may wish to start by copying the [contents of the existing core version](https://github.com/WordPress/WordPress/blob/2e6e53d26f69c1c486bd021710c61d02dd9e144e/wp-includes/pluggable.php#L1770) into your own copy. You can now customize the logic for your own needs.
Since this function passes the `$user_id` as the first argument, you can use [`get_userdata`](https://codex.wordpress.org/Function_Reference/get_userdata) to obtain more information about the user (for example that user's roles) and then send different content depending on their role.
```
$user_data = get_userdata( $user_id );
if ( ! empty( $user_data->roles ) ) {
if ( in_array( 'role_a', $user_data->roles, true ) {
// custom content for role a
} elseif ( in_array( 'role_b', $user_data->roles, true ) {
// custom content for role b
}
}
``` |
264,617 | <p>I have made simple wordpress layout and the border-bottom in footer do not show. Here is the part of the code of my <code>style.css</code> file:</p>
<pre><code>.site-header {
border-bottom: 2px solid #999;
}
.site-footer {
border-top: 20px solid #999;
}
</code></pre>
<p>The header border shows correctly but the footer doesn't. Thank you for any ideas.</p>
| [
{
"answer_id": 264609,
"author": "Jared Cobb",
"author_id": 6737,
"author_profile": "https://wordpress.stackexchange.com/users/6737",
"pm_score": 1,
"selected": false,
"text": "<p>Yes, this is possible. WordPress defines a function named <a href=\"https://developer.wordpress.org/reference/functions/wp_new_user_notification/\" rel=\"nofollow noreferrer\"><code>wp_new_user_notification</code></a>. You can override this function by creating your own version (also named <code>wp_new_user_notification</code>) in your own theme or plugin.</p>\n\n<p>You may wish to start by copying the <a href=\"https://github.com/WordPress/WordPress/blob/2e6e53d26f69c1c486bd021710c61d02dd9e144e/wp-includes/pluggable.php#L1770\" rel=\"nofollow noreferrer\">contents of the existing core version</a> into your own copy. You can now customize the logic for your own needs.</p>\n\n<p>Since this function passes the <code>$user_id</code> as the first argument, you can use <a href=\"https://codex.wordpress.org/Function_Reference/get_userdata\" rel=\"nofollow noreferrer\"><code>get_userdata</code></a> to obtain more information about the user (for example that user's roles) and then send different content depending on their role.</p>\n\n<pre><code>$user_data = get_userdata( $user_id );\nif ( ! empty( $user_data->roles ) ) {\n if ( in_array( 'role_a', $user_data->roles, true ) {\n // custom content for role a\n } elseif ( in_array( 'role_b', $user_data->roles, true ) {\n // custom content for role b\n }\n}\n</code></pre>\n"
},
{
"answer_id": 264789,
"author": "rasel mahmud",
"author_id": 96944,
"author_profile": "https://wordpress.stackexchange.com/users/96944",
"pm_score": 0,
"selected": false,
"text": "<p>i have solved the issue. Thanks for your great help @jared-cobb</p>\n\n<pre><code> function send_welcome_email_to_new_user($user_id) {\n $user = get_userdata($user_id);\n $user_email = $user->user_email;\n\n // email will send only for \"A\" registers\n if ( in_array( 'A', $user->roles )) {\n $to = $user_email;\n $subject = \"Hi A, welcome to our site!\";\n $body = '\n <h1>Dear A,</h1></br>\n <p>Thank you for joining our site. Your account is now active.</p>\n ';\n $headers = array('Content-Type: text/html; charset=UTF-8');\n if (wp_mail($to, $subject, $body, $headers)) {\n error_log(\"email has been successfully sent to user whose email is \" . $user_email);\n }\n }\n\n // email will send only for \"B\" registers\n if ( in_array( 'B', $user->roles )) {\n $to = $user_email;\n $subject = \"Hi B, welcome to our site!\";\n $body = '\n <h1>Dear B,</h1></br>\n <p>Thank you for joining our site. Your account is now active.</p>\n ';\n $headers = array('Content-Type: text/html; charset=UTF-8');\n if (wp_mail($to, $subject, $body, $headers)) {\n error_log(\"email has been successfully sent to user whose email is \" . $user_email);\n }\n }\n\n }\n add_action('user_register', 'send_welcome_email_to_new_user');\n</code></pre>\n"
}
]
| 2017/04/23 | [
"https://wordpress.stackexchange.com/questions/264617",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118380/"
]
| I have made simple wordpress layout and the border-bottom in footer do not show. Here is the part of the code of my `style.css` file:
```
.site-header {
border-bottom: 2px solid #999;
}
.site-footer {
border-top: 20px solid #999;
}
```
The header border shows correctly but the footer doesn't. Thank you for any ideas. | Yes, this is possible. WordPress defines a function named [`wp_new_user_notification`](https://developer.wordpress.org/reference/functions/wp_new_user_notification/). You can override this function by creating your own version (also named `wp_new_user_notification`) in your own theme or plugin.
You may wish to start by copying the [contents of the existing core version](https://github.com/WordPress/WordPress/blob/2e6e53d26f69c1c486bd021710c61d02dd9e144e/wp-includes/pluggable.php#L1770) into your own copy. You can now customize the logic for your own needs.
Since this function passes the `$user_id` as the first argument, you can use [`get_userdata`](https://codex.wordpress.org/Function_Reference/get_userdata) to obtain more information about the user (for example that user's roles) and then send different content depending on their role.
```
$user_data = get_userdata( $user_id );
if ( ! empty( $user_data->roles ) ) {
if ( in_array( 'role_a', $user_data->roles, true ) {
// custom content for role a
} elseif ( in_array( 'role_b', $user_data->roles, true ) {
// custom content for role b
}
}
``` |
264,642 | <p>I have sidebar.php and it show 10 popularpost of my wordpress post. But i want just Display popularpost of the last 2 days. How i can correct it?</p>
<p>Thanks</p>
<pre><code> </div>
<?php } if (of_get_option('most_radio')==1) { ?>
<div class="rmenu col-lg-12 col-sm-12 col-xs-12">
<header class="title-panel">
<div class="title-arrow"></div>
<h2 class="title-text"><?php echo of_get_option('most_title'); ?></h2>
</header>
<footer class="most-viewed">
<div class="most-viewed-content mCustomScrollbar" data-mcs-theme="dark-thin">
<?php if(of_get_option('most_radio_select')==1){
$popularpost = new WP_Query( array(
'post_status' =>'publish',
'post_type' =>'post',
'posts_per_page' => of_get_option('most_count'),
'orderby' => 'meta_value_num',
'meta_key' => 'post_views_count',
'order' => 'DESC'
)
); ?>
<ol>
<?php
if($popularpost->have_posts()) : while($popularpost->have_posts()) : $popularpost->the_post();
?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> - <?php echo getPostViews(get_the_ID()); ?> </li>
<?php endwhile; endif; ?></ol> <? }else{?>
<ol>
<?php
$big_query = new WP_Query(array(
'post_status' =>'publish',
'post_type' =>'post',
'cat' => of_get_option('most_select_categories'),
'posts_per_page' => of_get_option('most_count'))); ?>
<?php if($big_query->have_posts()) : while($big_query->have_posts()) : $big_query->the_post();?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>
<?php endif; ?>
</ol>
<?php } ?>
</code></pre>
<p>
</p>
| [
{
"answer_id": 264645,
"author": "v-stackOverFollower",
"author_id": 118148,
"author_profile": "https://wordpress.stackexchange.com/users/118148",
"pm_score": 1,
"selected": true,
"text": "<p>in argument list please also pass date_query, try below example.</p>\n\n<pre><code>$args = array(\n 'posts_per_page' => 10,\n 'post_type' => 'post',\n 'order' => 'DESC',\n 'date_query' => array(\n 'after' => '2 days ago', \n 'inclusive' => true\n )\n); \n$posts = get_posts($args);\n</code></pre>\n"
},
{
"answer_id": 264650,
"author": "Mervan Agency",
"author_id": 118206,
"author_profile": "https://wordpress.stackexchange.com/users/118206",
"pm_score": 1,
"selected": false,
"text": "<p>I think you forgot to add date_query argument in your query, please check below example.</p>\n\n<pre><code>$args = array(\n'posts_per_page' => of_get_option('most_count'),\n'post_type' => 'post',\n'orderby' => 'meta_value_num',\n'meta_key' => 'post_views_count', \n'order' => 'DESC',\n'post_status' =>'publish', \n'date_query' => array(\n 'after' => date('Y-m-d', strtotime('-2 days')) \n));\n\n $posts = get_posts($args);\n</code></pre>\n\n<p>As of 3.7 you can use date_query <a href=\"http://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters\" rel=\"nofollow noreferrer\">http://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters</a></p>\n"
}
]
| 2017/04/24 | [
"https://wordpress.stackexchange.com/questions/264642",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118301/"
]
| I have sidebar.php and it show 10 popularpost of my wordpress post. But i want just Display popularpost of the last 2 days. How i can correct it?
Thanks
```
</div>
<?php } if (of_get_option('most_radio')==1) { ?>
<div class="rmenu col-lg-12 col-sm-12 col-xs-12">
<header class="title-panel">
<div class="title-arrow"></div>
<h2 class="title-text"><?php echo of_get_option('most_title'); ?></h2>
</header>
<footer class="most-viewed">
<div class="most-viewed-content mCustomScrollbar" data-mcs-theme="dark-thin">
<?php if(of_get_option('most_radio_select')==1){
$popularpost = new WP_Query( array(
'post_status' =>'publish',
'post_type' =>'post',
'posts_per_page' => of_get_option('most_count'),
'orderby' => 'meta_value_num',
'meta_key' => 'post_views_count',
'order' => 'DESC'
)
); ?>
<ol>
<?php
if($popularpost->have_posts()) : while($popularpost->have_posts()) : $popularpost->the_post();
?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> - <?php echo getPostViews(get_the_ID()); ?> </li>
<?php endwhile; endif; ?></ol> <? }else{?>
<ol>
<?php
$big_query = new WP_Query(array(
'post_status' =>'publish',
'post_type' =>'post',
'cat' => of_get_option('most_select_categories'),
'posts_per_page' => of_get_option('most_count'))); ?>
<?php if($big_query->have_posts()) : while($big_query->have_posts()) : $big_query->the_post();?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>
<?php endif; ?>
</ol>
<?php } ?>
``` | in argument list please also pass date\_query, try below example.
```
$args = array(
'posts_per_page' => 10,
'post_type' => 'post',
'order' => 'DESC',
'date_query' => array(
'after' => '2 days ago',
'inclusive' => true
)
);
$posts = get_posts($args);
``` |
264,681 | <p>We moved the site to HTTPS recently (for the most part following this guide: <a href="https://www.bram.us/2014/12/06/migrating-your-wordpress-website-from-http-to-https/" rel="nofollow noreferrer">https://www.bram.us/2014/12/06/migrating-your-wordpress-website-from-http-to-https/</a> ) </p>
<p>Now, most things are working perfectly - with the site loading as HTTPS and having the green icon on most pages. (The site name has been updated to reference the change.)</p>
<p>But all of the permalinks (at the top of editing page/post) still show as http. And with a password protected page, entering the password isn't loading as it's still trying to access it via http. </p>
<p>I've changed the link to HTTPS in: </p>
<ul>
<li>Settings>general</li>
<li><p>in wp-config.php:define ('WP_HOME','<a href="https://example.org.uk" rel="nofollow noreferrer">https://example.org.uk</a>'); same for WP_SITEURL</p></li>
<li><p>In PHPMyAdmin (changed under siteurl and home in the wp_options table)</p></li>
</ul>
<p>Why might this be, and what can I do to alter it?</p>
<p>Edit: I have tried saving the permalinks again, no change</p>
| [
{
"answer_id": 264687,
"author": "ahendwh2",
"author_id": 112098,
"author_profile": "https://wordpress.stackexchange.com/users/112098",
"pm_score": 0,
"selected": false,
"text": "<p>Did you cleared (resaved) your permalinks?</p>\n\n<p><strong>Settings -> Permalinks -> Click on \"Save Changes\"</strong></p>\n"
},
{
"answer_id": 264754,
"author": "Akshat",
"author_id": 114978,
"author_profile": "https://wordpress.stackexchange.com/users/114978",
"pm_score": 1,
"selected": false,
"text": "<p>If you are using Apache as your web server then add</p>\n\n<pre><code># ensure https\nRewriteCond %{HTTP:X-Forwarded-Proto} !https \nRewriteCond %{HTTPS} off\nRewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n</code></pre>\n\n<p>in your .htaccess file, this can be found in the root wordpress directory.\nAlternatively you can use <a href=\"https://wordpress.org/plugins/wp-force-ssl/\" rel=\"nofollow noreferrer\">WP Force SSL</a> plugin.</p>\n"
}
]
| 2017/04/24 | [
"https://wordpress.stackexchange.com/questions/264681",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/116966/"
]
| We moved the site to HTTPS recently (for the most part following this guide: <https://www.bram.us/2014/12/06/migrating-your-wordpress-website-from-http-to-https/> )
Now, most things are working perfectly - with the site loading as HTTPS and having the green icon on most pages. (The site name has been updated to reference the change.)
But all of the permalinks (at the top of editing page/post) still show as http. And with a password protected page, entering the password isn't loading as it's still trying to access it via http.
I've changed the link to HTTPS in:
* Settings>general
* in wp-config.php:define ('WP\_HOME','<https://example.org.uk>'); same for WP\_SITEURL
* In PHPMyAdmin (changed under siteurl and home in the wp\_options table)
Why might this be, and what can I do to alter it?
Edit: I have tried saving the permalinks again, no change | If you are using Apache as your web server then add
```
# ensure https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
```
in your .htaccess file, this can be found in the root wordpress directory.
Alternatively you can use [WP Force SSL](https://wordpress.org/plugins/wp-force-ssl/) plugin. |
264,686 | <p>I have a problem with Add to Basket background and width display on mobile phone. I do not know why it has been like that.</p>
<p>Can you guys checkout my website <a href="https://www.theturkishshop.com" rel="nofollow noreferrer">https://www.theturkishshop.com</a> and let me know how I can fix "ADD TO BASKET" button, which is displaying not correctly ( the background of the left is white). Thanks and look forward to hearing ideas from you guys. </p>
<p>Thanks</p>
| [
{
"answer_id": 264689,
"author": "Tarun modi",
"author_id": 115973,
"author_profile": "https://wordpress.stackexchange.com/users/115973",
"pm_score": 0,
"selected": false,
"text": "<p>Hello You needs to add following css:</p>\n\n<pre><code>a.button.product_type_simple.add_to_cart_button.ajax_add_to_cart {\n background-color: #CAA300 !important;\n background-position: 7% center !important;\n width: 77%;\n}\n</code></pre>\n"
},
{
"answer_id": 264692,
"author": "ahendwh2",
"author_id": 112098,
"author_profile": "https://wordpress.stackexchange.com/users/112098",
"pm_score": 2,
"selected": true,
"text": "<p>You have to add <code>background-image: none !important;</code> to your buttons CSS.</p>\n\n<p>Complete CSS-Rule:</p>\n\n<pre><code>@media screen and (max-width: 767px) {\n a.button.product_type_simple.add_to_cart_button.ajax_add_to_cart {\n background-image: none !important;\n }\n}\n</code></pre>\n"
}
]
| 2017/04/24 | [
"https://wordpress.stackexchange.com/questions/264686",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107174/"
]
| I have a problem with Add to Basket background and width display on mobile phone. I do not know why it has been like that.
Can you guys checkout my website <https://www.theturkishshop.com> and let me know how I can fix "ADD TO BASKET" button, which is displaying not correctly ( the background of the left is white). Thanks and look forward to hearing ideas from you guys.
Thanks | You have to add `background-image: none !important;` to your buttons CSS.
Complete CSS-Rule:
```
@media screen and (max-width: 767px) {
a.button.product_type_simple.add_to_cart_button.ajax_add_to_cart {
background-image: none !important;
}
}
``` |
264,693 | <p>Looking for some fresh eyes on this,</p>
<p>I have a custom archive for my CPT and it's Taxonomies.</p>
<p>The page has a input search form to filter posts of the CPT as well as drop downs to filter by terms.</p>
<p>The issue is that on page load, when the loop instantiates WP_Query args are overridden by <code>get_query_vars</code>.</p>
<p>For example, the <code>posts_per_page</code> is set to 2.
However, <code>query_vars</code> hijacks the args and changes it to 12 (for some reason, not declared anywhere else on the site)</p>
<p>Logic below.</p>
<pre><code>$q = get_query_var( 'q' );
$args = array(
'post_type' => $post_type,
'post_status' => 'publish',
'orderby' => 'post_date',
'order' => 'DESC',
'paged' => $paged,
'posts_per_page' => $posts_per_page, // tried 2
'tax_query' => $tax_query,
's' => $q
);
$wp_query = new WP_Query( $args );
</code></pre>
<p>Form - see <code>q</code> as value</p>
<pre><code> <form id="filter-form" role="search" method="get" class="" action="<?php the_permalink(); ?>">
<!-- Query -->
<label>
<span class="screen-reader-text"><?php echo _x( 'Enter Keyword', 'label' )?></span>
<input type="search" class="search-field"
placeholder="Keywords"
value="<?= $q ?>"
name="q"
title="<?php echo esc_attr_x( 'Enter Keyword', 'label' ) ?>"/>
</label>
etc
</code></pre>
<p>The filter is registered and hooked in functions.php as per codex</p>
<pre><code>function add_query_vars_filter( $vars ){
$vars[] = "q";
return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );
</code></pre>
| [
{
"answer_id": 264689,
"author": "Tarun modi",
"author_id": 115973,
"author_profile": "https://wordpress.stackexchange.com/users/115973",
"pm_score": 0,
"selected": false,
"text": "<p>Hello You needs to add following css:</p>\n\n<pre><code>a.button.product_type_simple.add_to_cart_button.ajax_add_to_cart {\n background-color: #CAA300 !important;\n background-position: 7% center !important;\n width: 77%;\n}\n</code></pre>\n"
},
{
"answer_id": 264692,
"author": "ahendwh2",
"author_id": 112098,
"author_profile": "https://wordpress.stackexchange.com/users/112098",
"pm_score": 2,
"selected": true,
"text": "<p>You have to add <code>background-image: none !important;</code> to your buttons CSS.</p>\n\n<p>Complete CSS-Rule:</p>\n\n<pre><code>@media screen and (max-width: 767px) {\n a.button.product_type_simple.add_to_cart_button.ajax_add_to_cart {\n background-image: none !important;\n }\n}\n</code></pre>\n"
}
]
| 2017/04/24 | [
"https://wordpress.stackexchange.com/questions/264693",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96432/"
]
| Looking for some fresh eyes on this,
I have a custom archive for my CPT and it's Taxonomies.
The page has a input search form to filter posts of the CPT as well as drop downs to filter by terms.
The issue is that on page load, when the loop instantiates WP\_Query args are overridden by `get_query_vars`.
For example, the `posts_per_page` is set to 2.
However, `query_vars` hijacks the args and changes it to 12 (for some reason, not declared anywhere else on the site)
Logic below.
```
$q = get_query_var( 'q' );
$args = array(
'post_type' => $post_type,
'post_status' => 'publish',
'orderby' => 'post_date',
'order' => 'DESC',
'paged' => $paged,
'posts_per_page' => $posts_per_page, // tried 2
'tax_query' => $tax_query,
's' => $q
);
$wp_query = new WP_Query( $args );
```
Form - see `q` as value
```
<form id="filter-form" role="search" method="get" class="" action="<?php the_permalink(); ?>">
<!-- Query -->
<label>
<span class="screen-reader-text"><?php echo _x( 'Enter Keyword', 'label' )?></span>
<input type="search" class="search-field"
placeholder="Keywords"
value="<?= $q ?>"
name="q"
title="<?php echo esc_attr_x( 'Enter Keyword', 'label' ) ?>"/>
</label>
etc
```
The filter is registered and hooked in functions.php as per codex
```
function add_query_vars_filter( $vars ){
$vars[] = "q";
return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );
``` | You have to add `background-image: none !important;` to your buttons CSS.
Complete CSS-Rule:
```
@media screen and (max-width: 767px) {
a.button.product_type_simple.add_to_cart_button.ajax_add_to_cart {
background-image: none !important;
}
}
``` |
264,749 | <p>Is there a way to trigger the post saving or updating event in code? such as <code>do_action('save_post', $post_id)</code>;
The function here seems to imply that a WP_POST object needs to be passed in. Is there a way to basically imitate the action of updating the post with all its existing values. The point is for the other hooks linked to all trigger on post update. Maybe do a <code>wp_insert_post()</code>, just passing in the post id? </p>
<p><a href="https://developer.wordpress.org/reference/hooks/save_post/" rel="noreferrer">https://developer.wordpress.org/reference/hooks/save_post/</a><br>
<code>do_action( 'save_post', int $post_ID, WP_Post $post, bool $update )</code></p>
| [
{
"answer_id": 264785,
"author": "Welcher",
"author_id": 27210,
"author_profile": "https://wordpress.stackexchange.com/users/27210",
"pm_score": -1,
"selected": false,
"text": "<p>The answer to your question is to call <code>do_action</code> with the correct parameters. However, I would like to know more about why you're doing this - is there a post your saving programmatically?</p>\n"
},
{
"answer_id": 401120,
"author": "Martin Zeitler",
"author_id": 10288,
"author_profile": "https://wordpress.stackexchange.com/users/10288",
"pm_score": 0,
"selected": false,
"text": "<p>It's <a href=\"https://developer.wordpress.org/reference/functions/wp_insert_post/\" rel=\"nofollow noreferrer\"><code>wp_insert_post()</code></a> vs.\n<a href=\"https://developer.wordpress.org/reference/functions/wp_update_post/\" rel=\"nofollow noreferrer\"><code>wp_update_post()</code></a> - where update will ultimately also call:</p>\n<pre><code>return wp_insert_post( $postarr, $wp_error, $fire_after_hooks );\n</code></pre>\n<p>The term "once" implies that it is being fired "afterwards".</p>\n<pre><code>/**\n * Fires once a post has been saved.\n *\n * @since 1.5.0\n *\n * @param int $post_ID Post ID.\n * @param WP_Post $post Post object.\n * @param bool $update Whether this is an existing post being updated.\n */\ndo_action( 'save_post', $post_ID, $post, $update );\n</code></pre>\n<p>When inserting a post, <code>save_post</code> is being fired while <code>$fire_after_hooks</code> is <code>true</code>.<br/>\nAnd usually one may want to insert/update the record and not only fire the hook ...</p>\n"
}
]
| 2017/04/24 | [
"https://wordpress.stackexchange.com/questions/264749",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/117263/"
]
| Is there a way to trigger the post saving or updating event in code? such as `do_action('save_post', $post_id)`;
The function here seems to imply that a WP\_POST object needs to be passed in. Is there a way to basically imitate the action of updating the post with all its existing values. The point is for the other hooks linked to all trigger on post update. Maybe do a `wp_insert_post()`, just passing in the post id?
<https://developer.wordpress.org/reference/hooks/save_post/>
`do_action( 'save_post', int $post_ID, WP_Post $post, bool $update )` | It's [`wp_insert_post()`](https://developer.wordpress.org/reference/functions/wp_insert_post/) vs.
[`wp_update_post()`](https://developer.wordpress.org/reference/functions/wp_update_post/) - where update will ultimately also call:
```
return wp_insert_post( $postarr, $wp_error, $fire_after_hooks );
```
The term "once" implies that it is being fired "afterwards".
```
/**
* Fires once a post has been saved.
*
* @since 1.5.0
*
* @param int $post_ID Post ID.
* @param WP_Post $post Post object.
* @param bool $update Whether this is an existing post being updated.
*/
do_action( 'save_post', $post_ID, $post, $update );
```
When inserting a post, `save_post` is being fired while `$fire_after_hooks` is `true`.
And usually one may want to insert/update the record and not only fire the hook ... |
264,757 | <p>I have built an store on WooCommerce, I've used <a href="https://wordpress.org/support/plugin/wc-cancel-order" rel="nofollow noreferrer">WC Cancel Order</a> plugin to implement Cancel Order functionality for COD as well. But when any user requests for cancellation and even after it's approved by the admin, the quantity of the product does not restore.</p>
| [
{
"answer_id": 264785,
"author": "Welcher",
"author_id": 27210,
"author_profile": "https://wordpress.stackexchange.com/users/27210",
"pm_score": -1,
"selected": false,
"text": "<p>The answer to your question is to call <code>do_action</code> with the correct parameters. However, I would like to know more about why you're doing this - is there a post your saving programmatically?</p>\n"
},
{
"answer_id": 401120,
"author": "Martin Zeitler",
"author_id": 10288,
"author_profile": "https://wordpress.stackexchange.com/users/10288",
"pm_score": 0,
"selected": false,
"text": "<p>It's <a href=\"https://developer.wordpress.org/reference/functions/wp_insert_post/\" rel=\"nofollow noreferrer\"><code>wp_insert_post()</code></a> vs.\n<a href=\"https://developer.wordpress.org/reference/functions/wp_update_post/\" rel=\"nofollow noreferrer\"><code>wp_update_post()</code></a> - where update will ultimately also call:</p>\n<pre><code>return wp_insert_post( $postarr, $wp_error, $fire_after_hooks );\n</code></pre>\n<p>The term "once" implies that it is being fired "afterwards".</p>\n<pre><code>/**\n * Fires once a post has been saved.\n *\n * @since 1.5.0\n *\n * @param int $post_ID Post ID.\n * @param WP_Post $post Post object.\n * @param bool $update Whether this is an existing post being updated.\n */\ndo_action( 'save_post', $post_ID, $post, $update );\n</code></pre>\n<p>When inserting a post, <code>save_post</code> is being fired while <code>$fire_after_hooks</code> is <code>true</code>.<br/>\nAnd usually one may want to insert/update the record and not only fire the hook ...</p>\n"
}
]
| 2017/04/24 | [
"https://wordpress.stackexchange.com/questions/264757",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114978/"
]
| I have built an store on WooCommerce, I've used [WC Cancel Order](https://wordpress.org/support/plugin/wc-cancel-order) plugin to implement Cancel Order functionality for COD as well. But when any user requests for cancellation and even after it's approved by the admin, the quantity of the product does not restore. | It's [`wp_insert_post()`](https://developer.wordpress.org/reference/functions/wp_insert_post/) vs.
[`wp_update_post()`](https://developer.wordpress.org/reference/functions/wp_update_post/) - where update will ultimately also call:
```
return wp_insert_post( $postarr, $wp_error, $fire_after_hooks );
```
The term "once" implies that it is being fired "afterwards".
```
/**
* Fires once a post has been saved.
*
* @since 1.5.0
*
* @param int $post_ID Post ID.
* @param WP_Post $post Post object.
* @param bool $update Whether this is an existing post being updated.
*/
do_action( 'save_post', $post_ID, $post, $update );
```
When inserting a post, `save_post` is being fired while `$fire_after_hooks` is `true`.
And usually one may want to insert/update the record and not only fire the hook ... |
264,780 | <p>I'm trying to do custom function when new user register then adds new user role, new user role is the username. </p>
<p>For example, when user register and the username is apple, It will automatically create a role called Apple and assign to Apple user.</p>
<pre><code>add_action( 'user_register', 'add_new_role' );
function add_new_role() {
$result = add_role(
'user_name',
__( 'user_name' ),
array(
'read' => true, // true allows this capability
'edit_posts' => true,
'delete_posts' => false, // Use false to explicitly deny
)
);
}
</code></pre>
<p>This code can be implemented when a new user is registered and create a role called username, I don't know how to get the username from the form and I want it automatically assign the new role to the new user.</p>
<p>Thank you for the help.</p>
| [
{
"answer_id": 264786,
"author": "hwl",
"author_id": 118366,
"author_profile": "https://wordpress.stackexchange.com/users/118366",
"pm_score": 0,
"selected": false,
"text": "<p>The function <em>get_userdata()</em> will return a WP_User object so you can access the <em>user_login</em> (aka username).\nAlso, once you have that WP_User object in a variable, you can just do </p>\n\n<p>$variable->add_role()</p>\n\n<p>In full, something like this:</p>\n\n<pre><code>add_action('user_register', 'add_role_to_new_user', 10, 1);\nfunction add_role_to_new_user( $user_id ) {\n\n $newUser = get_userdata( $user_id ); //WP_User object so we can get the login name\n\n $newRoleName = $newUser->user_login; // login name in variable\n\n $newUser->add_role(\n $newRoleName,\n __( $newRoleName ),\n array(\n 'read' => true, // true allows this capability\n 'edit_posts' => true,\n 'delete_posts' => false, // Use false to explicitly deny\n ); //\n }\n\n}\n</code></pre>\n\n<p><strong>Just to clarify some usage as your needs/intent may dictate approach:</strong></p>\n\n<p>For @iyrin's point of <em>wp_get_current_user</em>, that is returning the id of the currently logged in user. If something alters the registration process (requires double-opt-in, etc.), then does <em>wp_get_current_user</em> have a value? No idea.</p>\n\n<p><em>get_userdata</em> here is taking the id from the newly registered user, regardless of if they are logged in.</p>\n\n<p>Secondly, using <em>wp_update_user</em> will <strong>replace</strong> the value of role. \n<em>add_role</em> will only add the role, not remove any previous role. </p>\n\n<p>So if your sign up gives a role of subscriber, <em>add_role</em> would add, in addition to that, a role with the user's login name.\n<em>wp_update_user</em> will replace the subscriber role with the user's login name role.</p>\n\n<p>I hope that helps.</p>\n"
},
{
"answer_id": 264790,
"author": "iyrin",
"author_id": 33393,
"author_profile": "https://wordpress.stackexchange.com/users/33393",
"pm_score": 2,
"selected": true,
"text": "<p>The <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/user_register\" rel=\"nofollow noreferrer\"><code>user_register</code></a> hook passes the parameter <code>$user_id</code> to your function. Get the login name after instantiating a user object with <a href=\"https://codex.wordpress.org/Function_Reference/get_userdata\" rel=\"nofollow noreferrer\"><code>get_userdata( $user_id )</code></a>. </p>\n\n<p>Update the assigned user role with <a href=\"https://developer.wordpress.org/reference/functions/wp_update_user/\" rel=\"nofollow noreferrer\"><code>wp_update_user</code></a>. Alternatively, you can use <a href=\"https://codex.wordpress.org/Function_Reference/add_role\" rel=\"nofollow noreferrer\"><code>add_role</code></a> to assign the new role in addition to the currently assigned role instead of removing the currently defined role with <code>wp_update_user</code>.</p>\n\n<pre><code>add_action( 'user_register', 'abc_assign_role' );\n\nfunction abc_assign_role( $user_id ) {\n // Instantiate user object.\n $userobj = get_userdata( $user_id );\n // Define new role using the login name of this user object.\n $new_role = $userobj->user_login;\n\n // Create the role.\n add_role(\n $new_role,\n __( $new_role ),\n array(\n 'read' => true,\n 'edit_posts' => true,\n 'delete_posts' => false,\n )\n );\n\n // Assign a new role to this user, replacing the currently assigned role.\n wp_update_user( array( 'ID' => $user_id, 'role' => $new_role ) );\n // Assign additional role to the user, leaving the default role that is currently assigned to the user.\n // $userobj->add_role( $new_role );\n}\n</code></pre>\n"
}
]
| 2017/04/25 | [
"https://wordpress.stackexchange.com/questions/264780",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118364/"
]
| I'm trying to do custom function when new user register then adds new user role, new user role is the username.
For example, when user register and the username is apple, It will automatically create a role called Apple and assign to Apple user.
```
add_action( 'user_register', 'add_new_role' );
function add_new_role() {
$result = add_role(
'user_name',
__( 'user_name' ),
array(
'read' => true, // true allows this capability
'edit_posts' => true,
'delete_posts' => false, // Use false to explicitly deny
)
);
}
```
This code can be implemented when a new user is registered and create a role called username, I don't know how to get the username from the form and I want it automatically assign the new role to the new user.
Thank you for the help. | The [`user_register`](https://codex.wordpress.org/Plugin_API/Action_Reference/user_register) hook passes the parameter `$user_id` to your function. Get the login name after instantiating a user object with [`get_userdata( $user_id )`](https://codex.wordpress.org/Function_Reference/get_userdata).
Update the assigned user role with [`wp_update_user`](https://developer.wordpress.org/reference/functions/wp_update_user/). Alternatively, you can use [`add_role`](https://codex.wordpress.org/Function_Reference/add_role) to assign the new role in addition to the currently assigned role instead of removing the currently defined role with `wp_update_user`.
```
add_action( 'user_register', 'abc_assign_role' );
function abc_assign_role( $user_id ) {
// Instantiate user object.
$userobj = get_userdata( $user_id );
// Define new role using the login name of this user object.
$new_role = $userobj->user_login;
// Create the role.
add_role(
$new_role,
__( $new_role ),
array(
'read' => true,
'edit_posts' => true,
'delete_posts' => false,
)
);
// Assign a new role to this user, replacing the currently assigned role.
wp_update_user( array( 'ID' => $user_id, 'role' => $new_role ) );
// Assign additional role to the user, leaving the default role that is currently assigned to the user.
// $userobj->add_role( $new_role );
}
``` |
264,802 | <p>I want to know is there any wordpres function that allow me to check whether the given string is title of any wordpress custom post type or not.</p>
| [
{
"answer_id": 264806,
"author": "David Klhufek",
"author_id": 113922,
"author_profile": "https://wordpress.stackexchange.com/users/113922",
"pm_score": 2,
"selected": false,
"text": "<p>you can do it with Function <strong>post_type_exists</strong>\n<a href=\"https://codex.wordpress.org/Function_Reference/post_type_exists\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/post_type_exists</a></p>\n\n<p><strong>Examples</strong></p>\n\n<pre><code>if ( post_type_exists( 'book' ) ) {\n echo 'the Book post type exists';\n}\n$exists = post_type_exists( 'post' );\n// returns true\n\n$exists = post_type_exists( 'page' );\n// returns true\n\n$exists = post_type_exists( 'book' );\n// returns true if book is a registered post type\n\n$exists = post_type_exists( 'xyz' );\n// returns false if xyz is not a registered post type\n</code></pre>\n"
},
{
"answer_id": 264812,
"author": "Wpdev1101",
"author_id": 117292,
"author_profile": "https://wordpress.stackexchange.com/users/117292",
"pm_score": 1,
"selected": false,
"text": "<p>I have found a solution for this query. Wordpress has inbuilt query which allows you to check whether the post exists in wordpress or not.\nThe function I have found is post_exists(). Which is located into wp-admin/includes/posts.php</p>\n"
}
]
| 2017/04/25 | [
"https://wordpress.stackexchange.com/questions/264802",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/117292/"
]
| I want to know is there any wordpres function that allow me to check whether the given string is title of any wordpress custom post type or not. | you can do it with Function **post\_type\_exists**
<https://codex.wordpress.org/Function_Reference/post_type_exists>
**Examples**
```
if ( post_type_exists( 'book' ) ) {
echo 'the Book post type exists';
}
$exists = post_type_exists( 'post' );
// returns true
$exists = post_type_exists( 'page' );
// returns true
$exists = post_type_exists( 'book' );
// returns true if book is a registered post type
$exists = post_type_exists( 'xyz' );
// returns false if xyz is not a registered post type
``` |
264,822 | <p>I currently have a multisite install with 4 sites and 4 domains, like so:</p>
<p><code>Site 1</code> -> <code>site1.com</code></p>
<p><code>Site 2</code> -> <code>site2.com</code></p>
<p><code>Site 3</code> -> <code>site3.com</code></p>
<p><code>Site 4</code> -> <code>site4.com</code></p>
<p>There was a typo in the domain of <code>Site 3</code>, so we changed <code>site3.com</code> to <code>site3-new.com</code>. So far so good. Now we want <code>site3-new.com</code> to show <code>Site 3</code>, and we want <code>site3.com</code> to show <code>site3-new.com</code>.</p>
<p>That last step is causing me endless headache. What's happening right now is that visiting <code>site3-new.com</code> opens up <code>Site 3</code>, while visiting <code>site3.com</code> opens <code>Site 1</code> (it redirects 302 to <code>site1.com</code>), presumably because in wp-config <code>site1.com</code> is set as <code>'DOMAIN_CURRENT_SITE'</code>.</p>
<p>What can I do to show 1 site from the multisite instalation for 2 separate domains?</p>
<p>Thanks.</p>
| [
{
"answer_id": 264806,
"author": "David Klhufek",
"author_id": 113922,
"author_profile": "https://wordpress.stackexchange.com/users/113922",
"pm_score": 2,
"selected": false,
"text": "<p>you can do it with Function <strong>post_type_exists</strong>\n<a href=\"https://codex.wordpress.org/Function_Reference/post_type_exists\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/post_type_exists</a></p>\n\n<p><strong>Examples</strong></p>\n\n<pre><code>if ( post_type_exists( 'book' ) ) {\n echo 'the Book post type exists';\n}\n$exists = post_type_exists( 'post' );\n// returns true\n\n$exists = post_type_exists( 'page' );\n// returns true\n\n$exists = post_type_exists( 'book' );\n// returns true if book is a registered post type\n\n$exists = post_type_exists( 'xyz' );\n// returns false if xyz is not a registered post type\n</code></pre>\n"
},
{
"answer_id": 264812,
"author": "Wpdev1101",
"author_id": 117292,
"author_profile": "https://wordpress.stackexchange.com/users/117292",
"pm_score": 1,
"selected": false,
"text": "<p>I have found a solution for this query. Wordpress has inbuilt query which allows you to check whether the post exists in wordpress or not.\nThe function I have found is post_exists(). Which is located into wp-admin/includes/posts.php</p>\n"
}
]
| 2017/04/25 | [
"https://wordpress.stackexchange.com/questions/264822",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82285/"
]
| I currently have a multisite install with 4 sites and 4 domains, like so:
`Site 1` -> `site1.com`
`Site 2` -> `site2.com`
`Site 3` -> `site3.com`
`Site 4` -> `site4.com`
There was a typo in the domain of `Site 3`, so we changed `site3.com` to `site3-new.com`. So far so good. Now we want `site3-new.com` to show `Site 3`, and we want `site3.com` to show `site3-new.com`.
That last step is causing me endless headache. What's happening right now is that visiting `site3-new.com` opens up `Site 3`, while visiting `site3.com` opens `Site 1` (it redirects 302 to `site1.com`), presumably because in wp-config `site1.com` is set as `'DOMAIN_CURRENT_SITE'`.
What can I do to show 1 site from the multisite instalation for 2 separate domains?
Thanks. | you can do it with Function **post\_type\_exists**
<https://codex.wordpress.org/Function_Reference/post_type_exists>
**Examples**
```
if ( post_type_exists( 'book' ) ) {
echo 'the Book post type exists';
}
$exists = post_type_exists( 'post' );
// returns true
$exists = post_type_exists( 'page' );
// returns true
$exists = post_type_exists( 'book' );
// returns true if book is a registered post type
$exists = post_type_exists( 'xyz' );
// returns false if xyz is not a registered post type
``` |
264,866 | <p>Is it possible to create a sign up form that can work through WP REST API for visitors to be able to create accounts on my site?</p>
<p>I can create such a form and use it to create new users. This works with wp_rest nonce when I am logged in as administrator.</p>
<p>But if there is a visitor which is not logged in, the same form does not work of course. I think this is a question of authentication. Can you suggest a general idea how this can work? How can I allow visitors to be able to sign up with REST API?</p>
| [
{
"answer_id": 265005,
"author": "JSP",
"author_id": 23259,
"author_profile": "https://wordpress.stackexchange.com/users/23259",
"pm_score": 2,
"selected": false,
"text": "<p>You could create your own signup routine using <code>wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php</code> (WP v4.7.4) as a reference implementation. You could also modify the WordPress version by doing something like the following:</p>\n\n<pre><code>function nLbwuEa8_modify_create_user_route() {\n $users_controller = new WP_REST_Users_Controller();\n\n register_rest_route( 'wp/v2', '/users', array(\n array(\n 'methods' => WP_REST_Server::CREATABLE,\n 'callback' => array($users_controller, 'create_item'),\n 'permission_callback' => function( $request ) {\n\n // METHOD 1: Silently force the role to be a subscriber\n // $request->set_param('roles', array('subscriber'));\n\n // METHOD 2: Be nice and provide an error message\n if ( ! current_user_can( 'create_users' ) && $request['roles'] !== array('subscriber')) {\n\n return new WP_Error(\n 'rest_cannot_create_user',\n __( 'Sorry, you are only allowed to create new users with the subscriber role.' ),\n array( 'status' => rest_authorization_required_code() )\n );\n\n }\n\n return true;\n },\n 'args' => $users_controller->get_endpoint_args_for_item_schema( WP_REST_Server::CREATABLE ),\n ),\n ) );\n\n} );\nadd_action( 'rest_api_init', 'nLbwuEa8_modify_create_user_route' );\n</code></pre>\n\n<p>The important parts being the <code>permission_callback</code> key (where you are essentially disabling authentication). And the <code>args</code> key that could be used to add a captcha so spammers don't overrun the service. Hope this helps.</p>\n"
},
{
"answer_id": 280052,
"author": "Shawn H",
"author_id": 32680,
"author_profile": "https://wordpress.stackexchange.com/users/32680",
"pm_score": 0,
"selected": false,
"text": "<p>I would create a custom route for your site that collects the fields you need and then calls the internal wp_insert_user() function. This way you'd be able to validate the information the user is providing, including restricting which role they're allowed to get. I'd also be tempted to limit the # of users that can be created by the same IP address in a day, or something like that.</p>\n"
},
{
"answer_id": 302330,
"author": "Jack Song",
"author_id": 134082,
"author_profile": "https://wordpress.stackexchange.com/users/134082",
"pm_score": 3,
"selected": false,
"text": "<p>hopefully you've found the answer already. Here's our solution, for your reference. :D</p>\n<p>The following code should add User Registration via REST API to your WordPress Website. It supports Registration of 'subscriber' and 'customer'.</p>\n<p>Add it to your function.php</p>\n<pre><code>add_action('rest_api_init', 'wp_rest_user_endpoints');\n/**\n * Register a new user\n *\n * @param WP_REST_Request $request Full details about the request.\n * @return array $args.\n **/\nfunction wp_rest_user_endpoints($request) {\n /**\n * Handle Register User request.\n */\n register_rest_route('wp/v2', 'users/register', array(\n 'methods' => 'POST',\n 'callback' => 'wc_rest_user_endpoint_handler',\n ));\n}\nfunction wc_rest_user_endpoint_handler($request = null) {\n $response = array();\n $parameters = $request->get_json_params();\n $username = sanitize_text_field($parameters['username']);\n $email = sanitize_text_field($parameters['email']);\n $password = sanitize_text_field($parameters['password']);\n // $role = sanitize_text_field($parameters['role']);\n $error = new WP_Error();\n if (empty($username)) {\n $error->add(400, __("Username field 'username' is required.", 'wp-rest-user'), array('status' => 400));\n return $error;\n }\n if (empty($email)) {\n $error->add(401, __("Email field 'email' is required.", 'wp-rest-user'), array('status' => 400));\n return $error;\n }\n if (empty($password)) {\n $error->add(404, __("Password field 'password' is required.", 'wp-rest-user'), array('status' => 400));\n return $error;\n }\n // if (empty($role)) {\n // $role = 'subscriber';\n // } else {\n // if ($GLOBALS['wp_roles']->is_role($role)) {\n // // Silence is gold\n // } else {\n // $error->add(405, __("Role field 'role' is not a valid. Check your User Roles from Dashboard.", 'wp_rest_user'), array('status' => 400));\n // return $error;\n // }\n // }\n $user_id = username_exists($username);\n if (!$user_id && email_exists($email) == false) {\n $user_id = wp_create_user($username, $password, $email);\n if (!is_wp_error($user_id)) {\n // Ger User Meta Data (Sensitive, Password included. DO NOT pass to front end.)\n $user = get_user_by('id', $user_id);\n // $user->set_role($role);\n $user->set_role('subscriber');\n // WooCommerce specific code\n if (class_exists('WooCommerce')) {\n $user->set_role('customer');\n }\n // Ger User Data (Non-Sensitive, Pass to front end.)\n $response['code'] = 200;\n $response['message'] = __("User '" . $username . "' Registration was Successful", "wp-rest-user");\n } else {\n return $user_id;\n }\n } else {\n $error->add(406, __("Email already exists, please try 'Reset Password'", 'wp-rest-user'), array('status' => 400));\n return $error;\n }\n return new WP_REST_Response($response, 123);\n}\n</code></pre>\n<p>IMHO, a more better way would to include the additional function as a seperate plugin. So even when your user changed theme, your api calls won't be affected.</p>\n<p>Therefore I've developed a <strong>plugin</strong> for User Registration via REST API in WordPress. Better yet, it supports creating 'customer' for WooCommerce too!</p>\n<p><a href=\"https://wordpress.org/plugins/wp-rest-user/\" rel=\"nofollow noreferrer\">WP REST User</a>, check it out if you want.</p>\n"
},
{
"answer_id": 345921,
"author": "riot",
"author_id": 164004,
"author_profile": "https://wordpress.stackexchange.com/users/164004",
"pm_score": 0,
"selected": false,
"text": "<p>Now there is a plugin called <a href=\"https://wordpress.org/plugins/wp-webhooks/\" rel=\"nofollow noreferrer\">WP Webhooks</a> that can do this. </p>\n\n<p>According to the plugin page:</p>\n\n<p>It allows you to trigger actions (such as creating a user or a post) in WordPress upon receiving data from other services. </p>\n\n<p>Many form solutions work with Zapier (including Gravity Forms, JotForm, Formidable, and even Google Forms) so one of these could be used to trigger a new user signup using this method.</p>\n\n<p>Wordpress is already has <a href=\"https://zapier.com/apps/wordpress/integrations\" rel=\"nofollow noreferrer\">native Zapier support</a> without this plugin, but creating a new user is not a supported action using the native WordPress Zapier app.</p>\n"
},
{
"answer_id": 375175,
"author": "Mozart",
"author_id": 116632,
"author_profile": "https://wordpress.stackexchange.com/users/116632",
"pm_score": -1,
"selected": false,
"text": "<p>Try <a href=\"https://wordpress.org/plugins/wp-rest-user/\" rel=\"nofollow noreferrer\">WP REST User</a> it has create user and reset password functionality</p>\n"
}
]
| 2017/04/25 | [
"https://wordpress.stackexchange.com/questions/264866",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118403/"
]
| Is it possible to create a sign up form that can work through WP REST API for visitors to be able to create accounts on my site?
I can create such a form and use it to create new users. This works with wp\_rest nonce when I am logged in as administrator.
But if there is a visitor which is not logged in, the same form does not work of course. I think this is a question of authentication. Can you suggest a general idea how this can work? How can I allow visitors to be able to sign up with REST API? | hopefully you've found the answer already. Here's our solution, for your reference. :D
The following code should add User Registration via REST API to your WordPress Website. It supports Registration of 'subscriber' and 'customer'.
Add it to your function.php
```
add_action('rest_api_init', 'wp_rest_user_endpoints');
/**
* Register a new user
*
* @param WP_REST_Request $request Full details about the request.
* @return array $args.
**/
function wp_rest_user_endpoints($request) {
/**
* Handle Register User request.
*/
register_rest_route('wp/v2', 'users/register', array(
'methods' => 'POST',
'callback' => 'wc_rest_user_endpoint_handler',
));
}
function wc_rest_user_endpoint_handler($request = null) {
$response = array();
$parameters = $request->get_json_params();
$username = sanitize_text_field($parameters['username']);
$email = sanitize_text_field($parameters['email']);
$password = sanitize_text_field($parameters['password']);
// $role = sanitize_text_field($parameters['role']);
$error = new WP_Error();
if (empty($username)) {
$error->add(400, __("Username field 'username' is required.", 'wp-rest-user'), array('status' => 400));
return $error;
}
if (empty($email)) {
$error->add(401, __("Email field 'email' is required.", 'wp-rest-user'), array('status' => 400));
return $error;
}
if (empty($password)) {
$error->add(404, __("Password field 'password' is required.", 'wp-rest-user'), array('status' => 400));
return $error;
}
// if (empty($role)) {
// $role = 'subscriber';
// } else {
// if ($GLOBALS['wp_roles']->is_role($role)) {
// // Silence is gold
// } else {
// $error->add(405, __("Role field 'role' is not a valid. Check your User Roles from Dashboard.", 'wp_rest_user'), array('status' => 400));
// return $error;
// }
// }
$user_id = username_exists($username);
if (!$user_id && email_exists($email) == false) {
$user_id = wp_create_user($username, $password, $email);
if (!is_wp_error($user_id)) {
// Ger User Meta Data (Sensitive, Password included. DO NOT pass to front end.)
$user = get_user_by('id', $user_id);
// $user->set_role($role);
$user->set_role('subscriber');
// WooCommerce specific code
if (class_exists('WooCommerce')) {
$user->set_role('customer');
}
// Ger User Data (Non-Sensitive, Pass to front end.)
$response['code'] = 200;
$response['message'] = __("User '" . $username . "' Registration was Successful", "wp-rest-user");
} else {
return $user_id;
}
} else {
$error->add(406, __("Email already exists, please try 'Reset Password'", 'wp-rest-user'), array('status' => 400));
return $error;
}
return new WP_REST_Response($response, 123);
}
```
IMHO, a more better way would to include the additional function as a seperate plugin. So even when your user changed theme, your api calls won't be affected.
Therefore I've developed a **plugin** for User Registration via REST API in WordPress. Better yet, it supports creating 'customer' for WooCommerce too!
[WP REST User](https://wordpress.org/plugins/wp-rest-user/), check it out if you want. |
264,896 | <p>I'm trying to query a custom post type's category to display in another custom post type, but only if they have matching categories.</p>
<p>I'm new to coding a fairly complex WordPress site from scratch (it's fun) - I think I am probably typing the query wrong - any help will be appreciated.</p>
<pre><code> <section id="meet-team">
<div class="container">
<h2>Title will be custom field</h2>
<p class="lead">custom field text will be in here</p>
<div class="row">
<?php $category = get_category( get_query_var( 'cat' ) );
</code></pre>
<p>$cat_id = $category->cat_ID; ?></p>
<pre><code> <?php get_posts($args =array(
'posts_per_page' => 2,
'post_type' => 'team',
'category' =>$cat_ID) ); ?> <!-- this is the bit I think I am struggling with -->
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div class="col-6">
<?php if ( has_post_thumbnail()) { $url = wp_get_attachment_url( get_post_thumbnail_id() ); ?>
<img src="<?php echo $url; ?>" alt="<?php the_title() ?>">
<h3><?php the_title() ?></h3>
<p><?php the_excerpt() ?></p>
<a href="<?php the_permalink() ?>"></a>
</div><!-- col -->
<?php } ?>
<?php endwhile; endif; ?>
</div><!-- row -->
</div><!-- container -->
</section><!-- meet-team -->
<?php wp_reset_query(); ?>
</code></pre>
| [
{
"answer_id": 264900,
"author": "jdm2112",
"author_id": 45202,
"author_profile": "https://wordpress.stackexchange.com/users/45202",
"pm_score": 0,
"selected": false,
"text": "<p>Based on your posted code, you have a mismatch in your variable<code>$cat_id</code>. In the first instance, where you assign a value, it is all lowercase:</p>\n\n<pre><code>$cat_id = $category->cat_ID;\n</code></pre>\n\n<p>In your query args, you have capitalized the ID portion:</p>\n\n<pre><code>'category' => $cat_ID <-- does not match your earlier var\n</code></pre>\n"
},
{
"answer_id": 264908,
"author": "Michael",
"author_id": 4884,
"author_profile": "https://wordpress.stackexchange.com/users/4884",
"pm_score": 2,
"selected": true,
"text": "<p>if you are adding the custom query into the single template, try working with <a href=\"https://developer.wordpress.org/reference/functions/get_the_category/\" rel=\"nofollow noreferrer\"><code>get_the_category()</code></a> to get the cat_id for your query; \nalso, <a href=\"https://codex.wordpress.org/Template_Tags/get_posts\" rel=\"nofollow noreferrer\"><code>get_posts()</code></a> does not work with <code>if( have_posts() )</code> etc.</p>\n\n<p>example code, using a custom query:</p>\n\n<pre><code> <?php \n $cat = get_the_category();\n\n $cat_id = $cat[0]->term_ID; \n\n $cpt_match_query = new WP_Query( array(\n 'posts_per_page' => 2, \n 'post_type' => 'team', \n 'cat' => $cat_id) ); \n\n if ( $cpt_match_query->have_posts() ) : \n while ( $cpt_match_query->have_posts() ) : \n $cpt_match_query->the_post(); \n ?>\n\n YOUR OUTPUT SECTION\n\n <?php \n endwhile;\n endif; \n wp_reset_postdata();\n ?>\n</code></pre>\n\n<p>the above does not take care of the html tags in your code, which also need to be readjusted.</p>\n"
}
]
| 2017/04/25 | [
"https://wordpress.stackexchange.com/questions/264896",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114208/"
]
| I'm trying to query a custom post type's category to display in another custom post type, but only if they have matching categories.
I'm new to coding a fairly complex WordPress site from scratch (it's fun) - I think I am probably typing the query wrong - any help will be appreciated.
```
<section id="meet-team">
<div class="container">
<h2>Title will be custom field</h2>
<p class="lead">custom field text will be in here</p>
<div class="row">
<?php $category = get_category( get_query_var( 'cat' ) );
```
$cat\_id = $category->cat\_ID; ?>
```
<?php get_posts($args =array(
'posts_per_page' => 2,
'post_type' => 'team',
'category' =>$cat_ID) ); ?> <!-- this is the bit I think I am struggling with -->
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div class="col-6">
<?php if ( has_post_thumbnail()) { $url = wp_get_attachment_url( get_post_thumbnail_id() ); ?>
<img src="<?php echo $url; ?>" alt="<?php the_title() ?>">
<h3><?php the_title() ?></h3>
<p><?php the_excerpt() ?></p>
<a href="<?php the_permalink() ?>"></a>
</div><!-- col -->
<?php } ?>
<?php endwhile; endif; ?>
</div><!-- row -->
</div><!-- container -->
</section><!-- meet-team -->
<?php wp_reset_query(); ?>
``` | if you are adding the custom query into the single template, try working with [`get_the_category()`](https://developer.wordpress.org/reference/functions/get_the_category/) to get the cat\_id for your query;
also, [`get_posts()`](https://codex.wordpress.org/Template_Tags/get_posts) does not work with `if( have_posts() )` etc.
example code, using a custom query:
```
<?php
$cat = get_the_category();
$cat_id = $cat[0]->term_ID;
$cpt_match_query = new WP_Query( array(
'posts_per_page' => 2,
'post_type' => 'team',
'cat' => $cat_id) );
if ( $cpt_match_query->have_posts() ) :
while ( $cpt_match_query->have_posts() ) :
$cpt_match_query->the_post();
?>
YOUR OUTPUT SECTION
<?php
endwhile;
endif;
wp_reset_postdata();
?>
```
the above does not take care of the html tags in your code, which also need to be readjusted. |
264,924 | <p>This is my table. I simply would like one select statement that returns coupon_code, max_uses, and times_used. I don't know how to join it all to do that.</p>
<pre><code>mysql> select * from wp_postmeta where post_id = '207717';
+---------+---------+------------------------+-------------------------------+
| meta_id | post_id | meta_key | meta_value |
+---------+---------+------------------------+-------------------------------+
| 795679 | 207717 | coupon_code | emeraldcity |
| 795689 | 207717 | max_uses | 30 |
| 795699 | 207717 | start_date | 2016-07-22 |
| 795704 | 207717 | _end_date | WPMUDEV_Field_Datepicker |
| 795705 | 207717 | _edit_lock | 1492003198:1 |
| 913311 | 207717 | times_used | 22 |
+---------+---------+------------------------+-------------------------------+
</code></pre>
<p>For example, this gets me just max_uses.</p>
<pre><code>mysql> select * from wp_postmeta where post_id = '207717' and meta_key = 'max_uses';
+---------+---------+----------+------------+
| meta_id | post_id | meta_key | meta_value |
+---------+---------+----------+------------+
| 795689 | 207717 | max_uses | 30 |
+---------+---------+----------+------------+
</code></pre>
| [
{
"answer_id": 264926,
"author": "Welcher",
"author_id": 27210,
"author_profile": "https://wordpress.stackexchange.com/users/27210",
"pm_score": 1,
"selected": false,
"text": "<p>If you use <a href=\"https://developer.wordpress.org/reference/functions/get_post_meta/\" rel=\"nofollow noreferrer\">get_post_meta()</a> with just the first parameter ( post ID ) you'll get an array of all the post meta for the passed ID. You'll get more than you expect but you can then use any number of ways to get the data that you want out.</p>\n\n<p><code>$post_meta = get_post_meta( 207717 )</code></p>\n"
},
{
"answer_id": 264928,
"author": "Oleg Butuzov",
"author_id": 14536,
"author_profile": "https://wordpress.stackexchange.com/users/14536",
"pm_score": 0,
"selected": false,
"text": "<p>You can use <a href=\"https://dev.mysql.com/doc/refman/5.7/en/derived-tables.html\" rel=\"nofollow noreferrer\">IN</a> Clause</p>\n\n<pre><code>mysql> select * from wp_postmeta where post_id = '207717' and meta_key IN ( 'max_uses', 'coupon_code');\n+---------+---------+-------------+-------------+\n| meta_id | post_id | meta_key | meta_value |\n+---------+---------+-------------+-------------+\n| 795679 | 207717 | coupon_code | emeraldcity | \n| 795689 | 207717 | max_uses | 30 |\n+---------+---------+-------------+-------------+\n</code></pre>\n"
}
]
| 2017/04/26 | [
"https://wordpress.stackexchange.com/questions/264924",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118439/"
]
| This is my table. I simply would like one select statement that returns coupon\_code, max\_uses, and times\_used. I don't know how to join it all to do that.
```
mysql> select * from wp_postmeta where post_id = '207717';
+---------+---------+------------------------+-------------------------------+
| meta_id | post_id | meta_key | meta_value |
+---------+---------+------------------------+-------------------------------+
| 795679 | 207717 | coupon_code | emeraldcity |
| 795689 | 207717 | max_uses | 30 |
| 795699 | 207717 | start_date | 2016-07-22 |
| 795704 | 207717 | _end_date | WPMUDEV_Field_Datepicker |
| 795705 | 207717 | _edit_lock | 1492003198:1 |
| 913311 | 207717 | times_used | 22 |
+---------+---------+------------------------+-------------------------------+
```
For example, this gets me just max\_uses.
```
mysql> select * from wp_postmeta where post_id = '207717' and meta_key = 'max_uses';
+---------+---------+----------+------------+
| meta_id | post_id | meta_key | meta_value |
+---------+---------+----------+------------+
| 795689 | 207717 | max_uses | 30 |
+---------+---------+----------+------------+
``` | If you use [get\_post\_meta()](https://developer.wordpress.org/reference/functions/get_post_meta/) with just the first parameter ( post ID ) you'll get an array of all the post meta for the passed ID. You'll get more than you expect but you can then use any number of ways to get the data that you want out.
`$post_meta = get_post_meta( 207717 )` |
264,930 | <p>I am using Wordpress, I have some URL issue. </p>
<p>My current URL is IP address on server: <code>http://www.192.10.1.22/states/?q=ohio</code></p>
<p>I want URL: <code>http://www.192.10.1.22/states/ohio</code></p>
<p>I used following code in <code>functions.php</code> file and it's working in my
local but when I upload in Cpanel then it's now working given me an error
page not found.</p>
<pre><code>function custom_rewrite_rule() {
add_rewrite_rule(
'states/([^/]*)/?',
'index.php/states/?q=$1',
'top' );
}
add_action('init', 'custom_rewrite_rule', 10, 0);
</code></pre>
<p>I also update permalink and apache mode_rewrite is also on. So how could I solve this issue?</p>
| [
{
"answer_id": 264926,
"author": "Welcher",
"author_id": 27210,
"author_profile": "https://wordpress.stackexchange.com/users/27210",
"pm_score": 1,
"selected": false,
"text": "<p>If you use <a href=\"https://developer.wordpress.org/reference/functions/get_post_meta/\" rel=\"nofollow noreferrer\">get_post_meta()</a> with just the first parameter ( post ID ) you'll get an array of all the post meta for the passed ID. You'll get more than you expect but you can then use any number of ways to get the data that you want out.</p>\n\n<p><code>$post_meta = get_post_meta( 207717 )</code></p>\n"
},
{
"answer_id": 264928,
"author": "Oleg Butuzov",
"author_id": 14536,
"author_profile": "https://wordpress.stackexchange.com/users/14536",
"pm_score": 0,
"selected": false,
"text": "<p>You can use <a href=\"https://dev.mysql.com/doc/refman/5.7/en/derived-tables.html\" rel=\"nofollow noreferrer\">IN</a> Clause</p>\n\n<pre><code>mysql> select * from wp_postmeta where post_id = '207717' and meta_key IN ( 'max_uses', 'coupon_code');\n+---------+---------+-------------+-------------+\n| meta_id | post_id | meta_key | meta_value |\n+---------+---------+-------------+-------------+\n| 795679 | 207717 | coupon_code | emeraldcity | \n| 795689 | 207717 | max_uses | 30 |\n+---------+---------+-------------+-------------+\n</code></pre>\n"
}
]
| 2017/04/26 | [
"https://wordpress.stackexchange.com/questions/264930",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118443/"
]
| I am using Wordpress, I have some URL issue.
My current URL is IP address on server: `http://www.192.10.1.22/states/?q=ohio`
I want URL: `http://www.192.10.1.22/states/ohio`
I used following code in `functions.php` file and it's working in my
local but when I upload in Cpanel then it's now working given me an error
page not found.
```
function custom_rewrite_rule() {
add_rewrite_rule(
'states/([^/]*)/?',
'index.php/states/?q=$1',
'top' );
}
add_action('init', 'custom_rewrite_rule', 10, 0);
```
I also update permalink and apache mode\_rewrite is also on. So how could I solve this issue? | If you use [get\_post\_meta()](https://developer.wordpress.org/reference/functions/get_post_meta/) with just the first parameter ( post ID ) you'll get an array of all the post meta for the passed ID. You'll get more than you expect but you can then use any number of ways to get the data that you want out.
`$post_meta = get_post_meta( 207717 )` |
264,932 | <p>Some time ago, I added the following lines to my custom theme's functions.php file, in order to allow authors on my site to edit posts and drafts from all users:</p>
<pre><code>function add_theme_caps() {
$role = get_role( 'author' );
$role->add_cap( 'edit_others_posts' );
}
add_action( 'admin_init', 'add_theme_caps');
</code></pre>
<p>It worked as expected. However, I now no longer want that functionality. I have removed those lines from my functions.php file, but authors can still edit all of the posts on the site. It's been a few hours since I updated the functions file in my theme's root folder and I have done hard reloads and reloads emptying the browser cache, but there is still no change.</p>
<p>Any ideas on what the problem could be? Could it be that those lines of code changed some other central Wordpress file? Or am I missing something by simply removing the code?</p>
| [
{
"answer_id": 264946,
"author": "JCM",
"author_id": 100958,
"author_profile": "https://wordpress.stackexchange.com/users/100958",
"pm_score": 1,
"selected": false,
"text": "<p>It looks like I have solved my own problem. I'm guessing that a function like that creates a permanent change, regardless of whether the function remains in the functions.php file. So, to fix this, I just added a new function reversing this adding. Here is that function:</p>\n\n<pre><code>function remove_theme_caps() {\n$role = get_role( 'author' );\n$role->remove_cap( 'edit_others_posts' );\n}\nadd_action( 'admin_init', 'remove_theme_caps');\n</code></pre>\n\n<p>This has restored the default setting of not allowing authors to edit other users' posts. And after uploading my functions file with this code, I have since deleted this section of code and re-uploaded my functions file, and the change (back to the default setting) has remained. So, problem solved!</p>\n"
},
{
"answer_id": 351881,
"author": "Jess_Pinkman",
"author_id": 171161,
"author_profile": "https://wordpress.stackexchange.com/users/171161",
"pm_score": 0,
"selected": false,
"text": "<p>add_cap will write to the database, this is not an operation you want to run every single time. You should hook this in very specific situations. ( most common would be register_activation_hook )</p>\n"
}
]
| 2017/04/26 | [
"https://wordpress.stackexchange.com/questions/264932",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/100958/"
]
| Some time ago, I added the following lines to my custom theme's functions.php file, in order to allow authors on my site to edit posts and drafts from all users:
```
function add_theme_caps() {
$role = get_role( 'author' );
$role->add_cap( 'edit_others_posts' );
}
add_action( 'admin_init', 'add_theme_caps');
```
It worked as expected. However, I now no longer want that functionality. I have removed those lines from my functions.php file, but authors can still edit all of the posts on the site. It's been a few hours since I updated the functions file in my theme's root folder and I have done hard reloads and reloads emptying the browser cache, but there is still no change.
Any ideas on what the problem could be? Could it be that those lines of code changed some other central Wordpress file? Or am I missing something by simply removing the code? | It looks like I have solved my own problem. I'm guessing that a function like that creates a permanent change, regardless of whether the function remains in the functions.php file. So, to fix this, I just added a new function reversing this adding. Here is that function:
```
function remove_theme_caps() {
$role = get_role( 'author' );
$role->remove_cap( 'edit_others_posts' );
}
add_action( 'admin_init', 'remove_theme_caps');
```
This has restored the default setting of not allowing authors to edit other users' posts. And after uploading my functions file with this code, I have since deleted this section of code and re-uploaded my functions file, and the change (back to the default setting) has remained. So, problem solved! |
264,939 | <p>I want to fetch multiple posts with categories and tags
currently I'm using this query:</p>
<pre><code>$pagesize = 20;
$pageNumber = 1;
$mysql = mysqli_query($con,"SELECT p.post_title,
p.ID,
p.post_content,
p.post_date,
p.post_name as url,
t.name as category_name
FROM wp_posts p,
wp_terms t,
wp_term_relationships r,
wp_term_taxonomy tt
WHERE p.post_status='publish' AND
tt.taxonomy = 'post_tag' AND
p.id=r.object_id AND
r.term_taxonomy_id=tt.term_taxonomy_id AND
tt.term_id = t.term_id
ORDER BY p.post_date desc
LIMIT ".(int)($pageNumber*$pageSize).",".(int)$pageSize."") or die ("error".mysqli_error($con));
</code></pre>
<p>The mysqli-connection works. But when I run this code, I only get a blank page. How can I fix this?</p>
| [
{
"answer_id": 264946,
"author": "JCM",
"author_id": 100958,
"author_profile": "https://wordpress.stackexchange.com/users/100958",
"pm_score": 1,
"selected": false,
"text": "<p>It looks like I have solved my own problem. I'm guessing that a function like that creates a permanent change, regardless of whether the function remains in the functions.php file. So, to fix this, I just added a new function reversing this adding. Here is that function:</p>\n\n<pre><code>function remove_theme_caps() {\n$role = get_role( 'author' );\n$role->remove_cap( 'edit_others_posts' );\n}\nadd_action( 'admin_init', 'remove_theme_caps');\n</code></pre>\n\n<p>This has restored the default setting of not allowing authors to edit other users' posts. And after uploading my functions file with this code, I have since deleted this section of code and re-uploaded my functions file, and the change (back to the default setting) has remained. So, problem solved!</p>\n"
},
{
"answer_id": 351881,
"author": "Jess_Pinkman",
"author_id": 171161,
"author_profile": "https://wordpress.stackexchange.com/users/171161",
"pm_score": 0,
"selected": false,
"text": "<p>add_cap will write to the database, this is not an operation you want to run every single time. You should hook this in very specific situations. ( most common would be register_activation_hook )</p>\n"
}
]
| 2017/04/26 | [
"https://wordpress.stackexchange.com/questions/264939",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118452/"
]
| I want to fetch multiple posts with categories and tags
currently I'm using this query:
```
$pagesize = 20;
$pageNumber = 1;
$mysql = mysqli_query($con,"SELECT p.post_title,
p.ID,
p.post_content,
p.post_date,
p.post_name as url,
t.name as category_name
FROM wp_posts p,
wp_terms t,
wp_term_relationships r,
wp_term_taxonomy tt
WHERE p.post_status='publish' AND
tt.taxonomy = 'post_tag' AND
p.id=r.object_id AND
r.term_taxonomy_id=tt.term_taxonomy_id AND
tt.term_id = t.term_id
ORDER BY p.post_date desc
LIMIT ".(int)($pageNumber*$pageSize).",".(int)$pageSize."") or die ("error".mysqli_error($con));
```
The mysqli-connection works. But when I run this code, I only get a blank page. How can I fix this? | It looks like I have solved my own problem. I'm guessing that a function like that creates a permanent change, regardless of whether the function remains in the functions.php file. So, to fix this, I just added a new function reversing this adding. Here is that function:
```
function remove_theme_caps() {
$role = get_role( 'author' );
$role->remove_cap( 'edit_others_posts' );
}
add_action( 'admin_init', 'remove_theme_caps');
```
This has restored the default setting of not allowing authors to edit other users' posts. And after uploading my functions file with this code, I have since deleted this section of code and re-uploaded my functions file, and the change (back to the default setting) has remained. So, problem solved! |
264,942 | <p>I was trying to find an answer since many days. Can It be done that =>
Can we have one admin panel for 2 different wordpress sites ?</p>
<p>2- Can we have 2 different wordpress websites that uses the single database ??</p>
| [
{
"answer_id": 264946,
"author": "JCM",
"author_id": 100958,
"author_profile": "https://wordpress.stackexchange.com/users/100958",
"pm_score": 1,
"selected": false,
"text": "<p>It looks like I have solved my own problem. I'm guessing that a function like that creates a permanent change, regardless of whether the function remains in the functions.php file. So, to fix this, I just added a new function reversing this adding. Here is that function:</p>\n\n<pre><code>function remove_theme_caps() {\n$role = get_role( 'author' );\n$role->remove_cap( 'edit_others_posts' );\n}\nadd_action( 'admin_init', 'remove_theme_caps');\n</code></pre>\n\n<p>This has restored the default setting of not allowing authors to edit other users' posts. And after uploading my functions file with this code, I have since deleted this section of code and re-uploaded my functions file, and the change (back to the default setting) has remained. So, problem solved!</p>\n"
},
{
"answer_id": 351881,
"author": "Jess_Pinkman",
"author_id": 171161,
"author_profile": "https://wordpress.stackexchange.com/users/171161",
"pm_score": 0,
"selected": false,
"text": "<p>add_cap will write to the database, this is not an operation you want to run every single time. You should hook this in very specific situations. ( most common would be register_activation_hook )</p>\n"
}
]
| 2017/04/26 | [
"https://wordpress.stackexchange.com/questions/264942",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118454/"
]
| I was trying to find an answer since many days. Can It be done that =>
Can we have one admin panel for 2 different wordpress sites ?
2- Can we have 2 different wordpress websites that uses the single database ?? | It looks like I have solved my own problem. I'm guessing that a function like that creates a permanent change, regardless of whether the function remains in the functions.php file. So, to fix this, I just added a new function reversing this adding. Here is that function:
```
function remove_theme_caps() {
$role = get_role( 'author' );
$role->remove_cap( 'edit_others_posts' );
}
add_action( 'admin_init', 'remove_theme_caps');
```
This has restored the default setting of not allowing authors to edit other users' posts. And after uploading my functions file with this code, I have since deleted this section of code and re-uploaded my functions file, and the change (back to the default setting) has remained. So, problem solved! |
264,964 | <p>is it possible to make my website redirect every link that starts with something like </p>
<blockquote>
<p>/nl/products/motors/</p>
</blockquote>
<p>to just </p>
<blockquote>
<p>/motors/</p>
</blockquote>
<p>even when a link has something like </p>
<blockquote>
<p>/nl/products/motors/allotherinfo/moreinfo/ect./</p>
</blockquote>
<p>to redirect something like this to </p>
<blockquote>
<p>/motors/</p>
</blockquote>
<p>at the moment i get loads of 404 errors because i changed my website and i think this is not good for my google rankings. </p>
<p>Thanks for taking the time to read this,</p>
<p>Sjoerd</p>
| [
{
"answer_id": 264966,
"author": "Aishan",
"author_id": 89530,
"author_profile": "https://wordpress.stackexchange.com/users/89530",
"pm_score": -1,
"selected": false,
"text": "<p>Redirect rule if the URL contains a certain word?\nPlease try with the code below:</p>\n\n<pre><code>RewriteCond %{REQUEST_URI} motors\nRewriteRule .* motors\n</code></pre>\n"
},
{
"answer_id": 264971,
"author": "Aftab",
"author_id": 64614,
"author_profile": "https://wordpress.stackexchange.com/users/64614",
"pm_score": 1,
"selected": false,
"text": "<p>You can use below code in .htaccess file</p>\n\n<pre><code>Redirect ^/nl/products/motors/.*$ /motors/\n</code></pre>\n\n<p>So here if you url will match /nl/products/motors/ then it will redirect to /motors/</p>\n"
}
]
| 2017/04/26 | [
"https://wordpress.stackexchange.com/questions/264964",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90770/"
]
| is it possible to make my website redirect every link that starts with something like
>
> /nl/products/motors/
>
>
>
to just
>
> /motors/
>
>
>
even when a link has something like
>
> /nl/products/motors/allotherinfo/moreinfo/ect./
>
>
>
to redirect something like this to
>
> /motors/
>
>
>
at the moment i get loads of 404 errors because i changed my website and i think this is not good for my google rankings.
Thanks for taking the time to read this,
Sjoerd | You can use below code in .htaccess file
```
Redirect ^/nl/products/motors/.*$ /motors/
```
So here if you url will match /nl/products/motors/ then it will redirect to /motors/ |
264,969 | <p>I've tried this for the plugin BP Activity Share but it doesn't seem to work... this is what I have, where am I going wrong?</p>
<pre><code>/**disable the BP Activity share for all except admin**/
add_action('admin_init', 'my_filter_the_plugins');
function my_filter_the_plugins()
{
global $current_user;
if (in_array('Participant', 'Subscriber', $current_user->roles)) {
deactivate_plugins( // deactivate for participant and subscriber
array(
'/bp-activity-share/bp-activity-share.php'
),
true, // silent mode (no deactivation hooks fired)
false // network wide)
);
} else { // activate for those than can use it
activate_plugins(
array(
'/bp-activity-share/bp-activity-share.php'
),
'', // redirect url, does not matter (default is '')
false, // network wise
true // silent mode (no activation hooks fired)
);
}
}
</code></pre>
| [
{
"answer_id": 264976,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": false,
"text": "<p>This is actually a basic PHP problem:</p>\n\n<pre><code>if (in_array('Participant', 'Subscriber', $current_user->roles)) {\n</code></pre>\n\n<p>That's not how <code>in_array</code> works. <code>in_array</code> checks if the first bit is in the second bit. So is <code>Participant</code> inside <code>$current_user->roles</code>.</p>\n\n<p>What you've written however, checks if <code>Participant</code> is inside <code>Subscriber</code>, then passed an array as the 3rd argument, which is meant to be a <code>true</code> or <code>false</code> value.</p>\n\n<p>Instead, do 2 <code>in_array</code> checks and check either are true, e.g.</p>\n\n<pre><code>if ( in_array('example', $current_user->roles) || in_array('example2', $current_user->roles) ) {\n</code></pre>\n\n<p>I would also note that the code you posted should be generating PHP warnings and notices. Turn on <code>WP_DEBUG</code> and it should print those out.</p>\n\n<h2>Will This do the trick?</h2>\n\n<p>The original answer you've been working off of has major problems, as mentioned by <a href=\"https://wordpress.stackexchange.com/a/264982/736\">Mark Kapluns answer</a>. Once a plugin is loaded, it's too late, deactivating it will only work for the next page load, and if that page load is an administrator, well, it's going to be a mess.</p>\n\n<p>So instead you have 2 options:</p>\n\n<ul>\n<li>Do the check inside the plugin at the very top, and return if you don't want to load it. The plugin won't be deactivated, but none of its code will run.</li>\n<li>Don't deactivate the plugin, and instead use roles, capabilities, and filters, to disable or hide the functionality you don't want. This is what most WordPress users do, and will avoid you needing to make the changes every time the plugin updates</li>\n</ul>\n\n<p>In this case, you're lucky, the BP activity share plugin uses hooks to load everything, therefore you should be able to unhook everything</p>\n"
},
{
"answer_id": 264981,
"author": "bueltge",
"author_id": 170,
"author_profile": "https://wordpress.stackexchange.com/users/170",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the <code>in_array</code> function to solve this. A custom function helps you to solve without a usage of a complex conditional check.</p>\n\n<p>The follow small function should use for the check like this:\n<code>if ( _fb_recursive_in_array('Participant', 'Subscriber', $current_user->roles ) ) { ...</code></p>\n\n<pre><code>/**\n * Recursive search in array.\n *\n * @param string $needle\n * @param array $haystack\n *\n * @return bool\n */\nfunction _fb_recursive_in_array( $needle, $haystack ) {\n\n if ( '' === $haystack ) {\n return FALSE;\n }\n\n if ( ! $haystack ) {\n return FALSE;\n }\n\n foreach ( $haystack as $stalk ) {\n if ( $needle === $stalk\n || ( is_array( $stalk )\n && _fb_recursive_in_array( $needle, $stalk )\n )\n ) {\n return TRUE;\n }\n }\n\n return FALSE;\n}\n</code></pre>\n"
},
{
"answer_id": 264982,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>You can not deactivate plugins that way. What your code will actually do (as @tom indicted, right now your check is wrong) is to disable/enable the plugin for the <strong>next request being handled, not the current one</strong>. </p>\n\n<p>Once a PHP file is \"required\" you can not \"un require\" it and the only way to remove the functionality is to remove whatever subscriptions it had done to actions and filters.</p>\n\n<p>Probably the only way you might get similar functionality is to disable the plugin and require its main file when the conditions are right.</p>\n"
},
{
"answer_id": 264984,
"author": "Nathan",
"author_id": 118468,
"author_profile": "https://wordpress.stackexchange.com/users/118468",
"pm_score": 0,
"selected": false,
"text": "<p>Thank you for your explanation and suggestions Tom.</p>\n\n<p>It helped me to get it working The working solution:</p>\n\n<pre><code>add_action('admin_init', 'my_filter_the_plugins'); \nfunction my_filter_the_plugins()\n{\n global $current_user;\nif ( in_array('participant', $current_user->roles) || in_array('subscriber', \n$current_user->roles) ) {\n deactivate_plugins( // deactivate for participant and subscriber\n array(\n '/bp-activity-share/bp-activity-share.php'\n ),\n true // silent mode (no activation hooks fired)\n );\n } else { // activate for those than can use it\n activate_plugins(\n array(\n '/bp-activity-share/bp-activity-share.php'\n ),\n '', // redirect url, does not matter (default is '')\n false // network wide)\n );\n }\n}\n</code></pre>\n"
}
]
| 2017/04/26 | [
"https://wordpress.stackexchange.com/questions/264969",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118468/"
]
| I've tried this for the plugin BP Activity Share but it doesn't seem to work... this is what I have, where am I going wrong?
```
/**disable the BP Activity share for all except admin**/
add_action('admin_init', 'my_filter_the_plugins');
function my_filter_the_plugins()
{
global $current_user;
if (in_array('Participant', 'Subscriber', $current_user->roles)) {
deactivate_plugins( // deactivate for participant and subscriber
array(
'/bp-activity-share/bp-activity-share.php'
),
true, // silent mode (no deactivation hooks fired)
false // network wide)
);
} else { // activate for those than can use it
activate_plugins(
array(
'/bp-activity-share/bp-activity-share.php'
),
'', // redirect url, does not matter (default is '')
false, // network wise
true // silent mode (no activation hooks fired)
);
}
}
``` | This is actually a basic PHP problem:
```
if (in_array('Participant', 'Subscriber', $current_user->roles)) {
```
That's not how `in_array` works. `in_array` checks if the first bit is in the second bit. So is `Participant` inside `$current_user->roles`.
What you've written however, checks if `Participant` is inside `Subscriber`, then passed an array as the 3rd argument, which is meant to be a `true` or `false` value.
Instead, do 2 `in_array` checks and check either are true, e.g.
```
if ( in_array('example', $current_user->roles) || in_array('example2', $current_user->roles) ) {
```
I would also note that the code you posted should be generating PHP warnings and notices. Turn on `WP_DEBUG` and it should print those out.
Will This do the trick?
-----------------------
The original answer you've been working off of has major problems, as mentioned by [Mark Kapluns answer](https://wordpress.stackexchange.com/a/264982/736). Once a plugin is loaded, it's too late, deactivating it will only work for the next page load, and if that page load is an administrator, well, it's going to be a mess.
So instead you have 2 options:
* Do the check inside the plugin at the very top, and return if you don't want to load it. The plugin won't be deactivated, but none of its code will run.
* Don't deactivate the plugin, and instead use roles, capabilities, and filters, to disable or hide the functionality you don't want. This is what most WordPress users do, and will avoid you needing to make the changes every time the plugin updates
In this case, you're lucky, the BP activity share plugin uses hooks to load everything, therefore you should be able to unhook everything |
264,987 | <p>I have made a favorite plugin. With a shortcode I'm able to display the button to 'a wish/favorite list' anywhere I want the button. This button is for adding the post_IDs of pages/posts/blogs/articles etc in a cookie array with this code:<br></p>
<pre><code><?php
if (isset($_POST['submit_wishlist'])){
if (!isset($_COOKIE['favorites'])){
//echo 'not set <br>';
$cookie_value = get_the_ID();
$init_value = array($cookie_value);
$init_value = serialize($init_value);
//echo $init_value;
setcookie('favorites', $init_value, time() + (86400 * 30), "/");
wp_redirect($_SERVER['HTTP_REFERER']);
} else {
//echo 'set <br>';
$cookie_value = get_the_ID();
$prev_value = $_COOKIE['favorites'];
$prev_value = stripslashes($prev_value);
$prev_value = unserialize($prev_value);
array_push($prev_value, $cookie_value);
$new_value = serialize($prev_value);
//echo $new_value;
setcookie('favorites', $new_value, time() + (86400 * 30), "/");
wp_redirect($_SERVER['HTTP_REFERER']);
}
}
?>
</code></pre>
<p>This is working fine, and the post_ids getting stored in the cookie array. With the code <code>print_r(unserialize($_COOKIE['favorites']));</code> I'm able to print the Cookie and get a overview of all the stored post_ids.</p>
<p><strong>Problem/Question</strong><br>
Currently I've add a new shortcode for displaying the favorite list. Each value of that list, is getting a trashbutton for deleting/unset that cookie. Now I need to get the following code to work:</p>
<pre><code><?php
$all_favorites= unserialize($_COOKIE['favorites']);
echo '<table>';
foreach($all_favorites as $key => $value) {
echo '<tr>';
echo 'Post-ID = ' . $value . ' ';
?>
<form method="POST"><button type="submit" class="btn btn-default" name="delete"><span class="glyphicon glyphicon-trash"></span></button>
<input type="hidden" name="delete_id" value="<?php echo $value; ?>" />
</form><br>
<?php
echo '</tr>';
}
echo '</table>';
if (isset($_POST['delete'])){
//function for setting new cookie, function is displayed on each page before the get_header()
set_cookie_delete();
}
?>
</code></pre>
<p>The output of this part of code:</p>
<p><a href="https://i.stack.imgur.com/uWWrm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uWWrm.png" alt="enter image description here"></a><br><br></p>
<p><strong>Edit</strong><br>
<em>The function:</em></p>
<pre><code><?php
function set_cookie_delete(){
$all_favorites = unserialize($_COOKIE['favorites']);
$delete_id = $_POST['delete_id'];
echo 'deleted value = ' . ' ' . $delete_id . '<br>';
$array_delete = array_diff($all_favorites, array($delete_id));
$array_delete = serialize($array_delete);
print_r($array_delete);
wp_redirect($_SERVER['HTTP_REFERER']);
setcookie('favorites', $array_delete, time() + (86400 * 30), "/");
//echo '<br><br>';
//print_r($_COOKIE);
}
?>
</code></pre>
<p>What I don't understand is why my <code>setcookie();</code> is not working. It's on the beginning of the page and I first refresh the page so the cookie is able to set, right?</p>
<p>Every help will be appreciated, thanks in advance!</p>
| [
{
"answer_id": 264993,
"author": "Laxmana",
"author_id": 40948,
"author_profile": "https://wordpress.stackexchange.com/users/40948",
"pm_score": 2,
"selected": false,
"text": "<p>You need to put the id of each item inside form to indicate the item that will be deleted.</p>\n\n<pre><code><?php \n$all_favorites= unserialize($_COOKIE['favorites']);\n\necho '<table>';\nforeach($all_favorites as $key => $value) {\n echo '<tr>';\n echo 'Post-ID = ' . $value . ' ';\n ?>\n <form method=\"POST\">\n <input type=\"hidden\" name=\"id\" value=\"<?php echo $value; ?>\">\n <button type=\"submit\" class=\"btn btn-default\" name=\"delete\">\n <span class=\"glyphicon glyphicon-trash\"></span>\n </button>\n </form><br>\n <?php\n echo '</tr>';\n}\necho '</table>';\nif (isset($_POST['delete'])){\n $id = $_POST['id']; // do security checks (sanitize etc)\n // unset post with $id from cookie\n\n}\n?>\n</code></pre>\n"
},
{
"answer_id": 265237,
"author": "W. White",
"author_id": 115316,
"author_profile": "https://wordpress.stackexchange.com/users/115316",
"pm_score": 1,
"selected": false,
"text": "<p><strong>SOLUTION</strong><BR></p>\n\n<p>First of all, many thanks to Laxmana for pushing me in the right direction!</p>\n\n<p>I have the function <code>set_cookie_delete()</code> to this code:<br>\n<em>The function</em><br></p>\n\n<pre><code><?php\n if (isset($_POST['delete'])){\n $all_favorites = unserialize($_COOKIE['favorites']);\n $delete_id = $_POST['delete_id'];\n //echo 'deleted value = ' . ' ' . $delete_id . '<br>';\n\n $array_delete = array_diff($all_favorites, array($delete_id));\n $array_delete = serialize($array_delete);\n //print_r($array_delete);\n\n setcookie('favorites', $array_delete, time() + (86400 * 30), \"/\");\n wp_redirect($_SERVER['HTTP_REFERER']);\n }\n?>\n</code></pre>\n"
}
]
| 2017/04/26 | [
"https://wordpress.stackexchange.com/questions/264987",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115316/"
]
| I have made a favorite plugin. With a shortcode I'm able to display the button to 'a wish/favorite list' anywhere I want the button. This button is for adding the post\_IDs of pages/posts/blogs/articles etc in a cookie array with this code:
```
<?php
if (isset($_POST['submit_wishlist'])){
if (!isset($_COOKIE['favorites'])){
//echo 'not set <br>';
$cookie_value = get_the_ID();
$init_value = array($cookie_value);
$init_value = serialize($init_value);
//echo $init_value;
setcookie('favorites', $init_value, time() + (86400 * 30), "/");
wp_redirect($_SERVER['HTTP_REFERER']);
} else {
//echo 'set <br>';
$cookie_value = get_the_ID();
$prev_value = $_COOKIE['favorites'];
$prev_value = stripslashes($prev_value);
$prev_value = unserialize($prev_value);
array_push($prev_value, $cookie_value);
$new_value = serialize($prev_value);
//echo $new_value;
setcookie('favorites', $new_value, time() + (86400 * 30), "/");
wp_redirect($_SERVER['HTTP_REFERER']);
}
}
?>
```
This is working fine, and the post\_ids getting stored in the cookie array. With the code `print_r(unserialize($_COOKIE['favorites']));` I'm able to print the Cookie and get a overview of all the stored post\_ids.
**Problem/Question**
Currently I've add a new shortcode for displaying the favorite list. Each value of that list, is getting a trashbutton for deleting/unset that cookie. Now I need to get the following code to work:
```
<?php
$all_favorites= unserialize($_COOKIE['favorites']);
echo '<table>';
foreach($all_favorites as $key => $value) {
echo '<tr>';
echo 'Post-ID = ' . $value . ' ';
?>
<form method="POST"><button type="submit" class="btn btn-default" name="delete"><span class="glyphicon glyphicon-trash"></span></button>
<input type="hidden" name="delete_id" value="<?php echo $value; ?>" />
</form><br>
<?php
echo '</tr>';
}
echo '</table>';
if (isset($_POST['delete'])){
//function for setting new cookie, function is displayed on each page before the get_header()
set_cookie_delete();
}
?>
```
The output of this part of code:
[](https://i.stack.imgur.com/uWWrm.png)
**Edit**
*The function:*
```
<?php
function set_cookie_delete(){
$all_favorites = unserialize($_COOKIE['favorites']);
$delete_id = $_POST['delete_id'];
echo 'deleted value = ' . ' ' . $delete_id . '<br>';
$array_delete = array_diff($all_favorites, array($delete_id));
$array_delete = serialize($array_delete);
print_r($array_delete);
wp_redirect($_SERVER['HTTP_REFERER']);
setcookie('favorites', $array_delete, time() + (86400 * 30), "/");
//echo '<br><br>';
//print_r($_COOKIE);
}
?>
```
What I don't understand is why my `setcookie();` is not working. It's on the beginning of the page and I first refresh the page so the cookie is able to set, right?
Every help will be appreciated, thanks in advance! | You need to put the id of each item inside form to indicate the item that will be deleted.
```
<?php
$all_favorites= unserialize($_COOKIE['favorites']);
echo '<table>';
foreach($all_favorites as $key => $value) {
echo '<tr>';
echo 'Post-ID = ' . $value . ' ';
?>
<form method="POST">
<input type="hidden" name="id" value="<?php echo $value; ?>">
<button type="submit" class="btn btn-default" name="delete">
<span class="glyphicon glyphicon-trash"></span>
</button>
</form><br>
<?php
echo '</tr>';
}
echo '</table>';
if (isset($_POST['delete'])){
$id = $_POST['id']; // do security checks (sanitize etc)
// unset post with $id from cookie
}
?>
``` |
264,997 | <p>I've literally spent half a day trying to find a solution for this problem.</p>
<p>From one WordPress installation I need to query multiple other WordPress installations' databases.</p>
<p>I'd very much like to use the $wpdb way, as this is what I've always used (just haven't ever had the need to access more than one database).</p>
<p>I've created a wpdb object by using this method:</p>
<pre><code>$new_db_connection = new wpdb(*DB INFORMATION INSERTED HERE*)
</code></pre>
<p>However, as stated on WordPress' own site, only one wpdb connection can exist at a time.</p>
<blockquote>
<p>The $wpdb object can talk to any number of tables, but only to one database at a time; by default the WordPress database. In the rare case you need to connect to another database, you will need to instantiate your own object from the wpdb class with your own database connection information.</p>
</blockquote>
<p>My question to you guys is: How do I create a new wpdb object after the first? It doesn't work to unset() the first database.</p>
<p>My workflow is: Query one DB, get data and store in variable, query next DB, get data and store in variable ... etc.</p>
<p><strong>Edit:
My question isn't a duplicate, since I'm looking for a way to create more than one new wpdb object.</strong></p>
<p>I need to create a new wpdb object, access the external DB through it and store result in variable, then create ANOTHER new wpdb object and do the same and so on.</p>
<p>However, it only works for the first new wpdb object. It has to be because of the quote from WordPress' site. If I comment out the first wpdb object then the second one works.</p>
| [
{
"answer_id": 265002,
"author": "user1049961",
"author_id": 47664,
"author_profile": "https://wordpress.stackexchange.com/users/47664",
"pm_score": 1,
"selected": false,
"text": "<p>The <code>$new_db_connection</code> is your new db object. </p>\n\n<p>Just use that to access the other db, ie. </p>\n\n<pre><code>$new_db_connection->get_row(\"your query\");\n</code></pre>\n"
},
{
"answer_id": 408798,
"author": "Stelio Kontos",
"author_id": 225095,
"author_profile": "https://wordpress.stackexchange.com/users/225095",
"pm_score": 0,
"selected": false,
"text": "<p>Sounds like a caching issue; calling <code>wp_cache_flush()</code> between each subsequent connection should resolve the issue.</p>\n<p>On a side note:</p>\n<blockquote>\n<p>However, as stated on WordPress' own site, only one wpdb connection can exist at a time.</p>\n</blockquote>\n<p>I've seen numerous people misinterpret this portion of the documentation referenced by the OP, so it's worth pointing out the difference between the <code>wpdb</code> class and the global <code>$wpdb</code> object. One can instantiate as many instances of the <code>wpdb</code> class as they like for numerous disparate database connections. One instance per connection. Just don't try connecting that global <code>$wpdb</code> instance to another database and expect the original connection to magically keep working.</p>\n<p><a href=\"https://developer.wordpress.org/reference/classes/wpdb/#more-information\" rel=\"nofollow noreferrer\">From the WordPress docs:</a></p>\n<blockquote>\n<p>By default, WordPress uses this class to instantiate the global $wpdb object, providing access to the WordPress database.</p>\n<p>...</p>\n<p>An instantiated wpdb class can talk to any number of tables, but only to one database at a time. In the rare case you need to connect to another database, instantiate your own object from the wpdb class with your own database connection information.</p>\n</blockquote>\n"
},
{
"answer_id": 413585,
"author": "Andrew",
"author_id": 221199,
"author_profile": "https://wordpress.stackexchange.com/users/221199",
"pm_score": 0,
"selected": false,
"text": "<p>I was curious about this too, so I dug into the WordPress source to see where <code>new wpdb</code> was found.</p>\n<p>I found it <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/load.php#L562\" rel=\"nofollow noreferrer\">here</a> in <code>load.php</code>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$dbuser = defined( 'DB_USER' ) ? DB_USER : '';\n$dbpassword = defined( 'DB_PASSWORD' ) ? DB_PASSWORD : '';\n$dbname = defined( 'DB_NAME' ) ? DB_NAME : '';\n$dbhost = defined( 'DB_HOST' ) ? DB_HOST : '';\n\n$wpdb = new wpdb( $dbuser, $dbpassword, $dbname, $dbhost );\n</code></pre>\n<p>All you'd need to do is rename <code>$wpdb</code> to wherver you wanted to call it which was <code>$new_db_connection</code>.</p>\n"
}
]
| 2017/04/26 | [
"https://wordpress.stackexchange.com/questions/264997",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118480/"
]
| I've literally spent half a day trying to find a solution for this problem.
From one WordPress installation I need to query multiple other WordPress installations' databases.
I'd very much like to use the $wpdb way, as this is what I've always used (just haven't ever had the need to access more than one database).
I've created a wpdb object by using this method:
```
$new_db_connection = new wpdb(*DB INFORMATION INSERTED HERE*)
```
However, as stated on WordPress' own site, only one wpdb connection can exist at a time.
>
> The $wpdb object can talk to any number of tables, but only to one database at a time; by default the WordPress database. In the rare case you need to connect to another database, you will need to instantiate your own object from the wpdb class with your own database connection information.
>
>
>
My question to you guys is: How do I create a new wpdb object after the first? It doesn't work to unset() the first database.
My workflow is: Query one DB, get data and store in variable, query next DB, get data and store in variable ... etc.
**Edit:
My question isn't a duplicate, since I'm looking for a way to create more than one new wpdb object.**
I need to create a new wpdb object, access the external DB through it and store result in variable, then create ANOTHER new wpdb object and do the same and so on.
However, it only works for the first new wpdb object. It has to be because of the quote from WordPress' site. If I comment out the first wpdb object then the second one works. | The `$new_db_connection` is your new db object.
Just use that to access the other db, ie.
```
$new_db_connection->get_row("your query");
``` |
265,010 | <p>I need to allow .exe file uploads through the admin media manager. So far I have tried</p>
<pre><code>function enable_extended_upload ( $mime_types = array() ) {
$mime_types['exe'] = 'application/octet-stream';
return $mime_types;
}
add_filter('upload_mimes', 'enable_extended_upload');
</code></pre>
<p>Three different sources have given me three different mime types for .exe. They are <code>application/octet-stream</code>, <code>application/exe</code>, and <code>application/x-msdownload</code>. None have worked.</p>
<p>Since my site happens to be a network, I've tried to whitelist the filetype under Network Settings -> Upload Settings, like so</p>
<p><a href="https://i.stack.imgur.com/xvhDU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xvhDU.png" alt="files"></a></p>
<p>It didn't work either.</p>
<p>The only thing that works is setting the constant <code>define('ALLOW_UNFILTERED_UPLOADS', true);</code> in wp-config.php, AND having the above mime type snippet, but is not the ideal solution since all files will be allowed.</p>
<p>How can I whitelist .exe nowadays?</p>
| [
{
"answer_id": 265657,
"author": "bueltge",
"author_id": 170,
"author_profile": "https://wordpress.stackexchange.com/users/170",
"pm_score": 1,
"selected": false,
"text": "<p>WordPress provide a hook to change the default mime types, like your hint in the question. The follow small code source demonstrated the change to allow a exe-file.</p>\n\n<pre><code>add_filter( 'upload_mimes', 'fb_enable_extended_upload' );\nfunction fb_enable_extended_upload ( array $mime_types = [] ) {\n\n $mime_types[ 'exe' ] = 'application/exe'; \n\n return $mime_types;\n} \n</code></pre>\n\n<p>It is not necessary to change the database entry <code>upload_filetypes</code>.</p>\n"
},
{
"answer_id": 280961,
"author": "yacsha",
"author_id": 128452,
"author_profile": "https://wordpress.stackexchange.com/users/128452",
"pm_score": 0,
"selected": false,
"text": "<p>I have had exactly the same problem and after exploring the wordpress source code, exactly the file <code>'/wp_includes/functions.php'</code>, I conclude that wordpress has disabled by default upload to swf and exe files (see function <code>get_allowed_mime_types</code>) , and the only way to skip this is to enable <code>ALLOW_UNFILTERED_UPLOADS</code> in <code>wp-config</code> (see function <code>wp_upload_bits</code>).</p>\n\n<p>Update: In addition, you must define your own <code>enable_extended_upload</code> function to enable the recognition of exe files in the upload files dialog box.</p>\n\n<p>The only thing that changes when you enable <code>ALLOW_UNFILTERED_UPLOADS</code> in true is the upload of swf and exe files, since no more files will be loaded than those defined by default in wordpress. This means that if you want to load a <code>\"zzz\" file</code>, it will not load unless you set it to its own <code>enable_extended_upload</code> function.</p>\n\n<p>Then I put the most relevant code of the functions involved:</p>\n\n<pre><code>function get_allowed_mime_types( $user = null ) {\n $t = wp_get_mime_types();\n\n unset( $t['swf'], $t['exe'] );\n\n ....\n\n /**\n * Filters list of allowed mime types and file extensions.\n *\n * @since 2.0.0\n *\n * @param array $t Mime types keyed by the file extension regex corresponding to\n * those types. 'swf' and 'exe' removed from full list. 'htm|html' also\n * removed depending on '$user' capabilities.\n * @param int|WP_User|null $user User ID, User object or null if not provided (indicates current user).\n */\n return apply_filters( 'upload_mimes', $t, $user );\n}\n\n\nfunction wp_check_filetype( $filename, $mimes = null ) {\n if ( empty($mimes) )\n $mimes = get_allowed_mime_types();\n $type = false;\n $ext = false;\n\n foreach ( $mimes as $ext_preg => $mime_match ) {\n $ext_preg = '!\\.(' . $ext_preg . ')$!i';\n if ( preg_match( $ext_preg, $filename, $ext_matches ) ) {\n $type = $mime_match;\n $ext = $ext_matches[1];\n break;\n }\n }\n\n return compact( 'ext', 'type' );\n}\n\n\nfunction wp_upload_bits( $name, $deprecated, $bits, $time = null ) {\n ....\n\n $wp_filetype = wp_check_filetype( $name );\n if ( ! $wp_filetype['ext'] && ! current_user_can( 'unfiltered_upload' ) )\n return array( 'error' => __( 'Sorry, this file type is not permitted for security reasons.' ) );\n ?>\n ...\n</code></pre>\n"
}
]
| 2017/04/26 | [
"https://wordpress.stackexchange.com/questions/265010",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/44937/"
]
| I need to allow .exe file uploads through the admin media manager. So far I have tried
```
function enable_extended_upload ( $mime_types = array() ) {
$mime_types['exe'] = 'application/octet-stream';
return $mime_types;
}
add_filter('upload_mimes', 'enable_extended_upload');
```
Three different sources have given me three different mime types for .exe. They are `application/octet-stream`, `application/exe`, and `application/x-msdownload`. None have worked.
Since my site happens to be a network, I've tried to whitelist the filetype under Network Settings -> Upload Settings, like so
[](https://i.stack.imgur.com/xvhDU.png)
It didn't work either.
The only thing that works is setting the constant `define('ALLOW_UNFILTERED_UPLOADS', true);` in wp-config.php, AND having the above mime type snippet, but is not the ideal solution since all files will be allowed.
How can I whitelist .exe nowadays? | WordPress provide a hook to change the default mime types, like your hint in the question. The follow small code source demonstrated the change to allow a exe-file.
```
add_filter( 'upload_mimes', 'fb_enable_extended_upload' );
function fb_enable_extended_upload ( array $mime_types = [] ) {
$mime_types[ 'exe' ] = 'application/exe';
return $mime_types;
}
```
It is not necessary to change the database entry `upload_filetypes`. |
265,020 | <p>I've seen many solutions but none seem to work for me... I've got a grid off the loop/content on <code>single.php</code> that renders the whole grid as is, so I use the function as below which works fine, but only if I specify the exact taxonomy term (<code>client-1</code>).</p>
<pre><code>function my_query_args($query_args, $grid_name) {
if ($grid_name == 'client-grid') {
$query_args['tax_query'] = array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => 'client-1',
),
);
}
return $query_args;
}
add_filter('tg_wp_query_args', 'my_query_args');
</code></pre>
<p>But I want the term of the <strong>current post</strong> instead so I thought that below would work, but it renders all posts in the grid no matter what I do.</p>
<pre><code>function my_query_args($terms_list, $grid_name) {
if ($grid_name == 'client-grid') {
$terms_list = get_terms
(array(
'taxonomy' => 'category',
'parent' => 0,
)
);
}
return $terms_list;
}
add_filter('tg_wp_query_args', 'my_query_args');
</code></pre>
<p>Thankful for any input.</p>
<p><strong>EDIT</strong></p>
<p>Thinking of something like this (which obvs doesn't works), but anyone that can point in the right direction?</p>
<pre><code>$term_id = get_queried_object_id();
function my_query_args($query_args, $grid_name) {
if ($grid_name == 'JTS-SINGLE') {
$query_args['tax_query'] = array(
array(
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => $term_id
),
);
}
return $query_args;
}
add_filter('tg_wp_query_args', 'my_query_args', 10, 2);
</code></pre>
| [
{
"answer_id": 265029,
"author": "essexboyracer",
"author_id": 74358,
"author_profile": "https://wordpress.stackexchange.com/users/74358",
"pm_score": 0,
"selected": false,
"text": "<p>Have a look at <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_post_terms\" rel=\"nofollow noreferrer\">wp_get_post_terms</a> which allows you to specify a posiID, which is what I think you are getting at</p>\n"
},
{
"answer_id": 265097,
"author": "FNTC",
"author_id": 118493,
"author_profile": "https://wordpress.stackexchange.com/users/118493",
"pm_score": 1,
"selected": false,
"text": "<p><strong>SOLVED</strong></p>\n\n<p>This was what I was looking for and it works like a charm.</p>\n\n<pre><code>function my_query_args($query_args, $grid_name) {\n\n$term_list = get_the_terms( get_the_ID(), 'category' )[0]->slug;\n\nif ($grid_name == 'JTS-SINGLE') {\n $query_args['tax_query'] = array(\n array(\n 'taxonomy' => 'category',\n 'field' => 'slug',\n 'terms' => array( $term_list ),\n ),\n );\n}\nreturn $query_args;\n\n}\nadd_filter('tg_wp_query_args', 'my_query_args', 10, 2);\n</code></pre>\n"
}
]
| 2017/04/26 | [
"https://wordpress.stackexchange.com/questions/265020",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118493/"
]
| I've seen many solutions but none seem to work for me... I've got a grid off the loop/content on `single.php` that renders the whole grid as is, so I use the function as below which works fine, but only if I specify the exact taxonomy term (`client-1`).
```
function my_query_args($query_args, $grid_name) {
if ($grid_name == 'client-grid') {
$query_args['tax_query'] = array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => 'client-1',
),
);
}
return $query_args;
}
add_filter('tg_wp_query_args', 'my_query_args');
```
But I want the term of the **current post** instead so I thought that below would work, but it renders all posts in the grid no matter what I do.
```
function my_query_args($terms_list, $grid_name) {
if ($grid_name == 'client-grid') {
$terms_list = get_terms
(array(
'taxonomy' => 'category',
'parent' => 0,
)
);
}
return $terms_list;
}
add_filter('tg_wp_query_args', 'my_query_args');
```
Thankful for any input.
**EDIT**
Thinking of something like this (which obvs doesn't works), but anyone that can point in the right direction?
```
$term_id = get_queried_object_id();
function my_query_args($query_args, $grid_name) {
if ($grid_name == 'JTS-SINGLE') {
$query_args['tax_query'] = array(
array(
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => $term_id
),
);
}
return $query_args;
}
add_filter('tg_wp_query_args', 'my_query_args', 10, 2);
``` | **SOLVED**
This was what I was looking for and it works like a charm.
```
function my_query_args($query_args, $grid_name) {
$term_list = get_the_terms( get_the_ID(), 'category' )[0]->slug;
if ($grid_name == 'JTS-SINGLE') {
$query_args['tax_query'] = array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => array( $term_list ),
),
);
}
return $query_args;
}
add_filter('tg_wp_query_args', 'my_query_args', 10, 2);
``` |
265,068 | <p>My theme automatically puts the sidebar above the content rather than below it when going responsive/mobile. </p>
<p>I am trying to figure out how I can get it to go below the content instead, as having it above is really hurting customer experience because they have to scroll so much to see the product.</p>
<p>This is the demo of the theme I am using which shows the issue: <a href="http://sooperstore.themesforge.com/shop/twist-bandeau-bikini-top/" rel="nofollow noreferrer">http://sooperstore.themesforge.com/shop/twist-bandeau-bikini-top/</a></p>
<p>Is there a bit of CSS code I can add which will force a rearrange so the content is shown above the sidebar when it goes responsive?</p>
| [
{
"answer_id": 265071,
"author": "Aishan",
"author_id": 89530,
"author_profile": "https://wordpress.stackexchange.com/users/89530",
"pm_score": 2,
"selected": false,
"text": "<p>Depending on which device you want to target, you'll need to use a media query, you can read more about those here:\n<a href=\"http://css-tricks.com/snippets/css/media-queries-for-standard-devices/\" rel=\"nofollow noreferrer\">CssTrick</a>: </p>\n\n<pre><code>@media only screen and (max-width : 320px) {\n #content { \n display: flex; \n /* Optional, if you want the DIVs 100% width: */ \n flex-direction: column;\n }\n #content > .wooside { order: 1; }\n #content > .nine { order: 2; }\n} \n</code></pre>\n\n<p>Hope you understand!!</p>\n"
},
{
"answer_id": 265121,
"author": "Vinod Dalvi",
"author_id": 14347,
"author_profile": "https://wordpress.stackexchange.com/users/14347",
"pm_score": 0,
"selected": false,
"text": "<p>To achieve this you can use below custom CSS code on your site using this free WordPress plugin <a href=\"https://wordpress.org/plugins/simple-custom-css/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/simple-custom-css/</a></p>\n\n<pre><code>@media only screen and (max-width : 767px) { \n\n #content { \n display: flex; \n flex-direction: column;\n } \n\n #content > .three.first { \n order: 2; \n } \n\n #content > .nine { \n order: 1; \n } \n}\n</code></pre>\n"
}
]
| 2017/04/27 | [
"https://wordpress.stackexchange.com/questions/265068",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94819/"
]
| My theme automatically puts the sidebar above the content rather than below it when going responsive/mobile.
I am trying to figure out how I can get it to go below the content instead, as having it above is really hurting customer experience because they have to scroll so much to see the product.
This is the demo of the theme I am using which shows the issue: <http://sooperstore.themesforge.com/shop/twist-bandeau-bikini-top/>
Is there a bit of CSS code I can add which will force a rearrange so the content is shown above the sidebar when it goes responsive? | Depending on which device you want to target, you'll need to use a media query, you can read more about those here:
[CssTrick](http://css-tricks.com/snippets/css/media-queries-for-standard-devices/):
```
@media only screen and (max-width : 320px) {
#content {
display: flex;
/* Optional, if you want the DIVs 100% width: */
flex-direction: column;
}
#content > .wooside { order: 1; }
#content > .nine { order: 2; }
}
```
Hope you understand!! |
265,092 | <p>I need to pass a php string that is stored in <code>$attr['footer_caption']</code> inside a shortcode function to a js file where the highcharts are initialized.</p>
<pre><code>$fields = array(
array(
'label' => esc_html( 'Footer label' ),
'description' => esc_html( 'Choose the footer label' ),
'attr' => 'footer_caption',
'type' => 'text',
),
public static function shortcode_ui_chart( $attr, $content, $shortcode_tag ) {
$attr = shortcode_atts( array(
'chart' => null,
'footer_caption' => null,
), $attr, $shortcode_tag );
</code></pre>
<p>I've been reading about localize script but couldnt get it to work. Is there a simple way to perfom this? I want the string from that php array in this variable:</p>
<pre><code> Highcharts.setOptions({
chart: {
type: 'column',
events: {
load: function () {
var teste 'WANT TO PASS $attr['footer_caption'] HERE'
var label = this.renderer.label(teste)
</code></pre>
| [
{
"answer_id": 265071,
"author": "Aishan",
"author_id": 89530,
"author_profile": "https://wordpress.stackexchange.com/users/89530",
"pm_score": 2,
"selected": false,
"text": "<p>Depending on which device you want to target, you'll need to use a media query, you can read more about those here:\n<a href=\"http://css-tricks.com/snippets/css/media-queries-for-standard-devices/\" rel=\"nofollow noreferrer\">CssTrick</a>: </p>\n\n<pre><code>@media only screen and (max-width : 320px) {\n #content { \n display: flex; \n /* Optional, if you want the DIVs 100% width: */ \n flex-direction: column;\n }\n #content > .wooside { order: 1; }\n #content > .nine { order: 2; }\n} \n</code></pre>\n\n<p>Hope you understand!!</p>\n"
},
{
"answer_id": 265121,
"author": "Vinod Dalvi",
"author_id": 14347,
"author_profile": "https://wordpress.stackexchange.com/users/14347",
"pm_score": 0,
"selected": false,
"text": "<p>To achieve this you can use below custom CSS code on your site using this free WordPress plugin <a href=\"https://wordpress.org/plugins/simple-custom-css/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/simple-custom-css/</a></p>\n\n<pre><code>@media only screen and (max-width : 767px) { \n\n #content { \n display: flex; \n flex-direction: column;\n } \n\n #content > .three.first { \n order: 2; \n } \n\n #content > .nine { \n order: 1; \n } \n}\n</code></pre>\n"
}
]
| 2017/04/27 | [
"https://wordpress.stackexchange.com/questions/265092",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/117473/"
]
| I need to pass a php string that is stored in `$attr['footer_caption']` inside a shortcode function to a js file where the highcharts are initialized.
```
$fields = array(
array(
'label' => esc_html( 'Footer label' ),
'description' => esc_html( 'Choose the footer label' ),
'attr' => 'footer_caption',
'type' => 'text',
),
public static function shortcode_ui_chart( $attr, $content, $shortcode_tag ) {
$attr = shortcode_atts( array(
'chart' => null,
'footer_caption' => null,
), $attr, $shortcode_tag );
```
I've been reading about localize script but couldnt get it to work. Is there a simple way to perfom this? I want the string from that php array in this variable:
```
Highcharts.setOptions({
chart: {
type: 'column',
events: {
load: function () {
var teste 'WANT TO PASS $attr['footer_caption'] HERE'
var label = this.renderer.label(teste)
``` | Depending on which device you want to target, you'll need to use a media query, you can read more about those here:
[CssTrick](http://css-tricks.com/snippets/css/media-queries-for-standard-devices/):
```
@media only screen and (max-width : 320px) {
#content {
display: flex;
/* Optional, if you want the DIVs 100% width: */
flex-direction: column;
}
#content > .wooside { order: 1; }
#content > .nine { order: 2; }
}
```
Hope you understand!! |
265,104 | <p>I'm trying to run a query twice, once in a template part (page.php) and once in theme's functions.php. I'm doing this because i need to output some styles to theme's header, since i'm not allowed to use hardcoded inline styles.</p>
<p>This is my main query:</p>
<pre><code>if (have_posts()) {
while (have_posts()) {
the_post();
// Do some stuff, like the_permalink();
}
}
</code></pre>
<p>Now this is the way i'm outputting my styles to the header:</p>
<pre><code>function header_styles(){
if (have_posts()) {
global $post;?>
<style><?php
while (have_posts()){
the_post();
echo " .background-".$post->ID." { background-image: url('".get_the_post_thumbnail_url( $post->ID,'thumbnail' )."');}";
print_r($post);
}
wp_reset_postdata();?>
</style><?php
}
}
add_action('wp_head','header_styles');
</code></pre>
<p>This works fine on homepage and archive pages. But now i'm stuck in accessing a custom query. If i assign the query to a variable in the first code and use it in a custom template file (such as <code>My Page</code> which is created using <code>custom-page.php</code>), i can no longer access the query. For example, using this code in <code>custom-page.php</code>:</p>
<pre><code>$custom_query = new WP_Query($args);
if ($custom_query->have_posts()) {
while ($custom_query->have_posts()) {
$custom_query->the_post();
// Do some stuff, like the_permalink();
}
}
</code></pre>
<p>Now i can output the custom query, but can't access it in <code>functions.php</code>.</p>
<p>Is it possible to workaround this?</p>
| [
{
"answer_id": 265289,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 3,
"selected": true,
"text": "<p>You could cache the results for that page load. It should hit it in <code>header.php</code>, cache the object, and in <code>index.php</code> you can check availability.</p>\n\n<h1>Header</h1>\n\n<pre><code>$custom_query = new WP_Query( $args );\n\nif( $custom_query->have_posts() ) {\n\n // Cache Query before loop\n wp_cache_add( 'custom_query', $custom_query );\n\n while( $custom_query->have_posts() ) { \n $custom_query->the_post();\n // Do some stuff, like the_permalink();\n }\n\n wp_reset_postdata();\n}\n</code></pre>\n\n<h1>Other Files</h1>\n\n<pre><code>$custom_query = wp_cache_get( 'custom_query', $custom_query );\n\nif( ! empty( $custom_query ) && $custom_query->have_posts() ) {\n\n while( $custom_query->have_posts() ) { \n $custom_query->the_post();\n // Do some stuff, like the_permalink();\n }\n\n wp_reset_postdata();\n}\n</code></pre>\n\n<ul>\n<li><a href=\"https://codex.wordpress.org/Class_Reference/WP_Object_Cache\" rel=\"nofollow noreferrer\">The Codex on the WP_Object_Cache Class</a> </li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/wp_cache_add/\" rel=\"nofollow noreferrer\">Developer Resources on wp_cache_add()</a> </li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/wp_cache_get/\" rel=\"nofollow noreferrer\">Developer Resources on wp_cache_get()</a></li>\n</ul>\n"
},
{
"answer_id": 265321,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>I explained my reservations with the answer by @howdy_mcgee in the comments there, so here is what I think is the proper way to do it.</p>\n\n<pre><code>function wpse_265104_get_cached_query($args) {\n static $query;\n\n $hash = md5(serialize($args))\n\n if (!isset($query)) {\n $query = array();\n }\n if (!isset($query[$hash])) {\n $query[$hash] = new wp_Query($args);\n }\n\n $query[$hash]->rewind();\n return $query[$hash];\n}\n</code></pre>\n\n<p>Now all you need to do is call <code>wpse_265104_get_cached_query</code> with the exact same parameters you would have called <code>wp_query</code> and you do not need to worry about execution paths and which code was executed first, and you get the loop in an \"fresh\" state. As a bonus this function can cache more than one specific query.</p>\n"
}
]
| 2017/04/27 | [
"https://wordpress.stackexchange.com/questions/265104",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94498/"
]
| I'm trying to run a query twice, once in a template part (page.php) and once in theme's functions.php. I'm doing this because i need to output some styles to theme's header, since i'm not allowed to use hardcoded inline styles.
This is my main query:
```
if (have_posts()) {
while (have_posts()) {
the_post();
// Do some stuff, like the_permalink();
}
}
```
Now this is the way i'm outputting my styles to the header:
```
function header_styles(){
if (have_posts()) {
global $post;?>
<style><?php
while (have_posts()){
the_post();
echo " .background-".$post->ID." { background-image: url('".get_the_post_thumbnail_url( $post->ID,'thumbnail' )."');}";
print_r($post);
}
wp_reset_postdata();?>
</style><?php
}
}
add_action('wp_head','header_styles');
```
This works fine on homepage and archive pages. But now i'm stuck in accessing a custom query. If i assign the query to a variable in the first code and use it in a custom template file (such as `My Page` which is created using `custom-page.php`), i can no longer access the query. For example, using this code in `custom-page.php`:
```
$custom_query = new WP_Query($args);
if ($custom_query->have_posts()) {
while ($custom_query->have_posts()) {
$custom_query->the_post();
// Do some stuff, like the_permalink();
}
}
```
Now i can output the custom query, but can't access it in `functions.php`.
Is it possible to workaround this? | You could cache the results for that page load. It should hit it in `header.php`, cache the object, and in `index.php` you can check availability.
Header
======
```
$custom_query = new WP_Query( $args );
if( $custom_query->have_posts() ) {
// Cache Query before loop
wp_cache_add( 'custom_query', $custom_query );
while( $custom_query->have_posts() ) {
$custom_query->the_post();
// Do some stuff, like the_permalink();
}
wp_reset_postdata();
}
```
Other Files
===========
```
$custom_query = wp_cache_get( 'custom_query', $custom_query );
if( ! empty( $custom_query ) && $custom_query->have_posts() ) {
while( $custom_query->have_posts() ) {
$custom_query->the_post();
// Do some stuff, like the_permalink();
}
wp_reset_postdata();
}
```
* [The Codex on the WP\_Object\_Cache Class](https://codex.wordpress.org/Class_Reference/WP_Object_Cache)
* [Developer Resources on wp\_cache\_add()](https://developer.wordpress.org/reference/functions/wp_cache_add/)
* [Developer Resources on wp\_cache\_get()](https://developer.wordpress.org/reference/functions/wp_cache_get/) |
265,120 | <p>I'm finding this next to impossible to find any info on. I'm looking for a way to assign each category level a number and then add that number to the body class.
e.g. the parent category archive would show the class <code>.catlevel-1</code>, whereas the child category archive would show class <code>.catlevel-2</code> ... and so on.</p>
| [
{
"answer_id": 265125,
"author": "Vinod Dalvi",
"author_id": 14347,
"author_profile": "https://wordpress.stackexchange.com/users/14347",
"pm_score": 3,
"selected": true,
"text": "<p>You can achieve this by using the following custom code. You can use the code by adding it in the functions.php file of child theme or in the custom plugin file.</p>\n\n<pre><code>add_filter( 'body_class', 'custom_cat_archiev_class' );\nfunction custom_cat_archiev_class( $classes ) {\n if ( is_category() ) {\n $cat = get_queried_object();\n $ancestors = get_ancestors( $cat->term_id, 'category', 'taxonomy' );\n $classes[] = 'catlevel-' . ( count( $ancestors ) + 1 );\n }\n return $classes;\n}\n</code></pre>\n"
},
{
"answer_id": 265127,
"author": "Bruno Cantuaria",
"author_id": 65717,
"author_profile": "https://wordpress.stackexchange.com/users/65717",
"pm_score": -1,
"selected": false,
"text": "<p>Interesting! It's not that hard, you will need to use the filter <code>body_class</code>:</p>\n\n<pre><code>add_filter('body_class', 'category_level_as_class');\nfunction category_level_as_class($classes) {\n\n //First check if we're at a category archive page\n if (is_category()) {\n //Set our counter\n $i = 1;\n\n //Get current category parent\n $category = get_the_category();\n $parent = $category[0]->parent;\n\n //Loop through categories parent\n while ($parent > 0) {\n $i++;\n //Now get parent category info\n $category = get_category($parent);\n $parent = $category->parent;\n }\n\n //Add the class\n $classes[] = 'catlevel-' . $i;\n }\n\n return $classes;\n}\n</code></pre>\n"
}
]
| 2017/04/27 | [
"https://wordpress.stackexchange.com/questions/265120",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37346/"
]
| I'm finding this next to impossible to find any info on. I'm looking for a way to assign each category level a number and then add that number to the body class.
e.g. the parent category archive would show the class `.catlevel-1`, whereas the child category archive would show class `.catlevel-2` ... and so on. | You can achieve this by using the following custom code. You can use the code by adding it in the functions.php file of child theme or in the custom plugin file.
```
add_filter( 'body_class', 'custom_cat_archiev_class' );
function custom_cat_archiev_class( $classes ) {
if ( is_category() ) {
$cat = get_queried_object();
$ancestors = get_ancestors( $cat->term_id, 'category', 'taxonomy' );
$classes[] = 'catlevel-' . ( count( $ancestors ) + 1 );
}
return $classes;
}
``` |
265,149 | <p>I would like to display two different post types in the same query... nothing strange so far. But I would like to declare what taxonomies include and what exclude for both post types, so, for instance, I would like to display posts from the category "16" but that do not belong to "19" as well, and portfolio items from taxonomy "32" that do not belong to "34" at the same time.</p>
<p>I thought this is the right way:</p>
<pre><code>$args = array(
'post_status' => 'publish',
'posts_per_page' => -1,
'orderby' => 'date',
'tax_query' => array(
'relation' => 'OR',
array(
'relation' => 'AND',
array(
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => array( 16 ),
'operator' => 'IN'
),
array(
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => array( 19 ),
'operator' => 'NOT IN'
),
),
array(
'relation' => 'AND',
array(
'taxonomy' => 'portfolio_category',
'field' => 'term_id',
'terms' => array( 32 ),
'operator' => 'IN'
),
array(
'taxonomy' => 'portfolio_category',
'field' => 'term_id',
'terms' => array( 34 ),
'operator' => 'NOT IN'
),
),
),
);
</code></pre>
<p>but it doesn't work. Any clue on this?</p>
| [
{
"answer_id": 265155,
"author": "BlueSuiter",
"author_id": 92665,
"author_profile": "https://wordpress.stackexchange.com/users/92665",
"pm_score": 0,
"selected": false,
"text": "<p>Try to run it like this, verify the results.\nAlso, make sure there are enough posts to give you results. </p>\n\n<p>\n\n<pre><code>$args = array(\n 'post_status' => 'publish',\n 'posts_per_page' => -1,\n 'orderby' => 'date',\n 'tax_query' => array(\n 'relation' => 'OR',\n array(\n 'relation' => 'AND',\n array(\n 'taxonomy' => 'category',\n 'field' => 'term_id',\n 'terms' => array( 16 ),\n 'operator' => 'IN'\n ),\n array(\n 'taxonomy' => 'category',\n 'field' => 'term_id',\n 'terms' => array( 19 ),\n 'operator' => 'NOT IN'\n ),\n ),\n array(\n 'relation' => 'AND',\n array(\n 'taxonomy' => 'portfolio_category',\n 'field' => 'term_id',\n 'terms' => array( 32 ),\n 'operator' => 'IN'\n ),\n array(\n 'taxonomy' => 'portfolio_category',\n 'field' => 'term_id',\n 'terms' => array( 34 ),\n 'operator' => 'NOT IN'\n ),\n ),\n ),\n);\n$wp_query = new WP_Query();\necho '<pre>';\nprint_r($wp_query);\nexit;\n</code></pre>\n"
},
{
"answer_id": 380238,
"author": "Tony Djukic",
"author_id": 60844,
"author_profile": "https://wordpress.stackexchange.com/users/60844",
"pm_score": 1,
"selected": false,
"text": "<p>Ok, according to the codex, if you use <code>tax_query</code> in your arguments for WP_Query, then it will change the default of <code>post_type</code> from <code>posts</code> to <code>any</code>, BUT if a post_type has <code>exclude_from_search</code> set to <code>true</code> then it still won't include it in <code>any</code>. So since we don't know what the configuration is on the portfolio post_type, I suggest you explicitly instruct the query to search for both <code>posts</code> and your <code>portfolio_post_type</code>.</p>\n<pre><code>$args = array(\n //you'll need to put in the correct post-type for your portfolio items.\n //the codex says that if you use 'tax_query' that post_type should default to 'any'\n //but for the sake of it, try this...\n 'post_type' => array( 'posts, portfolio_post_type' ),\n 'post_status' => 'publish',\n 'posts_per_page' => -1,\n 'orderby' => 'date',\n 'tax_query' => array(\n 'relation' => 'OR',\n array(\n 'relation' => 'AND',\n array(\n 'taxonomy' => 'category',\n 'field' => 'term_id',\n 'terms' => array( 16 ),\n 'operator' => 'IN'\n ),\n array(\n 'taxonomy' => 'category',\n 'field' => 'term_id',\n 'terms' => array( 19 ),\n 'operator' => 'NOT IN'\n ),\n ),\n array(\n 'relation' => 'AND',\n array(\n 'taxonomy' => 'portfolio_category',\n 'field' => 'term_id',\n 'terms' => array( 32 ),\n 'operator' => 'IN'\n ),\n array(\n 'taxonomy' => 'portfolio_category',\n 'field' => 'term_id',\n 'terms' => array( 34 ),\n 'operator' => 'NOT IN'\n ),\n ),\n ),\n);\n</code></pre>\n<p>Here's the codex section that discusses this: <a href=\"https://developer.wordpress.org/reference/classes/wp_query/#post-type-parameters\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/classes/wp_query/#post-type-parameters</a></p>\n<p>Sincerely hope this helps.</p>\n"
}
]
| 2017/04/27 | [
"https://wordpress.stackexchange.com/questions/265149",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/33681/"
]
| I would like to display two different post types in the same query... nothing strange so far. But I would like to declare what taxonomies include and what exclude for both post types, so, for instance, I would like to display posts from the category "16" but that do not belong to "19" as well, and portfolio items from taxonomy "32" that do not belong to "34" at the same time.
I thought this is the right way:
```
$args = array(
'post_status' => 'publish',
'posts_per_page' => -1,
'orderby' => 'date',
'tax_query' => array(
'relation' => 'OR',
array(
'relation' => 'AND',
array(
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => array( 16 ),
'operator' => 'IN'
),
array(
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => array( 19 ),
'operator' => 'NOT IN'
),
),
array(
'relation' => 'AND',
array(
'taxonomy' => 'portfolio_category',
'field' => 'term_id',
'terms' => array( 32 ),
'operator' => 'IN'
),
array(
'taxonomy' => 'portfolio_category',
'field' => 'term_id',
'terms' => array( 34 ),
'operator' => 'NOT IN'
),
),
),
);
```
but it doesn't work. Any clue on this? | Ok, according to the codex, if you use `tax_query` in your arguments for WP\_Query, then it will change the default of `post_type` from `posts` to `any`, BUT if a post\_type has `exclude_from_search` set to `true` then it still won't include it in `any`. So since we don't know what the configuration is on the portfolio post\_type, I suggest you explicitly instruct the query to search for both `posts` and your `portfolio_post_type`.
```
$args = array(
//you'll need to put in the correct post-type for your portfolio items.
//the codex says that if you use 'tax_query' that post_type should default to 'any'
//but for the sake of it, try this...
'post_type' => array( 'posts, portfolio_post_type' ),
'post_status' => 'publish',
'posts_per_page' => -1,
'orderby' => 'date',
'tax_query' => array(
'relation' => 'OR',
array(
'relation' => 'AND',
array(
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => array( 16 ),
'operator' => 'IN'
),
array(
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => array( 19 ),
'operator' => 'NOT IN'
),
),
array(
'relation' => 'AND',
array(
'taxonomy' => 'portfolio_category',
'field' => 'term_id',
'terms' => array( 32 ),
'operator' => 'IN'
),
array(
'taxonomy' => 'portfolio_category',
'field' => 'term_id',
'terms' => array( 34 ),
'operator' => 'NOT IN'
),
),
),
);
```
Here's the codex section that discusses this: <https://developer.wordpress.org/reference/classes/wp_query/#post-type-parameters>
Sincerely hope this helps. |
265,164 | <p>I have a custom WP table that I query to get back an array of values. What I need is to make these variables exist throughout the entire WP site. </p>
<p>I'm not sure what the best way to do that is.
Here's my function: </p>
<pre><code>function get_dealer_info(){
global $wpdb;
$table_name = $wpdb->prefix . "dealer_info";
$dealerInfo = $wpdb->get_results( "SELECT * FROM $table_name" );
return $dealerInfo;
}
global $dealerInfo;
add_action('init', 'get_dealer_info');
</code></pre>
<p>So I'd like to use this like </p>
<pre><code>echo $dealerInfo['field1'];
</code></pre>
<p>Or something of the sort. Does that make sense? </p>
| [
{
"answer_id": 265165,
"author": "somebodysomewhere",
"author_id": 44937,
"author_profile": "https://wordpress.stackexchange.com/users/44937",
"pm_score": 1,
"selected": false,
"text": "<p>Notice how in your function you are globalizing <code>$wpdb</code>? That's because somewhere else in the WP core, they created a variable called <code>$wpdb</code>. Now, when you need to use <code>$wpdb</code> outside of its natural scope, you can write <code>global $wpdb;</code> to make it available to you where you need it.</p>\n\n<p>You can do the same thing with your own variable. In your functions.php, you can have <code>$dealerInfo = get_dealer_info();</code> and then where ever you need to use it, you can just call <code>global $dealerInfo;</code> then use it how you please.</p>\n"
},
{
"answer_id": 265232,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 3,
"selected": true,
"text": "<p>Do not use globals. Ever. </p>\n\n<ol>\n<li>You <strong>don't need</strong> your object everywhere. You need it only where your code is running.</li>\n<li>Globals are hard to debug, everyone can write to them or just delete them.</li>\n<li>Unit tests with globals are possible, but awkward. You have to change the global state for each test, ie. something outside of the scope of your testable code.</li>\n</ol>\n\n<p>Make your callbacks object methods instead.</p>\n\n<p>Simple example for such a class:</p>\n\n<pre><code>class DealerInfo\n{\n /**\n * @var \\wpdb\n */\n private $wpdb;\n\n private $table_name = '';\n\n private $results = [];\n\n public function __construct( \\wpdb $wpdb, $table_name )\n {\n $this->wpdb = $wpdb;\n $this->table_name = $table_name;\n }\n\n public function entry( $id )\n {\n if ( empty( $this->results ) )\n $this->fetch();\n\n if ( empty( $this->results[ $id ] ) )\n return [];\n\n return $this->results[ $id ];\n }\n\n private function fetch()\n {\n $full_table_name = $this->wpdb->prefix . $this->table_name;\n $this->results = $this->wpdb->get_results( \"SELECT * FROM $full_table_name\" );\n }\n}\n</code></pre>\n\n<p>Now you can set up that class early, for example on <code>wp_loaded</code>, and register the method to get the entry details as a callback …</p>\n\n<pre><code>add_action( 'wp_loaded', function() {\n\n global $wpdb;\n\n $dealer_info = new DealerInfo( $wpdb, 'dealer_info' );\n\n add_filter( 'show_dealer_details', [ $dealer_info, 'entry' ] );\n});\n</code></pre>\n\n<p>… and where you want to use <code>echo $dealerInfo['field1'];</code>, you can now use:</p>\n\n<pre><code>// 4 is the dealer id in the database\n$dealer_details = apply_filters( 'show_dealer_details', [], 4 );\n\nif ( ! empty( $dealer_details ) )\n{\n // print the details\n}\n</code></pre>\n\n<p>Everything is still nicely isolated, except the WP hook API of course.</p>\n"
}
]
| 2017/04/27 | [
"https://wordpress.stackexchange.com/questions/265164",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/44899/"
]
| I have a custom WP table that I query to get back an array of values. What I need is to make these variables exist throughout the entire WP site.
I'm not sure what the best way to do that is.
Here's my function:
```
function get_dealer_info(){
global $wpdb;
$table_name = $wpdb->prefix . "dealer_info";
$dealerInfo = $wpdb->get_results( "SELECT * FROM $table_name" );
return $dealerInfo;
}
global $dealerInfo;
add_action('init', 'get_dealer_info');
```
So I'd like to use this like
```
echo $dealerInfo['field1'];
```
Or something of the sort. Does that make sense? | Do not use globals. Ever.
1. You **don't need** your object everywhere. You need it only where your code is running.
2. Globals are hard to debug, everyone can write to them or just delete them.
3. Unit tests with globals are possible, but awkward. You have to change the global state for each test, ie. something outside of the scope of your testable code.
Make your callbacks object methods instead.
Simple example for such a class:
```
class DealerInfo
{
/**
* @var \wpdb
*/
private $wpdb;
private $table_name = '';
private $results = [];
public function __construct( \wpdb $wpdb, $table_name )
{
$this->wpdb = $wpdb;
$this->table_name = $table_name;
}
public function entry( $id )
{
if ( empty( $this->results ) )
$this->fetch();
if ( empty( $this->results[ $id ] ) )
return [];
return $this->results[ $id ];
}
private function fetch()
{
$full_table_name = $this->wpdb->prefix . $this->table_name;
$this->results = $this->wpdb->get_results( "SELECT * FROM $full_table_name" );
}
}
```
Now you can set up that class early, for example on `wp_loaded`, and register the method to get the entry details as a callback …
```
add_action( 'wp_loaded', function() {
global $wpdb;
$dealer_info = new DealerInfo( $wpdb, 'dealer_info' );
add_filter( 'show_dealer_details', [ $dealer_info, 'entry' ] );
});
```
… and where you want to use `echo $dealerInfo['field1'];`, you can now use:
```
// 4 is the dealer id in the database
$dealer_details = apply_filters( 'show_dealer_details', [], 4 );
if ( ! empty( $dealer_details ) )
{
// print the details
}
```
Everything is still nicely isolated, except the WP hook API of course. |
265,172 | <p>my site started acting up a few days ago, running the debug I get these lines.</p>
<p>Tried to mess around with the DB but couldn't get my head through it.</p>
<p>Do you have any idea what those lines imply?</p>
<blockquote>
<p>Warning: mysqli_real_connect(): (HY000/2002): Can't connect to local
MySQL server through socket '/var/lib/mysql/mysql.sock' (2 "No such
file or directory") in
/home/u420302506/public_html/wp-includes/wp-db.php on line 1490</p>
<p>Deprecated: mysql_connect(): The mysql extension is deprecated and
will be removed in the future: use mysqli or PDO instead in
/home/u420302506/public_html/wp-includes/wp-db.php on line 1520</p>
<p>Warning: mysql_connect(): Can't connect to local MySQL server through
socket '/var/lib/mysql/mysql.sock' (2 "No such file or directory") in
/home/u420302506/public_html/wp-includes/wp-db.php on line 1520</p>
</blockquote>
<p>Line 1490:</p>
<blockquote>
<p>mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );</p>
</blockquote>
<p>Line 1520:</p>
<blockquote>
<p>this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );</p>
</blockquote>
| [
{
"answer_id": 265197,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 0,
"selected": false,
"text": "<p>Try using the IP address of your local server instead of <code>localhost</code>. That means set <code>127.0.0.1</code> at <code>DB_HOST</code> in <code>wp-config.php</code>. So the full thing will be like-</p>\n\n<pre><code>/** MySQL hostname */\ndefine('DB_HOST', '127.0.0.1');\n</code></pre>\n\n<p>Check those below answers for more information-</p>\n\n<p><a href=\"https://stackoverflow.com/questions/13769504/mysqlimysqli-hy000-2002-cant-connect-to-local-mysql-server-through-sock\">https://stackoverflow.com/questions/13769504/mysqlimysqli-hy000-2002-cant-connect-to-local-mysql-server-through-sock</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/4219970/warning-mysql-connect-2002-no-such-file-or-directory-trying-to-connect-vi\">https://stackoverflow.com/questions/4219970/warning-mysql-connect-2002-no-such-file-or-directory-trying-to-connect-vi</a></p>\n"
},
{
"answer_id": 265198,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>The error messages show signs of mismatch between your wordpress version and your PHP (or even mysql) version. Sounds like you are trying to run old wordpress version on new php version, or that you do not have mysqli extension of PHP active.</p>\n\n<p>This will explain the last two errors, but not the first one. The first one seems to be a sign that either mysql and its relevant drivers are misconfigured or that the mysql just shutsdown from time to time.</p>\n\n<p>If you are on a shared hosting, call their support, if it is your own VPS you need to get someone to check out your setup (assuming you have enough memory to handle your load).</p>\n"
},
{
"answer_id": 319471,
"author": "Joshua JJ S",
"author_id": 76191,
"author_profile": "https://wordpress.stackexchange.com/users/76191",
"pm_score": 2,
"selected": false,
"text": "<p>I had this same error. For me, this happened because I moved the datadir of my database.</p>\n\n<p>On centos \n- the default location of the datadir is /var/lib/mysql\n- and the default loc of the socket file is /var/lib/mysql/mysql.sock</p>\n\n<p>I moved the datadir to /datadir/mysql. The Mysql db server started fine and the 'mysql' command line client worked fine.</p>\n\n<p>However, when I started apache and then accessed my wordpress site, I got that error.</p>\n\n<p>The fix was to update /etc/php.ini.</p>\n\n<p>There are three settings in that file for the mysql.sock location for:\n- pdo\n- mysql\n- mysqli</p>\n\n<p>Below are the changes I made for those three settings - to set each one to \"/datadir/mysql/mysql.sock\". Prior to my change, all three were just blank after the '=', and so the default location was used.</p>\n\n<pre><code>[Pdo_mysql]\n ...\n; Default socket name for local MySQL connects. If empty, uses the built-in\n; MySQL defaults.\n; http://php.net/pdo_mysql.default-socket\npdo_mysql.default_socket=/datadir/mysql/mysql.sock\n\n\n [MySQL]\n ...\n; Default socket name for local MySQL connects. If empty, uses the built-in\n; MySQL defaults.\n; http://php.net/mysql.default-socket\nmysql.default_socket = /datadir/mysql/mysql.sock\n\n\n[MySQLi]\n ...\n; Default socket name for local MySQL connects. If empty, uses the built-in\n; MySQL defaults.\n; http://php.net/mysqli.default-socket\nmysqli.default_socket = /datadir/mysql/mysql.sock\n</code></pre>\n"
},
{
"answer_id": 334730,
"author": "Arvind Singh",
"author_id": 113501,
"author_profile": "https://wordpress.stackexchange.com/users/113501",
"pm_score": 1,
"selected": false,
"text": "<p>Try to replace your current host from localhost to <strong><code>127.0.0.1</code></strong> in your wp-config.php. If you can then try to restart your MYSQL services. </p>\n"
},
{
"answer_id": 359241,
"author": "PauloBoaventura",
"author_id": 170967,
"author_profile": "https://wordpress.stackexchange.com/users/170967",
"pm_score": 0,
"selected": false,
"text": "<p>In Wordpress I was having a problem between mysqli and PDO.\nI solved it with the command yum update & yum upgrade, no centos and he gave me the following updates:</p>\n\n<p>================================================== ==============================\n Package Arch Version Repository Size\n================================================== ==============================\nInstalling:\n lsphp73-mysqlnd x86_64 7.3.15-1.el7 litespeed 132 k\n replacing lsphp73-mysqlnd.x86_64 7.3.14-1.el7\nUpdating:\n lsphp73 x86_64 7.3.15-1.el7 litespeed 5.0 M\n lsphp73-bcmath x86_64 7.3.15-1.el7 litespeed 27 k\n lsphp73-common x86_64 7.3.15-1.el7 litespeed 650 k\n lsphp73-gd x86_64 7.3.15-1.el7 litespeed 114 k\n lsphp73-imap x86_64 7.3.15-1.el7 litespeed 32k\n lsphp73-mbstring x86_64 7.3.15-1.el7 litespeed 559 k\n lsphp73-opcache x86_64 7.3.15-1.el7 litespeed 191 k\n lsphp73-pdo x86_64 7.3.15-1.el7 litespeed 67 k\n lsphp73-process x86_64 7.3.15-1.el7 litespeed 29 k\n lsphp73-soap x86_64 7.3.15-1.el7 litespeed 120 k\n lsphp73-xml x86_64 7.3.15-1.el7 litespeed 126 k\n openlitespeed x86_64 1.6.9-1.el7 litespeed 37 M</p>\n\n<p>Transaction Summary\n================================================== ==============================\nInstall 1 Package\nUpgrade 12 Packages</p>\n\n<p>Total download size: 44 M\nDownloading packages:\nNo Presto metadata available for litespeed</p>\n\n<hr>\n\n<p>Total 13 MB / s | 44 MB 00:03</p>\n\n<p>Besides that mine\n fastcgi_pass unix: /var/php-nginx/15822663384347.sock/socket;</p>\n\n<p>It was causing conflict.</p>\n\n<p>but it still didn't solve the problem.</p>\n\n<p>The solution found was to change the username and password in the file that connects the cms with the database and I saw that suddenly it could be the username that has a dot or is the same domain name.</p>\n"
}
]
| 2017/04/27 | [
"https://wordpress.stackexchange.com/questions/265172",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118596/"
]
| my site started acting up a few days ago, running the debug I get these lines.
Tried to mess around with the DB but couldn't get my head through it.
Do you have any idea what those lines imply?
>
> Warning: mysqli\_real\_connect(): (HY000/2002): Can't connect to local
> MySQL server through socket '/var/lib/mysql/mysql.sock' (2 "No such
> file or directory") in
> /home/u420302506/public\_html/wp-includes/wp-db.php on line 1490
>
>
> Deprecated: mysql\_connect(): The mysql extension is deprecated and
> will be removed in the future: use mysqli or PDO instead in
> /home/u420302506/public\_html/wp-includes/wp-db.php on line 1520
>
>
> Warning: mysql\_connect(): Can't connect to local MySQL server through
> socket '/var/lib/mysql/mysql.sock' (2 "No such file or directory") in
> /home/u420302506/public\_html/wp-includes/wp-db.php on line 1520
>
>
>
Line 1490:
>
> mysqli\_real\_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client\_flags );
>
>
>
Line 1520:
>
> this->dbh = mysql\_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new\_link, $client\_flags );
>
>
> | I had this same error. For me, this happened because I moved the datadir of my database.
On centos
- the default location of the datadir is /var/lib/mysql
- and the default loc of the socket file is /var/lib/mysql/mysql.sock
I moved the datadir to /datadir/mysql. The Mysql db server started fine and the 'mysql' command line client worked fine.
However, when I started apache and then accessed my wordpress site, I got that error.
The fix was to update /etc/php.ini.
There are three settings in that file for the mysql.sock location for:
- pdo
- mysql
- mysqli
Below are the changes I made for those three settings - to set each one to "/datadir/mysql/mysql.sock". Prior to my change, all three were just blank after the '=', and so the default location was used.
```
[Pdo_mysql]
...
; Default socket name for local MySQL connects. If empty, uses the built-in
; MySQL defaults.
; http://php.net/pdo_mysql.default-socket
pdo_mysql.default_socket=/datadir/mysql/mysql.sock
[MySQL]
...
; Default socket name for local MySQL connects. If empty, uses the built-in
; MySQL defaults.
; http://php.net/mysql.default-socket
mysql.default_socket = /datadir/mysql/mysql.sock
[MySQLi]
...
; Default socket name for local MySQL connects. If empty, uses the built-in
; MySQL defaults.
; http://php.net/mysqli.default-socket
mysqli.default_socket = /datadir/mysql/mysql.sock
``` |
265,177 | <p>I've installed Custom Post Type UI plugin on my client's site. I have registered two new post types called Resources and Case Studies. I've enabled them to have categories and tags support. All of this works fine.</p>
<p>However, I want to be able to show a list of categories for only the case studies in the case studies sidebar and a list of the categories for the resource posts in the resources sidebar. Right now they appear to overlap and share categories and tags. Is there something I am missing?</p>
<p>If you view this page you will see the sidebar shows <a href="http://goconcentric.com/resources/resource-2/" rel="nofollow noreferrer">http://goconcentric.com/resources/resource-2/</a> case studies as an option when this is a resource post. Similarly case study posts have a link to resources. I want the categories to be separate and only show on the pages in their hierarchy.</p>
| [
{
"answer_id": 265197,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 0,
"selected": false,
"text": "<p>Try using the IP address of your local server instead of <code>localhost</code>. That means set <code>127.0.0.1</code> at <code>DB_HOST</code> in <code>wp-config.php</code>. So the full thing will be like-</p>\n\n<pre><code>/** MySQL hostname */\ndefine('DB_HOST', '127.0.0.1');\n</code></pre>\n\n<p>Check those below answers for more information-</p>\n\n<p><a href=\"https://stackoverflow.com/questions/13769504/mysqlimysqli-hy000-2002-cant-connect-to-local-mysql-server-through-sock\">https://stackoverflow.com/questions/13769504/mysqlimysqli-hy000-2002-cant-connect-to-local-mysql-server-through-sock</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/4219970/warning-mysql-connect-2002-no-such-file-or-directory-trying-to-connect-vi\">https://stackoverflow.com/questions/4219970/warning-mysql-connect-2002-no-such-file-or-directory-trying-to-connect-vi</a></p>\n"
},
{
"answer_id": 265198,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>The error messages show signs of mismatch between your wordpress version and your PHP (or even mysql) version. Sounds like you are trying to run old wordpress version on new php version, or that you do not have mysqli extension of PHP active.</p>\n\n<p>This will explain the last two errors, but not the first one. The first one seems to be a sign that either mysql and its relevant drivers are misconfigured or that the mysql just shutsdown from time to time.</p>\n\n<p>If you are on a shared hosting, call their support, if it is your own VPS you need to get someone to check out your setup (assuming you have enough memory to handle your load).</p>\n"
},
{
"answer_id": 319471,
"author": "Joshua JJ S",
"author_id": 76191,
"author_profile": "https://wordpress.stackexchange.com/users/76191",
"pm_score": 2,
"selected": false,
"text": "<p>I had this same error. For me, this happened because I moved the datadir of my database.</p>\n\n<p>On centos \n- the default location of the datadir is /var/lib/mysql\n- and the default loc of the socket file is /var/lib/mysql/mysql.sock</p>\n\n<p>I moved the datadir to /datadir/mysql. The Mysql db server started fine and the 'mysql' command line client worked fine.</p>\n\n<p>However, when I started apache and then accessed my wordpress site, I got that error.</p>\n\n<p>The fix was to update /etc/php.ini.</p>\n\n<p>There are three settings in that file for the mysql.sock location for:\n- pdo\n- mysql\n- mysqli</p>\n\n<p>Below are the changes I made for those three settings - to set each one to \"/datadir/mysql/mysql.sock\". Prior to my change, all three were just blank after the '=', and so the default location was used.</p>\n\n<pre><code>[Pdo_mysql]\n ...\n; Default socket name for local MySQL connects. If empty, uses the built-in\n; MySQL defaults.\n; http://php.net/pdo_mysql.default-socket\npdo_mysql.default_socket=/datadir/mysql/mysql.sock\n\n\n [MySQL]\n ...\n; Default socket name for local MySQL connects. If empty, uses the built-in\n; MySQL defaults.\n; http://php.net/mysql.default-socket\nmysql.default_socket = /datadir/mysql/mysql.sock\n\n\n[MySQLi]\n ...\n; Default socket name for local MySQL connects. If empty, uses the built-in\n; MySQL defaults.\n; http://php.net/mysqli.default-socket\nmysqli.default_socket = /datadir/mysql/mysql.sock\n</code></pre>\n"
},
{
"answer_id": 334730,
"author": "Arvind Singh",
"author_id": 113501,
"author_profile": "https://wordpress.stackexchange.com/users/113501",
"pm_score": 1,
"selected": false,
"text": "<p>Try to replace your current host from localhost to <strong><code>127.0.0.1</code></strong> in your wp-config.php. If you can then try to restart your MYSQL services. </p>\n"
},
{
"answer_id": 359241,
"author": "PauloBoaventura",
"author_id": 170967,
"author_profile": "https://wordpress.stackexchange.com/users/170967",
"pm_score": 0,
"selected": false,
"text": "<p>In Wordpress I was having a problem between mysqli and PDO.\nI solved it with the command yum update & yum upgrade, no centos and he gave me the following updates:</p>\n\n<p>================================================== ==============================\n Package Arch Version Repository Size\n================================================== ==============================\nInstalling:\n lsphp73-mysqlnd x86_64 7.3.15-1.el7 litespeed 132 k\n replacing lsphp73-mysqlnd.x86_64 7.3.14-1.el7\nUpdating:\n lsphp73 x86_64 7.3.15-1.el7 litespeed 5.0 M\n lsphp73-bcmath x86_64 7.3.15-1.el7 litespeed 27 k\n lsphp73-common x86_64 7.3.15-1.el7 litespeed 650 k\n lsphp73-gd x86_64 7.3.15-1.el7 litespeed 114 k\n lsphp73-imap x86_64 7.3.15-1.el7 litespeed 32k\n lsphp73-mbstring x86_64 7.3.15-1.el7 litespeed 559 k\n lsphp73-opcache x86_64 7.3.15-1.el7 litespeed 191 k\n lsphp73-pdo x86_64 7.3.15-1.el7 litespeed 67 k\n lsphp73-process x86_64 7.3.15-1.el7 litespeed 29 k\n lsphp73-soap x86_64 7.3.15-1.el7 litespeed 120 k\n lsphp73-xml x86_64 7.3.15-1.el7 litespeed 126 k\n openlitespeed x86_64 1.6.9-1.el7 litespeed 37 M</p>\n\n<p>Transaction Summary\n================================================== ==============================\nInstall 1 Package\nUpgrade 12 Packages</p>\n\n<p>Total download size: 44 M\nDownloading packages:\nNo Presto metadata available for litespeed</p>\n\n<hr>\n\n<p>Total 13 MB / s | 44 MB 00:03</p>\n\n<p>Besides that mine\n fastcgi_pass unix: /var/php-nginx/15822663384347.sock/socket;</p>\n\n<p>It was causing conflict.</p>\n\n<p>but it still didn't solve the problem.</p>\n\n<p>The solution found was to change the username and password in the file that connects the cms with the database and I saw that suddenly it could be the username that has a dot or is the same domain name.</p>\n"
}
]
| 2017/04/27 | [
"https://wordpress.stackexchange.com/questions/265177",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/116115/"
]
| I've installed Custom Post Type UI plugin on my client's site. I have registered two new post types called Resources and Case Studies. I've enabled them to have categories and tags support. All of this works fine.
However, I want to be able to show a list of categories for only the case studies in the case studies sidebar and a list of the categories for the resource posts in the resources sidebar. Right now they appear to overlap and share categories and tags. Is there something I am missing?
If you view this page you will see the sidebar shows <http://goconcentric.com/resources/resource-2/> case studies as an option when this is a resource post. Similarly case study posts have a link to resources. I want the categories to be separate and only show on the pages in their hierarchy. | I had this same error. For me, this happened because I moved the datadir of my database.
On centos
- the default location of the datadir is /var/lib/mysql
- and the default loc of the socket file is /var/lib/mysql/mysql.sock
I moved the datadir to /datadir/mysql. The Mysql db server started fine and the 'mysql' command line client worked fine.
However, when I started apache and then accessed my wordpress site, I got that error.
The fix was to update /etc/php.ini.
There are three settings in that file for the mysql.sock location for:
- pdo
- mysql
- mysqli
Below are the changes I made for those three settings - to set each one to "/datadir/mysql/mysql.sock". Prior to my change, all three were just blank after the '=', and so the default location was used.
```
[Pdo_mysql]
...
; Default socket name for local MySQL connects. If empty, uses the built-in
; MySQL defaults.
; http://php.net/pdo_mysql.default-socket
pdo_mysql.default_socket=/datadir/mysql/mysql.sock
[MySQL]
...
; Default socket name for local MySQL connects. If empty, uses the built-in
; MySQL defaults.
; http://php.net/mysql.default-socket
mysql.default_socket = /datadir/mysql/mysql.sock
[MySQLi]
...
; Default socket name for local MySQL connects. If empty, uses the built-in
; MySQL defaults.
; http://php.net/mysqli.default-socket
mysqli.default_socket = /datadir/mysql/mysql.sock
``` |
265,234 | <p>I've created a simple custom post type.
In my wordpress site, permalinks are set to Post Name.</p>
<p>In the admin screen for posts of my custom post type, no permalink editor is displayed.</p>
<p>How do I make this show up, as it does normally for the default post types?</p>
<p>This is how I've created the definition:</p>
<pre><code>function register_cpt_staff_member() {
$labels = array(
'name' => __( 'staff', 'staff-member' ),
'singular_name' => __( 'staff-member', 'staff-member' ),
'add_new' => __( 'Add New', 'Staff Member' ),
'add_new_item' => __( 'Add New Staff Member', 'staff_member' ),
'edit_item' => __( 'Edit Staff Member', 'staff_member' ),
'new_item' => __( 'New Staff Member', 'staff_member' ),
'view_item' => __( 'View Staff Member', 'staff_member' ),
'search_items' => __( 'Search Staff Members', 'staff_member' ),
'not_found' => __( 'No results found', 'staff_member' ),
'not_found_in_trash' => __( 'No staff found in Trash', 'staff_member' ),
'parent_item_colon' => __( 'Parent Staff Member:', 'staff_member' ),
'menu_name' => __( 'Staff', 'Staff_member' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => false,
'supports' => array( 'title', 'editor', 'thumbnail', 'custom-fields' ),
'public' => false,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'show_in_nav_menus' => false,
'publicly_queryable' => true,
'exclude_from_search' => true,
'has_archive' => false,
'query_var' => true,
'can_export' => true,
'rewrite' => true,
'capability_type' => 'post'
);
register_post_type( 'staff_member', $args );
}
</code></pre>
| [
{
"answer_id": 265236,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 3,
"selected": true,
"text": "<p>Your CPT is not public, therefor the \"posts\" of that type have no reason to have a public URL (AKA permalink), therefor wordpress do not bother to add the permalink (actually slug) UI.</p>\n"
},
{
"answer_id": 265264,
"author": "Tansukh Parmar",
"author_id": 60770,
"author_profile": "https://wordpress.stackexchange.com/users/60770",
"pm_score": -1,
"selected": false,
"text": "<pre><code>function testimonials_custome_post(){\n $labels = array(\n 'name' => __('Testimonials', 'testimonials'),\n 'singular_name' => __('Testimonials', 'testimonials'),\n 'add_new' => __('New Testimonials', 'testimonials'),\n 'add_new_item' => __('Add new Testimonials', 'testimonials'),\n 'edit_item' => __('Edit Testimonials', 'testimonials'),\n 'new_item' => __('New Testimonials', 'testimonials'),\n 'view_item' => __('View Testimonials', 'testimonials'),\n 'search_item' => __('Search Testimonials', 'testimonials'),\n 'not_found' => __('No The Testimonials Found', 'testimonials'),\n 'not_found_in_trash' => __('No The Testimonials found in trash', 'testimonials')\n );\n $args = array(\n 'labels' => $labels,\n 'public' => true,\n 'menu_icon' => 'dashicons-pressthis',\n 'supports' => array(\n 'title',\n 'editor',\n ),\n );\n\n register_post_type('testimonials', $args);\n}\n\nadd_action('init', 'testimonials_custome_post' ); \n</code></pre>\n\n<p>WORKING CODE FOR CUSTOM POST </p>\n"
}
]
| 2017/04/28 | [
"https://wordpress.stackexchange.com/questions/265234",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/26187/"
]
| I've created a simple custom post type.
In my wordpress site, permalinks are set to Post Name.
In the admin screen for posts of my custom post type, no permalink editor is displayed.
How do I make this show up, as it does normally for the default post types?
This is how I've created the definition:
```
function register_cpt_staff_member() {
$labels = array(
'name' => __( 'staff', 'staff-member' ),
'singular_name' => __( 'staff-member', 'staff-member' ),
'add_new' => __( 'Add New', 'Staff Member' ),
'add_new_item' => __( 'Add New Staff Member', 'staff_member' ),
'edit_item' => __( 'Edit Staff Member', 'staff_member' ),
'new_item' => __( 'New Staff Member', 'staff_member' ),
'view_item' => __( 'View Staff Member', 'staff_member' ),
'search_items' => __( 'Search Staff Members', 'staff_member' ),
'not_found' => __( 'No results found', 'staff_member' ),
'not_found_in_trash' => __( 'No staff found in Trash', 'staff_member' ),
'parent_item_colon' => __( 'Parent Staff Member:', 'staff_member' ),
'menu_name' => __( 'Staff', 'Staff_member' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => false,
'supports' => array( 'title', 'editor', 'thumbnail', 'custom-fields' ),
'public' => false,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'show_in_nav_menus' => false,
'publicly_queryable' => true,
'exclude_from_search' => true,
'has_archive' => false,
'query_var' => true,
'can_export' => true,
'rewrite' => true,
'capability_type' => 'post'
);
register_post_type( 'staff_member', $args );
}
``` | Your CPT is not public, therefor the "posts" of that type have no reason to have a public URL (AKA permalink), therefor wordpress do not bother to add the permalink (actually slug) UI. |
265,297 | <p>We have a site that somehow has both http and https versions accessible. We want to force it all to https. When we try to set the WordPress and Site URLS to https the site ends up in a redirect loop.</p>
<p>Using Really Simple SSL doesn't really help as we still end up with a redirect loop.</p>
<p>Redirection plugin isn't doing anything that would cause this.</p>
<p>I didn't even know you could get a WordPress site to display both versions, let alone how one would go about changing this.</p>
<p>Googling/searching Stack exchange for this is rather difficult for obvious reasons, so I apologize if this has been answered somewhere else.</p>
<p>Has anyone seen this issue before?</p>
| [
{
"answer_id": 265320,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 3,
"selected": true,
"text": "<p>If you can access the SSL version of your blog without a problem, then it means you can redirect all your traffic to it. To do so, take these 2 steps:</p>\n\n<ol>\n<li><p>Access your database using PhpMyAdmin or any other software you want. Head over to <code>wp_options</code> table, and change to values of <code>siteurl</code> and <code>homeurl</code> to SSL version of your blog (for example <code>https://example.com</code>).</p></li>\n<li><p>Using any FTP software open and edit your <code>.htaccess</code> file the following way:</p></li>\n</ol>\n\n<p>This will redirect all traffics to the secure version of your blog.</p>\n\n<pre><code><IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /\n\nRewriteCond %{ENV:HTTPS} !=on\nRewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]\n\n#BEGIN WordPress\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n</IfModule>\n</code></pre>\n\n<p>Remember not to remove the original rules created by WordPress (the lines below #BEGIN WordPress)</p>\n"
},
{
"answer_id": 265354,
"author": "Disk01",
"author_id": 82479,
"author_profile": "https://wordpress.stackexchange.com/users/82479",
"pm_score": 0,
"selected": false,
"text": "<p>Jack Johansson have answered you rightly! Alternative to this you could also install \"<a href=\"https://wordpress.org/plugins/wp-force-https/\" rel=\"nofollow noreferrer\">WordPress Force HTTPS</a>\" plugin to do this without messing up with <code>.htaccess</code></p>\n\n<blockquote>\n <p>Note: Don't forget to install Cloudflare plugin if in case you are using cloudflare else your site will enter into infinite redirect loop.</p>\n</blockquote>\n"
}
]
| 2017/04/28 | [
"https://wordpress.stackexchange.com/questions/265297",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111880/"
]
| We have a site that somehow has both http and https versions accessible. We want to force it all to https. When we try to set the WordPress and Site URLS to https the site ends up in a redirect loop.
Using Really Simple SSL doesn't really help as we still end up with a redirect loop.
Redirection plugin isn't doing anything that would cause this.
I didn't even know you could get a WordPress site to display both versions, let alone how one would go about changing this.
Googling/searching Stack exchange for this is rather difficult for obvious reasons, so I apologize if this has been answered somewhere else.
Has anyone seen this issue before? | If you can access the SSL version of your blog without a problem, then it means you can redirect all your traffic to it. To do so, take these 2 steps:
1. Access your database using PhpMyAdmin or any other software you want. Head over to `wp_options` table, and change to values of `siteurl` and `homeurl` to SSL version of your blog (for example `https://example.com`).
2. Using any FTP software open and edit your `.htaccess` file the following way:
This will redirect all traffics to the secure version of your blog.
```
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{ENV:HTTPS} !=on
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
#BEGIN WordPress
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
```
Remember not to remove the original rules created by WordPress (the lines below #BEGIN WordPress) |
265,318 | <p>I am trying to understand when usage of admin url is required. If I do this in my plugins page, they all do the same thing.</p>
<pre><code><a href="<?php echo admin_url("admin.php?page=fap_playlist_manager"); ?>">Back to Playlist manager</a>
<a href="admin.php?page=fap_playlist_manager">Back to Playlist manager</a>
<a href="?page=fap_playlist_manager">Back to Playlist manager</a>
</code></pre>
<p>What does this depends on?</p>
| [
{
"answer_id": 265308,
"author": "Mervan Agency",
"author_id": 118206,
"author_profile": "https://wordpress.stackexchange.com/users/118206",
"pm_score": 1,
"selected": false,
"text": "<p>I am not sure how you removed <code>?p=</code> from the link but you can use <code>get_shortlink</code> filter to override the shortlink. You can refer following article for more details.</p>\n\n<p><a href=\"http://www.wpbeginner.com/wp-themes/how-to-display-wordpress-shortlinks-in-your-theme/\" rel=\"nofollow noreferrer\">http://www.wpbeginner.com/wp-themes/how-to-display-wordpress-shortlinks-in-your-theme/</a></p>\n\n<p>Reference to <code>get_shortlink</code> filter: <a href=\"https://developer.wordpress.org/reference/hooks/get_shortlink/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/get_shortlink/</a></p>\n\n<p>Can you share some more details on how you removed the ?p= from the link?</p>\n"
},
{
"answer_id": 265314,
"author": "Punitkumar Patel",
"author_id": 117461,
"author_profile": "https://wordpress.stackexchange.com/users/117461",
"pm_score": 1,
"selected": false,
"text": "<p>@yogu You can add <a href=\"https://i.stack.imgur.com/BPsYp.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BPsYp.png\" alt=\"%post_id%\"></a> in permalink to get required structure. <code>site-url.com/22 (without ?p=)</code></p>\n\n<p>For specific post you can add following function and add specific condition for it : </p>\n\n<pre><code>add_filter( 'post_link', 'custom_permalink', 10, 3 );\nfunction custom_permalink( $permalink, $post, $leavename ) {\n // For shortlink condition\n if ( 'Shortlink Condition here' ) {\n $permalink = trailingslashit( home_url('/'. $post->ID .'/' ) );\n }\n return $permalink;\n}\nadd_action('generate_rewrite_rules', 'custom_rewrite_rules');\nfunction custom_rewrite_rules( $wp_rewrite ) {\n // This rule will will match the post id in %post_id% struture\n $new_rules['^([^/]*)-([0-9]+)/?'] = 'index.php?p=$matches[2]';\n $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;\n return $wp_rewrite;\n}\n</code></pre>\n"
},
{
"answer_id": 385000,
"author": "harry",
"author_id": 203280,
"author_profile": "https://wordpress.stackexchange.com/users/203280",
"pm_score": 0,
"selected": false,
"text": "<p>Wordpress redirects without the parameter: ?p. Regardless of whether it's pages or posts ...</p>\n<p>For example:\nsite.com/922 (post or page ID...), this should redirect.</p>\n<p>If you want to change link one at the head of your site:</p>\n<pre><code>add_filter('pre_get_shortlink', function () {\n return home_url('/') . get_the_ID();\n}, 10, 3);\n</code></pre>\n<p>In wordpress docs: <a href=\"https://developer.wordpress.org/reference/hooks/pre_get_shortlink/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/pre_get_shortlink/</a></p>\n"
}
]
| 2017/04/29 | [
"https://wordpress.stackexchange.com/questions/265318",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/45321/"
]
| I am trying to understand when usage of admin url is required. If I do this in my plugins page, they all do the same thing.
```
<a href="<?php echo admin_url("admin.php?page=fap_playlist_manager"); ?>">Back to Playlist manager</a>
<a href="admin.php?page=fap_playlist_manager">Back to Playlist manager</a>
<a href="?page=fap_playlist_manager">Back to Playlist manager</a>
```
What does this depends on? | I am not sure how you removed `?p=` from the link but you can use `get_shortlink` filter to override the shortlink. You can refer following article for more details.
<http://www.wpbeginner.com/wp-themes/how-to-display-wordpress-shortlinks-in-your-theme/>
Reference to `get_shortlink` filter: <https://developer.wordpress.org/reference/hooks/get_shortlink/>
Can you share some more details on how you removed the ?p= from the link? |
265,324 | <p><code>bootstrap-slider.js</code> offered by seiyria not working in WordPress. It seems that resource file isn't linked properly. What am I missing here? Any idea?</p>
<p>Link Resource to WordPress(<code>functions.php</code>): </p>
<pre><code>if (!function_exists('techcare_enqueue_scripts')):
function techcare_enqueue_scripts() {
/* Enqueue Scripts Begin */
wp_deregister_script('jquery');
wp_enqueue_script('jquery', get_template_directory_uri().
'/scripts/jquery-2.1.4.js', false, null, false);
wp_deregister_script('modernizr');
wp_enqueue_script('modernizr', get_template_directory_uri().
'/scripts/modernizr.min.js', false, null, false);
wp_deregister_script('classie');
wp_enqueue_script('classie', get_template_directory_uri().
'/scripts/classie.js', false, null, false);
wp_deregister_script('api');
wp_enqueue_script('api', 'https://www.google.com/recaptcha/api.js', false, null, false);
wp_deregister_script('script-1');
wp_enqueue_script('script-1', 'https://maps.googleapis.com/maps/api/js?key=AIzaSyBJPGck9G3Pf4f912F_NyyEPFU9mOroxKo&callback=initMap', false, null, false);
wp_deregister_script('script-2');
wp_enqueue_script('script-2', 'https://maps.googleapis.com/maps/api/js?sensor=false', false, null, false);
wp_deregister_script('jquery');
wp_enqueue_script('jquery', get_template_directory_uri().
'/scripts/jquery-2.1.4.js', false, null, true);
wp_deregister_script('jquerymagnificpopup');
wp_enqueue_script('jquerymagnificpopup', get_template_directory_uri().
'/scripts/jquery.magnific-popup.min.js', false, null, true);
wp_deregister_script('smoothscroll');
wp_enqueue_script('smoothscroll', get_template_directory_uri().
'/scripts/SmoothScroll.js', false, null, true);
wp_deregister_script('apscrolltop');
wp_enqueue_script('apscrolltop', get_template_directory_uri().
'/scripts/ap-scroll-top.js', false, null, true);
wp_deregister_script('bootstrapdatepicker');
wp_enqueue_script('bootstrapdatepicker', get_template_directory_uri().
'/scripts/bootstrap-datepicker.min.js', false, null, true);
wp_deregister_script('bootstrap');
wp_enqueue_script('bootstrap', get_template_directory_uri().
'/scripts/bootstrap.min.js', false, null, true);
wp_deregister_script('wow');
wp_enqueue_script('wow', get_template_directory_uri().
'/scripts/wow.min.js', false, null, true);
wp_deregister_script('main');
wp_enqueue_script('main', get_template_directory_uri().
'/scripts/main.js', false, null, true);
wp_deregister_script('jquerycounterup');
wp_enqueue_script('jquerycounterup', get_template_directory_uri().
'/scripts/jquery.counterup.min.js', false, null, true);
wp_deregister_script('waypoints');
wp_enqueue_script('waypoints', get_template_directory_uri().
'/../cdnjs.cloudflare.com/ajax/libs/waypoints/2.0.3/waypoints.min.js', false, null, true);
wp_deregister_script('slick');
wp_enqueue_script('slick', get_template_directory_uri().
'/scripts/slick.min.js', false, null, true);
wp_deregister_script('jqueryvalidate');
wp_enqueue_script('jqueryvalidate', get_template_directory_uri().
'/scripts/vendor/jquery-validation/jquery.validate.min.js', false, null, true);
wp_deregister_script('jqueryvalidateunobtrusive');
wp_enqueue_script('jqueryvalidateunobtrusive', get_template_directory_uri().
'/scripts/vendor/jquery-validation/jquery.validate.unobtrusive.min.js', false, null, true);
wp_deregister_script('ajaxhandler');
wp_enqueue_script('ajaxhandler', get_template_directory_uri().
'/scripts/ajaxhandler.js', false, null, true);
wp_deregister_script('script-3');
wp_enqueue_script('script-3', 'https://maps.googleapis.com/maps/api/js?key=AIzaSyBJPGck9G3Pf4f912F_NyyEPFU9mOroxKo&callback=initMap', false, null, false);
wp_deregister_script('script-4');
wp_enqueue_script('script-4', 'https://maps.googleapis.com/maps/api/js?sensor=false', false, null, false);
wp_deregister_script('bootstrapslider');
wp_enqueue_script('bootstrapslider', 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.2/bootstrap-slider.js', false, null, false);
wp_deregister_script('bootstrapslider');
wp_enqueue_script('bootstrapslider', 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.2/bootstrap-slider.min.js', false, null, false);
/* Enqueue Scripts End */
/* Enqueue Styles Begin */
wp_deregister_style('bootstrap');
wp_enqueue_style('bootstrap', get_template_directory_uri().
'/css/bootstrap.min.css', false, null, 'all');
wp_deregister_style('bootstrapdatepicker');
wp_enqueue_style('bootstrapdatepicker', get_template_directory_uri().
'/Css/bootstrap-datepicker3.css', false, null, 'all');
wp_deregister_style('fontawesome');
wp_enqueue_style('fontawesome', get_template_directory_uri().
'/css/font-awesome.css', false, null, 'all');
wp_deregister_style('animate');
wp_enqueue_style('animate', get_template_directory_uri().
'/css/animate.css', false, null, 'all');
wp_deregister_style('effect');
wp_enqueue_style('effect', get_template_directory_uri().
'/css/effect1.css', false, null, 'all');
wp_deregister_style('style');
wp_enqueue_style('style', get_template_directory_uri().
'/css/style.css', false, null, 'all');
wp_deregister_style('responsive');
wp_enqueue_style('responsive', get_template_directory_uri().
'/css/responsive.css', false, null, 'all');
wp_deregister_style('rotate');
wp_enqueue_style('rotate', get_template_directory_uri().
'/css/rotate.css', false, null, 'all');
wp_deregister_style('normalize');
wp_enqueue_style('normalize', get_template_directory_uri().
'/css/normalize.css', false, null, 'all');
wp_deregister_style('set');
wp_enqueue_style('set', get_template_directory_uri().
'/css/set1.css', false, null, 'all');
wp_deregister_style('pricing');
wp_enqueue_style('pricing', get_template_directory_uri().
'/css/pricing.css', false, null, 'all');
wp_deregister_style('bootstrapslider');
wp_enqueue_style('bootstrapslider', 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.2/css/bootstrap-slider.css', false, null, 'all');
wp_deregister_style('bootstrapslider');
wp_enqueue_style('bootstrapslider', 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.2/css/bootstrap-slider.min.css', false, null, 'all');
wp_deregister_style('intltelinput');
wp_enqueue_style('intltelinput', get_template_directory_uri().
'/countryCode/css/intlTelInput.css', false, null, 'all');
/* Enqueue Styles End */
}
add_action('wp_enqueue_scripts', 'techcare_enqueue_scripts');
endif;
</code></pre>
<p>Link Resource to WordPress (portion of code):</p>
<pre><code>wp_deregister_script( 'bootstrapslider' );
wp_enqueue_script( 'bootstrapslider', 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.2/bootstrap-slider.js', false, null, false);
wp_deregister_script( 'bootstrapslider' );
wp_enqueue_script( 'bootstrapslider', 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.2/bootstrap-slider.min.js', false, null, false);
wp_deregister_style( 'bootstrapslider' );
wp_enqueue_style( 'bootstrapslider', 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.2/css/bootstrap-slider.css', false, null, 'all');
wp_deregister_style( 'bootstrapslider' );
wp_enqueue_style( 'bootstrapslider', 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.2/css/bootstrap-slider.min.css', false, null, 'all');
</code></pre>
<p>Here's the HTML part :</p>
<pre><code><input id="web" data-slider-id='web' type="text" data-slider-min="0" data-slider-max="100" data-slider-step="1" data-slider-value="0" />
</code></pre>
<p>JQuery Part :</p>
<pre><code> // With JQuery
$("#web").slider();
$("#web").on("slide", function(slideEvt) {
$("#webVal").text(slideEvt.value);
$("#web1Val").text('$'+slideEvt.value);
$("#web2Val").text('$'+slideEvt.value*10);
$("#looking").text('a Web');
});
</code></pre>
<p>Here's the demo page <a href="http://techcarebd.com/techcare.beta/pricing/design-only/" rel="nofollow noreferrer">link</a>.</p>
| [
{
"answer_id": 265308,
"author": "Mervan Agency",
"author_id": 118206,
"author_profile": "https://wordpress.stackexchange.com/users/118206",
"pm_score": 1,
"selected": false,
"text": "<p>I am not sure how you removed <code>?p=</code> from the link but you can use <code>get_shortlink</code> filter to override the shortlink. You can refer following article for more details.</p>\n\n<p><a href=\"http://www.wpbeginner.com/wp-themes/how-to-display-wordpress-shortlinks-in-your-theme/\" rel=\"nofollow noreferrer\">http://www.wpbeginner.com/wp-themes/how-to-display-wordpress-shortlinks-in-your-theme/</a></p>\n\n<p>Reference to <code>get_shortlink</code> filter: <a href=\"https://developer.wordpress.org/reference/hooks/get_shortlink/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/get_shortlink/</a></p>\n\n<p>Can you share some more details on how you removed the ?p= from the link?</p>\n"
},
{
"answer_id": 265314,
"author": "Punitkumar Patel",
"author_id": 117461,
"author_profile": "https://wordpress.stackexchange.com/users/117461",
"pm_score": 1,
"selected": false,
"text": "<p>@yogu You can add <a href=\"https://i.stack.imgur.com/BPsYp.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BPsYp.png\" alt=\"%post_id%\"></a> in permalink to get required structure. <code>site-url.com/22 (without ?p=)</code></p>\n\n<p>For specific post you can add following function and add specific condition for it : </p>\n\n<pre><code>add_filter( 'post_link', 'custom_permalink', 10, 3 );\nfunction custom_permalink( $permalink, $post, $leavename ) {\n // For shortlink condition\n if ( 'Shortlink Condition here' ) {\n $permalink = trailingslashit( home_url('/'. $post->ID .'/' ) );\n }\n return $permalink;\n}\nadd_action('generate_rewrite_rules', 'custom_rewrite_rules');\nfunction custom_rewrite_rules( $wp_rewrite ) {\n // This rule will will match the post id in %post_id% struture\n $new_rules['^([^/]*)-([0-9]+)/?'] = 'index.php?p=$matches[2]';\n $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;\n return $wp_rewrite;\n}\n</code></pre>\n"
},
{
"answer_id": 385000,
"author": "harry",
"author_id": 203280,
"author_profile": "https://wordpress.stackexchange.com/users/203280",
"pm_score": 0,
"selected": false,
"text": "<p>Wordpress redirects without the parameter: ?p. Regardless of whether it's pages or posts ...</p>\n<p>For example:\nsite.com/922 (post or page ID...), this should redirect.</p>\n<p>If you want to change link one at the head of your site:</p>\n<pre><code>add_filter('pre_get_shortlink', function () {\n return home_url('/') . get_the_ID();\n}, 10, 3);\n</code></pre>\n<p>In wordpress docs: <a href=\"https://developer.wordpress.org/reference/hooks/pre_get_shortlink/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/pre_get_shortlink/</a></p>\n"
}
]
| 2017/04/29 | [
"https://wordpress.stackexchange.com/questions/265324",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118691/"
]
| `bootstrap-slider.js` offered by seiyria not working in WordPress. It seems that resource file isn't linked properly. What am I missing here? Any idea?
Link Resource to WordPress(`functions.php`):
```
if (!function_exists('techcare_enqueue_scripts')):
function techcare_enqueue_scripts() {
/* Enqueue Scripts Begin */
wp_deregister_script('jquery');
wp_enqueue_script('jquery', get_template_directory_uri().
'/scripts/jquery-2.1.4.js', false, null, false);
wp_deregister_script('modernizr');
wp_enqueue_script('modernizr', get_template_directory_uri().
'/scripts/modernizr.min.js', false, null, false);
wp_deregister_script('classie');
wp_enqueue_script('classie', get_template_directory_uri().
'/scripts/classie.js', false, null, false);
wp_deregister_script('api');
wp_enqueue_script('api', 'https://www.google.com/recaptcha/api.js', false, null, false);
wp_deregister_script('script-1');
wp_enqueue_script('script-1', 'https://maps.googleapis.com/maps/api/js?key=AIzaSyBJPGck9G3Pf4f912F_NyyEPFU9mOroxKo&callback=initMap', false, null, false);
wp_deregister_script('script-2');
wp_enqueue_script('script-2', 'https://maps.googleapis.com/maps/api/js?sensor=false', false, null, false);
wp_deregister_script('jquery');
wp_enqueue_script('jquery', get_template_directory_uri().
'/scripts/jquery-2.1.4.js', false, null, true);
wp_deregister_script('jquerymagnificpopup');
wp_enqueue_script('jquerymagnificpopup', get_template_directory_uri().
'/scripts/jquery.magnific-popup.min.js', false, null, true);
wp_deregister_script('smoothscroll');
wp_enqueue_script('smoothscroll', get_template_directory_uri().
'/scripts/SmoothScroll.js', false, null, true);
wp_deregister_script('apscrolltop');
wp_enqueue_script('apscrolltop', get_template_directory_uri().
'/scripts/ap-scroll-top.js', false, null, true);
wp_deregister_script('bootstrapdatepicker');
wp_enqueue_script('bootstrapdatepicker', get_template_directory_uri().
'/scripts/bootstrap-datepicker.min.js', false, null, true);
wp_deregister_script('bootstrap');
wp_enqueue_script('bootstrap', get_template_directory_uri().
'/scripts/bootstrap.min.js', false, null, true);
wp_deregister_script('wow');
wp_enqueue_script('wow', get_template_directory_uri().
'/scripts/wow.min.js', false, null, true);
wp_deregister_script('main');
wp_enqueue_script('main', get_template_directory_uri().
'/scripts/main.js', false, null, true);
wp_deregister_script('jquerycounterup');
wp_enqueue_script('jquerycounterup', get_template_directory_uri().
'/scripts/jquery.counterup.min.js', false, null, true);
wp_deregister_script('waypoints');
wp_enqueue_script('waypoints', get_template_directory_uri().
'/../cdnjs.cloudflare.com/ajax/libs/waypoints/2.0.3/waypoints.min.js', false, null, true);
wp_deregister_script('slick');
wp_enqueue_script('slick', get_template_directory_uri().
'/scripts/slick.min.js', false, null, true);
wp_deregister_script('jqueryvalidate');
wp_enqueue_script('jqueryvalidate', get_template_directory_uri().
'/scripts/vendor/jquery-validation/jquery.validate.min.js', false, null, true);
wp_deregister_script('jqueryvalidateunobtrusive');
wp_enqueue_script('jqueryvalidateunobtrusive', get_template_directory_uri().
'/scripts/vendor/jquery-validation/jquery.validate.unobtrusive.min.js', false, null, true);
wp_deregister_script('ajaxhandler');
wp_enqueue_script('ajaxhandler', get_template_directory_uri().
'/scripts/ajaxhandler.js', false, null, true);
wp_deregister_script('script-3');
wp_enqueue_script('script-3', 'https://maps.googleapis.com/maps/api/js?key=AIzaSyBJPGck9G3Pf4f912F_NyyEPFU9mOroxKo&callback=initMap', false, null, false);
wp_deregister_script('script-4');
wp_enqueue_script('script-4', 'https://maps.googleapis.com/maps/api/js?sensor=false', false, null, false);
wp_deregister_script('bootstrapslider');
wp_enqueue_script('bootstrapslider', 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.2/bootstrap-slider.js', false, null, false);
wp_deregister_script('bootstrapslider');
wp_enqueue_script('bootstrapslider', 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.2/bootstrap-slider.min.js', false, null, false);
/* Enqueue Scripts End */
/* Enqueue Styles Begin */
wp_deregister_style('bootstrap');
wp_enqueue_style('bootstrap', get_template_directory_uri().
'/css/bootstrap.min.css', false, null, 'all');
wp_deregister_style('bootstrapdatepicker');
wp_enqueue_style('bootstrapdatepicker', get_template_directory_uri().
'/Css/bootstrap-datepicker3.css', false, null, 'all');
wp_deregister_style('fontawesome');
wp_enqueue_style('fontawesome', get_template_directory_uri().
'/css/font-awesome.css', false, null, 'all');
wp_deregister_style('animate');
wp_enqueue_style('animate', get_template_directory_uri().
'/css/animate.css', false, null, 'all');
wp_deregister_style('effect');
wp_enqueue_style('effect', get_template_directory_uri().
'/css/effect1.css', false, null, 'all');
wp_deregister_style('style');
wp_enqueue_style('style', get_template_directory_uri().
'/css/style.css', false, null, 'all');
wp_deregister_style('responsive');
wp_enqueue_style('responsive', get_template_directory_uri().
'/css/responsive.css', false, null, 'all');
wp_deregister_style('rotate');
wp_enqueue_style('rotate', get_template_directory_uri().
'/css/rotate.css', false, null, 'all');
wp_deregister_style('normalize');
wp_enqueue_style('normalize', get_template_directory_uri().
'/css/normalize.css', false, null, 'all');
wp_deregister_style('set');
wp_enqueue_style('set', get_template_directory_uri().
'/css/set1.css', false, null, 'all');
wp_deregister_style('pricing');
wp_enqueue_style('pricing', get_template_directory_uri().
'/css/pricing.css', false, null, 'all');
wp_deregister_style('bootstrapslider');
wp_enqueue_style('bootstrapslider', 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.2/css/bootstrap-slider.css', false, null, 'all');
wp_deregister_style('bootstrapslider');
wp_enqueue_style('bootstrapslider', 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.2/css/bootstrap-slider.min.css', false, null, 'all');
wp_deregister_style('intltelinput');
wp_enqueue_style('intltelinput', get_template_directory_uri().
'/countryCode/css/intlTelInput.css', false, null, 'all');
/* Enqueue Styles End */
}
add_action('wp_enqueue_scripts', 'techcare_enqueue_scripts');
endif;
```
Link Resource to WordPress (portion of code):
```
wp_deregister_script( 'bootstrapslider' );
wp_enqueue_script( 'bootstrapslider', 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.2/bootstrap-slider.js', false, null, false);
wp_deregister_script( 'bootstrapslider' );
wp_enqueue_script( 'bootstrapslider', 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.2/bootstrap-slider.min.js', false, null, false);
wp_deregister_style( 'bootstrapslider' );
wp_enqueue_style( 'bootstrapslider', 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.2/css/bootstrap-slider.css', false, null, 'all');
wp_deregister_style( 'bootstrapslider' );
wp_enqueue_style( 'bootstrapslider', 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.2/css/bootstrap-slider.min.css', false, null, 'all');
```
Here's the HTML part :
```
<input id="web" data-slider-id='web' type="text" data-slider-min="0" data-slider-max="100" data-slider-step="1" data-slider-value="0" />
```
JQuery Part :
```
// With JQuery
$("#web").slider();
$("#web").on("slide", function(slideEvt) {
$("#webVal").text(slideEvt.value);
$("#web1Val").text('$'+slideEvt.value);
$("#web2Val").text('$'+slideEvt.value*10);
$("#looking").text('a Web');
});
```
Here's the demo page [link](http://techcarebd.com/techcare.beta/pricing/design-only/). | I am not sure how you removed `?p=` from the link but you can use `get_shortlink` filter to override the shortlink. You can refer following article for more details.
<http://www.wpbeginner.com/wp-themes/how-to-display-wordpress-shortlinks-in-your-theme/>
Reference to `get_shortlink` filter: <https://developer.wordpress.org/reference/hooks/get_shortlink/>
Can you share some more details on how you removed the ?p= from the link? |
265,328 | <p>I have created a child theme. </p>
<p>In the parent theme there is a file <code>functions_custom.php</code>, which has some functions definitions. The file included in <code>functions.php</code> in the parent theme.</p>
<p>Now I want to make some changes in one function that's in the <code>functions_custom.php</code> file and the function used in <code>single.php</code> to <code>echo</code> some dynamic content.</p>
<p>So how to override that function in child theme?</p>
| [
{
"answer_id": 265336,
"author": "Mervan Agency",
"author_id": 118206,
"author_profile": "https://wordpress.stackexchange.com/users/118206",
"pm_score": 3,
"selected": false,
"text": "<p>I am not sure if the function in the <code>functions_custom.php</code> that you wants to override is a pluggable functions like below:</p>\n\n<pre><code>if ( ! function_exists ( 'function_name' ) ) {\n function function_name() {\n // Function Code\n }\n}\n</code></pre>\n\n<p>If it is pluggable function then you can simply write function with same name in your child theme and WordPress will run the Child Theme function first.</p>\n"
},
{
"answer_id": 265357,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": -1,
"selected": false,
"text": "<p>If it's not pluggable. you may want check this question/answer:</p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/7557/how-to-override-parent-functions-in-child-themes\">How to override parent functions in child themes?</a></p>\n"
},
{
"answer_id": 265437,
"author": "Tarun modi",
"author_id": 115973,
"author_profile": "https://wordpress.stackexchange.com/users/115973",
"pm_score": 0,
"selected": false,
"text": "<p>You can simple copy the functions_custom.php in your child theme and do whatever in the this file.</p>\n"
}
]
| 2017/04/29 | [
"https://wordpress.stackexchange.com/questions/265328",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74147/"
]
| I have created a child theme.
In the parent theme there is a file `functions_custom.php`, which has some functions definitions. The file included in `functions.php` in the parent theme.
Now I want to make some changes in one function that's in the `functions_custom.php` file and the function used in `single.php` to `echo` some dynamic content.
So how to override that function in child theme? | I am not sure if the function in the `functions_custom.php` that you wants to override is a pluggable functions like below:
```
if ( ! function_exists ( 'function_name' ) ) {
function function_name() {
// Function Code
}
}
```
If it is pluggable function then you can simply write function with same name in your child theme and WordPress will run the Child Theme function first. |
265,335 | <p>I have a custom post loop going into a template I made - the row has to be outside of the loop, or the posts don't line up vertically. However, I need some spacing between the posts - image below to illustrate:
<a href="https://i.stack.imgur.com/KtZ3m.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KtZ3m.jpg" alt="Showing my row of posts with no padding"></a></p>
<p>I have tried setting the row padding/margin in css but obvs it only applies to the row containing the loop and not anything flowing into the loop. I am not sure how I go about styling this. I am assuming I add another class around the col which I have also tried.</p>
| [
{
"answer_id": 265353,
"author": "Disk01",
"author_id": 82479,
"author_profile": "https://wordpress.stackexchange.com/users/82479",
"pm_score": 1,
"selected": false,
"text": "<p>There are several possible ways that you could do, these are:</p>\n\n<ol>\n<li>Adding <code><br /></code> html tag </li>\n<li>Making it inside <code><div style=\"...\">....</div></code></li>\n</ol>\n\n<p><strong>Example:</strong></p>\n\n<pre><code><div style=\"padding:10px;\">...</div>\n</code></pre>\n\n<p>You can also use <code><table></code> if you want</p>\n"
},
{
"answer_id": 265996,
"author": "Tarun modi",
"author_id": 115973,
"author_profile": "https://wordpress.stackexchange.com/users/115973",
"pm_score": 0,
"selected": false,
"text": "<p>Hi Tracy you can also use Bootstrap classes for better designing:</p>\n\n<pre><code><div class=\"container\">\n <div class=\"row\">\n <div class=\"col-sm-4\">\n <h3>Column 1</h3>\n <p>Lorem ipsum dolor..</p>\n <p>Ut enim ad..</p>\n </div>\n <div class=\"col-sm-4\">\n <h3>Column 2</h3>\n <p>Lorem ipsum dolor..</p>\n <p>Ut enim ad..</p>\n </div>\n <div class=\"col-sm-4\">\n <h3>Column 3</h3>\n <p>Lorem ipsum dolor..</p>\n <p>Ut enim ad..</p>\n </div>\n </div>\n </div>\n</code></pre>\n"
}
]
| 2017/04/29 | [
"https://wordpress.stackexchange.com/questions/265335",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114208/"
]
| I have a custom post loop going into a template I made - the row has to be outside of the loop, or the posts don't line up vertically. However, I need some spacing between the posts - image below to illustrate:
[](https://i.stack.imgur.com/KtZ3m.jpg)
I have tried setting the row padding/margin in css but obvs it only applies to the row containing the loop and not anything flowing into the loop. I am not sure how I go about styling this. I am assuming I add another class around the col which I have also tried. | There are several possible ways that you could do, these are:
1. Adding `<br />` html tag
2. Making it inside `<div style="...">....</div>`
**Example:**
```
<div style="padding:10px;">...</div>
```
You can also use `<table>` if you want |
265,337 | <p>i need to call a javascript only if screen resolution is greater than 500.</p>
<p>I found below code...</p>
<pre><code><script type='text/javascript' src='<?php echo $urlPlugin?>js/jquery.themepunch.revolution.min.js?rev=<?php echo RevSliderGlobals::SLIDER_REVISION; ?>'></script>
</code></pre>
<p>So, i modified it as below...</p>
<pre><code><script>
if (window.innerWidth > 500) {
var head = document.getElementsByTagName('head')[0];
var s1 = document.createElement("script");
s1.type = "text/javascript";
s1.src = "http://domain.com/wp-content/plugins/revslider/public/assets/js/jquery.themepunch.revolution.min.js";
head.appendChild(s1);
}
</script>
</code></pre>
<p>However that did not work.</p>
<p>Later i came to know about enqueue function. i have lines as following...</p>
<pre><code>wp_enqueue_script('revmin', RS_PLUGIN_URL .'public/assets/js/jquery.themepunch.revolution.min.js', 'tp-tools', $slver, $ft);
</code></pre>
<p>this function auto-calls scripts. so, how do i make it conditional??</p>
<p>instead of enqueueing script i used register_script so that the script can be called later.</p>
<p>Which is working. Then placed javascript code in header.php</p>
<p>However unable to call script if screen is greater than 500.</p>
<p>Also tried this...</p>
<pre><code> <script>
if( $(window).width() > 500 )
{
$.ajax({
url: 'http://domain.com/wp-content/plugins/revslider/public/assets/js/jquery.themepunch.revolution.min.js',
dataType: "script",
success: function() {
//success
}
});
}
</script>
</code></pre>
| [
{
"answer_id": 265339,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>You don't make it conditional on the server side, you just do not initialize/run it on client side when you detect that the width of the window is smaller than 500 pixels.</p>\n\n<p>Trying to detect screen dimension on server side is a big no-no and can fail in all kind of ways (caching, window size change, and probably more).</p>\n"
},
{
"answer_id": 265383,
"author": "David Klhufek",
"author_id": 113922,
"author_profile": "https://wordpress.stackexchange.com/users/113922",
"pm_score": 1,
"selected": false,
"text": "<p>you can use Window matchMedia() Method <a href=\"https://www.w3schools.com/jsref/met_win_matchmedia.asp\" rel=\"nofollow noreferrer\">https://www.w3schools.com/jsref/met_win_matchmedia.asp</a> like this: </p>\n\n<pre><code> <script type=\"text/javascript\">\n if (matchMedia('only screen and (min-width: 500px)').matches) {\n\n }\n </script>\n</code></pre>\n"
},
{
"answer_id": 265549,
"author": "mukto90",
"author_id": 57944,
"author_profile": "https://wordpress.stackexchange.com/users/57944",
"pm_score": 0,
"selected": false,
"text": "<p>You cannot make it conditional on the server. Follow the steps below.</p>\n\n<ol>\n<li>Enqueue the script in the regular way. I suppose, your code is correct for this-\n<code>wp_enqueue_script('revmin', RS_PLUGIN_URL .'public/assets/js/jquery.themepunch.revolution.min.js', 'tp-tools', $slver, $ft);</code></li>\n</ol>\n\n<p>See this for better understanding: <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_enqueue_script/</a></p>\n\n<ol start=\"2\">\n<li>In your JS, use the condition\n<code>\nif( $(window).width() > 500 ) {\n $.ajax({\n data: { 'action' : 'your-action', 'other_key' : other_value },\n url: ajaxurl, // previously defined.\n type: 'POST',\n success: function(data){\n // so something\n }\n })\n}\n</code></li>\n</ol>\n"
}
]
| 2017/04/29 | [
"https://wordpress.stackexchange.com/questions/265337",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86147/"
]
| i need to call a javascript only if screen resolution is greater than 500.
I found below code...
```
<script type='text/javascript' src='<?php echo $urlPlugin?>js/jquery.themepunch.revolution.min.js?rev=<?php echo RevSliderGlobals::SLIDER_REVISION; ?>'></script>
```
So, i modified it as below...
```
<script>
if (window.innerWidth > 500) {
var head = document.getElementsByTagName('head')[0];
var s1 = document.createElement("script");
s1.type = "text/javascript";
s1.src = "http://domain.com/wp-content/plugins/revslider/public/assets/js/jquery.themepunch.revolution.min.js";
head.appendChild(s1);
}
</script>
```
However that did not work.
Later i came to know about enqueue function. i have lines as following...
```
wp_enqueue_script('revmin', RS_PLUGIN_URL .'public/assets/js/jquery.themepunch.revolution.min.js', 'tp-tools', $slver, $ft);
```
this function auto-calls scripts. so, how do i make it conditional??
instead of enqueueing script i used register\_script so that the script can be called later.
Which is working. Then placed javascript code in header.php
However unable to call script if screen is greater than 500.
Also tried this...
```
<script>
if( $(window).width() > 500 )
{
$.ajax({
url: 'http://domain.com/wp-content/plugins/revslider/public/assets/js/jquery.themepunch.revolution.min.js',
dataType: "script",
success: function() {
//success
}
});
}
</script>
``` | you can use Window matchMedia() Method <https://www.w3schools.com/jsref/met_win_matchmedia.asp> like this:
```
<script type="text/javascript">
if (matchMedia('only screen and (min-width: 500px)').matches) {
}
</script>
``` |
265,363 | <p>So, we are building an internal WordPress theme for our company that will be used for a few dozen of our websites. The only thing that will differ between the sites is the color scheme.</p>
<p>We're trying to figure out what the best way to handle the colors to still allow updates to all sites without having to individually upload files for each.</p>
<p><strong>Child Theme</strong></p>
<p>We discussed trying to use a child theme for each internal site, but when scaling or adding a new feature, we would have to individually add the color scheme styles to each child theme. So, this is not ideal.</p>
<p><strong>Theme Customizer</strong></p>
<p>WordPress has the built-in theme customizer API which looks promising, but I was wondering if someone could provide some insight as to how that actually works. If we have elements like links, buttons, titles, etc. with their site's unique color scheme, does it have to render that CSS within <code><style></code> blocks for each element, then?</p>
<p>Meaning are you just creating styles in theme files in this manner:</p>
<pre><code><style>
.button {
color: <?php echo setting value here! ?>
}
</style>
</code></pre>
<p>If that is the case, do you handle most of the styles (the ones that don't require the custom variable) in an external stylesheet?</p>
<p><strong>Color Options</strong></p>
<p>A lot of WordPress themes just have a color settings page, which we could use as well, but I think that would be the same in terms of rendering the CSS within <code><style></code> blocks.</p>
<p><strong>Specific File</strong></p>
<p>Is it a ridiculous option to create a PHP file with all of your styles in it, that essentially use variables from WordPress? Something along the lines of:</p>
<pre><code><?php $primary = get color from WordPress ?>
<style>
.button {
display: block;
border-radius: 5px;
color: $primary;
}
</style>
</code></pre>
<p>Any ideas on the best way to handle this with the above options or something I missed?</p>
| [
{
"answer_id": 265339,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>You don't make it conditional on the server side, you just do not initialize/run it on client side when you detect that the width of the window is smaller than 500 pixels.</p>\n\n<p>Trying to detect screen dimension on server side is a big no-no and can fail in all kind of ways (caching, window size change, and probably more).</p>\n"
},
{
"answer_id": 265383,
"author": "David Klhufek",
"author_id": 113922,
"author_profile": "https://wordpress.stackexchange.com/users/113922",
"pm_score": 1,
"selected": false,
"text": "<p>you can use Window matchMedia() Method <a href=\"https://www.w3schools.com/jsref/met_win_matchmedia.asp\" rel=\"nofollow noreferrer\">https://www.w3schools.com/jsref/met_win_matchmedia.asp</a> like this: </p>\n\n<pre><code> <script type=\"text/javascript\">\n if (matchMedia('only screen and (min-width: 500px)').matches) {\n\n }\n </script>\n</code></pre>\n"
},
{
"answer_id": 265549,
"author": "mukto90",
"author_id": 57944,
"author_profile": "https://wordpress.stackexchange.com/users/57944",
"pm_score": 0,
"selected": false,
"text": "<p>You cannot make it conditional on the server. Follow the steps below.</p>\n\n<ol>\n<li>Enqueue the script in the regular way. I suppose, your code is correct for this-\n<code>wp_enqueue_script('revmin', RS_PLUGIN_URL .'public/assets/js/jquery.themepunch.revolution.min.js', 'tp-tools', $slver, $ft);</code></li>\n</ol>\n\n<p>See this for better understanding: <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_enqueue_script/</a></p>\n\n<ol start=\"2\">\n<li>In your JS, use the condition\n<code>\nif( $(window).width() > 500 ) {\n $.ajax({\n data: { 'action' : 'your-action', 'other_key' : other_value },\n url: ajaxurl, // previously defined.\n type: 'POST',\n success: function(data){\n // so something\n }\n })\n}\n</code></li>\n</ol>\n"
}
]
| 2017/04/30 | [
"https://wordpress.stackexchange.com/questions/265363",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73975/"
]
| So, we are building an internal WordPress theme for our company that will be used for a few dozen of our websites. The only thing that will differ between the sites is the color scheme.
We're trying to figure out what the best way to handle the colors to still allow updates to all sites without having to individually upload files for each.
**Child Theme**
We discussed trying to use a child theme for each internal site, but when scaling or adding a new feature, we would have to individually add the color scheme styles to each child theme. So, this is not ideal.
**Theme Customizer**
WordPress has the built-in theme customizer API which looks promising, but I was wondering if someone could provide some insight as to how that actually works. If we have elements like links, buttons, titles, etc. with their site's unique color scheme, does it have to render that CSS within `<style>` blocks for each element, then?
Meaning are you just creating styles in theme files in this manner:
```
<style>
.button {
color: <?php echo setting value here! ?>
}
</style>
```
If that is the case, do you handle most of the styles (the ones that don't require the custom variable) in an external stylesheet?
**Color Options**
A lot of WordPress themes just have a color settings page, which we could use as well, but I think that would be the same in terms of rendering the CSS within `<style>` blocks.
**Specific File**
Is it a ridiculous option to create a PHP file with all of your styles in it, that essentially use variables from WordPress? Something along the lines of:
```
<?php $primary = get color from WordPress ?>
<style>
.button {
display: block;
border-radius: 5px;
color: $primary;
}
</style>
```
Any ideas on the best way to handle this with the above options or something I missed? | you can use Window matchMedia() Method <https://www.w3schools.com/jsref/met_win_matchmedia.asp> like this:
```
<script type="text/javascript">
if (matchMedia('only screen and (min-width: 500px)').matches) {
}
</script>
``` |
265,365 | <p>I'm trying to add the attribute data-featherlight with a value of 'mylightbox' to all my post featured images. I believe this is the code I need, but I do not know where I put it. I'm working with the baseline twentyseventeen theme.</p>
<pre><code>if ( has_post_thumbnail() ) {
the_post_thumbnail();
the_post_thumbnail('post_thumbnail', array('data-featherlight'=>'mylightbox'));
}
</code></pre>
<p>Thanks!</p>
| [
{
"answer_id": 267164,
"author": "Ajay Malhotra",
"author_id": 118989,
"author_profile": "https://wordpress.stackexchange.com/users/118989",
"pm_score": 1,
"selected": false,
"text": "<p>You can try like this:</p>\n\n<pre><code>if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it.\n the_post_thumbnail( 'full', array( 'class' => 'responsive-class' ) ); // show featured image\n } \n</code></pre>\n"
},
{
"answer_id": 267175,
"author": "hwl",
"author_id": 118366,
"author_profile": "https://wordpress.stackexchange.com/users/118366",
"pm_score": 0,
"selected": false,
"text": "<h2><code>post_thumbnail_html</code></h2>\n\n<p>To alter the html output, you need to hook the filter <a href=\"https://developer.wordpress.org/reference/hooks/post_thumbnail_html/\" rel=\"nofollow noreferrer\"><code>post_thumbnail_html</code></a></p>\n\n<blockquote>\n <p><strong>From Codex:</strong> </p>\n \n <p><code>apply_filters( 'post_thumbnail_html', string $html, int $post_id,\n string $post_thumbnail_id, string|array $size, string $attr )</code></p>\n \n <p>Filters the post thumbnail HTML.</p>\n</blockquote>\n\n<p>This filter is called by <code>get_the_post_thumbnail</code>on line 177 of <em>post_thumbnail_template.php</em> after <code>$html</code> has been set with:</p>\n\n<p><code>$html = wp_get_attachment_image( $post_thumbnail_id, $size, false, $attr );</code> </p>\n\n<p>Filter in context:</p>\n\n<pre><code>/**\n* Filters the post thumbnail HTML.\n * @param string $html The post thumbnail HTML.\n * @param int $post_id The post ID.\n * @param string $post_thumbnail_id The post thumbnail ID.\n * @param string|array $size The post thumbnail size. Image size or array of width and height values (in that order). Default 'post-thumbnail'.\n * @param string $attr Query string of attributes.\n*/\nreturn\n\n apply_filters( 'post_thumbnail_html', $html, $post->ID, $post_thumbnail_id, $size, $attr );\n</code></pre>\n\n<h2>Adding <code>data-featherlight=\"mylightbox\"</code> example:</h2>\n\n<p>So adding your <code>data-featherlight=\"mylightbox\"</code> would perhaps be something like: </p>\n\n<pre><code>add_filter('post_thumbnail_html', 'my_thumbnail_filter_method', 10, 5 );\nfunction my_thumbnail_filter_method($html, $post->ID, $post_thumbnail_id, $size, $attr) {\n $id = get_post_thumbnail_id();\n $src = wp_get_attachment_image_src($id, $size); \n $alt = get_the_title($id); /\n $class = $attr['class'];\n\n $html = '<img src=\"' . $src[0] . '\" alt=\"' . $alt . '\" class=\"' . $class . '\" data-featherlight=\"mylightbox\" />';\n}\n</code></pre>\n\n<hr>\n\n<p>Two other action hooks are present on either side of <code>$html</code> being set within <code>get_the_pos_thumbnail</code>. </p>\n\n<ol>\n<li><code>begin_fetch_post_thumbnail_html</code></li>\n<li><code>end_fetch_post_thumbnail_html</code></li>\n</ol>\n\n<p>but both are only passing <code>$post->ID, $post_thumbnail_id, $size</code>. \nSo, it looks like filtering <code>post_thumbnail_html</code> is the best way to access the <code><img></code> html string.</p>\n\n<hr>\n\n<p>A note on <a href=\"https://developer.wordpress.org/reference/functions/has_post_thumbnail/\" rel=\"nofollow noreferrer\"><code>has_post_thumbnail()</code></a>, since it seems to come up often:\nthis method will return true if any images are attached to post, not specifically for the post thumbnail (aka <em>featured image</em>). </p>\n"
}
]
| 2017/04/30 | [
"https://wordpress.stackexchange.com/questions/265365",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118713/"
]
| I'm trying to add the attribute data-featherlight with a value of 'mylightbox' to all my post featured images. I believe this is the code I need, but I do not know where I put it. I'm working with the baseline twentyseventeen theme.
```
if ( has_post_thumbnail() ) {
the_post_thumbnail();
the_post_thumbnail('post_thumbnail', array('data-featherlight'=>'mylightbox'));
}
```
Thanks! | You can try like this:
```
if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it.
the_post_thumbnail( 'full', array( 'class' => 'responsive-class' ) ); // show featured image
}
``` |
265,417 | <p>I have a hook, that detects opening the post(publication):</p>
<pre><code>add_action('the_post', 'post_callback');
function post_callback($post) {
$post->post_title = "New title";
$post->post_content = "New content";
}
</code></pre>
<p>It replaces <code>post_title, $post->post_content</code> data on the custom values.</p>
<p>How to change HTML meta data on the page(title, description) inside function: <code>post_callback</code>?</p>
| [
{
"answer_id": 265441,
"author": "Toufic Batache",
"author_id": 118735,
"author_profile": "https://wordpress.stackexchange.com/users/118735",
"pm_score": 3,
"selected": true,
"text": "<p>I have recently solved my issue, I went on wordpress support, found my issue and <a href=\"https://support.cloudflare.com/hc/en-us/articles/203487280-How-do-I-fix-mixed-content-issues-or-the-infinite-redirect-loop-error-after-enabling-Flexible-SSL-with-WordPress-\" rel=\"noreferrer\">how to fix it</a>. I installed the <a href=\"https://en-gb.wordpress.org/plugins/ssl-insecure-content-fixer/\" rel=\"noreferrer\">SSL Insecure Content Fixer plugin</a> and chose in the plugin settings for SSL Detection, the setting that was recommended. Then, I went to the settings and set my Wordpress and site URL to https://. This all together fixes the infinite redirect loop.</p>\n"
},
{
"answer_id": 265443,
"author": "user3768679",
"author_id": 82975,
"author_profile": "https://wordpress.stackexchange.com/users/82975",
"pm_score": 1,
"selected": false,
"text": "<p>What you can do is try to go to settings --> General and and change your Wordpress address site to a non-www URL if it has a www in it. Also, do not include a slash at the end. </p>\n\n<p>One more thing, if you have any plugins activated, disable all of them and enable them one by one and see if any of them are causing an error.</p>\n"
}
]
| 2017/04/30 | [
"https://wordpress.stackexchange.com/questions/265417",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118742/"
]
| I have a hook, that detects opening the post(publication):
```
add_action('the_post', 'post_callback');
function post_callback($post) {
$post->post_title = "New title";
$post->post_content = "New content";
}
```
It replaces `post_title, $post->post_content` data on the custom values.
How to change HTML meta data on the page(title, description) inside function: `post_callback`? | I have recently solved my issue, I went on wordpress support, found my issue and [how to fix it](https://support.cloudflare.com/hc/en-us/articles/203487280-How-do-I-fix-mixed-content-issues-or-the-infinite-redirect-loop-error-after-enabling-Flexible-SSL-with-WordPress-). I installed the [SSL Insecure Content Fixer plugin](https://en-gb.wordpress.org/plugins/ssl-insecure-content-fixer/) and chose in the plugin settings for SSL Detection, the setting that was recommended. Then, I went to the settings and set my Wordpress and site URL to https://. This all together fixes the infinite redirect loop. |
265,449 | <p>I am using the following code (<a href="https://developer.wordpress.org/reference/hooks/set_user_role/" rel="nofollow noreferrer">https://developer.wordpress.org/reference/hooks/set_user_role/</a>) to sync user role between his blogs on a multisite installation.</p>
<p>My question is if this approach can lead to an infinite loop?</p>
<pre><code>// Sync user role
add_action( 'set_user_role', 'sync_user_role', 10, 2 );
function sync_user_role( $user_id, $role ) {
$blogs = get_blogs_of_user( $user_id );
$blogs_count = count( $blogs );
if ( $blogs_count > 1 ) {
foreach ( $blogs as $blog ) {
$user_blog = new WP_User( $user_id, '', $blog->userblog_id );
$user_blog->set_role( $role );
}
}
}
</code></pre>
| [
{
"answer_id": 265460,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>Yes it will give you infinite loop, because you're calling the <code>WP_User::set_role</code> method within the <code>set_user_role</code> action that's again fired within the the <code>WP_User::set_role</code> method.</p>\n\n<p>Not sure what the setup is but you can try to run it only once, with</p>\n\n<pre><code>remove_action( current_action(), __FUNCTION__ );\n</code></pre>\n\n<p>as the first line in your callback, or use another hook.</p>\n\n<p><em>Update: I just noticed that I miswrote <code>filter</code> instead of <code>action</code>, but that would have worked the same though ;-) It's now adjusted.</em></p>\n"
},
{
"answer_id": 265473,
"author": "Pascal Knecht",
"author_id": 105101,
"author_profile": "https://wordpress.stackexchange.com/users/105101",
"pm_score": 0,
"selected": false,
"text": "<p>You have to remove the filter before you set the rule. See code example below: </p>\n\n<pre>\n// Sync user role\nadd_action( 'set_user_role', 'sync_user_role', 10, 2 );\nfunction sync_user_role( $user_id, $role ) {\n\n $blogs = get_blogs_of_user( $user_id );\n\n $blogs_count = count( $blogs );\n\n if ( $blogs_count > 1 ) {\n foreach ( $blogs as $blog ) {\n\n $user_blog = new WP_User( $user_id, '', $blog->userblog_id );\n remove_action( 'set_user_role', 'sync_user_role', 10);\n $user_blog->set_role( $role );\n add_action( 'set_user_role', 'sync_user_role', 10, 2 );\n }\n }\n}\n</pre>\n"
}
]
| 2017/05/01 | [
"https://wordpress.stackexchange.com/questions/265449",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/30792/"
]
| I am using the following code (<https://developer.wordpress.org/reference/hooks/set_user_role/>) to sync user role between his blogs on a multisite installation.
My question is if this approach can lead to an infinite loop?
```
// Sync user role
add_action( 'set_user_role', 'sync_user_role', 10, 2 );
function sync_user_role( $user_id, $role ) {
$blogs = get_blogs_of_user( $user_id );
$blogs_count = count( $blogs );
if ( $blogs_count > 1 ) {
foreach ( $blogs as $blog ) {
$user_blog = new WP_User( $user_id, '', $blog->userblog_id );
$user_blog->set_role( $role );
}
}
}
``` | Yes it will give you infinite loop, because you're calling the `WP_User::set_role` method within the `set_user_role` action that's again fired within the the `WP_User::set_role` method.
Not sure what the setup is but you can try to run it only once, with
```
remove_action( current_action(), __FUNCTION__ );
```
as the first line in your callback, or use another hook.
*Update: I just noticed that I miswrote `filter` instead of `action`, but that would have worked the same though ;-) It's now adjusted.* |
265,487 | <p>I need help with structuring permalink for the custom post type that I made. I think I tried all the answers here. I'm hoping somebody can help me. </p>
<p><strong>More Info</strong></p>
<p>The custom post is looks like this in my url <code>www.domain.com/oa/beauty/post-name</code>
but I want it to looks like this <code>www.domain.com/beauty/post-name/</code>
The <code>beauty</code> is an example of the category name.</p>
<p>The custom permalink structure in the setting is set as <code>/%category%/%postname%/</code> and I would like my custom posts' permalink to be the same format. If the custom posts' category is <code>health</code> then its permalink would be <code>localhost/health/post-title</code>. I used <code>post_type_link</code> filter to change the permalink.</p>
<p><a href="https://i.stack.imgur.com/kM6wK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kM6wK.png" alt="enter image description here"></a></p>
<p>In my custom post type I tried to rename the url and then saved it but when I visit it the permalink (url) is leading to 404. Even after re-saving the permalink in the settings, the problem still there.</p>
<p>This is how I setup and registered the custom post (in case I set the wrong arguments)</p>
<pre><code>$args = array(
'labels' => $labels,
'public' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_icon' => 'dashicons-star-filled',
'query_var' => true,
'rewrite' => array('slug' => 'oa', 'with_front' => false),
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => false,
'menu_position' => 1,
'supports' => array('title', 'thumbnail', 'comments'),
'taxonomies' => array('category', 'post_tag'),
'show_in_rest' => true,
'rest_base' => 'oa-api',
'rest_controller_class' => 'WP_REST_Posts_Controller',
);
</code></pre>
<p>From what I researched, it seems that I should use <code>add_rewrite_rule</code> method. But I don't understand how rewrite works. Is this the right direction or am I missing something else?</p>
<p>I would like to solve this programmatically, not with a plugin.</p>
| [
{
"answer_id": 265460,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>Yes it will give you infinite loop, because you're calling the <code>WP_User::set_role</code> method within the <code>set_user_role</code> action that's again fired within the the <code>WP_User::set_role</code> method.</p>\n\n<p>Not sure what the setup is but you can try to run it only once, with</p>\n\n<pre><code>remove_action( current_action(), __FUNCTION__ );\n</code></pre>\n\n<p>as the first line in your callback, or use another hook.</p>\n\n<p><em>Update: I just noticed that I miswrote <code>filter</code> instead of <code>action</code>, but that would have worked the same though ;-) It's now adjusted.</em></p>\n"
},
{
"answer_id": 265473,
"author": "Pascal Knecht",
"author_id": 105101,
"author_profile": "https://wordpress.stackexchange.com/users/105101",
"pm_score": 0,
"selected": false,
"text": "<p>You have to remove the filter before you set the rule. See code example below: </p>\n\n<pre>\n// Sync user role\nadd_action( 'set_user_role', 'sync_user_role', 10, 2 );\nfunction sync_user_role( $user_id, $role ) {\n\n $blogs = get_blogs_of_user( $user_id );\n\n $blogs_count = count( $blogs );\n\n if ( $blogs_count > 1 ) {\n foreach ( $blogs as $blog ) {\n\n $user_blog = new WP_User( $user_id, '', $blog->userblog_id );\n remove_action( 'set_user_role', 'sync_user_role', 10);\n $user_blog->set_role( $role );\n add_action( 'set_user_role', 'sync_user_role', 10, 2 );\n }\n }\n}\n</pre>\n"
}
]
| 2017/05/01 | [
"https://wordpress.stackexchange.com/questions/265487",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118572/"
]
| I need help with structuring permalink for the custom post type that I made. I think I tried all the answers here. I'm hoping somebody can help me.
**More Info**
The custom post is looks like this in my url `www.domain.com/oa/beauty/post-name`
but I want it to looks like this `www.domain.com/beauty/post-name/`
The `beauty` is an example of the category name.
The custom permalink structure in the setting is set as `/%category%/%postname%/` and I would like my custom posts' permalink to be the same format. If the custom posts' category is `health` then its permalink would be `localhost/health/post-title`. I used `post_type_link` filter to change the permalink.
[](https://i.stack.imgur.com/kM6wK.png)
In my custom post type I tried to rename the url and then saved it but when I visit it the permalink (url) is leading to 404. Even after re-saving the permalink in the settings, the problem still there.
This is how I setup and registered the custom post (in case I set the wrong arguments)
```
$args = array(
'labels' => $labels,
'public' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_icon' => 'dashicons-star-filled',
'query_var' => true,
'rewrite' => array('slug' => 'oa', 'with_front' => false),
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => false,
'menu_position' => 1,
'supports' => array('title', 'thumbnail', 'comments'),
'taxonomies' => array('category', 'post_tag'),
'show_in_rest' => true,
'rest_base' => 'oa-api',
'rest_controller_class' => 'WP_REST_Posts_Controller',
);
```
From what I researched, it seems that I should use `add_rewrite_rule` method. But I don't understand how rewrite works. Is this the right direction or am I missing something else?
I would like to solve this programmatically, not with a plugin. | Yes it will give you infinite loop, because you're calling the `WP_User::set_role` method within the `set_user_role` action that's again fired within the the `WP_User::set_role` method.
Not sure what the setup is but you can try to run it only once, with
```
remove_action( current_action(), __FUNCTION__ );
```
as the first line in your callback, or use another hook.
*Update: I just noticed that I miswrote `filter` instead of `action`, but that would have worked the same though ;-) It's now adjusted.* |
265,499 | <p>I am building an <a href="http://www.wpbeginner.com/wp-tutorials/how-to-create-advanced-search-form-in-wordpress-for-custom-post-types/" rel="nofollow noreferrer">advanced search form</a> but the search is showing all post all time with this error too <code>array_key_exists() expects parameter 2 to be array, string was given</code></p>
<p>this is my code in <code>header.php</code></p>
<pre><code><?php $query_types = get_query_var('post_type'); ?>
<?php
$args = array(
'public' => true,
'_builtin' => false
);
$output = 'names'; // names or objects, note names is the default
$operator = 'and'; // 'and' or 'or'
$post_types = get_post_types( $args, $output, $operator );
//array array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = false ]] ) see http://php.net/manual/en/function.array-slice.php
foreach ( array_slice($post_types, 0, 5) as $post_type ) { //display max 5 post_type
?>
<li>
<a>
<input id="<?php echo $post_type ?>" class="btn btn-lg" type="checkbox" name="post_type[]" value="<?php echo $post_type ?>" <?php if (!empty($query_types) && array_key_exists($post_type , $query_types)) { echo 'checked="checked"'; } ?>/>
<!-- array_key_exists($post_type , $query_types) -->
<label for="<?php echo $post_type ?>"><span><?php echo $post_type ?></span></label>
</a>
</li>
<?php
}
?>
</code></pre>
<p>in <code>searchform.php</code> a have this:</p>
<pre><code><?php
$postType = array("construction","renovation","agrandissement","bradage");
foreach ($postType as &$value) {
echo '<input type="hidden" name="post_type[]" value="'.$value.'" />';
}
unset($value); // break the reference with the last element
?>
</code></pre>
<p>when I add <code>&& is_array($query_types)</code> in header.php <code>array_key_exists() expects parameter 2 to be array, string given</code> doesn`t show anymore but the result is empty.
i also get </p>
<pre><code>%5B%5D
</code></pre>
<p>in the url </p>
<pre><code>mywebsite.com/?s=LED70266765IKEA&post_type%5B%5D=boutique
</code></pre>
<p>please help me figuring out what I am doing wrong.</p>
<p><strong>UPDATE:</strong></p>
<p>here is my <code>search.php</code></p>
<pre><code><?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
?>
</code></pre>
<pre><code><section id="primary" class="row">
<main id="main" class="container" role="main">
<?php if ( have_posts() ) : ?>
<header class="page-header">
<h5 class="page-title">
<?php printf( __( 'Résultats de recherche pour: %s', 'igorconstructions' ), '<span>' . esc_html( get_search_query() ) . '</span>' ); ?>
</h5>
</header><!-- .page-header -->
<?php
// Start the loop.
while ( have_posts() ) : the_post();
/**
* Run the loop for the search to output the results.
* If you want to overload this in a child theme then include a file
* called content-search.php and that will be used instead.
*/
get_template_part( 'template-parts/content', 'search' );
// End the loop.
endwhile;
?>
<!-- PAGINATION -->
<div class="row">
<div class="col-md-12">
<div class="paging-navigation text-right">
<?php
the_posts_pagination( array(
'screen_reader_text' => ( '' ),
'type' => 'list',
'end_size' => 3,
'mid_size' => 3,
'format' => '?paged=%#%',
'prev_text' => '<span class="icon-angle-left">&larr;</span>',
'next_text' => '<span class="icon-angle-right">&rarr;</span>',
'before_page_number' => 'Page',
'after_page_number' => '',
) );
?>
</div><!-- end pagination container -->
</div><!-- end large-12 -->
</div>
<!-- end PAGINATION -->
<?php
// If no content, include the "No posts found" template.
else :
get_template_part( 'template-parts/content', 'none' );
endif;
?>
</main><!-- .site-main -->
</section><!-- .content-area -->
</code></pre>
<p>and <code>content-search.php</code> looks like this:</p>
<pre><code> <?php if(isset($_GET['post_type'])) {
$type = $_GET['post_type'];
//$type = $wp_query->query['post_type'];
if ( in_array( $type, array('boutique','news','text') ) ) {?>
<section class="col-md-4">
<article id="product-<?php the_ID(); ?>" <?php post_class(); ?>>
<!--
Thumbnail
-->
<div class="product-image">
<figure class="product-thumb">
<!-- === Confitional thumbnail=== -->
<?php if ( (function_exists('has_post_thumbnail')) && (has_post_thumbnail())) : ?>
<!--Image size //thumbnail medium large full-->
<?php the_post_thumbnail('medium', 'blog-thumb', array('class' => 'blog-thumb')); ?>
<?php else :?>
<img class="blog-thumb" src="<?php echo get_template_directory_uri(); ?>/images/cat-images/<?php $category = get_the_category(); echo $category[0]->slug; ?>.jpg" />
<?php endif; ?>
</figure>
</div>
<div class="product-description">
<!--
The Title
-->
<h4>
<a href="<?php the_permalink() ?>" rel="bookmark" title="m'en dire plus à ce sujet '<?php the_title_attribute(); ?>' svp!"><?php the_title(); ?></a>
</h4>
<P>
<?php
$url = get_post_meta( $post->ID, 'price', true );
if ($url) {
echo '<strong>à partir de:</strong> <strong class=thumbnail-price>'.$url.' FCFA TTC</strong>/ Unité';
}
?>
</P>
</div>
<div class="user-actions">
<!--
User actions
-->
<!-- Product reference-->
<p class="text-right">
<strong>Référence: </strong>
<span><?php echo get_post_meta( $post->ID, 'reference', true ) ?></span>
</p>
<p class="text-right">
<button class="action-btn-prim">
<a href="<?php the_permalink() ?>">Voir l'article</a>
</button>
</p>
<form class="text-right">
<button class="add-to-cart action-bt">
<a><svg class="pull-left" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:sketch="http://www.bohemiancoding.com/sketch/ns" width="20px" height="20px" viewBox="0 0 29 30" version="1.1">
<g xmlns="http://www.w3.org/2000/svg" id="Group">
<path fill="floralwhite" d="M5.87076823,28.1796875 C4.57567676,28.1796875 3.52246094,27.1264717 3.52246094,25.8313802 C3.52246094,24.5362887 4.57567676,23.4830729 5.87076823,23.4830729 C7.1658597,23.4830729 8.21907552,24.5362887 8.21907552,25.8313802 C8.21907552,27.1264717 7.1658597,28.1796875 5.87076823,28.1796875 L5.87076823,28.1796875 Z M5.87076823,24.6572266 C5.22322249,24.6572266 4.69661458,25.1838345 4.69661458,25.8313802 C4.69661458,26.4789259 5.22322249,27.0055339 5.87076823,27.0055339 C6.51831396,27.0055339 7.04492188,26.4789259 7.04492188,25.8313802 C7.04492188,25.1838345 6.51831396,24.6572266 5.87076823,24.6572266 L5.87076823,24.6572266 Z" id="Shape"/>
<path fill="floralwhite" d="M18.7864583,28.1796875 C17.4913669,28.1796875 16.438151,27.1264717 16.438151,25.8313802 C16.438151,24.5362887 17.4913669,23.4830729 18.7864583,23.4830729 C20.0815498,23.4830729 21.1347656,24.5362887 21.1347656,25.8313802 C21.1347656,27.1264717 20.0815498,28.1796875 18.7864583,28.1796875 L18.7864583,28.1796875 Z M18.7864583,24.6572266 C18.1389126,24.6572266 17.6123047,25.1838345 17.6123047,25.8313802 C17.6123047,26.4789259 18.1389126,27.0055339 18.7864583,27.0055339 C19.4340041,27.0055339 19.960612,26.4789259 19.960612,25.8313802 C19.960612,25.1838345 19.4340041,24.6572266 18.7864583,24.6572266 L18.7864583,24.6572266 Z" id="Shape"/>
<path fill="floralwhite" d="M12.3286133,9.39322917 C12.0039598,9.39322917 11.7415365,9.13080583 11.7415365,8.80615234 L11.7415365,0.587076823 C11.7415365,0.26242334 12.0039598,0 12.3286133,0 C12.6532668,0 12.9156901,0.26242334 12.9156901,0.587076823 L12.9156901,8.80615234 C12.9156901,9.13080583 12.6532668,9.39322917 12.3286133,9.39322917 L12.3286133,9.39322917 Z" id="Shape"/>
<path fill="floralwhite" d="M12.3286133,9.39322917 C12.1783216,9.39322917 12.0280299,9.33569564 11.91355,9.22121566 L8.39108903,5.69875472 C8.16154199,5.46920768 8.16154199,5.09817513 8.39108903,4.86862809 C8.62063607,4.63908105 8.99166862,4.63908105 9.22121566,4.86862809 L12.3286133,7.97602572 L15.4360109,4.86862809 C15.6655579,4.63908105 16.0365905,4.63908105 16.2661375,4.86862809 C16.4956846,5.09817513 16.4956846,5.46920768 16.2661375,5.69875472 L12.7436766,9.22121566 C12.6291966,9.33569564 12.4789049,9.39322917 12.3286133,9.39322917 L12.3286133,9.39322917 Z" id="Shape"/>
<path fill="floralwhite" d="M18.7864583,24.6572266 L5.87076823,24.6572266 C5.54611475,24.6572266 5.28369141,24.3948032 5.28369141,24.0701497 C5.28369141,23.7454963 5.54611475,23.4830729 5.87076823,23.4830729 L18.3214935,23.4830729 L22.9112601,3.97509717 C22.9740773,3.70973844 23.2106693,3.52246094 23.4830729,3.52246094 L27.5926107,3.52246094 C27.9172642,3.52246094 28.1796875,3.78488428 28.1796875,4.10953776 C28.1796875,4.43419124 27.9172642,4.69661458 27.5926107,4.69661458 L23.9480378,4.69661458 L19.3582712,24.2045903 C19.2954539,24.4699491 19.058862,24.6572266 18.7864583,24.6572266 L18.7864583,24.6572266 Z" id="Shape"/>
<path fill="floralwhite" d="M19.3735352,22.3089193 L4.10953776,22.3089193 C3.85650765,22.3089193 3.63283138,22.1474731 3.55298893,21.9073587 L0.0305279948,11.3399759 C-0.029940918,11.1609175 0.000587076823,10.9636597 0.11095752,10.8110197 C0.221327962,10.6577926 0.398625163,10.5673828 0.587076823,10.5673828 L21.7218424,10.5673828 C22.0464959,10.5673828 22.3089193,10.8298062 22.3089193,11.1544596 C22.3089193,11.4791131 22.0464959,11.7415365 21.7218424,11.7415365 L1.40193945,11.7415365 L4.53282015,21.1347656 L19.3735352,21.1347656 C19.6981886,21.1347656 19.960612,21.397189 19.960612,21.7218424 C19.960612,22.0464959 19.6981886,22.3089193 19.3735352,22.3089193 L19.3735352,22.3089193 Z" id="Shape"/>
</g>
</svg>
Ajouter
</a>
</button>
</form>
</div>
<hr>
</article>
</section>
<?php }
elseif($type == 'construction'){
}
elseif($type == 'blog'){
}
}else { ?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php if ( 'post' === get_post_type() ) : ?>
<?php else : ?>
<?php get_the_title() ?>
<?php endif; ?>
</code></pre>
<p></p>
| [
{
"answer_id": 265505,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 2,
"selected": true,
"text": "<p>The core issue is that you're having trouble creating a filtered search. Why not use a <code>pre_get_posts</code> hook to modify the query before it actually gets called, then you don't need to modify the template files at all:</p>\n\n<pre><code>/**\n * Modify WP_Query before it asks the database what data to retrieve\n * Belongs in functions.php\n *\n * @param WP_Query Object $query\n *\n * @return void\n */\nfunction wpse_265499( $query ) {\n\n // Don't run on admin\n if( $query->is_admin ) {\n return;\n }\n\n // IF main query and search page\n if( $query->is_main_query() && $query->is_search() ) {\n\n // IF we have our post type array set \n if( isset( $_GET, $_GET['post_type'] ) && ! empty( $_GET['post_type'] ) ) {\n $query->set( 'post_type', $_GET['post_type'] ); // Will be set as boutique\n }\n\n }\n\n}\nadd_action( 'pre_get_posts', 'wpse_265499' );\n</code></pre>\n\n<p>The above would be added to your <code>functions.php</code> file and what <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow noreferrer\"><code>pre_get_posts</code></a> does is before it goes to the database and grabs the data to be displayed, we can modify what is being requested. In this case we're saying IF we have <code>post_types</code> set in the URL as a <code>$_GET</code>, grab only those post types. So your main query will now only show the post types assigned in <code>$_GET</code> at which point there's no need for the conditional statements in your template.</p>\n\n<hr>\n\n<p>Let's break this down starting with the error itself.</p>\n\n<blockquote>\n <p>array_key_exists() expects parameter 2 to be array, string was given</p>\n</blockquote>\n\n<p>So based on the error we know that <a href=\"http://php.net/manual/en/function.array-key-exists.php\" rel=\"nofollow noreferrer\"><code>array_key_exists()</code></a> needs parameter 2 to be an array, so that it can search for a key, but at some point a string was given instead of an array.</p>\n\n<p>As far as I can tell you only have one instance of <a href=\"http://php.net/manual/en/function.array-key-exists.php\" rel=\"nofollow noreferrer\"><code>array_key_exists()</code></a> and it looks like this:</p>\n\n<pre><code>array_key_exists( $post_type , $query_types )\n</code></pre>\n\n<p>Combined with the PHP error we can surmise that <code>$query_types</code> must be a string instead of the array that we need for <a href=\"http://php.net/manual/en/function.array-key-exists.php\" rel=\"nofollow noreferrer\"><code>array_key_exists()</code></a> to work. Let's look at how <code>$query_types</code> is set:</p>\n\n<pre><code>$query_types = get_query_var( 'post_type' );\n</code></pre>\n\n<p>If we look at the <a href=\"https://developer.wordpress.org/reference/functions/get_query_var/\" rel=\"nofollow noreferrer\"><code>get_query_var()</code></a> function we see it <em>can</em> return an array because the return type is mixed. That being said, we're only asking for <strong>one</strong> <code>post_type</code> so it's probably returning a string for the queried post type.</p>\n\n<p>I'm not sure what it is you're trying to accomplish but hopefully that clears up the reason you're getting that error.</p>\n"
},
{
"answer_id": 266449,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 0,
"selected": false,
"text": "<p>The answer by Howdy_McGee is correct, but just to expand upon their answer:</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/get_query_var/\" rel=\"nofollow noreferrer\"><code>get_query_var()</code></a> is a function that requires one parameter and the second is an optional default value. It is a wrapper for <a href=\"https://core.trac.wordpress.org/browser/tags/4.7/src/wp-includes/class-wp-query.php#L1633\" rel=\"nofollow noreferrer\"><code>WP_Query::get()</code></a> that has the same parameters. This method checks whether <code>WP_Query->query_vars[ $query_var ]</code> exists, and if it does, returns that value.</p>\n\n<p>Query vars can be set using the <code>WP_Query::set()</code> method, and the value can be anything: null, integer, string, array, object, whatever. So the get method will return anything as long as it exists. In the case it doesn't exist, it will return whatever the second parameter was passed to <code>get_query_var()</code>. In this case, that was nothing, so it uses the default of an empty string.</p>\n\n<p><a href=\"https://secure.php.net/manual/en/function.array-key-exists.php\" rel=\"nofollow noreferrer\"><code>array_key_exists()</code></a>, as you've found out, requires that the second parameter be an array. Since we don't know that <code>get_query_var()</code> might not return an array, then we need to make sure before we pass it to a function that requires an array as an input.</p>\n\n<pre><code>//* Cast as an array\n$query_types = (array) get_query_var( 'post_type', [] );\n</code></pre>\n\n<p><a href=\"http://php.net/manual/en/language.types.array.php#language.types.array.casting\" rel=\"nofollow noreferrer\">PHP casting to array</a> will \"for any of the types integer, float, string, boolean and resource, converting a value to an array results in an array with a single element with index zero and the value of the scalar which was converted.\"</p>\n\n<p>Since the <code>$query_types</code> will be guaranteed to be an array, you shouldn't have that error, and hopefully your advanced search will work as intended.</p>\n"
}
]
| 2017/05/01 | [
"https://wordpress.stackexchange.com/questions/265499",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/27425/"
]
| I am building an [advanced search form](http://www.wpbeginner.com/wp-tutorials/how-to-create-advanced-search-form-in-wordpress-for-custom-post-types/) but the search is showing all post all time with this error too `array_key_exists() expects parameter 2 to be array, string was given`
this is my code in `header.php`
```
<?php $query_types = get_query_var('post_type'); ?>
<?php
$args = array(
'public' => true,
'_builtin' => false
);
$output = 'names'; // names or objects, note names is the default
$operator = 'and'; // 'and' or 'or'
$post_types = get_post_types( $args, $output, $operator );
//array array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = false ]] ) see http://php.net/manual/en/function.array-slice.php
foreach ( array_slice($post_types, 0, 5) as $post_type ) { //display max 5 post_type
?>
<li>
<a>
<input id="<?php echo $post_type ?>" class="btn btn-lg" type="checkbox" name="post_type[]" value="<?php echo $post_type ?>" <?php if (!empty($query_types) && array_key_exists($post_type , $query_types)) { echo 'checked="checked"'; } ?>/>
<!-- array_key_exists($post_type , $query_types) -->
<label for="<?php echo $post_type ?>"><span><?php echo $post_type ?></span></label>
</a>
</li>
<?php
}
?>
```
in `searchform.php` a have this:
```
<?php
$postType = array("construction","renovation","agrandissement","bradage");
foreach ($postType as &$value) {
echo '<input type="hidden" name="post_type[]" value="'.$value.'" />';
}
unset($value); // break the reference with the last element
?>
```
when I add `&& is_array($query_types)` in header.php `array_key_exists() expects parameter 2 to be array, string given` doesn`t show anymore but the result is empty.
i also get
```
%5B%5D
```
in the url
```
mywebsite.com/?s=LED70266765IKEA&post_type%5B%5D=boutique
```
please help me figuring out what I am doing wrong.
**UPDATE:**
here is my `search.php`
```
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
?>
```
```
<section id="primary" class="row">
<main id="main" class="container" role="main">
<?php if ( have_posts() ) : ?>
<header class="page-header">
<h5 class="page-title">
<?php printf( __( 'Résultats de recherche pour: %s', 'igorconstructions' ), '<span>' . esc_html( get_search_query() ) . '</span>' ); ?>
</h5>
</header><!-- .page-header -->
<?php
// Start the loop.
while ( have_posts() ) : the_post();
/**
* Run the loop for the search to output the results.
* If you want to overload this in a child theme then include a file
* called content-search.php and that will be used instead.
*/
get_template_part( 'template-parts/content', 'search' );
// End the loop.
endwhile;
?>
<!-- PAGINATION -->
<div class="row">
<div class="col-md-12">
<div class="paging-navigation text-right">
<?php
the_posts_pagination( array(
'screen_reader_text' => ( '' ),
'type' => 'list',
'end_size' => 3,
'mid_size' => 3,
'format' => '?paged=%#%',
'prev_text' => '<span class="icon-angle-left">←</span>',
'next_text' => '<span class="icon-angle-right">→</span>',
'before_page_number' => 'Page',
'after_page_number' => '',
) );
?>
</div><!-- end pagination container -->
</div><!-- end large-12 -->
</div>
<!-- end PAGINATION -->
<?php
// If no content, include the "No posts found" template.
else :
get_template_part( 'template-parts/content', 'none' );
endif;
?>
</main><!-- .site-main -->
</section><!-- .content-area -->
```
and `content-search.php` looks like this:
```
<?php if(isset($_GET['post_type'])) {
$type = $_GET['post_type'];
//$type = $wp_query->query['post_type'];
if ( in_array( $type, array('boutique','news','text') ) ) {?>
<section class="col-md-4">
<article id="product-<?php the_ID(); ?>" <?php post_class(); ?>>
<!--
Thumbnail
-->
<div class="product-image">
<figure class="product-thumb">
<!-- === Confitional thumbnail=== -->
<?php if ( (function_exists('has_post_thumbnail')) && (has_post_thumbnail())) : ?>
<!--Image size //thumbnail medium large full-->
<?php the_post_thumbnail('medium', 'blog-thumb', array('class' => 'blog-thumb')); ?>
<?php else :?>
<img class="blog-thumb" src="<?php echo get_template_directory_uri(); ?>/images/cat-images/<?php $category = get_the_category(); echo $category[0]->slug; ?>.jpg" />
<?php endif; ?>
</figure>
</div>
<div class="product-description">
<!--
The Title
-->
<h4>
<a href="<?php the_permalink() ?>" rel="bookmark" title="m'en dire plus à ce sujet '<?php the_title_attribute(); ?>' svp!"><?php the_title(); ?></a>
</h4>
<P>
<?php
$url = get_post_meta( $post->ID, 'price', true );
if ($url) {
echo '<strong>à partir de:</strong> <strong class=thumbnail-price>'.$url.' FCFA TTC</strong>/ Unité';
}
?>
</P>
</div>
<div class="user-actions">
<!--
User actions
-->
<!-- Product reference-->
<p class="text-right">
<strong>Référence: </strong>
<span><?php echo get_post_meta( $post->ID, 'reference', true ) ?></span>
</p>
<p class="text-right">
<button class="action-btn-prim">
<a href="<?php the_permalink() ?>">Voir l'article</a>
</button>
</p>
<form class="text-right">
<button class="add-to-cart action-bt">
<a><svg class="pull-left" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:sketch="http://www.bohemiancoding.com/sketch/ns" width="20px" height="20px" viewBox="0 0 29 30" version="1.1">
<g xmlns="http://www.w3.org/2000/svg" id="Group">
<path fill="floralwhite" d="M5.87076823,28.1796875 C4.57567676,28.1796875 3.52246094,27.1264717 3.52246094,25.8313802 C3.52246094,24.5362887 4.57567676,23.4830729 5.87076823,23.4830729 C7.1658597,23.4830729 8.21907552,24.5362887 8.21907552,25.8313802 C8.21907552,27.1264717 7.1658597,28.1796875 5.87076823,28.1796875 L5.87076823,28.1796875 Z M5.87076823,24.6572266 C5.22322249,24.6572266 4.69661458,25.1838345 4.69661458,25.8313802 C4.69661458,26.4789259 5.22322249,27.0055339 5.87076823,27.0055339 C6.51831396,27.0055339 7.04492188,26.4789259 7.04492188,25.8313802 C7.04492188,25.1838345 6.51831396,24.6572266 5.87076823,24.6572266 L5.87076823,24.6572266 Z" id="Shape"/>
<path fill="floralwhite" d="M18.7864583,28.1796875 C17.4913669,28.1796875 16.438151,27.1264717 16.438151,25.8313802 C16.438151,24.5362887 17.4913669,23.4830729 18.7864583,23.4830729 C20.0815498,23.4830729 21.1347656,24.5362887 21.1347656,25.8313802 C21.1347656,27.1264717 20.0815498,28.1796875 18.7864583,28.1796875 L18.7864583,28.1796875 Z M18.7864583,24.6572266 C18.1389126,24.6572266 17.6123047,25.1838345 17.6123047,25.8313802 C17.6123047,26.4789259 18.1389126,27.0055339 18.7864583,27.0055339 C19.4340041,27.0055339 19.960612,26.4789259 19.960612,25.8313802 C19.960612,25.1838345 19.4340041,24.6572266 18.7864583,24.6572266 L18.7864583,24.6572266 Z" id="Shape"/>
<path fill="floralwhite" d="M12.3286133,9.39322917 C12.0039598,9.39322917 11.7415365,9.13080583 11.7415365,8.80615234 L11.7415365,0.587076823 C11.7415365,0.26242334 12.0039598,0 12.3286133,0 C12.6532668,0 12.9156901,0.26242334 12.9156901,0.587076823 L12.9156901,8.80615234 C12.9156901,9.13080583 12.6532668,9.39322917 12.3286133,9.39322917 L12.3286133,9.39322917 Z" id="Shape"/>
<path fill="floralwhite" d="M12.3286133,9.39322917 C12.1783216,9.39322917 12.0280299,9.33569564 11.91355,9.22121566 L8.39108903,5.69875472 C8.16154199,5.46920768 8.16154199,5.09817513 8.39108903,4.86862809 C8.62063607,4.63908105 8.99166862,4.63908105 9.22121566,4.86862809 L12.3286133,7.97602572 L15.4360109,4.86862809 C15.6655579,4.63908105 16.0365905,4.63908105 16.2661375,4.86862809 C16.4956846,5.09817513 16.4956846,5.46920768 16.2661375,5.69875472 L12.7436766,9.22121566 C12.6291966,9.33569564 12.4789049,9.39322917 12.3286133,9.39322917 L12.3286133,9.39322917 Z" id="Shape"/>
<path fill="floralwhite" d="M18.7864583,24.6572266 L5.87076823,24.6572266 C5.54611475,24.6572266 5.28369141,24.3948032 5.28369141,24.0701497 C5.28369141,23.7454963 5.54611475,23.4830729 5.87076823,23.4830729 L18.3214935,23.4830729 L22.9112601,3.97509717 C22.9740773,3.70973844 23.2106693,3.52246094 23.4830729,3.52246094 L27.5926107,3.52246094 C27.9172642,3.52246094 28.1796875,3.78488428 28.1796875,4.10953776 C28.1796875,4.43419124 27.9172642,4.69661458 27.5926107,4.69661458 L23.9480378,4.69661458 L19.3582712,24.2045903 C19.2954539,24.4699491 19.058862,24.6572266 18.7864583,24.6572266 L18.7864583,24.6572266 Z" id="Shape"/>
<path fill="floralwhite" d="M19.3735352,22.3089193 L4.10953776,22.3089193 C3.85650765,22.3089193 3.63283138,22.1474731 3.55298893,21.9073587 L0.0305279948,11.3399759 C-0.029940918,11.1609175 0.000587076823,10.9636597 0.11095752,10.8110197 C0.221327962,10.6577926 0.398625163,10.5673828 0.587076823,10.5673828 L21.7218424,10.5673828 C22.0464959,10.5673828 22.3089193,10.8298062 22.3089193,11.1544596 C22.3089193,11.4791131 22.0464959,11.7415365 21.7218424,11.7415365 L1.40193945,11.7415365 L4.53282015,21.1347656 L19.3735352,21.1347656 C19.6981886,21.1347656 19.960612,21.397189 19.960612,21.7218424 C19.960612,22.0464959 19.6981886,22.3089193 19.3735352,22.3089193 L19.3735352,22.3089193 Z" id="Shape"/>
</g>
</svg>
Ajouter
</a>
</button>
</form>
</div>
<hr>
</article>
</section>
<?php }
elseif($type == 'construction'){
}
elseif($type == 'blog'){
}
}else { ?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php if ( 'post' === get_post_type() ) : ?>
<?php else : ?>
<?php get_the_title() ?>
<?php endif; ?>
``` | The core issue is that you're having trouble creating a filtered search. Why not use a `pre_get_posts` hook to modify the query before it actually gets called, then you don't need to modify the template files at all:
```
/**
* Modify WP_Query before it asks the database what data to retrieve
* Belongs in functions.php
*
* @param WP_Query Object $query
*
* @return void
*/
function wpse_265499( $query ) {
// Don't run on admin
if( $query->is_admin ) {
return;
}
// IF main query and search page
if( $query->is_main_query() && $query->is_search() ) {
// IF we have our post type array set
if( isset( $_GET, $_GET['post_type'] ) && ! empty( $_GET['post_type'] ) ) {
$query->set( 'post_type', $_GET['post_type'] ); // Will be set as boutique
}
}
}
add_action( 'pre_get_posts', 'wpse_265499' );
```
The above would be added to your `functions.php` file and what [`pre_get_posts`](https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts) does is before it goes to the database and grabs the data to be displayed, we can modify what is being requested. In this case we're saying IF we have `post_types` set in the URL as a `$_GET`, grab only those post types. So your main query will now only show the post types assigned in `$_GET` at which point there's no need for the conditional statements in your template.
---
Let's break this down starting with the error itself.
>
> array\_key\_exists() expects parameter 2 to be array, string was given
>
>
>
So based on the error we know that [`array_key_exists()`](http://php.net/manual/en/function.array-key-exists.php) needs parameter 2 to be an array, so that it can search for a key, but at some point a string was given instead of an array.
As far as I can tell you only have one instance of [`array_key_exists()`](http://php.net/manual/en/function.array-key-exists.php) and it looks like this:
```
array_key_exists( $post_type , $query_types )
```
Combined with the PHP error we can surmise that `$query_types` must be a string instead of the array that we need for [`array_key_exists()`](http://php.net/manual/en/function.array-key-exists.php) to work. Let's look at how `$query_types` is set:
```
$query_types = get_query_var( 'post_type' );
```
If we look at the [`get_query_var()`](https://developer.wordpress.org/reference/functions/get_query_var/) function we see it *can* return an array because the return type is mixed. That being said, we're only asking for **one** `post_type` so it's probably returning a string for the queried post type.
I'm not sure what it is you're trying to accomplish but hopefully that clears up the reason you're getting that error. |
265,507 | <p>I am in the process of changing my protocol from http to https.</p>
<p>I have wordpress installed as a subdirectory (eg: www.example.com/blog)</p>
<p>I have the server behind a load balancer, requests to the load balancer are encrypted but requests from the load balancer to the server are not.</p>
<p>I updated the <code>home</code> and <code>siteurl</code> parameters to reflect the https adddress.
And I added the following code to my <code>wp-config.php</code> file:</p>
<pre><code>if (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false)
$_SERVER['HTTPS']='on';
</code></pre>
<p>For some reason, when I go to the url <a href="https://www.example.com/blog" rel="nofollow noreferrer">https://www.example.com/blog</a>, the following redirects occur:
<a href="https://...blog" rel="nofollow noreferrer">https://...blog</a> -> <a href="http://...blog/" rel="nofollow noreferrer">http://...blog/</a></p>
<p><a href="http://...blog/" rel="nofollow noreferrer">http://...blog/</a> -> <a href="https://...blog/" rel="nofollow noreferrer">https://...blog/</a></p>
<p>I can live with one redirect (the one for adding the slash), but I don't understand why it redirects to the <code>http://</code> address. I don't see anything in my setup that still references <code>http://</code>.</p>
<p>Why is it doing this?</p>
<p>I have tried clearing my browser's cache. I also have an .htaccess file but I suspect it doesn't have anything to do with it because the redirects occur even when all the code in the <code>.htaccess</code> file is commented</p>
<p>In someone still finds the <code>htaccess</code> file relevant: I have two rules in the <code>htaccess</code> file:</p>
<pre><code>RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule . https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent]
</code></pre>
<p>for redirecting http to https</p>
<p>and</p>
<pre><code><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>
</code></pre>
<p>for adding the slash (I think).</p>
<p>Although the first rule isn't relevant (because I am going directly to the <code>https</code> address). And commenting the second rule has no effect on the issue in question.</p>
<p>Is there anywhere else in my setup where I need to update wordpress about the fact that I'm using <code>https</code>?</p>
<p>Thanks.</p>
| [
{
"answer_id": 265509,
"author": "mayersdesign",
"author_id": 106965,
"author_profile": "https://wordpress.stackexchange.com/users/106965",
"pm_score": 0,
"selected": false,
"text": "<p>You need to update the baseurls in your database. Namely the option_values for <strong><em>siteurl</em></strong> and <strong><em>home</em></strong> in the options table.</p>\n\n<p>The following code will do that for you robustly. Watch out for the prefix, which here I have indicated is \"wp_\" but which of course, it should not be! :) Also of course you need to change the site name:</p>\n\n<pre><code>UPDATE wp_options SET option_value = replace(option_value, 'http://www.example.com/blog', 'https://www.example.com/blog') WHERE option_name = 'home' OR option_name = 'siteurl';\nUPDATE wp_posts SET guid = REPLACE (guid, 'http://www.example.com/blog', 'https://www.example.com/blog');\nUPDATE wp_posts SET post_content = REPLACE (post_content, 'http://www.example.com/blog', 'https://www.example.com/blog');\nUPDATE wp_postmeta SET meta_value = REPLACE (meta_value, 'http://www.example.com/blog','https://www.example.com/blog');\n</code></pre>\n"
},
{
"answer_id": 265833,
"author": "JItendra Rana",
"author_id": 87433,
"author_profile": "https://wordpress.stackexchange.com/users/87433",
"pm_score": 0,
"selected": false,
"text": "<p>Try this in your .htaccess file </p>\n\n<pre><code><IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /blog/\n\nRewriteCond %{ENV:HTTPS} !=on\nRewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]\n\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /blog/index.php [L]\n</IfModule>\n</code></pre>\n\n<p>See if it helps</p>\n"
},
{
"answer_id": 265842,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>This is somewhat of a guess, but it is probably a result of the web server configuration. What your server probably does is to see that the request want to load the <code>blog</code> url of the site. It checks out and sees that <code>blog</code> is a directory adds a slash and redirects to it. Now because the load balancer sends an <code>http</code> request the web server redirect to <code>http</code>. After that the request is made to the wordpress directory and all your htaccess and wordpress logic kicks in and provides the correct info/redirects etc.</p>\n\n<p>Solution... if this is not only a good story, but also a true one, an http to https redirection in an htaccess of the root directory should probably fix it. </p>\n\n<p>If it actually does fix the issue (and you think the fix worth your time) you will want to consider merging the \"wordpress\" htaccess into the root one as apache reads all the htaccess in each directory in the hierarchy on each request and \"runs\" them which is a pointless waste of time.</p>\n"
},
{
"answer_id": 266366,
"author": "Felix",
"author_id": 110428,
"author_profile": "https://wordpress.stackexchange.com/users/110428",
"pm_score": 0,
"selected": false,
"text": "<p>You should not have to edit WordPress files yourself. WordPress can be used with either http or https without the need of manual code change.</p>\n\n<p>If you have to change the protocol for an existing WordPress site, you can do two things:</p>\n\n<ol>\n<li><p>Make sure, your blog is accessible through http and https. Then switch to your WordPress settings in the backend and just update the blogs url from <a href=\"http://example.org\" rel=\"nofollow noreferrer\">http://example.org</a> to <a href=\"https://example.org\" rel=\"nofollow noreferrer\">https://example.org</a>\nWordPress should update the database and .htaccess-file itself</p></li>\n<li><p>you can do a search & replace on the database. To do so, you have to be aware of serialized data, which is not recognized with a simple search & replace process. I suggest you to use a tool like from <a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow noreferrer\">interconnect</a></p></li>\n</ol>\n\n<p>Make sure your <em>wp-config.php</em> does not contain a hardcoded url (<a href=\"https://codex.wordpress.org/Changing_The_Site_URL\" rel=\"nofollow noreferrer\">see \"Changing The Site URL\"</a>), which will overwrite your changes again.</p>\n"
}
]
| 2017/05/01 | [
"https://wordpress.stackexchange.com/questions/265507",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102281/"
]
| I am in the process of changing my protocol from http to https.
I have wordpress installed as a subdirectory (eg: www.example.com/blog)
I have the server behind a load balancer, requests to the load balancer are encrypted but requests from the load balancer to the server are not.
I updated the `home` and `siteurl` parameters to reflect the https adddress.
And I added the following code to my `wp-config.php` file:
```
if (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false)
$_SERVER['HTTPS']='on';
```
For some reason, when I go to the url <https://www.example.com/blog>, the following redirects occur:
<https://...blog> -> <http://...blog/>
<http://...blog/> -> <https://...blog/>
I can live with one redirect (the one for adding the slash), but I don't understand why it redirects to the `http://` address. I don't see anything in my setup that still references `http://`.
Why is it doing this?
I have tried clearing my browser's cache. I also have an .htaccess file but I suspect it doesn't have anything to do with it because the redirects occur even when all the code in the `.htaccess` file is commented
In someone still finds the `htaccess` file relevant: I have two rules in the `htaccess` file:
```
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule . https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent]
```
for redirecting http to https
and
```
<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>
```
for adding the slash (I think).
Although the first rule isn't relevant (because I am going directly to the `https` address). And commenting the second rule has no effect on the issue in question.
Is there anywhere else in my setup where I need to update wordpress about the fact that I'm using `https`?
Thanks. | This is somewhat of a guess, but it is probably a result of the web server configuration. What your server probably does is to see that the request want to load the `blog` url of the site. It checks out and sees that `blog` is a directory adds a slash and redirects to it. Now because the load balancer sends an `http` request the web server redirect to `http`. After that the request is made to the wordpress directory and all your htaccess and wordpress logic kicks in and provides the correct info/redirects etc.
Solution... if this is not only a good story, but also a true one, an http to https redirection in an htaccess of the root directory should probably fix it.
If it actually does fix the issue (and you think the fix worth your time) you will want to consider merging the "wordpress" htaccess into the root one as apache reads all the htaccess in each directory in the hierarchy on each request and "runs" them which is a pointless waste of time. |
265,523 | <p>I have a custom post type, <code>card</code>, that I'm exposing through the WP REST API. Is there a way to require authentication, with cookie or Basic Auth header? I see an argument under the POST method block for password, but I'm not sure how to use it.</p>
<p><a href="https://i.stack.imgur.com/qTKgd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/qTKgd.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 266466,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 5,
"selected": true,
"text": "<p>When we register a rest route with <a href=\"https://developer.wordpress.org/reference/functions/register_rest_route/\" rel=\"noreferrer\"><code>register_rest_route()</code></a>, then we can use the <code>permission_callback</code> parameter with the kind of permission we want.</p>\n\n<p>Check for example how <code>WP_REST_Posts_Controller::register_routes()</code> and <code>WP_REST_Users_Controller::register_routes()</code> implement the permission callback.</p>\n\n<p>The password argument you're referring to is the content's password, that you can set for each post and that's not the same.</p>\n\n<p>But since you want to target existing routes, like:</p>\n\n<pre><code>/wp/v2/cards\n/wp/v2/cards/(?P<id>[\\d]+)\n/wp/v2/cards/...possibly some other patterns...\n</code></pre>\n\n<p>you could try e.g. the <code>rest_dispatch_request</code> filter to setup your additional permission check for those kind of routes. </p>\n\n<p><strong>Here's a demo plugin:</strong></p>\n\n<pre><code>add_filter( 'rest_dispatch_request', function( $dispatch_result, $request, $route, $hndlr )\n{\n $target_base = '/wp/v2/cards'; // Edit to your needs\n\n $pattern1 = untrailingslashit( $target_base ); // e.g. /wp/v2/cards\n $pattern2 = trailingslashit( $target_base ); // e.g. /wp/v2/cards/\n\n // Target only /wp/v2/cards and /wp/v2/cards/*\n if( $pattern1 !== $route && $pattern2 !== substr( $route, 0, strlen( $pattern2 ) ) )\n return $dispatch_result;\n\n // Additional permission check\n if( is_user_logged_in() ) // or e.g. current_user_can( 'manage_options' )\n return $dispatch_result;\n\n // Target GET method\n if( WP_REST_Server::READABLE !== $request->get_method() ) \n return $dispatch_result;\n\n return new \\WP_Error( \n 'rest_forbidden', \n esc_html__( 'Sorry, you are not allowed to do that.', 'wpse' ), \n [ 'status' => 403 ] \n );\n\n}, 10, 4 );\n</code></pre>\n\n<p>where we target the <code>/wp/v2/cards</code> and <code>/wp/v2/cards/*</code> GET routes, with additional user permission checks.</p>\n\n<p>When debugging it with the WordPress cookie authentication, we can e.g. test it directly with:</p>\n\n<pre><code>https://example.tld/wp-json/wp/v2/cards?_wpnonce=9467a0bf9c\n</code></pre>\n\n<p>where the nonce part has been generated from <code>wp_create_nonce( 'wp_rest' );</code></p>\n\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 266468,
"author": "Otto",
"author_id": 2232,
"author_profile": "https://wordpress.stackexchange.com/users/2232",
"pm_score": 2,
"selected": false,
"text": "<p>The \"password\" field you are seeing is actually not for the REST API, but for the Post entry itself. Individual posts in WordPress can be password protected such that you need the password in order to see their content.</p>\n\n<p>This form of individual post-password is not a strong password mechanism, it is a shared password. The password is the same for all users, and it is stored in the database unencrypted and unhashed. It is was never intended as a secure mechanism by any means, it is a simple mechanism to hide content in a simple way.</p>\n\n<p>If you want to use this mechanism with the REST API, then it is possible. For example, if the individual post's ID is 123, then a post can be retrieved like so:</p>\n\n<p><a href=\"http://example.com/wp-json/wp/v2/posts/123\" rel=\"nofollow noreferrer\">http://example.com/wp-json/wp/v2/posts/123</a></p>\n\n<p>If that post is password protected, then this URL will retrieve it:</p>\n\n<p><a href=\"http://example.com/wp-json/wp/v2/posts/123?password=example-pass\" rel=\"nofollow noreferrer\">http://example.com/wp-json/wp/v2/posts/123?password=example-pass</a></p>\n\n<p>Reference: <a href=\"https://developer.wordpress.org/rest-api/reference/posts/#retrieve-a-post\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/rest-api/reference/posts/#retrieve-a-post</a></p>\n\n<p>If you need stronger, user-based authentication, then WordPress offers a way to make posts \"private\" instead. This setting makes posts only visible to user accounts that have the \"read_private_posts\" capability, which is limited to the Administrator and Editor roles by default. (Note: Private only makes the post contents private, their Titles can still be exposed.)</p>\n\n<p>When you make a custom post type, this same capability is mapped to the plural of your type (using plural_base). So for a post type of cards, there would be a similar \"read_private_cards\" permission available for you to assign to user roles if desired.</p>\n\n<p>Now, Authentication on a user-level is not actually built into the REST API. The standard WordPress cookie based auth works fine, however the API offers no way to get that cookie. It will accept it if it is present, but you have to do the normal login flow to get such a cookie. If you want some other authentication approach, then you need a plugin for it.</p>\n\n<p>Four such plugins exist. These are OAuth 1.0, Application Passwords, JSON Web Tokens, and a Basic Authentication plugin. Note that the Basic Authentication is easiest, however it is also insecure and thus only recommended for testing and development purposes. It should not be used on a live production server.</p>\n\n<p>You can find more information about these plugins here:</p>\n\n<p><a href=\"https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/#authentication-plugins\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/#authentication-plugins</a></p>\n"
}
]
| 2017/05/01 | [
"https://wordpress.stackexchange.com/questions/265523",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83970/"
]
| I have a custom post type, `card`, that I'm exposing through the WP REST API. Is there a way to require authentication, with cookie or Basic Auth header? I see an argument under the POST method block for password, but I'm not sure how to use it.
[](https://i.stack.imgur.com/qTKgd.png) | When we register a rest route with [`register_rest_route()`](https://developer.wordpress.org/reference/functions/register_rest_route/), then we can use the `permission_callback` parameter with the kind of permission we want.
Check for example how `WP_REST_Posts_Controller::register_routes()` and `WP_REST_Users_Controller::register_routes()` implement the permission callback.
The password argument you're referring to is the content's password, that you can set for each post and that's not the same.
But since you want to target existing routes, like:
```
/wp/v2/cards
/wp/v2/cards/(?P<id>[\d]+)
/wp/v2/cards/...possibly some other patterns...
```
you could try e.g. the `rest_dispatch_request` filter to setup your additional permission check for those kind of routes.
**Here's a demo plugin:**
```
add_filter( 'rest_dispatch_request', function( $dispatch_result, $request, $route, $hndlr )
{
$target_base = '/wp/v2/cards'; // Edit to your needs
$pattern1 = untrailingslashit( $target_base ); // e.g. /wp/v2/cards
$pattern2 = trailingslashit( $target_base ); // e.g. /wp/v2/cards/
// Target only /wp/v2/cards and /wp/v2/cards/*
if( $pattern1 !== $route && $pattern2 !== substr( $route, 0, strlen( $pattern2 ) ) )
return $dispatch_result;
// Additional permission check
if( is_user_logged_in() ) // or e.g. current_user_can( 'manage_options' )
return $dispatch_result;
// Target GET method
if( WP_REST_Server::READABLE !== $request->get_method() )
return $dispatch_result;
return new \WP_Error(
'rest_forbidden',
esc_html__( 'Sorry, you are not allowed to do that.', 'wpse' ),
[ 'status' => 403 ]
);
}, 10, 4 );
```
where we target the `/wp/v2/cards` and `/wp/v2/cards/*` GET routes, with additional user permission checks.
When debugging it with the WordPress cookie authentication, we can e.g. test it directly with:
```
https://example.tld/wp-json/wp/v2/cards?_wpnonce=9467a0bf9c
```
where the nonce part has been generated from `wp_create_nonce( 'wp_rest' );`
Hope this helps! |
265,568 | <p>Is there any way through which I can declare the dynamic variable in php.
for eg, I am using a for loop and the variable name is $message. and I want to add some dynamic data at the end of the variable name. code is below</p>
<pre><code>foreach ($quant as $quantity) {
$message.$quantity['type'] = 'Listing ID : '.$quantity['product_id'].' With Quantity: '.$quantity['quantity'].'MT, State- '.$quantity['state_name'].' and Coal type-'.$quantity['coal_type'].'<br>';
}
</code></pre>
<p>so if the $quantity['type'] = 1, then the variable name should be $message1 and so on. currently I am trying to concatenate but it is wrong. Please tell me how it can be corrected. Thanks in advance </p>
| [
{
"answer_id": 265530,
"author": "Scott R. Godin",
"author_id": 118816,
"author_profile": "https://wordpress.stackexchange.com/users/118816",
"pm_score": 2,
"selected": false,
"text": "<p>One thing you can do to help reduce the amount of bloat is add a plugin that controls the number of previous revisions kept for Pages, Posts, etc (preferably one that allows for separate values for each type, such as last 5 revisions for pages and last 20 revisions for posts, or whatever.)</p>\n\n<p>There are numerous plugins that handle this, check around <a href=\"https://wordpress.org/plugins/search/revision+control/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/search/revision+control/</a> and similar</p>\n"
},
{
"answer_id": 265540,
"author": "Aishan",
"author_id": 89530,
"author_profile": "https://wordpress.stackexchange.com/users/89530",
"pm_score": 1,
"selected": false,
"text": "<p>The thing i do for this to minimize and optimize the database is by adding a two line of code on config.php</p>\n\n<pre><code>define('AUTOSAVE_INTERVAL', 300 ); //seconds (default is 60)\ndefine('WP_POST_REVISIONS', 5 ); //alter number of post revisions kept.\n</code></pre>\n\n<ul>\n<li>the constant ‘AUTOSAVE_INTERVAL’ represents the delay between the two autosaves in seconds.</li>\n<li>the constant ‘WP_POST_REVISIONS’ a record of each saved draft or published update. </li>\n</ul>\n\n<p>you can also use <a href=\"https://wordpress.org/plugins/wp-optimize/\" rel=\"nofollow noreferrer\">wp-optimize</a> plugin to optimize your Database and cleaning your WordPress database so that it runs at maximum efficiency.</p>\n"
}
]
| 2017/05/02 | [
"https://wordpress.stackexchange.com/questions/265568",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118777/"
]
| Is there any way through which I can declare the dynamic variable in php.
for eg, I am using a for loop and the variable name is $message. and I want to add some dynamic data at the end of the variable name. code is below
```
foreach ($quant as $quantity) {
$message.$quantity['type'] = 'Listing ID : '.$quantity['product_id'].' With Quantity: '.$quantity['quantity'].'MT, State- '.$quantity['state_name'].' and Coal type-'.$quantity['coal_type'].'<br>';
}
```
so if the $quantity['type'] = 1, then the variable name should be $message1 and so on. currently I am trying to concatenate but it is wrong. Please tell me how it can be corrected. Thanks in advance | One thing you can do to help reduce the amount of bloat is add a plugin that controls the number of previous revisions kept for Pages, Posts, etc (preferably one that allows for separate values for each type, such as last 5 revisions for pages and last 20 revisions for posts, or whatever.)
There are numerous plugins that handle this, check around <https://wordpress.org/plugins/search/revision+control/> and similar |
265,572 | <p>I was trying to remove a div having some ID from the_content WordPress.
I am trying to achieve something like this</p>
<pre><code>jQuery( "#some_id" ).remove();
</code></pre>
<p>but on server side,</p>
<p>I don't have a clue how I can do this on server side within the_content filter hook.</p>
<pre><code>add_filter( 'the_content', 'my_the_content_filter', 20 );
function my_the_content_filter( $content ) {
$content.find('#some_id').remove();
return $content;
}
</code></pre>
| [
{
"answer_id": 265530,
"author": "Scott R. Godin",
"author_id": 118816,
"author_profile": "https://wordpress.stackexchange.com/users/118816",
"pm_score": 2,
"selected": false,
"text": "<p>One thing you can do to help reduce the amount of bloat is add a plugin that controls the number of previous revisions kept for Pages, Posts, etc (preferably one that allows for separate values for each type, such as last 5 revisions for pages and last 20 revisions for posts, or whatever.)</p>\n\n<p>There are numerous plugins that handle this, check around <a href=\"https://wordpress.org/plugins/search/revision+control/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/search/revision+control/</a> and similar</p>\n"
},
{
"answer_id": 265540,
"author": "Aishan",
"author_id": 89530,
"author_profile": "https://wordpress.stackexchange.com/users/89530",
"pm_score": 1,
"selected": false,
"text": "<p>The thing i do for this to minimize and optimize the database is by adding a two line of code on config.php</p>\n\n<pre><code>define('AUTOSAVE_INTERVAL', 300 ); //seconds (default is 60)\ndefine('WP_POST_REVISIONS', 5 ); //alter number of post revisions kept.\n</code></pre>\n\n<ul>\n<li>the constant ‘AUTOSAVE_INTERVAL’ represents the delay between the two autosaves in seconds.</li>\n<li>the constant ‘WP_POST_REVISIONS’ a record of each saved draft or published update. </li>\n</ul>\n\n<p>you can also use <a href=\"https://wordpress.org/plugins/wp-optimize/\" rel=\"nofollow noreferrer\">wp-optimize</a> plugin to optimize your Database and cleaning your WordPress database so that it runs at maximum efficiency.</p>\n"
}
]
| 2017/05/02 | [
"https://wordpress.stackexchange.com/questions/265572",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118848/"
]
| I was trying to remove a div having some ID from the\_content WordPress.
I am trying to achieve something like this
```
jQuery( "#some_id" ).remove();
```
but on server side,
I don't have a clue how I can do this on server side within the\_content filter hook.
```
add_filter( 'the_content', 'my_the_content_filter', 20 );
function my_the_content_filter( $content ) {
$content.find('#some_id').remove();
return $content;
}
``` | One thing you can do to help reduce the amount of bloat is add a plugin that controls the number of previous revisions kept for Pages, Posts, etc (preferably one that allows for separate values for each type, such as last 5 revisions for pages and last 20 revisions for posts, or whatever.)
There are numerous plugins that handle this, check around <https://wordpress.org/plugins/search/revision+control/> and similar |
265,573 | <p>I have a function that runs with user input variable (comma separated numeric string) to update the terms (by id) in a custom taxonomy on a custom post type. Even though <a href="https://codex.wordpress.org/Function_Reference/wp_set_post_terms" rel="nofollow noreferrer">the docs say</a> I should use <code>wp_set_object_terms</code>, I can only get my terms to update by using <code>wp_set_post_terms</code>. The following code will work (using <code>wp_set_post_terms</code> but not using <code>wp_set_object_terms</code> at the end):</p>
<pre><code>if(isset($request['custom_tax'])) {
$customtaxarray = explode(",",$request['custom_tax']);
$only_integers = true;
foreach ($customtaxarray as $testcase) {
if (!ctype_digit($testcase)) {
$only_integers = false;
}
}
if ($only_integers) {
$customtax = $customtaxarray;
} else {
return array(
'code' => 'missing_integers',
'data' => array(
'status' => 403,
'message' => "custom_tax must be one or more (comma separated) integers.",
),
);
}
//update custom_tax
wp_set_post_terms($request['cpt_post_id'], $customtax, 'custom_tax' );
}
</code></pre>
| [
{
"answer_id": 265577,
"author": "Stephen",
"author_id": 11023,
"author_profile": "https://wordpress.stackexchange.com/users/11023",
"pm_score": 3,
"selected": true,
"text": "<p>After much trial and error, I have found a solution that will allow wp_set_object_terms to be used. Despite already checking if my strings were integers, apparently I needed to convert the array explicitly as well. So I changed this:</p>\n\n<p><code>$customtax = $customtaxarray;</code></p>\n\n<p>to this:</p>\n\n<p><code>$customtax = array_map('intval',$customtaxarray);</code></p>\n\n<p>and suddenly <code>wp_set_object_terms</code> now works. That does not explain why <code>wp_set_post_terms</code> was working instead (unless perhaps it does this conversion automatically?), but at least this is now working as expected. </p>\n"
},
{
"answer_id": 413467,
"author": "Onotolij",
"author_id": 229675,
"author_profile": "https://wordpress.stackexchange.com/users/229675",
"pm_score": 0,
"selected": false,
"text": "<p>It is important to observe the data types!\nThis is a working code:</p>\n<pre><code>wp_set_object_terms((int)$id, array_map('intval',$relation), 'product_cat');\n</code></pre>\n"
}
]
| 2017/05/02 | [
"https://wordpress.stackexchange.com/questions/265573",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/11023/"
]
| I have a function that runs with user input variable (comma separated numeric string) to update the terms (by id) in a custom taxonomy on a custom post type. Even though [the docs say](https://codex.wordpress.org/Function_Reference/wp_set_post_terms) I should use `wp_set_object_terms`, I can only get my terms to update by using `wp_set_post_terms`. The following code will work (using `wp_set_post_terms` but not using `wp_set_object_terms` at the end):
```
if(isset($request['custom_tax'])) {
$customtaxarray = explode(",",$request['custom_tax']);
$only_integers = true;
foreach ($customtaxarray as $testcase) {
if (!ctype_digit($testcase)) {
$only_integers = false;
}
}
if ($only_integers) {
$customtax = $customtaxarray;
} else {
return array(
'code' => 'missing_integers',
'data' => array(
'status' => 403,
'message' => "custom_tax must be one or more (comma separated) integers.",
),
);
}
//update custom_tax
wp_set_post_terms($request['cpt_post_id'], $customtax, 'custom_tax' );
}
``` | After much trial and error, I have found a solution that will allow wp\_set\_object\_terms to be used. Despite already checking if my strings were integers, apparently I needed to convert the array explicitly as well. So I changed this:
`$customtax = $customtaxarray;`
to this:
`$customtax = array_map('intval',$customtaxarray);`
and suddenly `wp_set_object_terms` now works. That does not explain why `wp_set_post_terms` was working instead (unless perhaps it does this conversion automatically?), but at least this is now working as expected. |
265,603 | <p><strong>Is there a way to extend the Wordpress Customizer, in order to enable multiple selections?</strong></p>
<p>This looks like what I want:
<a href="https://github.com/lucatume/multi-image-control" rel="nofollow noreferrer">https://github.com/lucatume/multi-image-control</a>. I don't get it to work. It only shows <code>add</code> button and <code>remove</code> button but they don't do anything.</p>
<p>Is there another existing extension script that I can use?</p>
| [
{
"answer_id": 266407,
"author": "Tom Groot",
"author_id": 118863,
"author_profile": "https://wordpress.stackexchange.com/users/118863",
"pm_score": 4,
"selected": true,
"text": "<p>What I eventually did was <strong>extending the <code>WP_Customize_Control</code></strong> class as follows:</p>\n\n<pre><code><?php\n\nif (!class_exists('WP_Customize_Image_Control')) {\n return null;\n}\n\nclass Multi_Image_Custom_Control extends WP_Customize_Control\n{\n public function enqueue()\n {\n wp_enqueue_style('multi-image-style', get_template_directory_uri().'/css/multi-image.css');\n wp_enqueue_script('multi-image-script', get_template_directory_uri().'/js/multi-image.js', array( 'jquery' ), rand(), true);\n }\n\n public function render_content()\n { ?>\n <label>\n <span class='customize-control-title'>Image</span>\n </label>\n <div>\n <ul class='images'></ul>\n </div>\n <div class='actions'>\n <a class=\"button-secondary upload\">Add</a>\n </div>\n\n <input class=\"wp-editor-area\" id=\"images-input\" type=\"hidden\" <?php $this->link(); ?>>\n <?php\n }\n}\n?>\n</code></pre>\n\n<p>I use javascript to open the WP media selector when the user clicks on 'Add'. When an image is selected, the image must appear inside <code><ul class='images'></ul></code>. Furthermore the user needs to be able to remove an image by clicking on an image. I made the following <strong>javascript file</strong>: </p>\n\n<pre><code>( function( $ ) {\n\n $(window).load(function(){\n var begin_attachment_string = $(\"#images-input\").val();\n var begin_attachment_array = begin_attachment_string.split(\",\");\n for(var i = 0; i < begin_attachment_array.length; i++){\n if(begin_attachment_array[i] != \"\"){\n $(\".images\").append( \"<li class='image-list'><img src='\"+begin_attachment_array[i]+\"'></li>\" );\n }\n }\n $(\".button-secondary.upload\").click(function(){\n var custom_uploader = wp.media.frames.file_frame = wp.media({\n multiple: true\n });\n\n custom_uploader.on('select', function() {\n var selection = custom_uploader.state().get('selection');\n var attachments = [];\n selection.map( function( attachment ) {\n attachment = attachment.toJSON();\n $(\".images\").append( \"<li class='image-list'><img src='\"+attachment.url+\"'></li>\" );\n attachments.push(attachment.url);\n //\n });\n var attachment_string = attachments.join() + \",\" + $('#images-input').val();\n $('#images-input').val(attachment_string).trigger('change');\n });\n custom_uploader.open();\n });\n\n $(\".images\").click(function(){\n var img_src = $(event.target).find(\"img\").attr('src');\n $(event.target).closest(\"li\").remove();\n var attachment_string = $('#images-input').val();\n attachment_string = attachment_string.replace(img_src+\",\", \"\");\n $('#images-input').val(attachment_string).trigger('change');\n });\n });\n\n} )( jQuery );\n</code></pre>\n\n<p>At last, I added <strong>some CSS</strong>:</p>\n\n<pre><code>.image-list{\n width: 100%;\n height: 150px;\n background-position: center;\n background-size: cover;\n background-repeat: no-repeat;\n -webkit-box-shadow: inset 0 0 15px rgba(0,0,0,.1), inset 0 0 0 1px rgba(0,0,0,.05);\n box-shadow: inset 0 0 15px rgba(0,0,0,.1), inset 0 0 0 1px rgba(0,0,0,.05);\n background: #eee;\n cursor: pointer;\n vertical-align: middle;\n display:flex;\n justify-content:center;\n align-items:center;\n overflow: hidden;\n position: relative;\n}\n.image-list:before{\n content: '';\n position: absolute;\n display: none;\n top: 0px;\n right: 0px;\n left: 0px;\n bottom: 0px;\n box-shadow: inset 0 0 0 1px #fff, inset 0 0 0 5px #c60c31;\n}\n.image-list:hover:before{\n display: block;\n}\n</code></pre>\n"
},
{
"answer_id": 393943,
"author": "Ben Sevcik",
"author_id": 210848,
"author_profile": "https://wordpress.stackexchange.com/users/210848",
"pm_score": 0,
"selected": false,
"text": "<p>@tom-groot this worked for me, but I tweaked it a few ways. This saves ids instead of the full url, removes the trailing comma, and avoids using "event" since it's deprecated.</p>\n<p>Javascript:</p>\n<pre><code> "use strict";\n $(window).load(function () {\n /*\n * Show photos on load\n */\n var begin_attachment_string = $("#images-input").val();\n var begin_attachment_array = begin_attachment_string.split(",");\n\n // get all attachments\n var promises = [];\n for (var i = 0; i < begin_attachment_array.length; i++) {\n var id = begin_attachment_array[i];\n if (id != "") {\n promises[i] = wp.media.attachment(id).fetch();\n }\n }\n // wait until they all finish since it's async\n Promise.all(promises)\n // add the images into the dom\n .then(function() {\n for (var i = 0; i < begin_attachment_array.length; i++) {\n var id = begin_attachment_array[i];\n if (begin_attachment_array[i] != "") {\n $(".images").append(\n "<li class='image-list'><img src='" +\n wp.media.attachment(id).get("url") +\n "' data-id='" +\n id +\n "'></li>"\n );\n }\n }\n })\n\n\n /*\n * Add Photos\n */\n $(".button-secondary.upload").click(function () {\n var custom_uploader = (wp.media.frames.file_frame = wp.media({\n multiple: true,\n }));\n\n custom_uploader.on("select", function () {\n var selection = custom_uploader.state().get("selection");\n var attachments = [];\n selection.map(function (attachment) {\n attachment = attachment.toJSON();\n $(".images").append(\n "<li class='image-list'><img src='" +\n attachment.url +\n "' data-id='" +\n attachment.id +\n "'></li>"\n );\n attachments.push(attachment.id);\n });\n var previous = $("#images-input").val() ? "," + $("#images-input").val() : ""; // get rid of trailing commas\n var attachment_string = attachments.join() + previous;\n $("#images-input").val(attachment_string).trigger("change");\n });\n custom_uploader.open();\n });\n\n\n /*\n * Remove images when you click on an image\n */\n $(".images").click(function (e) {\n var img_id = $(e.target).find("img").attr("data-id");\n $(e.target).closest("li").remove();\n var attachment_string = $("#images-input").val();\n attachment_string = attachment_string.replace(img_id, "");\n attachment_string = attachment_string.replaceAll(",,", ","); // get rid of duplicate commas\n attachment_string = attachment_string.replace(/^,+|,+$/g, ""); // get rid of leading or trailing commans\n $("#images-input").val(attachment_string).trigger("change");\n });\n });\n})(jQuery);\n</code></pre>\n<p>The php to call it:</p>\n<pre><code>\nfunction register_customize_sections( $wp_customize ) {\n \n $wp_customize->add_section( 'image_selector_section', array(\n 'title'=> __( 'Image Selector Section', 'TextDomain' ),\n 'priority' => 201\n ) );\n\n $wp_customize->add_setting( \n 'multi_image_selector', \n array(\n 'default' => array(),\n 'transport' => 'refresh',\n ) \n );\n\n $wp_customize->add_control( new Multi_Image_Custom_Control (\n $wp_customize,\n 'multi_image_selector',\n array(\n 'description' => 'Select One or Multiple Images',\n 'section' => 'image_selector_section',\n )\n ) );\n}\nadd_action('customize_register', 'register_customize_sections');```\n\n\n</code></pre>\n"
}
]
| 2017/05/02 | [
"https://wordpress.stackexchange.com/questions/265603",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118863/"
]
| **Is there a way to extend the Wordpress Customizer, in order to enable multiple selections?**
This looks like what I want:
<https://github.com/lucatume/multi-image-control>. I don't get it to work. It only shows `add` button and `remove` button but they don't do anything.
Is there another existing extension script that I can use? | What I eventually did was **extending the `WP_Customize_Control`** class as follows:
```
<?php
if (!class_exists('WP_Customize_Image_Control')) {
return null;
}
class Multi_Image_Custom_Control extends WP_Customize_Control
{
public function enqueue()
{
wp_enqueue_style('multi-image-style', get_template_directory_uri().'/css/multi-image.css');
wp_enqueue_script('multi-image-script', get_template_directory_uri().'/js/multi-image.js', array( 'jquery' ), rand(), true);
}
public function render_content()
{ ?>
<label>
<span class='customize-control-title'>Image</span>
</label>
<div>
<ul class='images'></ul>
</div>
<div class='actions'>
<a class="button-secondary upload">Add</a>
</div>
<input class="wp-editor-area" id="images-input" type="hidden" <?php $this->link(); ?>>
<?php
}
}
?>
```
I use javascript to open the WP media selector when the user clicks on 'Add'. When an image is selected, the image must appear inside `<ul class='images'></ul>`. Furthermore the user needs to be able to remove an image by clicking on an image. I made the following **javascript file**:
```
( function( $ ) {
$(window).load(function(){
var begin_attachment_string = $("#images-input").val();
var begin_attachment_array = begin_attachment_string.split(",");
for(var i = 0; i < begin_attachment_array.length; i++){
if(begin_attachment_array[i] != ""){
$(".images").append( "<li class='image-list'><img src='"+begin_attachment_array[i]+"'></li>" );
}
}
$(".button-secondary.upload").click(function(){
var custom_uploader = wp.media.frames.file_frame = wp.media({
multiple: true
});
custom_uploader.on('select', function() {
var selection = custom_uploader.state().get('selection');
var attachments = [];
selection.map( function( attachment ) {
attachment = attachment.toJSON();
$(".images").append( "<li class='image-list'><img src='"+attachment.url+"'></li>" );
attachments.push(attachment.url);
//
});
var attachment_string = attachments.join() + "," + $('#images-input').val();
$('#images-input').val(attachment_string).trigger('change');
});
custom_uploader.open();
});
$(".images").click(function(){
var img_src = $(event.target).find("img").attr('src');
$(event.target).closest("li").remove();
var attachment_string = $('#images-input').val();
attachment_string = attachment_string.replace(img_src+",", "");
$('#images-input').val(attachment_string).trigger('change');
});
});
} )( jQuery );
```
At last, I added **some CSS**:
```
.image-list{
width: 100%;
height: 150px;
background-position: center;
background-size: cover;
background-repeat: no-repeat;
-webkit-box-shadow: inset 0 0 15px rgba(0,0,0,.1), inset 0 0 0 1px rgba(0,0,0,.05);
box-shadow: inset 0 0 15px rgba(0,0,0,.1), inset 0 0 0 1px rgba(0,0,0,.05);
background: #eee;
cursor: pointer;
vertical-align: middle;
display:flex;
justify-content:center;
align-items:center;
overflow: hidden;
position: relative;
}
.image-list:before{
content: '';
position: absolute;
display: none;
top: 0px;
right: 0px;
left: 0px;
bottom: 0px;
box-shadow: inset 0 0 0 1px #fff, inset 0 0 0 5px #c60c31;
}
.image-list:hover:before{
display: block;
}
``` |
265,614 | <p>I'd like to remove, or at least hide, the Order field from the Page Attributes box. Anyone have a way to go about do this?</p>
<p><img src="https://i.stack.imgur.com/ykpQb.png" alt="order"></p>
| [
{
"answer_id": 265626,
"author": "wp.ryan.b",
"author_id": 49571,
"author_profile": "https://wordpress.stackexchange.com/users/49571",
"pm_score": 1,
"selected": false,
"text": "<p>I went with jQuery to remove the elements.</p>\n\n<pre><code>jQuery(document).ready(function() {\n jQuery('#pageparentdiv label[for=menu_order]').parents('p').eq(0).remove();\n jQuery('#pageparentdiv input#menu_order').remove();\n});\n</code></pre>\n"
},
{
"answer_id": 265647,
"author": "Aishan",
"author_id": 89530,
"author_profile": "https://wordpress.stackexchange.com/users/89530",
"pm_score": 1,
"selected": false,
"text": "<p>if you really just want to hide it from displaying or completely remove it. It’s a part of core Page Attribute Metabox which could'nt be remove permanently \nbut this should help get you going in the right direction.</p>\n\n<pre><code>add_action('admin_head', 'hide_order_attribution');\nfunction hide_order_attribution() {\n echo '<style>\n label[for=\"menu_order\"],\n input[name=\"menu_order\"] {\n display:none;\n }\n </style>';\n} \n</code></pre>\n"
},
{
"answer_id": 381756,
"author": "Yaakov Klein",
"author_id": 164213,
"author_profile": "https://wordpress.stackexchange.com/users/164213",
"pm_score": 0,
"selected": false,
"text": "<p>I like the answer <a href=\"https://wordpress.stackexchange.com/a/265647/164213\">above</a>\nBut if you wont that it work also with Gutenberg you must to add this selector: <code>.components-base-control.editor-page-attributes__order</code></p>\n<pre><code> add_action('admin_head', 'hide_order_attribution');\n function hide_order_attribution() {\n echo '<style>\n label[for="menu_order"],\n input[name="menu_order"],\n .components-base-control.editor-page-attributes__order {\n display:none;\n }\n </style>';\n } \n</code></pre>\n"
},
{
"answer_id": 405220,
"author": "mrwweb",
"author_id": 9844,
"author_profile": "https://wordpress.stackexchange.com/users/9844",
"pm_score": 0,
"selected": false,
"text": "<p>If seeking to hide it in the WordPress block editor, the following CSS loaded into the admin works:</p>\n<pre><code>.editor-page-attributes__order {\n display: none;\n}\n</code></pre>\n<p>I'm sure there's a more complicated JavaScript approach, but this meets my needs.</p>\n"
}
]
| 2017/05/02 | [
"https://wordpress.stackexchange.com/questions/265614",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/49571/"
]
| I'd like to remove, or at least hide, the Order field from the Page Attributes box. Anyone have a way to go about do this?
 | I went with jQuery to remove the elements.
```
jQuery(document).ready(function() {
jQuery('#pageparentdiv label[for=menu_order]').parents('p').eq(0).remove();
jQuery('#pageparentdiv input#menu_order').remove();
});
``` |
265,656 | <p>I think that everything is in the title. I would like to find a way to change the status of a post to "pending" when the post is updated when the user is an "author". I already tried with differents plugin but none of them worked. I'm new to wordpress so i don't really understand how am i suppose to modify the code to get this feature.</p>
<p>Thx for your help !</p>
<p>(Sorry for my english)</p>
| [
{
"answer_id": 265659,
"author": "Aishan",
"author_id": 89530,
"author_profile": "https://wordpress.stackexchange.com/users/89530",
"pm_score": 0,
"selected": false,
"text": "<p>The user with author role is somebody who can publish and manage their own posts. So you can't change \nthe default capability of your author user to disable publish post. \nYou can set all users (authors) to contributors. Then they can only write posts and manage their posts but not publish them.</p>\n\n<p>For reference : <a href=\"https://codex.wordpress.org/Roles_and_Capabilities\" rel=\"nofollow noreferrer\">Roles and Capabilities</a></p>\n"
},
{
"answer_id": 265661,
"author": "BlueSuiter",
"author_id": 92665,
"author_profile": "https://wordpress.stackexchange.com/users/92665",
"pm_score": 3,
"selected": true,
"text": "<p>It is possible to <strong>stop author to publish post</strong>, and force him to <strong>Submit For Preview</strong>. Just add this code to your <code>functions.php</code> and you are all done.</p>\n\n<pre><code><?php\n function take_away_publish_permissions() {\n $user = get_role('author');\n $user->add_cap('publish_posts',false);\n }\n add_action('init', 'take_away_publish_permissions' );\n?>\n</code></pre>\n\n<p>** Updated Code ** \n<em>This code shared here is for setting post status to preview or pending whenever a author update a post.</em></p>\n\n<pre><code>function postPending($post_ID)\n { \n if(get_role('author'))\n {\n //Unhook this function\n remove_action('post_updated', 'postPending', 10, 3);\n\n return wp_update_post(array('ID' => $post_ID, 'post_status' => 'pending'));\n\n // re-hook this function\n add_action( 'post_updated', 'postPending', 10, 3 );\n }\n }\nadd_action('post_updated', 'postPending', 10, 3);\n</code></pre>\n\n<p><strong>NOTE:</strong> If you are calling a function such as wp_update_post that \nincludes the save_post hook, your hooked function will create an infinite loop. To avoid this, unhook your function before calling the \nfunction you need, then re-hook it afterward. For details look into this <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/save_post\" rel=\"nofollow noreferrer\">link</a></p>\n"
}
]
| 2017/05/03 | [
"https://wordpress.stackexchange.com/questions/265656",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118909/"
]
| I think that everything is in the title. I would like to find a way to change the status of a post to "pending" when the post is updated when the user is an "author". I already tried with differents plugin but none of them worked. I'm new to wordpress so i don't really understand how am i suppose to modify the code to get this feature.
Thx for your help !
(Sorry for my english) | It is possible to **stop author to publish post**, and force him to **Submit For Preview**. Just add this code to your `functions.php` and you are all done.
```
<?php
function take_away_publish_permissions() {
$user = get_role('author');
$user->add_cap('publish_posts',false);
}
add_action('init', 'take_away_publish_permissions' );
?>
```
\*\* Updated Code \*\*
*This code shared here is for setting post status to preview or pending whenever a author update a post.*
```
function postPending($post_ID)
{
if(get_role('author'))
{
//Unhook this function
remove_action('post_updated', 'postPending', 10, 3);
return wp_update_post(array('ID' => $post_ID, 'post_status' => 'pending'));
// re-hook this function
add_action( 'post_updated', 'postPending', 10, 3 );
}
}
add_action('post_updated', 'postPending', 10, 3);
```
**NOTE:** If you are calling a function such as wp\_update\_post that
includes the save\_post hook, your hooked function will create an infinite loop. To avoid this, unhook your function before calling the
function you need, then re-hook it afterward. For details look into this [link](https://codex.wordpress.org/Plugin_API/Action_Reference/save_post) |
265,671 | <p>I have a question which i can't sort out.</p>
<p>I'm having 1 WordPress installation on one main domain. But now I have many more domains refering to the main domain. What I want now is the following:</p>
<ul>
<li>When people go to the main domain "www.a.com" the logo "a.com" needs to show.</li>
<li>When people go the another domain for example "www.b.com" which refers to "www.a.com" the logo "b.com" needs to show. </li>
</ul>
<p>I can't figure out how to do this.</p>
<p>Maybe you guys can help me with this?</p>
| [
{
"answer_id": 265659,
"author": "Aishan",
"author_id": 89530,
"author_profile": "https://wordpress.stackexchange.com/users/89530",
"pm_score": 0,
"selected": false,
"text": "<p>The user with author role is somebody who can publish and manage their own posts. So you can't change \nthe default capability of your author user to disable publish post. \nYou can set all users (authors) to contributors. Then they can only write posts and manage their posts but not publish them.</p>\n\n<p>For reference : <a href=\"https://codex.wordpress.org/Roles_and_Capabilities\" rel=\"nofollow noreferrer\">Roles and Capabilities</a></p>\n"
},
{
"answer_id": 265661,
"author": "BlueSuiter",
"author_id": 92665,
"author_profile": "https://wordpress.stackexchange.com/users/92665",
"pm_score": 3,
"selected": true,
"text": "<p>It is possible to <strong>stop author to publish post</strong>, and force him to <strong>Submit For Preview</strong>. Just add this code to your <code>functions.php</code> and you are all done.</p>\n\n<pre><code><?php\n function take_away_publish_permissions() {\n $user = get_role('author');\n $user->add_cap('publish_posts',false);\n }\n add_action('init', 'take_away_publish_permissions' );\n?>\n</code></pre>\n\n<p>** Updated Code ** \n<em>This code shared here is for setting post status to preview or pending whenever a author update a post.</em></p>\n\n<pre><code>function postPending($post_ID)\n { \n if(get_role('author'))\n {\n //Unhook this function\n remove_action('post_updated', 'postPending', 10, 3);\n\n return wp_update_post(array('ID' => $post_ID, 'post_status' => 'pending'));\n\n // re-hook this function\n add_action( 'post_updated', 'postPending', 10, 3 );\n }\n }\nadd_action('post_updated', 'postPending', 10, 3);\n</code></pre>\n\n<p><strong>NOTE:</strong> If you are calling a function such as wp_update_post that \nincludes the save_post hook, your hooked function will create an infinite loop. To avoid this, unhook your function before calling the \nfunction you need, then re-hook it afterward. For details look into this <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/save_post\" rel=\"nofollow noreferrer\">link</a></p>\n"
}
]
| 2017/05/03 | [
"https://wordpress.stackexchange.com/questions/265671",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118918/"
]
| I have a question which i can't sort out.
I'm having 1 WordPress installation on one main domain. But now I have many more domains refering to the main domain. What I want now is the following:
* When people go to the main domain "www.a.com" the logo "a.com" needs to show.
* When people go the another domain for example "www.b.com" which refers to "www.a.com" the logo "b.com" needs to show.
I can't figure out how to do this.
Maybe you guys can help me with this? | It is possible to **stop author to publish post**, and force him to **Submit For Preview**. Just add this code to your `functions.php` and you are all done.
```
<?php
function take_away_publish_permissions() {
$user = get_role('author');
$user->add_cap('publish_posts',false);
}
add_action('init', 'take_away_publish_permissions' );
?>
```
\*\* Updated Code \*\*
*This code shared here is for setting post status to preview or pending whenever a author update a post.*
```
function postPending($post_ID)
{
if(get_role('author'))
{
//Unhook this function
remove_action('post_updated', 'postPending', 10, 3);
return wp_update_post(array('ID' => $post_ID, 'post_status' => 'pending'));
// re-hook this function
add_action( 'post_updated', 'postPending', 10, 3 );
}
}
add_action('post_updated', 'postPending', 10, 3);
```
**NOTE:** If you are calling a function such as wp\_update\_post that
includes the save\_post hook, your hooked function will create an infinite loop. To avoid this, unhook your function before calling the
function you need, then re-hook it afterward. For details look into this [link](https://codex.wordpress.org/Plugin_API/Action_Reference/save_post) |
265,733 | <p>I'm wondering when does WordPress initiate its main query which sets the global <code>$wp_query</code> and enable us to use <code>has_posts()</code> and <code>the_post()</code> functions. If I create a page using archive template, how does it know how to set its query?</p>
<p>I'm looking at the <em>archive.php</em> in one of the WordPress default themes. They have an archive page but it just calls <code>get_header()</code> and <code>has_posts()</code>, so that means the query is already set. So WordPress routes the url to use the custom post type param in the URL?</p>
<p>If I choose to make custom archive pages, where do I modify the main query? In the new archive template file?</p>
| [
{
"answer_id": 265737,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": false,
"text": "<p>After plugins and theme functions are loaded, WordPress parses the incoming request into query variables, by going through the list of rewrite rules to find a pattern that matches the request.</p>\n\n<p>There are a number of default rules for the built in types- pages, various archives, single views, pagination, feeds. You can add your own rules or endpoints manually, or register new content types which can auto-generate all those rules for your custom content.</p>\n\n<p>Once the request is converted to query variables, the query is run. In many cases, the results of the query are what determine which template gets loaded.</p>\n\n<p>Then of course the template is loaded, and everything is good.</p>\n\n<p>So that said, there are a number of actions and filters available to let you modify things at every step. To see a more detailed view of the process and what some of those things are, have a look at the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_a_Typical_Request\" rel=\"nofollow noreferrer\">Action Reference</a>.</p>\n\n<p>The simplest and most common method is the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow noreferrer\"><code>pre_get_posts</code> action</a>. This exposes the query variables and lets you modify things before the query is run. See <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\"><code>WP_Query</code></a> for a reference of query vars.</p>\n\n<p>If that doesn't satisfy your needs, have a look at the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/request\" rel=\"nofollow noreferrer\"><code>request</code> filter</a>, which allows more radical query manipulation, as it runs directly after query var extraction, before WordPress has made any decisions about the type of request that's happening.</p>\n"
},
{
"answer_id": 265738,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 3,
"selected": true,
"text": "<p>User <a href=\"https://wordpress.stackexchange.com/users/847/rarst\">Rarst</a> has a <a href=\"https://wordpress.stackexchange.com/a/26622/7355\">very famous answer</a> where he lays out <a href=\"https://i.imgur.com/SqQQE.png\" rel=\"nofollow noreferrer\">the load process</a>. Looking at this graph whenever <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-blog-header.php\" rel=\"nofollow noreferrer\"><code>wp-blog-header.php</code></a> gets loaded it calls function <code>wp()</code> which sets up many of WordPress globals like <code>$post</code> and <code>$wp_query</code>. ( <a href=\"https://wordpress.stackexchange.com/a/165736/7355\">Secondary Reference</a> by User <a href=\"https://wordpress.stackexchange.com/users/35541/gmazzap\">Gmazzap</a> )</p>\n\n<p>That's the technical side of things but it looks like the core of your questions is creating your own custom archive pages. WordPress has a <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">Template Hierarchy</a> which allows you to create <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/#custom-post-types\" rel=\"nofollow noreferrer\">custom archives</a> for things like Custom Post Types.</p>\n\n<p>Another common way to modify the main query is to use a <a href=\"https://developer.wordpress.org/plugins/hooks/\" rel=\"nofollow noreferrer\">Hook</a> in your functions.php file called <a href=\"https://developer.wordpress.org/reference/hooks/pre_get_posts/\" rel=\"nofollow noreferrer\"><code>pre_get_posts</code></a>. This will let you modify the query object before WordPress actually pings to database to get the information which makes it very easy to modify The Loop with different settings. An example could look like this which would modify The Loop to show 20 posts instead of the default 10:</p>\n\n<pre><code>function wpse_265733( $query ) {\n\n // Don't run on admin\n if( $query->is_admin ) {\n return;\n }\n\n // Run only on the blog page\n if( is_home() ) {\n $query->set( 'posts_per_page', 20 ); // Set posts per page to 20.\n }\n\n}\nadd_action( 'pre_get_posts', 'wpse_265733' );\n</code></pre>\n"
}
]
| 2017/05/03 | [
"https://wordpress.stackexchange.com/questions/265733",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/117263/"
]
| I'm wondering when does WordPress initiate its main query which sets the global `$wp_query` and enable us to use `has_posts()` and `the_post()` functions. If I create a page using archive template, how does it know how to set its query?
I'm looking at the *archive.php* in one of the WordPress default themes. They have an archive page but it just calls `get_header()` and `has_posts()`, so that means the query is already set. So WordPress routes the url to use the custom post type param in the URL?
If I choose to make custom archive pages, where do I modify the main query? In the new archive template file? | User [Rarst](https://wordpress.stackexchange.com/users/847/rarst) has a [very famous answer](https://wordpress.stackexchange.com/a/26622/7355) where he lays out [the load process](https://i.imgur.com/SqQQE.png). Looking at this graph whenever [`wp-blog-header.php`](https://github.com/WordPress/WordPress/blob/master/wp-blog-header.php) gets loaded it calls function `wp()` which sets up many of WordPress globals like `$post` and `$wp_query`. ( [Secondary Reference](https://wordpress.stackexchange.com/a/165736/7355) by User [Gmazzap](https://wordpress.stackexchange.com/users/35541/gmazzap) )
That's the technical side of things but it looks like the core of your questions is creating your own custom archive pages. WordPress has a [Template Hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/) which allows you to create [custom archives](https://developer.wordpress.org/themes/basics/template-hierarchy/#custom-post-types) for things like Custom Post Types.
Another common way to modify the main query is to use a [Hook](https://developer.wordpress.org/plugins/hooks/) in your functions.php file called [`pre_get_posts`](https://developer.wordpress.org/reference/hooks/pre_get_posts/). This will let you modify the query object before WordPress actually pings to database to get the information which makes it very easy to modify The Loop with different settings. An example could look like this which would modify The Loop to show 20 posts instead of the default 10:
```
function wpse_265733( $query ) {
// Don't run on admin
if( $query->is_admin ) {
return;
}
// Run only on the blog page
if( is_home() ) {
$query->set( 'posts_per_page', 20 ); // Set posts per page to 20.
}
}
add_action( 'pre_get_posts', 'wpse_265733' );
``` |
265,740 | <p>I was just wondering if it's possible somehow <em>(via an addon maybe?)</em> to set the initial focus when the WordPress media library pops up to be the search field?</p>
<p>I have a lot of posts where I need to select images very fast and need to type in the names of the images to find them and this would be exceptionally handy except I've looked on Wordpress.org and a few other places that I know of and can't find a plugin that can do this although someone here might know of one or perhaps a way of doing this?</p>
<p>Many thanks in advance,</p>
<p>Best wishes,</p>
<p>Mark</p>
| [
{
"answer_id": 265744,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 3,
"selected": true,
"text": "<p>Here's some code that will set the focus to the search field when clicking on the <kbd>Add Media</kbd> button or when opening the media modal when setting a featured image. Add this code to your theme's <code>functions.php</code> or to a plugin to use it.</p>\n\n<p>Note: This is an updated version of my original solution. I think this one is a little more flexible and reliable because it leverages the WP Media API.</p>\n\n<pre><code>/**\n * When a wp.media Modal is opened, set the focus to the media toolbar's search field.\n */\nadd_action( 'admin_footer-post-new.php', 'wpse_media_library_search_focus' );\nadd_action( 'admin_footer-post.php', 'wpse_media_library_search_focus' );\nfunction wpse_media_library_search_focus() { ?>\n<script type=\"text/javascript\">\n ( function( $ ) {\n $( document ).ready( function() {\n\n // Ensure the wp.media object is set, otherwise we can't do anything.\n if ( wp.media ) {\n\n // Ensure that the Modal is ready. This approach resolves the \n // need for timers which were used in a previous version of my answer\n // due to the modal not being ready yet.\n wp.media.view.Modal.prototype.on( \"ready\", function() {\n // console.log( \"media modal ready\" );\n\n // Execute this code when a Modal is opened.\n // via https://gist.github.com/soderlind/370720db977f27c20360\n wp.media.view.Modal.prototype.on( \"open\", function() {\n // console.log( \"media modal open\" );\n\n // Select the the .media-modal within the current backbone view,\n // find the search input, and set the focus.\n // http://stackoverflow.com/a/8934067/3059883\n $( \".media-modal\", this.el ).find( \"#media-search-input\" ).focus();\n });\n\n // Execute this code when a Modal is closed.\n wp.media.view.Modal.prototype.on( \"close\", function() {\n // console.log( \"media modal close\" );\n });\n });\n }\n\n });\n })( jQuery );\n</script><?php\n}\n</code></pre>\n\n<p>For posterity's sake, here is the original version that I posted. I think the version above is much better.</p>\n\n<pre><code>add_action( 'admin_footer-post-new.php', 'wpse_media_library_search_focus_old' );\nadd_action( 'admin_footer-post.php', 'wpse_media_library_search_focus_old' );\nfunction wpse_media_library_search_focus_old() {\n?>\n<script type=\"text/javascript\">\n(function($) {\n $(document).ready( function() {\n\n // Focus the search field for Posts\n // http://wordpress-hackers.1065353.n5.nabble.com/JavaScript-events-on-media-popup-td42941.html\n $(document.body).on( 'click', '.insert-media', function( event ) {\n wp.media.controller.Library.prototype.defaults.contentUserSetting = false;\n\n setTimeout(function(){\n $(\"[id^=__wp-uploader-id]\").each( function( index ) {\n if ( $(this).css('display') != 'none' ) {\n $(this).find(\"#media-search-input\").focus();\n }\n }); \n }, 20);\n\n }); \n\n // Focus the search field for Post Thumbnails\n $( '#set-post-thumbnail').on( 'click', function( event ) {\n wp.media.controller.FeaturedImage.prototype.defaults.contentUserSetting = true;\n setTimeout(function(){\n $(\"[id^=__wp-uploader-id]\").each( function( index ) {\n //alert( index + \": \" + value );\n if ( $(this).css('display') != 'none' ) {\n $(this).find(\"#media-search-input\").focus();\n }\n }); \n }, 20);\n\n }); \n });\n})(jQuery);\n</script><?php\n}\n</code></pre>\n"
},
{
"answer_id": 265753,
"author": "sMyles",
"author_id": 51201,
"author_profile": "https://wordpress.stackexchange.com/users/51201",
"pm_score": 0,
"selected": false,
"text": "<h2>First Method</h2>\n\n<p>This requires two parts, one to set the default tab as media library through filter, and one to add custom JS to set focus when Add Media is clicked</p>\n\n<p>1.) Set default tab as Media Library:</p>\n\n<pre><code>add_filter( 'media_upload_default_tab', 'smyles_set_default_media_tab' );\n\nfunction smyles_set_default_media_tab( $tab ){\n return 'library';\n}\n</code></pre>\n\n<p>2.) Add custom JS to set focus</p>\n\n<pre><code>add_action( 'admin_footer', 'smyles_set_default_media_focus' );\n\nfunction smyles_set_default_media_focus() {\n // Only output in footer when required\n if ( did_action( 'wp_enqueue_media' ) ):\n ?>\n <script type=\"text/javascript\">\n jQuery( document ).ready( function ( $ ) {\n\n $( document ).on( 'click', '.insert-media', function(){\n // Add slight delay before setting focus just in case\n setTimeout( function(){\n $( '#media-search-input' ).focus();\n }, 50 );\n });\n\n } );\n </script>\n <?php\n endif;\n}\n</code></pre>\n\n<h2>Second Method</h2>\n\n<p>The second method only requires one step, which adds JS that will automatically find the Media Library tab when Add Media is clicked, and click that tab, which will also automatically set focus on the search field.</p>\n\n<pre><code>add_action( 'admin_footer', 'smyles_set_default_media_focus_v2' );\n\nfunction smyles_set_default_media_focus_v2() {\n\n // Only execute when required\n if ( did_action( 'wp_enqueue_media' ) ):\n $tabs = media_upload_tabs();\n if( ! array_key_exists( 'library', $tabs ) ){\n return;\n }\n ?>\n <script type=\"text/javascript\">\n jQuery( document ).ready( function ( $ ) {\n\n $( document ).on( 'click', '.insert-media', function(){\n // Add slight delay for the modal to open\n setTimeout( function(){\n $( \"a:contains('<?php echo $tabs['library']; ?>')\" ).click();\n }, 50 );\n });\n\n } );\n </script>\n <?php\n endif;\n}\n</code></pre>\n\n<p>Voila! Profit!</p>\n"
},
{
"answer_id": 265899,
"author": "Mark Bowen",
"author_id": 118957,
"author_profile": "https://wordpress.stackexchange.com/users/118957",
"pm_score": 0,
"selected": false,
"text": "<p>With all thanks going to Dave Romsey for his above code I've now placed this into a quick plugin for WordPress incase anyone else ever needs anything like this.</p>\n\n<p>Thanks again Dave!</p>\n\n<p><strong>Download / Clone plugin</strong>\n<a href=\"https://github.com/MarkBowenPiano/media-library-search-focus\" rel=\"nofollow noreferrer\">https://github.com/MarkBowenPiano/media-library-search-focus</a></p>\n"
}
]
| 2017/05/03 | [
"https://wordpress.stackexchange.com/questions/265740",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118957/"
]
| I was just wondering if it's possible somehow *(via an addon maybe?)* to set the initial focus when the WordPress media library pops up to be the search field?
I have a lot of posts where I need to select images very fast and need to type in the names of the images to find them and this would be exceptionally handy except I've looked on Wordpress.org and a few other places that I know of and can't find a plugin that can do this although someone here might know of one or perhaps a way of doing this?
Many thanks in advance,
Best wishes,
Mark | Here's some code that will set the focus to the search field when clicking on the `Add Media` button or when opening the media modal when setting a featured image. Add this code to your theme's `functions.php` or to a plugin to use it.
Note: This is an updated version of my original solution. I think this one is a little more flexible and reliable because it leverages the WP Media API.
```
/**
* When a wp.media Modal is opened, set the focus to the media toolbar's search field.
*/
add_action( 'admin_footer-post-new.php', 'wpse_media_library_search_focus' );
add_action( 'admin_footer-post.php', 'wpse_media_library_search_focus' );
function wpse_media_library_search_focus() { ?>
<script type="text/javascript">
( function( $ ) {
$( document ).ready( function() {
// Ensure the wp.media object is set, otherwise we can't do anything.
if ( wp.media ) {
// Ensure that the Modal is ready. This approach resolves the
// need for timers which were used in a previous version of my answer
// due to the modal not being ready yet.
wp.media.view.Modal.prototype.on( "ready", function() {
// console.log( "media modal ready" );
// Execute this code when a Modal is opened.
// via https://gist.github.com/soderlind/370720db977f27c20360
wp.media.view.Modal.prototype.on( "open", function() {
// console.log( "media modal open" );
// Select the the .media-modal within the current backbone view,
// find the search input, and set the focus.
// http://stackoverflow.com/a/8934067/3059883
$( ".media-modal", this.el ).find( "#media-search-input" ).focus();
});
// Execute this code when a Modal is closed.
wp.media.view.Modal.prototype.on( "close", function() {
// console.log( "media modal close" );
});
});
}
});
})( jQuery );
</script><?php
}
```
For posterity's sake, here is the original version that I posted. I think the version above is much better.
```
add_action( 'admin_footer-post-new.php', 'wpse_media_library_search_focus_old' );
add_action( 'admin_footer-post.php', 'wpse_media_library_search_focus_old' );
function wpse_media_library_search_focus_old() {
?>
<script type="text/javascript">
(function($) {
$(document).ready( function() {
// Focus the search field for Posts
// http://wordpress-hackers.1065353.n5.nabble.com/JavaScript-events-on-media-popup-td42941.html
$(document.body).on( 'click', '.insert-media', function( event ) {
wp.media.controller.Library.prototype.defaults.contentUserSetting = false;
setTimeout(function(){
$("[id^=__wp-uploader-id]").each( function( index ) {
if ( $(this).css('display') != 'none' ) {
$(this).find("#media-search-input").focus();
}
});
}, 20);
});
// Focus the search field for Post Thumbnails
$( '#set-post-thumbnail').on( 'click', function( event ) {
wp.media.controller.FeaturedImage.prototype.defaults.contentUserSetting = true;
setTimeout(function(){
$("[id^=__wp-uploader-id]").each( function( index ) {
//alert( index + ": " + value );
if ( $(this).css('display') != 'none' ) {
$(this).find("#media-search-input").focus();
}
});
}, 20);
});
});
})(jQuery);
</script><?php
}
``` |
265,755 | <p>I didn't know how exactly I should form my title, so the question may be little different. I am new with WordPress developing and would need some advice. I don't need any code, I just want to hear your advice. </p>
<p>I have a page Books, and I'd like to allow admin to add books to that page through the admin dashboard. Basically, admin should only be able to enter 3 params (image, title, content) for every book he wants to add. Every book has the same HTML markup, only parameters are different. What would be the best way to implement this? I was thinking about creating a widget for that. Should I go with widget, plugin, or with something else?</p>
<pre><code><div id="book-wrap">
... every added book markup goes here
</div>
</code></pre>
| [
{
"answer_id": 265756,
"author": "Greg36",
"author_id": 64017,
"author_profile": "https://wordpress.stackexchange.com/users/64017",
"pm_score": 0,
"selected": false,
"text": "<p>You should use widgets for that only if the books there will be needed temporary when you delete widget its contents are deleted too.</p>\n\n<p>Otherwise, create book <a href=\"https://codex.wordpress.org/Post_Types\" rel=\"nofollow noreferrer\">custom post type</a>, then you can <a href=\"https://premium.wpmudev.org/blog/creating-meta-boxes/\" rel=\"nofollow noreferrer\">add metaboxes</a> for your needed data.</p>\n\n<p>Then you can create a page template with WP_Query loop to display all books.</p>\n\n<p>If your admin needs to re-order books on the page I would recommend using this plugin: <a href=\"https://wordpress.org/plugins/post-types-order/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/post-types-order/</a></p>\n"
},
{
"answer_id": 265757,
"author": "karimeo",
"author_id": 118963,
"author_profile": "https://wordpress.stackexchange.com/users/118963",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to do it the \"WordPress-way\", you would create a custom post-type for books called \"book\" ( For this take a look at <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/register_post_type</a> ). Then you would create an archive page for that post-type called \"archive-book.php\".</p>\n\n<p>I hope this helps a little bit. If you need more help, let me know. </p>\n"
}
]
| 2017/05/03 | [
"https://wordpress.stackexchange.com/questions/265755",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118483/"
]
| I didn't know how exactly I should form my title, so the question may be little different. I am new with WordPress developing and would need some advice. I don't need any code, I just want to hear your advice.
I have a page Books, and I'd like to allow admin to add books to that page through the admin dashboard. Basically, admin should only be able to enter 3 params (image, title, content) for every book he wants to add. Every book has the same HTML markup, only parameters are different. What would be the best way to implement this? I was thinking about creating a widget for that. Should I go with widget, plugin, or with something else?
```
<div id="book-wrap">
... every added book markup goes here
</div>
``` | If you want to do it the "WordPress-way", you would create a custom post-type for books called "book" ( For this take a look at <https://codex.wordpress.org/Function_Reference/register_post_type> ). Then you would create an archive page for that post-type called "archive-book.php".
I hope this helps a little bit. If you need more help, let me know. |
265,783 | <p>I am making a pagination for this website by using a custom query and <strong>get_next_posts_link</strong>, <strong>get_previous_posts_link</strong>. The problem is that the link to older entries (<strong>get_next_posts_link</strong>) only works once, meaning that if I click on it the second time, it will always lead to the home page, this is weird because when I inspect the link, the href attribute is: <code>http://localhost:8888/athena/event/page/3</code>.</p>
<p>There are 7 pages according to the variable <strong>$queryObject->max_num_pages</strong></p>
<p>A small screen capture video to show what I mean (27 seconds long):
<a href="https://www.useloom.com/share/f8f9ecac9dd54a49aa3613f9c0f5c9f9" rel="nofollow noreferrer">https://www.useloom.com/share/f8f9ecac9dd54a49aa3613f9c0f5c9f9</a></p>
<p>Here's my code:</p>
<pre><code> <!-- section list events-->
<?php
if(get_query_var('paged')){
$paged = get_query_var('paged');
} elseif (get_query_var('page')) {
$paged = get_query_var('page');
} else {
$paged = 1;
}
$query_args = array(
'post_type' => 'event',
'posts_per_page' => 3,
'paged' => $paged
);
$queryObject = new WP_Query($query_args);
?>
<section class="block-list-events">
<div class="container">
<div style="color: #000;">
<?php var_dump($queryObject->found_posts); ?>
</div>
<div class="list-events">
<?php if ($queryObject->have_posts()): while ($queryObject->have_posts()) : $queryObject->the_post(); ?>
<div class="item clearfix">
<div class="img tbl pull-left">
<div class="tbl-cell date">
<p><?php the_time('Y M') ?></p>
<p><span><?php the_time('j') ?></span></p>
</div>
<div class="tbl-cell img-a">
<a href="<?php echo get_the_permalink() ?>" title="<?php the_title(); ?>"><img src="<?php the_post_thumbnail_url('event-single'); ?>" width="530" height="300" alt="<?php the_title(); ?>"/></a>
</div>
</div>
<div class="info pull-left">
<p class="tag"><?php the_field('label'); ?></p>
<h4><a href="<?php echo get_the_permalink() ?>"><?php the_title(); ?></a></h4>
<p class="desc"><?php echo excerpt(25); ?></p>
<div class="button-view-detail">
<a class="btn btn-3" href="<?php echo get_the_permalink() ?>" title="<?php the_title(); ?>">View Details</a>
</div>
</div>
</div>
<?php endwhile; ?>
</div>
<?php endif; ?>
<div class="clearfix">
<!-- Pagination -->
<?php if ($queryObject->max_num_pages > 1) { // check if the max number of pages is greater than 1 ?>
<nav class="prev-next-posts">
<div class="prev-posts-link">
<?php echo get_next_posts_link( 'Older Entries', $queryObject->max_num_pages ); // display older posts link ?>
</div>
<div class="next-posts-link">
<?php echo get_previous_posts_link( 'Newer Entries', $queryObject->max_num_pages ); // display newer posts link ?>
</div>
</nav>
<?php } ?>
</div>
</section>
<!-- /end of section list events -->
</main>
<?php wp_reset_postdata(); ?>
<?php get_footer(); ?>
</code></pre>
<p>As suggested by @amit, I've updated my code but still the result is the same as before:</p>
<pre><code> <!-- section list events-->
<?php
if(get_query_var('paged')){
$paged = get_query_var('paged');
} elseif (get_query_var('page')) {
$paged = get_query_var('page');
} else {
$paged = 1;
}
$query_args = array(
'post_type' => 'event',
'numberposts' => -1,
'posts_per_page' => 3,
'paged' => $paged
);
$queryObject = new WP_Query($query_args);
// Pagination fix
$temp_query = $wp_query;
$wp_query = NULL;
$wp_query = $queryObject;
?>
<section class="block-list-events">
<div class="container">
<div style="color: #000;">
<?php var_dump($queryObject->found_posts); ?>
</div>
<div class="list-events">
<?php if ($queryObject->have_posts()): while ($queryObject->have_posts()) : $queryObject->the_post(); ?>
<div class="item clearfix">
<div class="img tbl pull-left">
<div class="tbl-cell date">
<p><?php the_time('Y M') ?></p>
<p><span><?php the_time('j') ?></span></p>
</div>
<div class="tbl-cell img-a">
<a href="<?php echo get_the_permalink() ?>" title="<?php the_title(); ?>"><img src="<?php the_post_thumbnail_url('event-single'); ?>" width="530" height="300" alt="<?php the_title(); ?>"/></a>
</div>
</div>
<div class="info pull-left">
<p class="tag"><?php the_field('label'); ?></p>
<h4><a href="<?php echo get_the_permalink() ?>"><?php the_title(); ?></a></h4>
<p class="desc"><?php echo excerpt(25); ?></p>
<div class="button-view-detail">
<a class="btn btn-3" href="<?php echo get_the_permalink() ?>" title="<?php the_title(); ?>">View Details</a>
</div>
</div>
</div>
<?php endwhile; ?>
</div>
<?php endif; ?>
<?php
// Reset postdata
wp_reset_postdata();
?>
<div class="clearfix">
<!-- Pagination -->
<?php if ($queryObject->max_num_pages > 1) { // check if the max number of pages is greater than 1 ?>
<nav class="prev-next-posts">
<div class="prev-posts-link">
<?php echo get_next_posts_link( 'Older Entries', $queryObject->max_num_pages ); // display older posts link ?>
</div>
<div class="next-posts-link">
<?php echo get_previous_posts_link( 'Newer Entries' ); // display newer posts link ?>
</div>
</nav>
<?php } ?>
</div>
</section>
<!-- /end of section list events -->
</main>
<?php
// Reset main query object
$wp_query = NULL;
$wp_query = $temp_query;
?>
<?php get_footer(); ?>
</code></pre>
| [
{
"answer_id": 265756,
"author": "Greg36",
"author_id": 64017,
"author_profile": "https://wordpress.stackexchange.com/users/64017",
"pm_score": 0,
"selected": false,
"text": "<p>You should use widgets for that only if the books there will be needed temporary when you delete widget its contents are deleted too.</p>\n\n<p>Otherwise, create book <a href=\"https://codex.wordpress.org/Post_Types\" rel=\"nofollow noreferrer\">custom post type</a>, then you can <a href=\"https://premium.wpmudev.org/blog/creating-meta-boxes/\" rel=\"nofollow noreferrer\">add metaboxes</a> for your needed data.</p>\n\n<p>Then you can create a page template with WP_Query loop to display all books.</p>\n\n<p>If your admin needs to re-order books on the page I would recommend using this plugin: <a href=\"https://wordpress.org/plugins/post-types-order/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/post-types-order/</a></p>\n"
},
{
"answer_id": 265757,
"author": "karimeo",
"author_id": 118963,
"author_profile": "https://wordpress.stackexchange.com/users/118963",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to do it the \"WordPress-way\", you would create a custom post-type for books called \"book\" ( For this take a look at <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/register_post_type</a> ). Then you would create an archive page for that post-type called \"archive-book.php\".</p>\n\n<p>I hope this helps a little bit. If you need more help, let me know. </p>\n"
}
]
| 2017/05/04 | [
"https://wordpress.stackexchange.com/questions/265783",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109276/"
]
| I am making a pagination for this website by using a custom query and **get\_next\_posts\_link**, **get\_previous\_posts\_link**. The problem is that the link to older entries (**get\_next\_posts\_link**) only works once, meaning that if I click on it the second time, it will always lead to the home page, this is weird because when I inspect the link, the href attribute is: `http://localhost:8888/athena/event/page/3`.
There are 7 pages according to the variable **$queryObject->max\_num\_pages**
A small screen capture video to show what I mean (27 seconds long):
<https://www.useloom.com/share/f8f9ecac9dd54a49aa3613f9c0f5c9f9>
Here's my code:
```
<!-- section list events-->
<?php
if(get_query_var('paged')){
$paged = get_query_var('paged');
} elseif (get_query_var('page')) {
$paged = get_query_var('page');
} else {
$paged = 1;
}
$query_args = array(
'post_type' => 'event',
'posts_per_page' => 3,
'paged' => $paged
);
$queryObject = new WP_Query($query_args);
?>
<section class="block-list-events">
<div class="container">
<div style="color: #000;">
<?php var_dump($queryObject->found_posts); ?>
</div>
<div class="list-events">
<?php if ($queryObject->have_posts()): while ($queryObject->have_posts()) : $queryObject->the_post(); ?>
<div class="item clearfix">
<div class="img tbl pull-left">
<div class="tbl-cell date">
<p><?php the_time('Y M') ?></p>
<p><span><?php the_time('j') ?></span></p>
</div>
<div class="tbl-cell img-a">
<a href="<?php echo get_the_permalink() ?>" title="<?php the_title(); ?>"><img src="<?php the_post_thumbnail_url('event-single'); ?>" width="530" height="300" alt="<?php the_title(); ?>"/></a>
</div>
</div>
<div class="info pull-left">
<p class="tag"><?php the_field('label'); ?></p>
<h4><a href="<?php echo get_the_permalink() ?>"><?php the_title(); ?></a></h4>
<p class="desc"><?php echo excerpt(25); ?></p>
<div class="button-view-detail">
<a class="btn btn-3" href="<?php echo get_the_permalink() ?>" title="<?php the_title(); ?>">View Details</a>
</div>
</div>
</div>
<?php endwhile; ?>
</div>
<?php endif; ?>
<div class="clearfix">
<!-- Pagination -->
<?php if ($queryObject->max_num_pages > 1) { // check if the max number of pages is greater than 1 ?>
<nav class="prev-next-posts">
<div class="prev-posts-link">
<?php echo get_next_posts_link( 'Older Entries', $queryObject->max_num_pages ); // display older posts link ?>
</div>
<div class="next-posts-link">
<?php echo get_previous_posts_link( 'Newer Entries', $queryObject->max_num_pages ); // display newer posts link ?>
</div>
</nav>
<?php } ?>
</div>
</section>
<!-- /end of section list events -->
</main>
<?php wp_reset_postdata(); ?>
<?php get_footer(); ?>
```
As suggested by @amit, I've updated my code but still the result is the same as before:
```
<!-- section list events-->
<?php
if(get_query_var('paged')){
$paged = get_query_var('paged');
} elseif (get_query_var('page')) {
$paged = get_query_var('page');
} else {
$paged = 1;
}
$query_args = array(
'post_type' => 'event',
'numberposts' => -1,
'posts_per_page' => 3,
'paged' => $paged
);
$queryObject = new WP_Query($query_args);
// Pagination fix
$temp_query = $wp_query;
$wp_query = NULL;
$wp_query = $queryObject;
?>
<section class="block-list-events">
<div class="container">
<div style="color: #000;">
<?php var_dump($queryObject->found_posts); ?>
</div>
<div class="list-events">
<?php if ($queryObject->have_posts()): while ($queryObject->have_posts()) : $queryObject->the_post(); ?>
<div class="item clearfix">
<div class="img tbl pull-left">
<div class="tbl-cell date">
<p><?php the_time('Y M') ?></p>
<p><span><?php the_time('j') ?></span></p>
</div>
<div class="tbl-cell img-a">
<a href="<?php echo get_the_permalink() ?>" title="<?php the_title(); ?>"><img src="<?php the_post_thumbnail_url('event-single'); ?>" width="530" height="300" alt="<?php the_title(); ?>"/></a>
</div>
</div>
<div class="info pull-left">
<p class="tag"><?php the_field('label'); ?></p>
<h4><a href="<?php echo get_the_permalink() ?>"><?php the_title(); ?></a></h4>
<p class="desc"><?php echo excerpt(25); ?></p>
<div class="button-view-detail">
<a class="btn btn-3" href="<?php echo get_the_permalink() ?>" title="<?php the_title(); ?>">View Details</a>
</div>
</div>
</div>
<?php endwhile; ?>
</div>
<?php endif; ?>
<?php
// Reset postdata
wp_reset_postdata();
?>
<div class="clearfix">
<!-- Pagination -->
<?php if ($queryObject->max_num_pages > 1) { // check if the max number of pages is greater than 1 ?>
<nav class="prev-next-posts">
<div class="prev-posts-link">
<?php echo get_next_posts_link( 'Older Entries', $queryObject->max_num_pages ); // display older posts link ?>
</div>
<div class="next-posts-link">
<?php echo get_previous_posts_link( 'Newer Entries' ); // display newer posts link ?>
</div>
</nav>
<?php } ?>
</div>
</section>
<!-- /end of section list events -->
</main>
<?php
// Reset main query object
$wp_query = NULL;
$wp_query = $temp_query;
?>
<?php get_footer(); ?>
``` | If you want to do it the "WordPress-way", you would create a custom post-type for books called "book" ( For this take a look at <https://codex.wordpress.org/Function_Reference/register_post_type> ). Then you would create an archive page for that post-type called "archive-book.php".
I hope this helps a little bit. If you need more help, let me know. |
265,806 | <p>I have the following WP_Query:</p>
<pre><code>$custom_query_args = array(
'post_type' => 'mcg_event',
'posts_per_page' => -1,
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'event_status',
'value' => 'archived',
),
array(
'key' => 'event_start_date',
'orderby' => 'meta_value_num',
'order' => 'ASC',
)
),
);
</code></pre>
<p>I'm looking to do 2 things: </p>
<ol>
<li>only fetch events that have an event_status of <code>archived</code></li>
<li>order the results by <code>event_start_date</code></li>
</ol>
<p>I can do either of these queries separately with no problem but when I put them together as above the order makes no difference.</p>
<p>What am I missing?</p>
| [
{
"answer_id": 265756,
"author": "Greg36",
"author_id": 64017,
"author_profile": "https://wordpress.stackexchange.com/users/64017",
"pm_score": 0,
"selected": false,
"text": "<p>You should use widgets for that only if the books there will be needed temporary when you delete widget its contents are deleted too.</p>\n\n<p>Otherwise, create book <a href=\"https://codex.wordpress.org/Post_Types\" rel=\"nofollow noreferrer\">custom post type</a>, then you can <a href=\"https://premium.wpmudev.org/blog/creating-meta-boxes/\" rel=\"nofollow noreferrer\">add metaboxes</a> for your needed data.</p>\n\n<p>Then you can create a page template with WP_Query loop to display all books.</p>\n\n<p>If your admin needs to re-order books on the page I would recommend using this plugin: <a href=\"https://wordpress.org/plugins/post-types-order/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/post-types-order/</a></p>\n"
},
{
"answer_id": 265757,
"author": "karimeo",
"author_id": 118963,
"author_profile": "https://wordpress.stackexchange.com/users/118963",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to do it the \"WordPress-way\", you would create a custom post-type for books called \"book\" ( For this take a look at <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/register_post_type</a> ). Then you would create an archive page for that post-type called \"archive-book.php\".</p>\n\n<p>I hope this helps a little bit. If you need more help, let me know. </p>\n"
}
]
| 2017/05/04 | [
"https://wordpress.stackexchange.com/questions/265806",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/119008/"
]
| I have the following WP\_Query:
```
$custom_query_args = array(
'post_type' => 'mcg_event',
'posts_per_page' => -1,
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'event_status',
'value' => 'archived',
),
array(
'key' => 'event_start_date',
'orderby' => 'meta_value_num',
'order' => 'ASC',
)
),
);
```
I'm looking to do 2 things:
1. only fetch events that have an event\_status of `archived`
2. order the results by `event_start_date`
I can do either of these queries separately with no problem but when I put them together as above the order makes no difference.
What am I missing? | If you want to do it the "WordPress-way", you would create a custom post-type for books called "book" ( For this take a look at <https://codex.wordpress.org/Function_Reference/register_post_type> ). Then you would create an archive page for that post-type called "archive-book.php".
I hope this helps a little bit. If you need more help, let me know. |
265,818 | <p><a href="https://i.stack.imgur.com/cwSWN.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cwSWN.jpg" alt="enter image description here"></a></p>
<p>As you can see the phrase is <strong><em>Want create site? Free wordpress themes..</em></strong></p>
<p>I tried editing in Yoast Facebook option still the phrase shows up, any solution?</p>
| [
{
"answer_id": 265820,
"author": "Alex MacArthur",
"author_id": 89080,
"author_profile": "https://wordpress.stackexchange.com/users/89080",
"pm_score": 0,
"selected": false,
"text": "<p>The plugin is pulling that content from somewhere on your page and placing it in Open Graph meta tags. Not sure why editing it in the settings doesn't work; could be a bug or confusing settings. I would try a different, simpler plugin for Open Graph management and see if the problem remains. Something like Complete Open Graph.</p>\n\n<p><a href=\"https://wordpress.org/plugins/complete-open-graph/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/complete-open-graph/</a></p>\n\n<p>After doing this, make sure to rescrape using Facebook's debugger: </p>\n\n<p><a href=\"https://developers.facebook.com/tools/debug/\" rel=\"nofollow noreferrer\">https://developers.facebook.com/tools/debug/</a></p>\n"
},
{
"answer_id": 265829,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": false,
"text": "<p>There's a reason people say that you shouldn't download free themes from outside of wordpress.org, they might contain hidden surprises</p>\n\n<p>In your case, the theme inserts an advertisement at the beginning of the post content div:</p>\n\n<pre><code><div style=\"position:absolute;top:0;left:-9999px;\">Want create site? Find <a href=\"http://dlwordpress.com/\">Free WordPress Themes</a> and plugins.</div><div style='clear: both'></div>\n</code></pre>\n\n<p>Since the style.css indicates this is a themeforest theme, and since the site dlwordpress.com offers it for free, <strong>this is a pirated theme and this kind of problem is to be expected</strong></p>\n\n<p>This has nothing to do with Yoast or other plugins, and it's a hardcoded surprise added to the theme by the pirates.</p>\n\n<p>Instead, <a href=\"https://themeforest.net/item/newsmag-news-magazine-newspaper/9512331?s_rank=1\" rel=\"noreferrer\">consider buying the real version of the theme for $49 USD on Theme Forest</a> instead of using a dodgy copy that might contain other hidden surprises and malware</p>\n"
}
]
| 2017/05/04 | [
"https://wordpress.stackexchange.com/questions/265818",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/119011/"
]
| [](https://i.stack.imgur.com/cwSWN.jpg)
As you can see the phrase is ***Want create site? Free wordpress themes..***
I tried editing in Yoast Facebook option still the phrase shows up, any solution? | There's a reason people say that you shouldn't download free themes from outside of wordpress.org, they might contain hidden surprises
In your case, the theme inserts an advertisement at the beginning of the post content div:
```
<div style="position:absolute;top:0;left:-9999px;">Want create site? Find <a href="http://dlwordpress.com/">Free WordPress Themes</a> and plugins.</div><div style='clear: both'></div>
```
Since the style.css indicates this is a themeforest theme, and since the site dlwordpress.com offers it for free, **this is a pirated theme and this kind of problem is to be expected**
This has nothing to do with Yoast or other plugins, and it's a hardcoded surprise added to the theme by the pirates.
Instead, [consider buying the real version of the theme for $49 USD on Theme Forest](https://themeforest.net/item/newsmag-news-magazine-newspaper/9512331?s_rank=1) instead of using a dodgy copy that might contain other hidden surprises and malware |
265,826 | <p>I have a PHP(Laravel) application that pushes data to WooCommerce through the WooCommerce REST API, everything works except for images. I was able to pin this down to <code>wp_safe_remote_get()</code> and <code>$args['reject_unsafe_urls']</code>.</p>
<p>I had found a way around this, but I cannot recall where I found it. I seem to remember a hook in functions.php that turned off this feature. It wasn't recommended, but it is the only recourse.</p>
<p>Can anyone help me out? Or does anyone have another solution? I'm only pushing URLs from an application I made from the same server.</p>
<p><em>Code Example from External Application</em></p>
<p><code>$this->woocommerce->post('products', ['product' => $book_data_array])</code></p>
<p>where <code>$this->woocommerce</code> is an instance of the WooCommerce API.</p>
<p>and <code>$book_data_array</code> is an array of data. For an example of the data arra, see: '<a href="http://woocommerce.github.io/woocommerce-rest-api-docs/wp-api-v1.html#create-a-product" rel="nofollow noreferrer">http://woocommerce.github.io/woocommerce-rest-api-docs/wp-api-v1.html#create-a-product</a>'</p>
<p>The only thing that doesn't work is images coming from the same server, which is a WordPress issue and has been confirmed as much by a WooCommerce dev. WordPress doesn't allow downloads from the same origin without an override.</p>
| [
{
"answer_id": 265820,
"author": "Alex MacArthur",
"author_id": 89080,
"author_profile": "https://wordpress.stackexchange.com/users/89080",
"pm_score": 0,
"selected": false,
"text": "<p>The plugin is pulling that content from somewhere on your page and placing it in Open Graph meta tags. Not sure why editing it in the settings doesn't work; could be a bug or confusing settings. I would try a different, simpler plugin for Open Graph management and see if the problem remains. Something like Complete Open Graph.</p>\n\n<p><a href=\"https://wordpress.org/plugins/complete-open-graph/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/complete-open-graph/</a></p>\n\n<p>After doing this, make sure to rescrape using Facebook's debugger: </p>\n\n<p><a href=\"https://developers.facebook.com/tools/debug/\" rel=\"nofollow noreferrer\">https://developers.facebook.com/tools/debug/</a></p>\n"
},
{
"answer_id": 265829,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": false,
"text": "<p>There's a reason people say that you shouldn't download free themes from outside of wordpress.org, they might contain hidden surprises</p>\n\n<p>In your case, the theme inserts an advertisement at the beginning of the post content div:</p>\n\n<pre><code><div style=\"position:absolute;top:0;left:-9999px;\">Want create site? Find <a href=\"http://dlwordpress.com/\">Free WordPress Themes</a> and plugins.</div><div style='clear: both'></div>\n</code></pre>\n\n<p>Since the style.css indicates this is a themeforest theme, and since the site dlwordpress.com offers it for free, <strong>this is a pirated theme and this kind of problem is to be expected</strong></p>\n\n<p>This has nothing to do with Yoast or other plugins, and it's a hardcoded surprise added to the theme by the pirates.</p>\n\n<p>Instead, <a href=\"https://themeforest.net/item/newsmag-news-magazine-newspaper/9512331?s_rank=1\" rel=\"noreferrer\">consider buying the real version of the theme for $49 USD on Theme Forest</a> instead of using a dodgy copy that might contain other hidden surprises and malware</p>\n"
}
]
| 2017/05/04 | [
"https://wordpress.stackexchange.com/questions/265826",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/42713/"
]
| I have a PHP(Laravel) application that pushes data to WooCommerce through the WooCommerce REST API, everything works except for images. I was able to pin this down to `wp_safe_remote_get()` and `$args['reject_unsafe_urls']`.
I had found a way around this, but I cannot recall where I found it. I seem to remember a hook in functions.php that turned off this feature. It wasn't recommended, but it is the only recourse.
Can anyone help me out? Or does anyone have another solution? I'm only pushing URLs from an application I made from the same server.
*Code Example from External Application*
`$this->woocommerce->post('products', ['product' => $book_data_array])`
where `$this->woocommerce` is an instance of the WooCommerce API.
and `$book_data_array` is an array of data. For an example of the data arra, see: '<http://woocommerce.github.io/woocommerce-rest-api-docs/wp-api-v1.html#create-a-product>'
The only thing that doesn't work is images coming from the same server, which is a WordPress issue and has been confirmed as much by a WooCommerce dev. WordPress doesn't allow downloads from the same origin without an override. | There's a reason people say that you shouldn't download free themes from outside of wordpress.org, they might contain hidden surprises
In your case, the theme inserts an advertisement at the beginning of the post content div:
```
<div style="position:absolute;top:0;left:-9999px;">Want create site? Find <a href="http://dlwordpress.com/">Free WordPress Themes</a> and plugins.</div><div style='clear: both'></div>
```
Since the style.css indicates this is a themeforest theme, and since the site dlwordpress.com offers it for free, **this is a pirated theme and this kind of problem is to be expected**
This has nothing to do with Yoast or other plugins, and it's a hardcoded surprise added to the theme by the pirates.
Instead, [consider buying the real version of the theme for $49 USD on Theme Forest](https://themeforest.net/item/newsmag-news-magazine-newspaper/9512331?s_rank=1) instead of using a dodgy copy that might contain other hidden surprises and malware |
265,868 | <p>I have the following query:</p>
<pre><code><?php
$args = array(
'hide_empty' => false,
'orderby' => 'title',
'order' => 'DESC'
);
$terms = get_terms( 'projets-location', $args );
if ( !empty( $terms ) && !is_wp_error( $terms ) ){
foreach ( $terms as $term ) { ?>
<h5 id="<?php echo $term->slug; ?>" class="filter-menu-item" data-filter=".<?php echo $term->slug; ?>">
<strong><?php echo $term->name; ?></strong>
</h5>
<?php }
} ?>
</code></pre>
<p>which shows all the taxonomy terms from the <code>projets-location</code> taxonomy, I've added the <code>orderby</code> and <code>order</code> attributes above but STILL they're not displaying in alphabetical order at all, am I being stupid her or is there something I'm going wrong? Any suggestions would be greatly appreciated!</p>
| [
{
"answer_id": 265873,
"author": "Mervan Agency",
"author_id": 118206,
"author_profile": "https://wordpress.stackexchange.com/users/118206",
"pm_score": 0,
"selected": false,
"text": "<p>As per the WordPress Codex for <code>get_terms</code> on this link \n <a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_terms/</a>, following terms fields are accepted in <code>order_by</code> argument <code>'name', 'slug', 'term_group', 'term_id', 'id', 'description'</code> and you are using <code>title</code> which is not in the accepted terms fields, so that might be the issue.</p>\n"
},
{
"answer_id": 265883,
"author": "s t",
"author_id": 90682,
"author_profile": "https://wordpress.stackexchange.com/users/90682",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>Since 4.5.0, taxonomies should be passed via the ‘taxonomy’ argument\n in the $args array:</p>\n</blockquote>\n\n<pre><code>$terms = get_terms( array(\n 'taxonomy' => 'projets-location',\n 'orderby' => 'name',\n 'order' => 'DESC' \n) );\n</code></pre>\n"
},
{
"answer_id": 306599,
"author": "Vincent Decaux",
"author_id": 104362,
"author_profile": "https://wordpress.stackexchange.com/users/104362",
"pm_score": 0,
"selected": false,
"text": "<p>I didn't success to order by name using the <strong>orderby</strong> argument, so I just used a sort function ::</p>\n\n<pre><code>// order by name ASC - change > to < to order by DESC\nfunction sortByName($a, $b) {\n return $a->name > $b->name;\n}\n\n$terms = get_terms( 'projets-location', $args );\nusort($subterms, 'sortByName');\n\nforeach ( $terms as $term ) {\n ....\n</code></pre>\n"
},
{
"answer_id": 388842,
"author": "Marcos Nakamine",
"author_id": 46049,
"author_profile": "https://wordpress.stackexchange.com/users/46049",
"pm_score": 0,
"selected": false,
"text": "<p>Try with wpdb</p>\n<pre><code><?php\nglobal $wpdb;\n$terms = $wpdb->get_results( "\n SELECT\n t.name,\n t.slug\n FROM\n {$wpdb->prefix}term_taxonomy AS tt\n INNER JOIN\n {$wpdb->prefix}terms AS t\n ON t.term_id = tt.term_id\n WHERE\n tt.taxonomy = 'projets-location'\n ORDER BY\n t.name DESC\n" );\n\nif ( !empty( $terms ) && !is_wp_error( $terms ) ){\n foreach ( $terms as $term ) { ?>\n\n <h5 id="<?php echo $term->slug; ?>" class="filter-menu-item" data-filter=".<?php echo $term->slug; ?>">\n <strong><?php echo $term->name; ?></strong>\n </h5>\n\n <?php }\n} ?>\n</code></pre>\n"
}
]
| 2017/05/04 | [
"https://wordpress.stackexchange.com/questions/265868",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/28065/"
]
| I have the following query:
```
<?php
$args = array(
'hide_empty' => false,
'orderby' => 'title',
'order' => 'DESC'
);
$terms = get_terms( 'projets-location', $args );
if ( !empty( $terms ) && !is_wp_error( $terms ) ){
foreach ( $terms as $term ) { ?>
<h5 id="<?php echo $term->slug; ?>" class="filter-menu-item" data-filter=".<?php echo $term->slug; ?>">
<strong><?php echo $term->name; ?></strong>
</h5>
<?php }
} ?>
```
which shows all the taxonomy terms from the `projets-location` taxonomy, I've added the `orderby` and `order` attributes above but STILL they're not displaying in alphabetical order at all, am I being stupid her or is there something I'm going wrong? Any suggestions would be greatly appreciated! | >
> Since 4.5.0, taxonomies should be passed via the ‘taxonomy’ argument
> in the $args array:
>
>
>
```
$terms = get_terms( array(
'taxonomy' => 'projets-location',
'orderby' => 'name',
'order' => 'DESC'
) );
``` |
265,903 | <p>Hello in the <code>init</code> action, I would like to add a filter to a fairly large function to modify variables in the <code>$vars</code> array, for example the Wordpress post ID.</p>
<p>That is to say:</p>
<pre class="lang-php prettyprint-override"><code> add_action( 'init',function(){
//code
add_filter( 'query_vars',function($vars){
$vars[] = array('ID' => $myid);
return $vars;
});
});
</code></pre>
<p>Is this possible?</p>
<p>EDIT: I am doing A/B/C tests of pages and with the same url I want to show a page with another ID, (i.e. edit the ID of the current post to display the complete content of another post).</p>
| [
{
"answer_id": 266152,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 1,
"selected": false,
"text": "<p>Yes, it's possible to do something like that. And in fact, if you want to remove actions/filters, then you will be almost certainly be required to use one hook to remove it.</p>\n\n<p>For instance, plugins load before the theme. So if a theme adds a hook to the <code>init</code> hook from the functions.php file like so:</p>\n\n<pre><code>add_action( 'init', 'wpse_265903_init' );\n</code></pre>\n\n<p>Plugins would not be able to remove that action until after the theme gets setup:</p>\n\n<pre><code>add_action( 'after_setup_theme', function() {\n remove_action( 'init', 'wpse_265903_init' );\n} );\n</code></pre>\n\n<p>Similarly, if you want some hooks to run only after the <code>admin_init</code> hook, then you can do something like this:</p>\n\n<pre><code>add_action( 'admin_init', function() {\n add_action( 'the_post', function() {\n do_something();\n } );\n} );\n</code></pre>\n\n<p>The <code>init</code> hook fires on every request though, so I'm not sure the purpose of adding hooks from that particular hook.</p>\n"
},
{
"answer_id": 266290,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 3,
"selected": true,
"text": "<p>To alter the page ID before the query is run, hook the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/request\" rel=\"nofollow noreferrer\"><code>request</code></a> filter.</p>\n\n<p>If you're using pretty permalinks, <code>pagename</code> will be set, you can overwrite <code>pagename</code> with another page slug:</p>\n\n<pre><code>function wpd_265903_request( $request ) {\n if( isset( $request['pagename'] ) ){ // any page\n $request['pagename'] = 'some-other-slug';\n }\n return $request;\n}\nadd_filter('request', 'wpd_265903_request');\n</code></pre>\n\n<p>or you can unset pagename and set <code>page_id</code>:</p>\n\n<pre><code>function wpd_265903_request( $request ) {\n if( isset( $request['pagename'] ) ){\n unset( $request['pagename'] );\n $request['page_id'] = 106;\n }\n return $request;\n}\nadd_filter( 'request', 'wpd_265903_request' );\n</code></pre>\n"
}
]
| 2017/05/04 | [
"https://wordpress.stackexchange.com/questions/265903",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78261/"
]
| Hello in the `init` action, I would like to add a filter to a fairly large function to modify variables in the `$vars` array, for example the Wordpress post ID.
That is to say:
```php
add_action( 'init',function(){
//code
add_filter( 'query_vars',function($vars){
$vars[] = array('ID' => $myid);
return $vars;
});
});
```
Is this possible?
EDIT: I am doing A/B/C tests of pages and with the same url I want to show a page with another ID, (i.e. edit the ID of the current post to display the complete content of another post). | To alter the page ID before the query is run, hook the [`request`](https://codex.wordpress.org/Plugin_API/Filter_Reference/request) filter.
If you're using pretty permalinks, `pagename` will be set, you can overwrite `pagename` with another page slug:
```
function wpd_265903_request( $request ) {
if( isset( $request['pagename'] ) ){ // any page
$request['pagename'] = 'some-other-slug';
}
return $request;
}
add_filter('request', 'wpd_265903_request');
```
or you can unset pagename and set `page_id`:
```
function wpd_265903_request( $request ) {
if( isset( $request['pagename'] ) ){
unset( $request['pagename'] );
$request['page_id'] = 106;
}
return $request;
}
add_filter( 'request', 'wpd_265903_request' );
``` |
265,906 | <p>I am trying to use wp_add_inline_style in plugin. I want to add some style when shortcode runs.</p>
<pre><code>add_action('wp_enqueue_scripts', 'cod_enqueue_scripts');
add_shortcode('cod', 'cod_process_shortcode');
function cod_enqueue_scripts() {
wp_enqueue_style('cod-style', plugins_url('css/style.css', __FILE__));
}
function cod_process_shortcode(){
$inline_css = "
.icon-color{
color:#ad3;
}";
wp_add_inline_style('cod-style', $inline_css);
}
</code></pre>
<p>This doesn't work, It will not hook to 'cod-style'.</p>
<p>It works if I do this: (first enqueue CSS then call wp_add_inline_style immediately afterwards)</p>
<pre><code>function cod_process_shortcode(){
wp_enqueue_style('cod-custom', plugins_url('css/blank.css', __FILE__));
$inline_css = "
.icon-color{
color:#ad3;
}";
wp_add_inline_style('cod-custom', $inline_css);
}
</code></pre>
<p>In the above example, I used an empty CSS file (blank.css) for testing. </p>
<p>I though maybe my original css file is not loaded yet, but even if I enqueue empty css in cod_enqueue_scripts, it will wont do it, like this:</p>
<pre><code>function cod_enqueue_scripts() {
wp_enqueue_style('cod-style', plugins_url('css/blank.css', __FILE__));
}
function cod_process_shortcode(){
$inline_css = "
.icon-color{
color:#ad3;
}";
wp_add_inline_style('cod-style', $inline_css);
}
</code></pre>
<p>I don't know what inline CSS I need until shortcode runs, and seems odd that the wp_add_inline_style will not hook to original wp_enqueue_style. </p>
| [
{
"answer_id": 265908,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 4,
"selected": true,
"text": "<p>Here's a solution based on <a href=\"https://www.cssigniter.com/ignite/late-enqueue-inline-css-wordpress/\" rel=\"nofollow noreferrer\">this post</a>, which allows the inline CSS to be rendered by a shortcode using a dependency without a path (basically a null file).</p>\n\n<pre><code>// Optional base styles\nadd_action( 'wp_enqueue_scripts', 'cod_enqueue_scripts' );\nfunction cod_enqueue_scripts() {\n wp_enqueue_style('cod-style', plugins_url('css/style.css', __FILE__));\n}\n\n// Shortcode handler which also outputs inline styles.\nadd_shortcode( 'cod', 'cod_process_shortcode');\nfunction cod_process_shortcode() {\n $color = '#ff0000';\n $css = 'body { background-color: ' . $color . '; }';\n\n wp_register_style( 'cod-inline-style', false );\n wp_enqueue_style( 'cod-inline-style' );\n wp_add_inline_style( 'cod-inline-style', $css );\n\n return \"<p>Shortcode output...</p>\";\n}\n</code></pre>\n\n<p>Alternatively, <a href=\"https://wordpress.stackexchange.com/a/226747/2807\">Rarst pointed out</a> that the <a href=\"https://developer.wordpress.org/reference/functions/gallery_shortcode/\" rel=\"nofollow noreferrer\">WordPress gallery shortcode</a> outputs dynamic styles. The gallery shortcode does not make use of <code>wp_add_inline_style()</code>, but the end result is essentially the same.</p>\n\n<p><strong>Edit:</strong> Here's an alternate version where the inline styles use the dependency of the original styles.</p>\n\n<pre><code>// Base styles\nadd_action( 'wp_enqueue_scripts', 'cod_enqueue_scripts' );\nfunction cod_enqueue_scripts() {\n wp_enqueue_style('cod-style', plugins_url('css/style.css', __FILE__));\n}\n\n// Shortcode handler which also outputs inline styles.\nadd_shortcode( 'cod', 'cod_process_shortcode');\nfunction cod_process_shortcode() {\n $color = '#bada55';\n $css = 'body { background-color: ' . $color . '; }';\n\n wp_register_style( 'cod-inline-style', false, array( 'cod-style' ) );\n wp_enqueue_style( 'cod-inline-style' );\n wp_add_inline_style( 'cod-inline-style', $css );\n\n return \"<p>Shortcode output...</p>\";\n}\n</code></pre>\n"
},
{
"answer_id": 276565,
"author": "Prakash Sunuwar",
"author_id": 125680,
"author_profile": "https://wordpress.stackexchange.com/users/125680",
"pm_score": 0,
"selected": false,
"text": "<p>This code is worked for me..</p>\n<pre class=\"lang-php prettyprint-override\"><code>// Optional base styles \nadd_action( 'wp_enqueue_scripts', 'cod_enqueue_scripts' );\nfunction cod_enqueue_scripts() {\n wp_enqueue_style('cod-style', plugins_url('css/style.css', __FILE__));\n}\n\n// Shortcode handler which also outputs inline styles.\nadd_shortcode( 'cod', 'cod_process_shortcode');\nfunction cod_process_shortcode() {\n // your fornt end html\n}\n\nfunction custom_inline_style(){\n $color = '#ff0000';\n $css = 'body { background-color: ' . $color . '; }';\n\n wp_add_inline_style( 'cod-style', $css ); // hook to add inline style\n}\nadd_action( 'wp_enqueue_scripts', 'custom_inline_style', 20 ); // if 20 \n</code></pre>\n<p>If the priority is not working you can give more than 20.</p>\n"
},
{
"answer_id": 284029,
"author": "NineTheme",
"author_id": 77840,
"author_profile": "https://wordpress.stackexchange.com/users/77840",
"pm_score": -1,
"selected": false,
"text": "<pre><code> wp_enqueue_style( 'ninetheme-custom-style', get_template_directory_uri() . '/css/update.css' );\n $css = '.package .btn_acele { background-color: #333; }';\n wp_add_inline_style( 'my-custom-style', $css );\n }\n</code></pre>\n\n<p>You can use it in WordPress Shortcode, no need add_action :) </p>\n"
}
]
| 2017/05/04 | [
"https://wordpress.stackexchange.com/questions/265906",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/45321/"
]
| I am trying to use wp\_add\_inline\_style in plugin. I want to add some style when shortcode runs.
```
add_action('wp_enqueue_scripts', 'cod_enqueue_scripts');
add_shortcode('cod', 'cod_process_shortcode');
function cod_enqueue_scripts() {
wp_enqueue_style('cod-style', plugins_url('css/style.css', __FILE__));
}
function cod_process_shortcode(){
$inline_css = "
.icon-color{
color:#ad3;
}";
wp_add_inline_style('cod-style', $inline_css);
}
```
This doesn't work, It will not hook to 'cod-style'.
It works if I do this: (first enqueue CSS then call wp\_add\_inline\_style immediately afterwards)
```
function cod_process_shortcode(){
wp_enqueue_style('cod-custom', plugins_url('css/blank.css', __FILE__));
$inline_css = "
.icon-color{
color:#ad3;
}";
wp_add_inline_style('cod-custom', $inline_css);
}
```
In the above example, I used an empty CSS file (blank.css) for testing.
I though maybe my original css file is not loaded yet, but even if I enqueue empty css in cod\_enqueue\_scripts, it will wont do it, like this:
```
function cod_enqueue_scripts() {
wp_enqueue_style('cod-style', plugins_url('css/blank.css', __FILE__));
}
function cod_process_shortcode(){
$inline_css = "
.icon-color{
color:#ad3;
}";
wp_add_inline_style('cod-style', $inline_css);
}
```
I don't know what inline CSS I need until shortcode runs, and seems odd that the wp\_add\_inline\_style will not hook to original wp\_enqueue\_style. | Here's a solution based on [this post](https://www.cssigniter.com/ignite/late-enqueue-inline-css-wordpress/), which allows the inline CSS to be rendered by a shortcode using a dependency without a path (basically a null file).
```
// Optional base styles
add_action( 'wp_enqueue_scripts', 'cod_enqueue_scripts' );
function cod_enqueue_scripts() {
wp_enqueue_style('cod-style', plugins_url('css/style.css', __FILE__));
}
// Shortcode handler which also outputs inline styles.
add_shortcode( 'cod', 'cod_process_shortcode');
function cod_process_shortcode() {
$color = '#ff0000';
$css = 'body { background-color: ' . $color . '; }';
wp_register_style( 'cod-inline-style', false );
wp_enqueue_style( 'cod-inline-style' );
wp_add_inline_style( 'cod-inline-style', $css );
return "<p>Shortcode output...</p>";
}
```
Alternatively, [Rarst pointed out](https://wordpress.stackexchange.com/a/226747/2807) that the [WordPress gallery shortcode](https://developer.wordpress.org/reference/functions/gallery_shortcode/) outputs dynamic styles. The gallery shortcode does not make use of `wp_add_inline_style()`, but the end result is essentially the same.
**Edit:** Here's an alternate version where the inline styles use the dependency of the original styles.
```
// Base styles
add_action( 'wp_enqueue_scripts', 'cod_enqueue_scripts' );
function cod_enqueue_scripts() {
wp_enqueue_style('cod-style', plugins_url('css/style.css', __FILE__));
}
// Shortcode handler which also outputs inline styles.
add_shortcode( 'cod', 'cod_process_shortcode');
function cod_process_shortcode() {
$color = '#bada55';
$css = 'body { background-color: ' . $color . '; }';
wp_register_style( 'cod-inline-style', false, array( 'cod-style' ) );
wp_enqueue_style( 'cod-inline-style' );
wp_add_inline_style( 'cod-inline-style', $css );
return "<p>Shortcode output...</p>";
}
``` |
265,907 | <p>So I'm building my first custom WooCommerce store and I'm finding that my styles class names are becoming a over the top and lengthy, or is this how it is. I use the inspector tool in Chrome to get the class names.</p>
<p>Here is an example of what I'm working with at the moment:</p>
<pre><code>.woocommerce
ul.products
li.product a {
...
}
.woocommerce
ul.products
li.product
.price del {
...
}
</code></pre>
<p>Is this normal practice to when building a custom store or is there a better way?</p>
<p>Thanks in advance</p>
<p>Stu :)</p>
| [
{
"answer_id": 267324,
"author": "Aniruddha Gawade",
"author_id": 101818,
"author_profile": "https://wordpress.stackexchange.com/users/101818",
"pm_score": 1,
"selected": false,
"text": "<p>It is always a good practice to use maximum number of classes, because using more classes gives more weight-age and it will always consider your <code>css</code> first. </p>\n\n<p>But try not to use <code>div</code> or <code>p</code> tag while styling for <code>price</code>. Because different product types use different elements (Eg. simple uses <code>p</code>, variable uses <code>span</code>). So it wont be a common code for all price tags.</p>\n"
},
{
"answer_id": 267329,
"author": "Takebo",
"author_id": 117159,
"author_profile": "https://wordpress.stackexchange.com/users/117159",
"pm_score": 3,
"selected": true,
"text": "<p>What i do is, disable Woocommerce default styles depending on what i want to customize, instead of overwriting the css.</p>\n\n<p>Woocommerce loads 3 styles by default:\nwoocommerce-general.css\nwoocommerce-layout.css\nwoocommerce-smallscreen.css</p>\n\n<p>If you want to fully customize you can disable all styles or, just the ones that you dont want by adding:</p>\n\n<pre><code>// Remove each style one by one\nadd_filter( 'woocommerce_enqueue_styles', 'jk_dequeue_styles' );\nfunction jk_dequeue_styles( $enqueue_styles ) {\n unset( $enqueue_styles['woocommerce-general'] ); // Remove the gloss\n unset( $enqueue_styles['woocommerce-layout'] ); // Remove the layout\n unset( $enqueue_styles['woocommerce-smallscreen'] ); // Remove the smallscreen optimisation\n return $enqueue_styles;\n}\n\n// Or just remove them all in one line\nadd_filter( 'woocommerce_enqueue_styles', '__return_false' );\n</code></pre>\n\n<p>Check the Woocommerce documentation for more detail <a href=\"https://docs.woocommerce.com/document/disable-the-default-stylesheet/\" rel=\"nofollow noreferrer\">Disable the default stylesheet</a></p>\n"
}
]
| 2017/05/04 | [
"https://wordpress.stackexchange.com/questions/265907",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93077/"
]
| So I'm building my first custom WooCommerce store and I'm finding that my styles class names are becoming a over the top and lengthy, or is this how it is. I use the inspector tool in Chrome to get the class names.
Here is an example of what I'm working with at the moment:
```
.woocommerce
ul.products
li.product a {
...
}
.woocommerce
ul.products
li.product
.price del {
...
}
```
Is this normal practice to when building a custom store or is there a better way?
Thanks in advance
Stu :) | What i do is, disable Woocommerce default styles depending on what i want to customize, instead of overwriting the css.
Woocommerce loads 3 styles by default:
woocommerce-general.css
woocommerce-layout.css
woocommerce-smallscreen.css
If you want to fully customize you can disable all styles or, just the ones that you dont want by adding:
```
// Remove each style one by one
add_filter( 'woocommerce_enqueue_styles', 'jk_dequeue_styles' );
function jk_dequeue_styles( $enqueue_styles ) {
unset( $enqueue_styles['woocommerce-general'] ); // Remove the gloss
unset( $enqueue_styles['woocommerce-layout'] ); // Remove the layout
unset( $enqueue_styles['woocommerce-smallscreen'] ); // Remove the smallscreen optimisation
return $enqueue_styles;
}
// Or just remove them all in one line
add_filter( 'woocommerce_enqueue_styles', '__return_false' );
```
Check the Woocommerce documentation for more detail [Disable the default stylesheet](https://docs.woocommerce.com/document/disable-the-default-stylesheet/) |
265,929 | <p>i want to get the latest date of post in the homepage of my site.
in this code :</p>
<pre><code>the_modified_date('d F Y');
</code></pre>
<p>date is different in different pages (For example page 1,2,...).
i want to show <strong>just</strong> the date of <strong>latest post</strong> that published.
thanks.</p>
| [
{
"answer_id": 265932,
"author": "Sapere Aude",
"author_id": 119069,
"author_profile": "https://wordpress.stackexchange.com/users/119069",
"pm_score": 1,
"selected": false,
"text": "<p>you can use <code>get_the_date('d F Y');</code></p>\n"
},
{
"answer_id": 265933,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 0,
"selected": false,
"text": "<p>The <em>last published post date</em> is: </p>\n\n<pre><code>$last_post_date = get_lastpostdate( 'blog', 'post' );\n</code></pre>\n\n<p>and the <em>last modified post date</em> is</p>\n\n<pre><code>$last_post_modified = get_lastpostmodified( 'blog', 'post' );\n</code></pre>\n\n<p>Here we use the <code>'post'</code> post type and the <code>'blog'</code> for the timezone.</p>\n\n<p>Check out the documentation on <a href=\"https://developer.wordpress.org/reference/functions/get_lastpostdate/\" rel=\"nofollow noreferrer\"><code>get_lastpostdate</code></a> and <a href=\"https://developer.wordpress.org/reference/functions/get_lastpostmodified/\" rel=\"nofollow noreferrer\"><code>get_lastpostmodified</code></a> for more info.</p>\n"
}
]
| 2017/05/05 | [
"https://wordpress.stackexchange.com/questions/265929",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118232/"
]
| i want to get the latest date of post in the homepage of my site.
in this code :
```
the_modified_date('d F Y');
```
date is different in different pages (For example page 1,2,...).
i want to show **just** the date of **latest post** that published.
thanks. | you can use `get_the_date('d F Y');` |
265,997 | <p>My code is like following:</p>
<pre><code><?php
function shortcode_callback() {
ob_start();
//my code here
ob_get_clean();
}
add_shortcode('shortcode', 'shortcode_callback');
?>
</code></pre>
<p>The above shortcode add to the page but the tile is showing at the bottom of the shortcode:</p>
<h1>My Title</h1>
<blockquote>
<p>[shortcode]</p>
</blockquote>
<p>There is anything wrong doing I am.</p>
| [
{
"answer_id": 266002,
"author": "Faysal Mahamud",
"author_id": 83752,
"author_profile": "https://wordpress.stackexchange.com/users/83752",
"pm_score": 1,
"selected": false,
"text": "<p>You Must return output, Follow the following code.</p>\n\n<pre><code>function shortcode_callback() {\n\n $test = 'you text';\n\n return $test;\n }\n\nadd_shortcode('shortcode', 'shortcode_callback');\n</code></pre>\n"
},
{
"answer_id": 266042,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 1,
"selected": true,
"text": "<p>You needs to change buffer like this:</p>\n\n<pre><code><?php\n\n function shortcode_callback() {\n\n ob_start();\n\n //my code here\n\n return ob_get_clean();\n\n }\n\n add_shortcode('shortcode', 'shortcode_callback');\n\n ?>\n</code></pre>\n\n<p>Please check after replace ob_get_clean(); in your code with return ob_get_clean(); then it's working fine.</p>\n"
}
]
| 2017/05/05 | [
"https://wordpress.stackexchange.com/questions/265997",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115973/"
]
| My code is like following:
```
<?php
function shortcode_callback() {
ob_start();
//my code here
ob_get_clean();
}
add_shortcode('shortcode', 'shortcode_callback');
?>
```
The above shortcode add to the page but the tile is showing at the bottom of the shortcode:
My Title
========
>
> [shortcode]
>
>
>
There is anything wrong doing I am. | You needs to change buffer like this:
```
<?php
function shortcode_callback() {
ob_start();
//my code here
return ob_get_clean();
}
add_shortcode('shortcode', 'shortcode_callback');
?>
```
Please check after replace ob\_get\_clean(); in your code with return ob\_get\_clean(); then it's working fine. |
266,005 | <p>I wasn't sure how to ask this. In WP, when the program runs, is it all "sequential"? By this I mean does WP hit the hook you registered and call it, wait, then proceed, synchronous? There's no Dependency Injection of IoC that I could find and no async.</p>
<p>I looked a the core, and I couldn't tell. I saw references to a few global variables and an array of hooks iterated over, but I did not understand the execution. I tried to with xdebug, but I have not grasped it yet.</p>
| [
{
"answer_id": 266008,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Yes it's all linear/sequential</strong>. There is no multi-threading or parallel execution in a PHP application. <strong>WordPress hooks run sequentially</strong>.</p>\n\n<p>When you hook into an action or filter, your code is just adding a <code>callable</code> object to an array somewhere. When the action fires, WordPress loops over those <code>callables</code> and calls them. As a sidenote, actions and filters use the same system and are technically the same.</p>\n\n<p>It makes sense to think or actions and hooks as manually fired events in a linear timeline, rather than callbacks from a process in another thread,</p>\n\n<p>Based on how things work in say Node, you may believe you can use hooks to hive off long running tasks or costly work to another thread. This is not the case, and running an infinite loop in a hook will cause the process to timeout. PHP processes run singlethreaded, and are not threadsafe, you can spawn additional processes, but that's entirely for you to manage, and has it's own issues.</p>\n"
},
{
"answer_id": 266010,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 4,
"selected": true,
"text": "<p>The <code>do_action()</code> and <code>apply_filters()</code> are both wrappers of the</p>\n\n<pre><code>WP_Hook::apply_filters()\n</code></pre>\n\n<p>method, that invokes the registered callbacks in <strong>sequential</strong> order (<a href=\"https://core.trac.wordpress.org/browser/tags/4.7/src/wp-includes/class-wp-hook.php#L276\" rel=\"nofollow noreferrer\">src</a>).</p>\n\n<p><strong>Here's a simple test:</strong></p>\n\n<p>Let's define a callback wrapper:</p>\n\n<pre><code>$callback_gen = function( $seconds ) { \n return function() use ( $seconds ) {\n sleep( $seconds ); \n printf( '%s finished' . PHP_EOL, $seconds ); \n };\n};\n</code></pre>\n\n<p>Next we register the callbacks to the <code>mytest</code> action:</p>\n\n<pre><code>add_action( 'mytest', $callback_gen( 3 ) );\nadd_action( 'mytest', $callback_gen( 5 ) );\nadd_action( 'mytest', $callback_gen( 1 ) );\n</code></pre>\n\n<p>Then we invoke the callbacks and measure the time it takes: </p>\n\n<pre><code>$start = microtime( true );\ndo_action( 'mytest' );\n$stop = microtime( true );\n</code></pre>\n\n<p>and display it with:</p>\n\n<pre><code>echo number_format( $stop - $start, 5 );\n</code></pre>\n\n<p>Here are outputs from 5 test runs:</p>\n\n<pre><code>3 finished \n5 finished \n1 finished \n9.00087\n\n3 finished \n5 finished \n1 finished \n9.00076\n\n3 finished \n5 finished \n1 finished \n9.00101\n\n3 finished \n5 finished \n1 finished \n9.00072\n\n3 finished \n5 finished \n1 finished \n9.00080\n</code></pre>\n\n<p>where the order is the same for each run, with total of c.a. 9 seconds, as expected for a <em>sequential</em> run order.</p>\n"
}
]
| 2017/05/05 | [
"https://wordpress.stackexchange.com/questions/266005",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/49089/"
]
| I wasn't sure how to ask this. In WP, when the program runs, is it all "sequential"? By this I mean does WP hit the hook you registered and call it, wait, then proceed, synchronous? There's no Dependency Injection of IoC that I could find and no async.
I looked a the core, and I couldn't tell. I saw references to a few global variables and an array of hooks iterated over, but I did not understand the execution. I tried to with xdebug, but I have not grasped it yet. | The `do_action()` and `apply_filters()` are both wrappers of the
```
WP_Hook::apply_filters()
```
method, that invokes the registered callbacks in **sequential** order ([src](https://core.trac.wordpress.org/browser/tags/4.7/src/wp-includes/class-wp-hook.php#L276)).
**Here's a simple test:**
Let's define a callback wrapper:
```
$callback_gen = function( $seconds ) {
return function() use ( $seconds ) {
sleep( $seconds );
printf( '%s finished' . PHP_EOL, $seconds );
};
};
```
Next we register the callbacks to the `mytest` action:
```
add_action( 'mytest', $callback_gen( 3 ) );
add_action( 'mytest', $callback_gen( 5 ) );
add_action( 'mytest', $callback_gen( 1 ) );
```
Then we invoke the callbacks and measure the time it takes:
```
$start = microtime( true );
do_action( 'mytest' );
$stop = microtime( true );
```
and display it with:
```
echo number_format( $stop - $start, 5 );
```
Here are outputs from 5 test runs:
```
3 finished
5 finished
1 finished
9.00087
3 finished
5 finished
1 finished
9.00076
3 finished
5 finished
1 finished
9.00101
3 finished
5 finished
1 finished
9.00072
3 finished
5 finished
1 finished
9.00080
```
where the order is the same for each run, with total of c.a. 9 seconds, as expected for a *sequential* run order. |
266,026 | <p>I'm on WordPress 4.7.4 and on my custom post types, I cannot assign tags as a regular user. </p>
<p>I have used CPTUI for creating everything, have mapped and created custom capabilities, have assigned roles to the custom caps, and have verified the user's roles are correct using <code>get_userdata()</code>, but I can't seem to get this working.</p>
<p>On the CPT, the taxonomies variable has <code>post_tag</code> set and I can see the tags meta box, I just can't do anything with it. I have tried to separate the term capabilities using the function below and the user has the <code>assign_post_tags</code> role, but it doesn't seem to do anything. Any help would be greatly appreciated.</p>
<p>Register CPT:</p>
<pre><code>function cptui_register_my_cpts_listing() {
/**
* Post Type: Listings.
*/
$labels = array(
"name" => __( 'Listings', 'text-domain' ),
"singular_name" => __( 'Listing', 'text-domain' ),
);
$args = array(
"label" => __( 'Listings', 'text-domain' ),
"labels" => $labels,
"description" => "",
"public" => true,
"publicly_queryable" => true,
"show_ui" => true,
"show_in_rest" => false,
"rest_base" => "",
"has_archive" => "archive-listing",
"show_in_menu" => true,
"exclude_from_search" => false,
"capability_type" => "listing",
"map_meta_cap" => true,
"hierarchical" => false,
"rewrite" => array( "slug" => "listing", "with_front" => true ),
"query_var" => "listing",
"supports" => array( "title", "editor", "thumbnail" ),
"taxonomies" => array( "post_tag", "location" ),
);
register_post_type( "listing", $args );
}
add_action( 'init', 'cptui_register_my_cpts_listing' );
</code></pre>
<p>Changing caps</p>
<pre><code>function set_builtin_tax_caps() {
$tax = get_taxonomy('post_tag');
$tax->cap->manage_terms = 'manage_post_tags';
$tax->cap->edit_terms = 'edit_post_tags';
$tax->cap->delete_terms = 'delete_post_tags';
$tax->cap->assign_terms = 'assign_post_tags';
$tax = get_taxonomy('category');
$tax->cap->manage_terms = 'manage_categories';
$tax->cap->edit_terms = 'edit_categories';
$tax->cap->delete_terms = 'delete_categories';
$tax->cap->assign_terms = 'assign_categories';
}
add_action('init', 'set_builtin_tax_caps');
</code></pre>
| [
{
"answer_id": 276245,
"author": "Nathan",
"author_id": 119119,
"author_profile": "https://wordpress.stackexchange.com/users/119119",
"pm_score": 0,
"selected": false,
"text": "<p>No matter what I tried, I couldn't get this working. I don't believe manually changing the terms are supported at this time for the post_tag taxonomy. Even if the user had the proper role and permission, you could not assign or edit post tags. The only solution I found was to create and register an entirely new taxonomy called \"tags\", define the custom capabilities, and set hierarchical to false.</p>\n"
},
{
"answer_id": 296144,
"author": "rogden",
"author_id": 109494,
"author_profile": "https://wordpress.stackexchange.com/users/109494",
"pm_score": 1,
"selected": false,
"text": "<p>It seems that although WP core creates four capability mappings for the built-in post_tag taxonomy (<code>manage_terms => manage_post_tags, edit_terms => edit_post_tags, delete_terms => delete_post_tags, assign_terms => assign_post_tags</code>) when it is registered, it uses different values when checking if the user has one of those capabilities. </p>\n\n<p>If you look at the implementation of the <code>map_meta_cap</code> function in WP core (in <code>wp-includes/capabilities.php</code> lines 513-523), you can see that the <code>edit_posts</code> capability is returned for <code>assign_post_tags</code> and <code>manage_categories</code> is returned for <code>manage_post_tags</code>, <code>edit_post_tags</code> and <code>delete_post_tags</code>. To fix this, you can add a filter and return the expected values:</p>\n\n<pre><code>add_filter( 'map_meta_cap', function( $caps, $cap, $user_id, $args ) {\n $caps_to_fix = [\n 'manage_post_tags',\n 'edit_post_tags',\n 'delete_post_tags',\n 'assign_post_tags',\n ];\n\n if ( in_array( $cap, $caps_to_fix ) ) {\n $caps = [ $cap ];\n }\n\n return $caps;\n}, 10, 4 );\n</code></pre>\n"
}
]
| 2017/05/05 | [
"https://wordpress.stackexchange.com/questions/266026",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/119119/"
]
| I'm on WordPress 4.7.4 and on my custom post types, I cannot assign tags as a regular user.
I have used CPTUI for creating everything, have mapped and created custom capabilities, have assigned roles to the custom caps, and have verified the user's roles are correct using `get_userdata()`, but I can't seem to get this working.
On the CPT, the taxonomies variable has `post_tag` set and I can see the tags meta box, I just can't do anything with it. I have tried to separate the term capabilities using the function below and the user has the `assign_post_tags` role, but it doesn't seem to do anything. Any help would be greatly appreciated.
Register CPT:
```
function cptui_register_my_cpts_listing() {
/**
* Post Type: Listings.
*/
$labels = array(
"name" => __( 'Listings', 'text-domain' ),
"singular_name" => __( 'Listing', 'text-domain' ),
);
$args = array(
"label" => __( 'Listings', 'text-domain' ),
"labels" => $labels,
"description" => "",
"public" => true,
"publicly_queryable" => true,
"show_ui" => true,
"show_in_rest" => false,
"rest_base" => "",
"has_archive" => "archive-listing",
"show_in_menu" => true,
"exclude_from_search" => false,
"capability_type" => "listing",
"map_meta_cap" => true,
"hierarchical" => false,
"rewrite" => array( "slug" => "listing", "with_front" => true ),
"query_var" => "listing",
"supports" => array( "title", "editor", "thumbnail" ),
"taxonomies" => array( "post_tag", "location" ),
);
register_post_type( "listing", $args );
}
add_action( 'init', 'cptui_register_my_cpts_listing' );
```
Changing caps
```
function set_builtin_tax_caps() {
$tax = get_taxonomy('post_tag');
$tax->cap->manage_terms = 'manage_post_tags';
$tax->cap->edit_terms = 'edit_post_tags';
$tax->cap->delete_terms = 'delete_post_tags';
$tax->cap->assign_terms = 'assign_post_tags';
$tax = get_taxonomy('category');
$tax->cap->manage_terms = 'manage_categories';
$tax->cap->edit_terms = 'edit_categories';
$tax->cap->delete_terms = 'delete_categories';
$tax->cap->assign_terms = 'assign_categories';
}
add_action('init', 'set_builtin_tax_caps');
``` | It seems that although WP core creates four capability mappings for the built-in post\_tag taxonomy (`manage_terms => manage_post_tags, edit_terms => edit_post_tags, delete_terms => delete_post_tags, assign_terms => assign_post_tags`) when it is registered, it uses different values when checking if the user has one of those capabilities.
If you look at the implementation of the `map_meta_cap` function in WP core (in `wp-includes/capabilities.php` lines 513-523), you can see that the `edit_posts` capability is returned for `assign_post_tags` and `manage_categories` is returned for `manage_post_tags`, `edit_post_tags` and `delete_post_tags`. To fix this, you can add a filter and return the expected values:
```
add_filter( 'map_meta_cap', function( $caps, $cap, $user_id, $args ) {
$caps_to_fix = [
'manage_post_tags',
'edit_post_tags',
'delete_post_tags',
'assign_post_tags',
];
if ( in_array( $cap, $caps_to_fix ) ) {
$caps = [ $cap ];
}
return $caps;
}, 10, 4 );
``` |
266,046 | <p>I want to add "Recent Posts" widget in a sidebar without a title but every time I add it, it shows "Recent Posts" text as title. How do I have it without title? I don't want to use any plugin for this.</p>
<p>Thank You.</p>
| [
{
"answer_id": 276245,
"author": "Nathan",
"author_id": 119119,
"author_profile": "https://wordpress.stackexchange.com/users/119119",
"pm_score": 0,
"selected": false,
"text": "<p>No matter what I tried, I couldn't get this working. I don't believe manually changing the terms are supported at this time for the post_tag taxonomy. Even if the user had the proper role and permission, you could not assign or edit post tags. The only solution I found was to create and register an entirely new taxonomy called \"tags\", define the custom capabilities, and set hierarchical to false.</p>\n"
},
{
"answer_id": 296144,
"author": "rogden",
"author_id": 109494,
"author_profile": "https://wordpress.stackexchange.com/users/109494",
"pm_score": 1,
"selected": false,
"text": "<p>It seems that although WP core creates four capability mappings for the built-in post_tag taxonomy (<code>manage_terms => manage_post_tags, edit_terms => edit_post_tags, delete_terms => delete_post_tags, assign_terms => assign_post_tags</code>) when it is registered, it uses different values when checking if the user has one of those capabilities. </p>\n\n<p>If you look at the implementation of the <code>map_meta_cap</code> function in WP core (in <code>wp-includes/capabilities.php</code> lines 513-523), you can see that the <code>edit_posts</code> capability is returned for <code>assign_post_tags</code> and <code>manage_categories</code> is returned for <code>manage_post_tags</code>, <code>edit_post_tags</code> and <code>delete_post_tags</code>. To fix this, you can add a filter and return the expected values:</p>\n\n<pre><code>add_filter( 'map_meta_cap', function( $caps, $cap, $user_id, $args ) {\n $caps_to_fix = [\n 'manage_post_tags',\n 'edit_post_tags',\n 'delete_post_tags',\n 'assign_post_tags',\n ];\n\n if ( in_array( $cap, $caps_to_fix ) ) {\n $caps = [ $cap ];\n }\n\n return $caps;\n}, 10, 4 );\n</code></pre>\n"
}
]
| 2017/05/06 | [
"https://wordpress.stackexchange.com/questions/266046",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/51790/"
]
| I want to add "Recent Posts" widget in a sidebar without a title but every time I add it, it shows "Recent Posts" text as title. How do I have it without title? I don't want to use any plugin for this.
Thank You. | It seems that although WP core creates four capability mappings for the built-in post\_tag taxonomy (`manage_terms => manage_post_tags, edit_terms => edit_post_tags, delete_terms => delete_post_tags, assign_terms => assign_post_tags`) when it is registered, it uses different values when checking if the user has one of those capabilities.
If you look at the implementation of the `map_meta_cap` function in WP core (in `wp-includes/capabilities.php` lines 513-523), you can see that the `edit_posts` capability is returned for `assign_post_tags` and `manage_categories` is returned for `manage_post_tags`, `edit_post_tags` and `delete_post_tags`. To fix this, you can add a filter and return the expected values:
```
add_filter( 'map_meta_cap', function( $caps, $cap, $user_id, $args ) {
$caps_to_fix = [
'manage_post_tags',
'edit_post_tags',
'delete_post_tags',
'assign_post_tags',
];
if ( in_array( $cap, $caps_to_fix ) ) {
$caps = [ $cap ];
}
return $caps;
}, 10, 4 );
``` |
266,055 | <p>I'm loading custom css stylesheet in my child theme 'functions.php' using this code</p>
<pre><code>if (ICL_LANGUAGE_CODE == 'ar') { ?>
<link rel="stylesheet" href="<?php echo get_stylesheet_directory_uri() . '/css/rtl.css' ?>" type="text/css">
</code></pre>
<p>When doing so, the media library can't be loaded, it just stick like this image:</p>
<p><a href="https://i.stack.imgur.com/xxLir.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xxLir.png" alt="enter image description here"></a></p>
<p>Just a loading spinner with no result, even uploading files is corrupted. When removing the code, everything works perfectly. </p>
<p>Any ideas?</p>
<hr>
| [
{
"answer_id": 266064,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 3,
"selected": true,
"text": "<p>If you are echoing this code straight from <code>functions.php</code> it would output way before anything else. It is too early in the load process.</p>\n\n<p>In most cases <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">enqueue</a> API functions should be used to output assets.</p>\n\n<p>Outside of that it is impossible to guess what precisely might it be breaking and how. Examining browser console for errors and such might net some information to go on.</p>\n"
},
{
"answer_id": 266086,
"author": "SopsoN",
"author_id": 110124,
"author_profile": "https://wordpress.stackexchange.com/users/110124",
"pm_score": 0,
"selected": false,
"text": "<p>Correct way to add custom CSS file to your theme is different. You need to add function like this to your functions.php. <strong>Have on mind</strong> path to file can be different in your case.</p>\n\n<pre><code>function include_css()\n{\n wp_enqueue_style( 'rtl', get_stylesheet_directory_uri() . '/css/rtl.css' );\n}\nadd_action( 'wp_enqueue_scripts', 'include_css' );\n</code></pre>\n"
},
{
"answer_id": 266088,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 0,
"selected": false,
"text": "<p>In addition to the problems pointed out in the other answers, in the posted code, you're missing the closing bracket <code>}</code>. If this is the exact code you're using, then when the PHP interpreter comes to this piece of malformed code, it will unceremoniously die.</p>\n\n<p>PHP if constructs can be formed in the following ways:</p>\n\n<p>With brackets surrounding 1 or more lines of instructions:</p>\n\n<pre><code>if( $something ) {\n do_something();\n}\n</code></pre>\n\n<p>An alternate format that will work with multiple lines:</p>\n\n<pre><code>if( $something ) :\n do_something();\nendif;\n</code></pre>\n\n<p>Another alternate format that only works with on line of instruction</p>\n\n<pre><code>if( $something )\n do_somthing();\n</code></pre>\n"
}
]
| 2017/05/06 | [
"https://wordpress.stackexchange.com/questions/266055",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102827/"
]
| I'm loading custom css stylesheet in my child theme 'functions.php' using this code
```
if (ICL_LANGUAGE_CODE == 'ar') { ?>
<link rel="stylesheet" href="<?php echo get_stylesheet_directory_uri() . '/css/rtl.css' ?>" type="text/css">
```
When doing so, the media library can't be loaded, it just stick like this image:
[](https://i.stack.imgur.com/xxLir.png)
Just a loading spinner with no result, even uploading files is corrupted. When removing the code, everything works perfectly.
Any ideas?
--- | If you are echoing this code straight from `functions.php` it would output way before anything else. It is too early in the load process.
In most cases [enqueue](https://developer.wordpress.org/reference/functions/wp_enqueue_style/) API functions should be used to output assets.
Outside of that it is impossible to guess what precisely might it be breaking and how. Examining browser console for errors and such might net some information to go on. |
266,094 | <p>First, thank you for your help. </p>
<p>I have created a custom template, added two metaboxes in Pages using a 'Page_Fiche_Metier.php' template.
One meta box is to upload an image. But the Upload Button is not opening the media library, although I have added the jQuery script. </p>
<pre><code>Here is the code for the meta-boxes.php
<?php
function prfx_custom_meta(){
global $post;
if ( 'page_fiche_metier.php' == get_post_meta( $post->ID, '_wp_page_template', true ) ) {
add_meta_box( 'prfx_meta', __( 'Vidéo Présentation Bas de Page', 'prfx-textdomain' ), 'prfx_meta_callback', 'page' );
}
}
add_action( 'add_meta_boxes', 'prfx_custom_meta' );
function prfx_meta_callback( $post ) {
wp_nonce_field( basename( __FILE__ ), 'prfx_nonce' );
$prfx_stored_meta = get_post_meta( $post->ID );
?>
<p>
<label for="meta-text" class="prfx-row-title"><?php _e( 'Titre', 'prfx-textdomain' )?></label>
<input type="text" name="meta-text" id="meta-text" value="<?php if ( isset ( $prfx_stored_meta['meta-text'] ) ) echo $prfx_stored_meta['meta-text'][0]; ?>" />
</p>
<p>
<label for="meta-url" class="prfx-row-title"><?php _e( 'URL', 'prfx-textdomain' )?></label>
<input type="text" name="meta-url" id="meta-url" value="<?php if ( isset ( $prfx_stored_meta['meta-url'] ) ) echo $prfx_stored_meta['meta-url'][0]; ?>" />
</p>
<p>
<label for="meta-image" class="prfx-row-title"><?php _e( 'Example File Upload', 'prfx-textdomain' )?></label>
<input type="text" name="meta-image" id="meta-image" value="<?php if ( isset ( $prfx_stored_meta['meta-image'] ) ) echo $prfx_stored_meta[
'meta-image'][0]; ?>" />
<input type="button" id="meta-image-button" class="button" value="<?php _e( 'Choisir un fichier', 'prfx-textdomain' )?>" />
</p>
<?php
}
function prfx_meta_save( $post_id ) {
// Checks save status
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST[ 'prfx_nonce' ] ) && wp_verify_nonce( $_POST[ 'prfx_nonce' ], basename( __FILE__ ) ) ) ? 'true' : 'false';
// Exits script depending on save status
if ( $is_autosave || $is_revision || !$is_valid_nonce ) {
return;
}
if( isset( $_POST[ 'meta-text' ] ) ) {
update_post_meta( $post_id, 'meta-text', sanitize_text_field( $_POST[ 'meta-text' ] ) );
}
if( isset( $_POST[ 'meta-url' ] ) ) {
update_post_meta( $post_id, 'meta-url', sanitize_text_field( $_POST[ 'meta-url' ] ) );
}
if( isset( $_POST[ 'meta-image' ] ) ) {
update_post_meta( $post_id, 'meta-image', $_POST[ 'meta-image' ] );
}
}
add_action( 'save_post', 'prfx_meta_save' );
function prfx_image_enqueue() {
global $typenow;
if( $typenow == 'post' ) {
wp_enqueue_media();
// Registers and enqueues the required javascript.
wp_register_script( 'meta-box-image', plugin_dir_url( __FILE__ ) . 'meta-box-image.js', array( 'jquery' ) );
wp_localize_script( 'meta-box-image', 'meta_image',
array(
'title' => __( 'Choose or Upload an Image', 'prfx-textdomain' ),
'button' => __( 'Use this image', 'prfx-textdomain' ),
)
);
wp_enqueue_script( 'meta-box-image' );
}
}
add_action( 'admin_enqueue_scripts', 'prfx_image_enqueue' );
</code></pre>
<p>And the code for js: </p>
<pre><code>/*
* Attaches the image uploader to the input field
*/
jQuery(document).ready(function($){
// Instantiates the variable that holds the media library frame.
var meta_image_frame;
// Runs when the image button is clicked.
$('#meta-image-button').click(function(e){
// Prevents the default action from occuring.
e.preventDefault();
// If the frame already exists, re-open it.
if ( meta_image_frame ) {
meta_image_frame.open();
return;
}
// Sets up the media library frame
meta_image_frame = wp.media.frames.meta_image_frame = wp.media({
title: meta_image.title,
button: { text: meta_image.button },
library: { type: 'image' }
});
// Runs when an image is selected.
meta_image_frame.on('select', function(){
// Grabs the attachment selection and creates a JSON representation of the model.
var media_attachment = meta_image_frame.state().get('selection').first().toJSON();
// Sends the attachment URL to our custom image input field.
$('#meta-image').val(media_attachment.url);
});
// Opens the media library frame.
meta_image_frame.open();
});
});
</code></pre>
| [
{
"answer_id": 266064,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 3,
"selected": true,
"text": "<p>If you are echoing this code straight from <code>functions.php</code> it would output way before anything else. It is too early in the load process.</p>\n\n<p>In most cases <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">enqueue</a> API functions should be used to output assets.</p>\n\n<p>Outside of that it is impossible to guess what precisely might it be breaking and how. Examining browser console for errors and such might net some information to go on.</p>\n"
},
{
"answer_id": 266086,
"author": "SopsoN",
"author_id": 110124,
"author_profile": "https://wordpress.stackexchange.com/users/110124",
"pm_score": 0,
"selected": false,
"text": "<p>Correct way to add custom CSS file to your theme is different. You need to add function like this to your functions.php. <strong>Have on mind</strong> path to file can be different in your case.</p>\n\n<pre><code>function include_css()\n{\n wp_enqueue_style( 'rtl', get_stylesheet_directory_uri() . '/css/rtl.css' );\n}\nadd_action( 'wp_enqueue_scripts', 'include_css' );\n</code></pre>\n"
},
{
"answer_id": 266088,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 0,
"selected": false,
"text": "<p>In addition to the problems pointed out in the other answers, in the posted code, you're missing the closing bracket <code>}</code>. If this is the exact code you're using, then when the PHP interpreter comes to this piece of malformed code, it will unceremoniously die.</p>\n\n<p>PHP if constructs can be formed in the following ways:</p>\n\n<p>With brackets surrounding 1 or more lines of instructions:</p>\n\n<pre><code>if( $something ) {\n do_something();\n}\n</code></pre>\n\n<p>An alternate format that will work with multiple lines:</p>\n\n<pre><code>if( $something ) :\n do_something();\nendif;\n</code></pre>\n\n<p>Another alternate format that only works with on line of instruction</p>\n\n<pre><code>if( $something )\n do_somthing();\n</code></pre>\n"
}
]
| 2017/05/06 | [
"https://wordpress.stackexchange.com/questions/266094",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/119161/"
]
| First, thank you for your help.
I have created a custom template, added two metaboxes in Pages using a 'Page\_Fiche\_Metier.php' template.
One meta box is to upload an image. But the Upload Button is not opening the media library, although I have added the jQuery script.
```
Here is the code for the meta-boxes.php
<?php
function prfx_custom_meta(){
global $post;
if ( 'page_fiche_metier.php' == get_post_meta( $post->ID, '_wp_page_template', true ) ) {
add_meta_box( 'prfx_meta', __( 'Vidéo Présentation Bas de Page', 'prfx-textdomain' ), 'prfx_meta_callback', 'page' );
}
}
add_action( 'add_meta_boxes', 'prfx_custom_meta' );
function prfx_meta_callback( $post ) {
wp_nonce_field( basename( __FILE__ ), 'prfx_nonce' );
$prfx_stored_meta = get_post_meta( $post->ID );
?>
<p>
<label for="meta-text" class="prfx-row-title"><?php _e( 'Titre', 'prfx-textdomain' )?></label>
<input type="text" name="meta-text" id="meta-text" value="<?php if ( isset ( $prfx_stored_meta['meta-text'] ) ) echo $prfx_stored_meta['meta-text'][0]; ?>" />
</p>
<p>
<label for="meta-url" class="prfx-row-title"><?php _e( 'URL', 'prfx-textdomain' )?></label>
<input type="text" name="meta-url" id="meta-url" value="<?php if ( isset ( $prfx_stored_meta['meta-url'] ) ) echo $prfx_stored_meta['meta-url'][0]; ?>" />
</p>
<p>
<label for="meta-image" class="prfx-row-title"><?php _e( 'Example File Upload', 'prfx-textdomain' )?></label>
<input type="text" name="meta-image" id="meta-image" value="<?php if ( isset ( $prfx_stored_meta['meta-image'] ) ) echo $prfx_stored_meta[
'meta-image'][0]; ?>" />
<input type="button" id="meta-image-button" class="button" value="<?php _e( 'Choisir un fichier', 'prfx-textdomain' )?>" />
</p>
<?php
}
function prfx_meta_save( $post_id ) {
// Checks save status
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST[ 'prfx_nonce' ] ) && wp_verify_nonce( $_POST[ 'prfx_nonce' ], basename( __FILE__ ) ) ) ? 'true' : 'false';
// Exits script depending on save status
if ( $is_autosave || $is_revision || !$is_valid_nonce ) {
return;
}
if( isset( $_POST[ 'meta-text' ] ) ) {
update_post_meta( $post_id, 'meta-text', sanitize_text_field( $_POST[ 'meta-text' ] ) );
}
if( isset( $_POST[ 'meta-url' ] ) ) {
update_post_meta( $post_id, 'meta-url', sanitize_text_field( $_POST[ 'meta-url' ] ) );
}
if( isset( $_POST[ 'meta-image' ] ) ) {
update_post_meta( $post_id, 'meta-image', $_POST[ 'meta-image' ] );
}
}
add_action( 'save_post', 'prfx_meta_save' );
function prfx_image_enqueue() {
global $typenow;
if( $typenow == 'post' ) {
wp_enqueue_media();
// Registers and enqueues the required javascript.
wp_register_script( 'meta-box-image', plugin_dir_url( __FILE__ ) . 'meta-box-image.js', array( 'jquery' ) );
wp_localize_script( 'meta-box-image', 'meta_image',
array(
'title' => __( 'Choose or Upload an Image', 'prfx-textdomain' ),
'button' => __( 'Use this image', 'prfx-textdomain' ),
)
);
wp_enqueue_script( 'meta-box-image' );
}
}
add_action( 'admin_enqueue_scripts', 'prfx_image_enqueue' );
```
And the code for js:
```
/*
* Attaches the image uploader to the input field
*/
jQuery(document).ready(function($){
// Instantiates the variable that holds the media library frame.
var meta_image_frame;
// Runs when the image button is clicked.
$('#meta-image-button').click(function(e){
// Prevents the default action from occuring.
e.preventDefault();
// If the frame already exists, re-open it.
if ( meta_image_frame ) {
meta_image_frame.open();
return;
}
// Sets up the media library frame
meta_image_frame = wp.media.frames.meta_image_frame = wp.media({
title: meta_image.title,
button: { text: meta_image.button },
library: { type: 'image' }
});
// Runs when an image is selected.
meta_image_frame.on('select', function(){
// Grabs the attachment selection and creates a JSON representation of the model.
var media_attachment = meta_image_frame.state().get('selection').first().toJSON();
// Sends the attachment URL to our custom image input field.
$('#meta-image').val(media_attachment.url);
});
// Opens the media library frame.
meta_image_frame.open();
});
});
``` | If you are echoing this code straight from `functions.php` it would output way before anything else. It is too early in the load process.
In most cases [enqueue](https://developer.wordpress.org/reference/functions/wp_enqueue_style/) API functions should be used to output assets.
Outside of that it is impossible to guess what precisely might it be breaking and how. Examining browser console for errors and such might net some information to go on. |
266,104 | <p>I want to display every 3 products in a <code><ul></code></p>
<p>Example of how HTML should look:</p>
<pre><code><ul>
<li>product looping 1</li>
<li>product looping 2</li>
<li>product looping 3</li>
</ul>
<ul>
<li>product looping 4</li>
<li>product looping 5</li>
<li>product looping 6</li>
</ul>
</code></pre>
<p>WP_Query Code:</p>
<pre><code><?php
$args = array(
'post_type' => 'product',
'posts_per_page' => 8,
'orderby' => 'date',
);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) : $loop->the_post();
//wc_get_template_part( 'content', 'product' );
?>
<li class="col-md-3">
<div class="gridproduto">
<a href="<?php the_permalink(); ?>">
<?php global $post, $product; ?>
<?php if ( $product->is_on_sale() ) : ?>
<?php echo apply_filters( 'woocommerce_sale_flash', '<span class="onsale">' . __( 'Sale!', 'woocommerce' ) . '</span>', $post, $product ); ?>
<?php endif; ?>
<span class="thumbnail-product">
<?php the_post_thumbnail( 'medium' ); ?>
</span>
</a>
<div class="main-infos">
<a href="<?php the_permalink(); ?>">
<h5><?php the_title(); ?></h5>
<div><?php echo $product->get_price_html(); ?></div>
<span class="preco_boleto">
<?php
$boleto = $product->get_price();
$desconto = 10;
$division = $boleto - ( $boleto * ($desconto / 100) );
echo "R$ " . number_format( round($division, 2), 2, ',', '.' );
?>
</span>
<span class="parcela">no boleto ou em até <br> 3x de <?php echo number_format( round( $product->get_price() / 3, 2), 2, ',', '.' ); ?> sem juros.</span>
</a>
<a href="#" class="btn-orange">Comprar</a>
</div>
</div>
</li>
<?php endwhile;
} else {
echo __( 'No products found' );
}
wp_reset_postdata();
?>
</code></pre>
| [
{
"answer_id": 266064,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 3,
"selected": true,
"text": "<p>If you are echoing this code straight from <code>functions.php</code> it would output way before anything else. It is too early in the load process.</p>\n\n<p>In most cases <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">enqueue</a> API functions should be used to output assets.</p>\n\n<p>Outside of that it is impossible to guess what precisely might it be breaking and how. Examining browser console for errors and such might net some information to go on.</p>\n"
},
{
"answer_id": 266086,
"author": "SopsoN",
"author_id": 110124,
"author_profile": "https://wordpress.stackexchange.com/users/110124",
"pm_score": 0,
"selected": false,
"text": "<p>Correct way to add custom CSS file to your theme is different. You need to add function like this to your functions.php. <strong>Have on mind</strong> path to file can be different in your case.</p>\n\n<pre><code>function include_css()\n{\n wp_enqueue_style( 'rtl', get_stylesheet_directory_uri() . '/css/rtl.css' );\n}\nadd_action( 'wp_enqueue_scripts', 'include_css' );\n</code></pre>\n"
},
{
"answer_id": 266088,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 0,
"selected": false,
"text": "<p>In addition to the problems pointed out in the other answers, in the posted code, you're missing the closing bracket <code>}</code>. If this is the exact code you're using, then when the PHP interpreter comes to this piece of malformed code, it will unceremoniously die.</p>\n\n<p>PHP if constructs can be formed in the following ways:</p>\n\n<p>With brackets surrounding 1 or more lines of instructions:</p>\n\n<pre><code>if( $something ) {\n do_something();\n}\n</code></pre>\n\n<p>An alternate format that will work with multiple lines:</p>\n\n<pre><code>if( $something ) :\n do_something();\nendif;\n</code></pre>\n\n<p>Another alternate format that only works with on line of instruction</p>\n\n<pre><code>if( $something )\n do_somthing();\n</code></pre>\n"
}
]
| 2017/05/07 | [
"https://wordpress.stackexchange.com/questions/266104",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/119173/"
]
| I want to display every 3 products in a `<ul>`
Example of how HTML should look:
```
<ul>
<li>product looping 1</li>
<li>product looping 2</li>
<li>product looping 3</li>
</ul>
<ul>
<li>product looping 4</li>
<li>product looping 5</li>
<li>product looping 6</li>
</ul>
```
WP\_Query Code:
```
<?php
$args = array(
'post_type' => 'product',
'posts_per_page' => 8,
'orderby' => 'date',
);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) : $loop->the_post();
//wc_get_template_part( 'content', 'product' );
?>
<li class="col-md-3">
<div class="gridproduto">
<a href="<?php the_permalink(); ?>">
<?php global $post, $product; ?>
<?php if ( $product->is_on_sale() ) : ?>
<?php echo apply_filters( 'woocommerce_sale_flash', '<span class="onsale">' . __( 'Sale!', 'woocommerce' ) . '</span>', $post, $product ); ?>
<?php endif; ?>
<span class="thumbnail-product">
<?php the_post_thumbnail( 'medium' ); ?>
</span>
</a>
<div class="main-infos">
<a href="<?php the_permalink(); ?>">
<h5><?php the_title(); ?></h5>
<div><?php echo $product->get_price_html(); ?></div>
<span class="preco_boleto">
<?php
$boleto = $product->get_price();
$desconto = 10;
$division = $boleto - ( $boleto * ($desconto / 100) );
echo "R$ " . number_format( round($division, 2), 2, ',', '.' );
?>
</span>
<span class="parcela">no boleto ou em até <br> 3x de <?php echo number_format( round( $product->get_price() / 3, 2), 2, ',', '.' ); ?> sem juros.</span>
</a>
<a href="#" class="btn-orange">Comprar</a>
</div>
</div>
</li>
<?php endwhile;
} else {
echo __( 'No products found' );
}
wp_reset_postdata();
?>
``` | If you are echoing this code straight from `functions.php` it would output way before anything else. It is too early in the load process.
In most cases [enqueue](https://developer.wordpress.org/reference/functions/wp_enqueue_style/) API functions should be used to output assets.
Outside of that it is impossible to guess what precisely might it be breaking and how. Examining browser console for errors and such might net some information to go on. |
266,141 | <p>Is it possible to loop through all the pages in a website? If so, how?</p>
<p>I'm building a one-pager resume website, and I want to display all of the website's pages as parts of my main page.</p>
| [
{
"answer_id": 266145,
"author": "Picard",
"author_id": 118566,
"author_profile": "https://wordpress.stackexchange.com/users/118566",
"pm_score": 1,
"selected": false,
"text": "<p>Are you talking about something like this:</p>\n\n<pre><code> $pages = get_pages(); \n foreach ($pages as $page) {\n echo $page->post_title;\n }\n</code></pre>\n\n<p>?</p>\n\n<p>Of course you can sort them (<code>sort_column</code>, <code>sort_order</code>), filter out (<code>exclude</code>) unwanted etc. by using specific arguments applied to <code>get_pages()</code> function - you can check them in the <a href=\"https://codex.wordpress.org/Function_Reference/get_pages\" rel=\"nofollow noreferrer\">Wordpress docs</a>.</p>\n"
},
{
"answer_id": 266155,
"author": "Gal Grünfeld",
"author_id": 116705,
"author_profile": "https://wordpress.stackexchange.com/users/116705",
"pm_score": 4,
"selected": true,
"text": "<p>I was able to learn how to do it. </p>\n\n<p>Here's a solution:</p>\n\n<pre><code>$pages = get_pages();\nforeach($pages as $page) {\n echo($page->post_content);\n}\n</code></pre>\n"
},
{
"answer_id": 309114,
"author": "Nicolay Hekkens",
"author_id": 147271,
"author_profile": "https://wordpress.stackexchange.com/users/147271",
"pm_score": -1,
"selected": false,
"text": "<p>I would suggest doing this:</p>\n\n<pre><code>query_posts(array('post_type' => 'page'));\n\nwhile (have_posts()) { \n the_post();\n get_template_part( 'templates/list/content', 'xxx' );\n}\n\nwp_reset_query();\n</code></pre>\n\n<p>Doing this you will be able to use </p>\n\n<pre><code>get_template_part( 'templates/list/content', 'xxx' );\n</code></pre>\n"
}
]
| 2017/05/07 | [
"https://wordpress.stackexchange.com/questions/266141",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/116705/"
]
| Is it possible to loop through all the pages in a website? If so, how?
I'm building a one-pager resume website, and I want to display all of the website's pages as parts of my main page. | I was able to learn how to do it.
Here's a solution:
```
$pages = get_pages();
foreach($pages as $page) {
echo($page->post_content);
}
``` |
266,146 | <p>As I'm new to Linux and WPCLI, I moved a site from one VPS to another but URL stayed the same and PHPmyadmin doesn't work so as of the moment I can't change the site URL from PHPmyadmin.</p>
<p>When I try to navigate to the site from the browser (after setting up a database, changing wp-config.php accordingly, uploading site dir with right permissions etc) I get a 500 error.</p>
<p>I ten went did <code>sudo tail /var/log/apache2/error.log</code> and saw an error regarding that site, but with the old url (so somewhere the url wasn't changed and this seems to be the source of the problem). This is the error:</p>
<blockquote>
<p>[Sun May 07 15:20:21.881125 2017] [:error] [pid 19110] [client
IP_ADDRESS:56239] PHP Fatal error:</p>
<p>Unknown: Failed opening required '/var/www/html/contentperhour.com/wordfence-waf.php' (include_path='.:/usr/share/php') in Unknown on line 0</p>
</blockquote>
<p>I thought it's Wordfence related so I tried to remove it:</p>
<pre><code>sudo wp plugin deactivate wordfence
sudo wp plugin uninstall wordfence
</code></pre>
<p>Removing Wordfence and restarting the server didn't help.</p>
<p>How could I change the URL of the site from outside the site or outside PHPmyadmin?</p>
| [
{
"answer_id": 266145,
"author": "Picard",
"author_id": 118566,
"author_profile": "https://wordpress.stackexchange.com/users/118566",
"pm_score": 1,
"selected": false,
"text": "<p>Are you talking about something like this:</p>\n\n<pre><code> $pages = get_pages(); \n foreach ($pages as $page) {\n echo $page->post_title;\n }\n</code></pre>\n\n<p>?</p>\n\n<p>Of course you can sort them (<code>sort_column</code>, <code>sort_order</code>), filter out (<code>exclude</code>) unwanted etc. by using specific arguments applied to <code>get_pages()</code> function - you can check them in the <a href=\"https://codex.wordpress.org/Function_Reference/get_pages\" rel=\"nofollow noreferrer\">Wordpress docs</a>.</p>\n"
},
{
"answer_id": 266155,
"author": "Gal Grünfeld",
"author_id": 116705,
"author_profile": "https://wordpress.stackexchange.com/users/116705",
"pm_score": 4,
"selected": true,
"text": "<p>I was able to learn how to do it. </p>\n\n<p>Here's a solution:</p>\n\n<pre><code>$pages = get_pages();\nforeach($pages as $page) {\n echo($page->post_content);\n}\n</code></pre>\n"
},
{
"answer_id": 309114,
"author": "Nicolay Hekkens",
"author_id": 147271,
"author_profile": "https://wordpress.stackexchange.com/users/147271",
"pm_score": -1,
"selected": false,
"text": "<p>I would suggest doing this:</p>\n\n<pre><code>query_posts(array('post_type' => 'page'));\n\nwhile (have_posts()) { \n the_post();\n get_template_part( 'templates/list/content', 'xxx' );\n}\n\nwp_reset_query();\n</code></pre>\n\n<p>Doing this you will be able to use </p>\n\n<pre><code>get_template_part( 'templates/list/content', 'xxx' );\n</code></pre>\n"
}
]
| 2017/05/07 | [
"https://wordpress.stackexchange.com/questions/266146",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
]
| As I'm new to Linux and WPCLI, I moved a site from one VPS to another but URL stayed the same and PHPmyadmin doesn't work so as of the moment I can't change the site URL from PHPmyadmin.
When I try to navigate to the site from the browser (after setting up a database, changing wp-config.php accordingly, uploading site dir with right permissions etc) I get a 500 error.
I ten went did `sudo tail /var/log/apache2/error.log` and saw an error regarding that site, but with the old url (so somewhere the url wasn't changed and this seems to be the source of the problem). This is the error:
>
> [Sun May 07 15:20:21.881125 2017] [:error] [pid 19110] [client
> IP\_ADDRESS:56239] PHP Fatal error:
>
>
> Unknown: Failed opening required '/var/www/html/contentperhour.com/wordfence-waf.php' (include\_path='.:/usr/share/php') in Unknown on line 0
>
>
>
I thought it's Wordfence related so I tried to remove it:
```
sudo wp plugin deactivate wordfence
sudo wp plugin uninstall wordfence
```
Removing Wordfence and restarting the server didn't help.
How could I change the URL of the site from outside the site or outside PHPmyadmin? | I was able to learn how to do it.
Here's a solution:
```
$pages = get_pages();
foreach($pages as $page) {
echo($page->post_content);
}
``` |
266,151 | <blockquote>
<p>Can we please stick ourselves to the genuine solution, not a slipshod
remedy. The objective of this question is to completely get rid of the
class "widget-item". please do not post compromised solutions like
manipulating CSS etc else the objective of posting the question will
be defied.</p>
</blockquote>
<p>I want to get rid of this class="<strong>widget-item</strong>" because this is creating extra margin/padding. Please see the image.<a href="https://i.stack.imgur.com/tRunb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tRunb.png" alt="enter image description here"></a></p>
<p>I want to get rid of this class, but not <code>div</code> as it might rupture the design.</p>
<p>I am sure there should be some method to remove this because when we write widgets for menus this is possible like this →</p>
<pre><code>'container' => 'nav',
'container_class' => 'footer-menu'
</code></pre>
<p>we can change <code>div</code> to <code>nav</code> and also insert our own class "<strong>footer-menu</strong>".</p>
<p>Live Link where this is happening could be seen <a href="http://codepen.trafficopedia.com/site01/" rel="nofollow noreferrer">here</a>.</p>
| [
{
"answer_id": 266157,
"author": "Picard",
"author_id": 118566,
"author_profile": "https://wordpress.stackexchange.com/users/118566",
"pm_score": 2,
"selected": false,
"text": "<p>The most straightforward way would be to overwrite this in your CSS file, for instance like this:</p>\n\n<pre><code>.widgettitle {\n padding: 0;\n margin: 0;\n}\n</code></pre>\n\n<p>Alternatively you can change the name of the class when registering your widget (possibly in your functions.php file) - look for the <code>'before_title'</code> parameter. Here's and example form the original twentysexteen template:</p>\n\n<pre><code>register_sidebar( array(\n 'name' => __( 'Sidebar', 'twentysixteen' ),\n 'id' => 'sidebar-1',\n 'description' => __( 'Add widgets here to appear in your sidebar.', 'twentysixteen' ),\n 'before_widget' => '<section id=\"%1$s\" class=\"widget %2$s\">',\n 'after_widget' => '</section>',\n 'before_title' => '<h2 class=\"widget-title\">',\n 'after_title' => '</h2>',\n ) );\n</code></pre>\n"
},
{
"answer_id": 266163,
"author": "Christina",
"author_id": 64742,
"author_profile": "https://wordpress.stackexchange.com/users/64742",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>widget-item</code> class is in the $params for registered sidebars in the theme you are using. If you want to remove it and replace it with something else, you can by using the <code>dynamic_sidebar_params</code> filter or you can find it in your theme (if you are using a parent theme and not a child theme) and just change it, however the results may be not what you expect because the padding and margin is not coming from that class.</p>\n\n<p>This filter below would be added last in your child theme's functions.php file AFTER all other functions and outside of all functions and after all includes/requires. In this example <code>widget-item</code> will be replaced by <code>my-widget-class</code> (which you would change). In this situation, <code>.widget-item</code> or any class here provides a global class to widgets and does not have padding or margin on it as in your image. When you use developer tools, you can clearly see that the child is the element with the margin and the padding. </p>\n\n<pre><code>function prefix_filter_widget_div_wrappper( $params ) {\n\n $params[0]['before_widget'] = '<div class=\"my-widget-class %2$s\">' ;\n\n $params[0]['after_widget'] = '</div>' ;\n\n return $params;\n\n}\nadd_filter( 'dynamic_sidebar_params' , 'prefix_filter_widget_div_wrappper' );\n</code></pre>\n\n<p>The issue in your situation is this <code>.newsletter</code> child of <code>.widget-item</code> and if you use CSS specificity, you can adjust the appearance for the location:</p>\n\n<pre><code>.newsletter {\n padding: 25px;\n ..etc.\n}\n</code></pre>\n\n<p>Like this:</p>\n\n<pre><code>.site-footer .newseltter {\n padding: 10px;\n margin: 0;\n}\n</code></pre>\n\n<h2>Conditional for <code>dynamic_sidebar_params</code> filter.</h2>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/register_sidebar\" rel=\"nofollow noreferrer\">Locate your registered sidebar ID by looking for where it is registered in your theme functions php file(s) parent or child</a>.</p>\n\n<pre><code>function prefix_filter_widget_div_wrappper_conditional( $params ) {\n\n //* where `register-sidebar-id` is the registered sidebar id (you would look for this in your theme's code)\n\n if ( 'registered-sidebar-id' === $params[0][ 'id' ] ) :\n\n $params[0]['before_widget'] = '<div class=\"my-widget-class %2$s\">' ;\n\n $params[0]['after_widget'] = '</div>' ;\n\n endif;\n\n return $params;\n\n}\nadd_filter( 'dynamic_sidebar_params' , 'prefix_filter_widget_div_wrappper_conditional' );\n</code></pre>\n"
},
{
"answer_id": 266165,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps the easiest way would be to create a plugin that enqueues a jQuery script.</p>\n\n<p>plugin.php</p>\n\n<pre><code>/**\n * Plugin Name: Remove Widget Item Class\n */\n\nadd_action( 'wp_enqueue_scripts', 'wpse_266151_enqueue_scripts' );\nwpse_266151_enqueue_scripts() {\n wp_enqueue_script(\n 'remove-widget-item-class', \n plugins_url( 'remove-widget-item-class.js', __FILE__ ), \n [ 'jquery' ]\n );\n}\n</code></pre>\n\n<p>remove-widget-item-class.js</p>\n\n<pre><code>jQuery( \".widget-item\" ).removeClass( \"widget-item\" );\n</code></pre>\n"
}
]
| 2017/05/07 | [
"https://wordpress.stackexchange.com/questions/266151",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105791/"
]
| >
> Can we please stick ourselves to the genuine solution, not a slipshod
> remedy. The objective of this question is to completely get rid of the
> class "widget-item". please do not post compromised solutions like
> manipulating CSS etc else the objective of posting the question will
> be defied.
>
>
>
I want to get rid of this class="**widget-item**" because this is creating extra margin/padding. Please see the image.[](https://i.stack.imgur.com/tRunb.png)
I want to get rid of this class, but not `div` as it might rupture the design.
I am sure there should be some method to remove this because when we write widgets for menus this is possible like this →
```
'container' => 'nav',
'container_class' => 'footer-menu'
```
we can change `div` to `nav` and also insert our own class "**footer-menu**".
Live Link where this is happening could be seen [here](http://codepen.trafficopedia.com/site01/). | The most straightforward way would be to overwrite this in your CSS file, for instance like this:
```
.widgettitle {
padding: 0;
margin: 0;
}
```
Alternatively you can change the name of the class when registering your widget (possibly in your functions.php file) - look for the `'before_title'` parameter. Here's and example form the original twentysexteen template:
```
register_sidebar( array(
'name' => __( 'Sidebar', 'twentysixteen' ),
'id' => 'sidebar-1',
'description' => __( 'Add widgets here to appear in your sidebar.', 'twentysixteen' ),
'before_widget' => '<section id="%1$s" class="widget %2$s">',
'after_widget' => '</section>',
'before_title' => '<h2 class="widget-title">',
'after_title' => '</h2>',
) );
``` |
266,243 | <p>I'm trying to count results for a given query, but I don't actually need the posts so I'm trying to figure out if there's a way to count posts without querying them. Something similar to <a href="https://codex.wordpress.org/Function_Reference/wp_count_posts" rel="nofollow noreferrer">https://codex.wordpress.org/Function_Reference/wp_count_posts</a></p>
<p>I'm counting posts by meta key/value so <code>wp_count_posts()</code> won't work.</p>
<p>Here's what I'm currently doing:</p>
<pre><code>$query = new WP_Query(array(
"post_type" => 'my-post-type',
"posts_per_page" => 0,
"meta_key" => "my_custom_key",
"meta_value" => "some_value",
));
echo $query->found_posts;
</code></pre>
| [
{
"answer_id": 266248,
"author": "Emin Rahmanov",
"author_id": 119256,
"author_profile": "https://wordpress.stackexchange.com/users/119256",
"pm_score": -1,
"selected": false,
"text": "<p>You set posts_per_page 0 value. posts_per_page for all posts set -1 or another positive number</p>\n\n<pre><code>$query = new WP_Query( array(\n \"post_type\" => 'my-post-type',\n \"posts_per_page\" => -1,\n \"meta_key\" => \"my_custom_key\",\n \"meta_value\" => \"some_value\",\n) );\n\necho $query->found_posts;\n</code></pre>\n"
},
{
"answer_id": 266289,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>The non perfect solution is to just minimize the amount of information carried by the query, and the side effects. This can be done by requesting only the post IDs and not populating any caches. </p>\n\n<p>Your query should be something like</p>\n\n<pre><code>$query = new WP_Query(array(\n ...\n 'fields' => 'ids',\n 'cache_results' => false,\n 'update_post_meta_cache' => false,\n 'update_post_term_cache' => false,\n));\n</code></pre>\n\n<p>So you still get too much information - an array of integers instead of one, but since the DB has to go over them in any case the main overhead is probably the time to transfer it, and if you do not expect 1000s of posts matching your query, then it should be good enough.</p>\n\n<p>The reason I would prefer this approach over trying to figure out all the required joins and write a proper SQL, is that it is much easier to read and modify than an SQL statement. Still requires a good comment about the why of it. </p>\n"
}
]
| 2017/05/08 | [
"https://wordpress.stackexchange.com/questions/266243",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/23829/"
]
| I'm trying to count results for a given query, but I don't actually need the posts so I'm trying to figure out if there's a way to count posts without querying them. Something similar to <https://codex.wordpress.org/Function_Reference/wp_count_posts>
I'm counting posts by meta key/value so `wp_count_posts()` won't work.
Here's what I'm currently doing:
```
$query = new WP_Query(array(
"post_type" => 'my-post-type',
"posts_per_page" => 0,
"meta_key" => "my_custom_key",
"meta_value" => "some_value",
));
echo $query->found_posts;
``` | The non perfect solution is to just minimize the amount of information carried by the query, and the side effects. This can be done by requesting only the post IDs and not populating any caches.
Your query should be something like
```
$query = new WP_Query(array(
...
'fields' => 'ids',
'cache_results' => false,
'update_post_meta_cache' => false,
'update_post_term_cache' => false,
));
```
So you still get too much information - an array of integers instead of one, but since the DB has to go over them in any case the main overhead is probably the time to transfer it, and if you do not expect 1000s of posts matching your query, then it should be good enough.
The reason I would prefer this approach over trying to figure out all the required joins and write a proper SQL, is that it is much easier to read and modify than an SQL statement. Still requires a good comment about the why of it. |
266,255 | <p>I'm using twenty seventeen theme on wordpress (writing a child theme)
When the home page first loads the nav bar is at the bottom of the screen, but the sub menu opens downwards and is therefore hidden. I'd like it to fly upwards until the page has scrolled down.
First, is there a simple way to change this that I'm perhaps missing? (because it seems like a basic thing, yet I can't find any answer anywhere)
Or do I need to change a class on scroll using jquery? (in which case I am really feeling about in the dark.)
Can anyone help me with this?
Vik</p>
| [
{
"answer_id": 266248,
"author": "Emin Rahmanov",
"author_id": 119256,
"author_profile": "https://wordpress.stackexchange.com/users/119256",
"pm_score": -1,
"selected": false,
"text": "<p>You set posts_per_page 0 value. posts_per_page for all posts set -1 or another positive number</p>\n\n<pre><code>$query = new WP_Query( array(\n \"post_type\" => 'my-post-type',\n \"posts_per_page\" => -1,\n \"meta_key\" => \"my_custom_key\",\n \"meta_value\" => \"some_value\",\n) );\n\necho $query->found_posts;\n</code></pre>\n"
},
{
"answer_id": 266289,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>The non perfect solution is to just minimize the amount of information carried by the query, and the side effects. This can be done by requesting only the post IDs and not populating any caches. </p>\n\n<p>Your query should be something like</p>\n\n<pre><code>$query = new WP_Query(array(\n ...\n 'fields' => 'ids',\n 'cache_results' => false,\n 'update_post_meta_cache' => false,\n 'update_post_term_cache' => false,\n));\n</code></pre>\n\n<p>So you still get too much information - an array of integers instead of one, but since the DB has to go over them in any case the main overhead is probably the time to transfer it, and if you do not expect 1000s of posts matching your query, then it should be good enough.</p>\n\n<p>The reason I would prefer this approach over trying to figure out all the required joins and write a proper SQL, is that it is much easier to read and modify than an SQL statement. Still requires a good comment about the why of it. </p>\n"
}
]
| 2017/05/08 | [
"https://wordpress.stackexchange.com/questions/266255",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/71273/"
]
| I'm using twenty seventeen theme on wordpress (writing a child theme)
When the home page first loads the nav bar is at the bottom of the screen, but the sub menu opens downwards and is therefore hidden. I'd like it to fly upwards until the page has scrolled down.
First, is there a simple way to change this that I'm perhaps missing? (because it seems like a basic thing, yet I can't find any answer anywhere)
Or do I need to change a class on scroll using jquery? (in which case I am really feeling about in the dark.)
Can anyone help me with this?
Vik | The non perfect solution is to just minimize the amount of information carried by the query, and the side effects. This can be done by requesting only the post IDs and not populating any caches.
Your query should be something like
```
$query = new WP_Query(array(
...
'fields' => 'ids',
'cache_results' => false,
'update_post_meta_cache' => false,
'update_post_term_cache' => false,
));
```
So you still get too much information - an array of integers instead of one, but since the DB has to go over them in any case the main overhead is probably the time to transfer it, and if you do not expect 1000s of posts matching your query, then it should be good enough.
The reason I would prefer this approach over trying to figure out all the required joins and write a proper SQL, is that it is much easier to read and modify than an SQL statement. Still requires a good comment about the why of it. |
266,270 | <p>I am trying to retrieve posts from a category. I have 2 level and 3 level category hierarchy. I am using tax query in pre get posts filter to alter the query. </p>
<p>The query works fine for the first level and third level category but shows no result for second level category. The query when examined has 0 = 1 added in the where clause for queries which yield no result.</p>
<p>For 2 level category the query works fine both for parent and child category. </p>
<p>I have woocommerce setup with Wordpress.</p>
<p>Below is the filter added:</p>
<pre><code>add_action('pre_get_posts', 'alter_category_search_query');
function alter_category_search_query($query) {
if ($query->is_main_query() && $query->is_search) {
$args = array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $_GET['cat'],
'include_children' => false
)
);
$query->set('tax_query', $args);
//we remove the actions hooked on the '__after_loop' (post navigation)
remove_all_actions('__after_loop');
}
}
</code></pre>
<p>Generated SQL:</p>
<pre><code>SELECT wp_posts.* FROM wp_posts LEFT JOIN wp_term_relationships ON
(wp_posts.ID = wp_term_relationships.object_id) INNER JOIN wp_postmeta ON (
wp_posts.ID = wp_postmeta.post_id ) WHERE 1=1 AND (
wp_term_relationships.term_taxonomy_id IN (17)
AND
0 = 1
) AND (
( wp_postmeta.meta_key = '_visibility' AND wp_postmeta.meta_value IN
('visible','search') )
) AND wp_posts.post_type = 'product' AND (wp_posts.post_status = 'publish')
GROUP BY wp_posts.ID ORDER BY wp_posts.menu_order ASC, wp_posts.post_title
ASC
</code></pre>
| [
{
"answer_id": 266248,
"author": "Emin Rahmanov",
"author_id": 119256,
"author_profile": "https://wordpress.stackexchange.com/users/119256",
"pm_score": -1,
"selected": false,
"text": "<p>You set posts_per_page 0 value. posts_per_page for all posts set -1 or another positive number</p>\n\n<pre><code>$query = new WP_Query( array(\n \"post_type\" => 'my-post-type',\n \"posts_per_page\" => -1,\n \"meta_key\" => \"my_custom_key\",\n \"meta_value\" => \"some_value\",\n) );\n\necho $query->found_posts;\n</code></pre>\n"
},
{
"answer_id": 266289,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>The non perfect solution is to just minimize the amount of information carried by the query, and the side effects. This can be done by requesting only the post IDs and not populating any caches. </p>\n\n<p>Your query should be something like</p>\n\n<pre><code>$query = new WP_Query(array(\n ...\n 'fields' => 'ids',\n 'cache_results' => false,\n 'update_post_meta_cache' => false,\n 'update_post_term_cache' => false,\n));\n</code></pre>\n\n<p>So you still get too much information - an array of integers instead of one, but since the DB has to go over them in any case the main overhead is probably the time to transfer it, and if you do not expect 1000s of posts matching your query, then it should be good enough.</p>\n\n<p>The reason I would prefer this approach over trying to figure out all the required joins and write a proper SQL, is that it is much easier to read and modify than an SQL statement. Still requires a good comment about the why of it. </p>\n"
}
]
| 2017/05/08 | [
"https://wordpress.stackexchange.com/questions/266270",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/21005/"
]
| I am trying to retrieve posts from a category. I have 2 level and 3 level category hierarchy. I am using tax query in pre get posts filter to alter the query.
The query works fine for the first level and third level category but shows no result for second level category. The query when examined has 0 = 1 added in the where clause for queries which yield no result.
For 2 level category the query works fine both for parent and child category.
I have woocommerce setup with Wordpress.
Below is the filter added:
```
add_action('pre_get_posts', 'alter_category_search_query');
function alter_category_search_query($query) {
if ($query->is_main_query() && $query->is_search) {
$args = array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $_GET['cat'],
'include_children' => false
)
);
$query->set('tax_query', $args);
//we remove the actions hooked on the '__after_loop' (post navigation)
remove_all_actions('__after_loop');
}
}
```
Generated SQL:
```
SELECT wp_posts.* FROM wp_posts LEFT JOIN wp_term_relationships ON
(wp_posts.ID = wp_term_relationships.object_id) INNER JOIN wp_postmeta ON (
wp_posts.ID = wp_postmeta.post_id ) WHERE 1=1 AND (
wp_term_relationships.term_taxonomy_id IN (17)
AND
0 = 1
) AND (
( wp_postmeta.meta_key = '_visibility' AND wp_postmeta.meta_value IN
('visible','search') )
) AND wp_posts.post_type = 'product' AND (wp_posts.post_status = 'publish')
GROUP BY wp_posts.ID ORDER BY wp_posts.menu_order ASC, wp_posts.post_title
ASC
``` | The non perfect solution is to just minimize the amount of information carried by the query, and the side effects. This can be done by requesting only the post IDs and not populating any caches.
Your query should be something like
```
$query = new WP_Query(array(
...
'fields' => 'ids',
'cache_results' => false,
'update_post_meta_cache' => false,
'update_post_term_cache' => false,
));
```
So you still get too much information - an array of integers instead of one, but since the DB has to go over them in any case the main overhead is probably the time to transfer it, and if you do not expect 1000s of posts matching your query, then it should be good enough.
The reason I would prefer this approach over trying to figure out all the required joins and write a proper SQL, is that it is much easier to read and modify than an SQL statement. Still requires a good comment about the why of it. |
266,272 | <p>I've written a shortcode for fetching the most viewed posts in the past week. I use a filter as the following in my shortcode's function:</p>
<pre><code>function weeks_popular(){
//Filter the date
function filter_where($where = '') {
$where .= " AND post_date > '" . date('Y-m-d', strtotime('-7 days')) . "'";
return $where;
}
add_filter('posts_where', 'filter_where');
$pops = new WP_Query(
array(
'posts_per_page' => 4,
'meta_key' => 'views',
'orderby' => 'meta_value_num',
'order' => 'DESC'
)
);
//If there is a post, start the loops
if ($pops->have_posts()) {
$pops_content='<div class="shortcode">';
while ($pops->have_posts()){
$pops->the_post();
$pops_content .= '<a href="'.get_the_permalink().'">'.get_the_title().'</a>';
}
$pops_content .= '</div>';
return $pops_content;
}
//Remove the date filter
remove_filter('posts_where', 'filter_where');
wp_reset_postdata();
}
add_shortcode( 'recent-posts', 'weeks_popular' );
</code></pre>
<p>I used this in a PHP widget before, and it worked fine. Now, there is a problem with it : It affects every other query on the page, including other shortcodes.</p>
<p>I'm resetting the post data after the query has finished, so i don't know what's wrong, since it used to work (and still does work) in a PHP widget. Just doesn't work in shortcode.</p>
<p>Am i missing something?</p>
| [
{
"answer_id": 266293,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>Note that you're returning from the shortcode's callback with:</p>\n\n<pre><code>return $pops_content;\n</code></pre>\n\n<p>before removing the filter's callback with:</p>\n\n<pre><code>remove_filter('posts_where', 'filter_where'); \n</code></pre>\n\n<p>So it's never called.</p>\n\n<p>That means you're affecting all the later <code>WP_Query</code> instances with your filter.</p>\n\n<p>Note that you can use <code>date_query</code> in <code>WP_Query</code> instead, so you don't need the <code>posts_where</code> filtering.</p>\n"
},
{
"answer_id": 266295,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<p>Ordering is the problem here:</p>\n\n<pre><code>//If there is a post, start the loops\nif ($pops->have_posts()) {\n $pops_content='<div class=\"shortcode\">';\n while ($pops->have_posts()){ \n $pops->the_post(); \n $pops_content .= '<a href=\"'.get_the_permalink().'\">'.get_the_title().'</a>';\n }\n $pops_content .= '</div>';\n return $pops_content;\n} \n//Remove the date filter\nremove_filter('posts_where', 'filter_where'); \nwp_reset_postdata(); \n</code></pre>\n\n<p>Your code will never call <code>wp_reset_postdata</code> or remove the filter as it returns early after the <code>while</code> loop.</p>\n\n<p>You should instead return at the end of the function, after the filter has been removed and the postdata reset.</p>\n\n<h3>A final note</h3>\n\n<p>Always calling <code>wp_reset_postdata</code> isn't wise. It's purpose is to cleanup, but if you never set any postdata, then what are you resetting? This can cause problems in nested loops, so always put the call inside the if statement just after the while loop.</p>\n"
},
{
"answer_id": 266299,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 1,
"selected": false,
"text": "<p>I resolved the issue by forgetting filters, and using a date query:</p>\n\n<pre><code>$pops = new WP_Query( \n array( \n 'posts_per_page' => 4,\n 'meta_key' => 'views',\n 'orderby' => 'meta_value_num',\n 'order' => 'DESC',\n 'date_query' => array(\n array(\n 'year' => date('Y'),\n 'week' => (date('W')-1),\n ),\n )\n ) \n );\n</code></pre>\n\n<p>Both of the provided answers by @birgire and @Tom are correct, and worked. However i marked the first answer as accepted.</p>\n"
}
]
| 2017/05/08 | [
"https://wordpress.stackexchange.com/questions/266272",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94498/"
]
| I've written a shortcode for fetching the most viewed posts in the past week. I use a filter as the following in my shortcode's function:
```
function weeks_popular(){
//Filter the date
function filter_where($where = '') {
$where .= " AND post_date > '" . date('Y-m-d', strtotime('-7 days')) . "'";
return $where;
}
add_filter('posts_where', 'filter_where');
$pops = new WP_Query(
array(
'posts_per_page' => 4,
'meta_key' => 'views',
'orderby' => 'meta_value_num',
'order' => 'DESC'
)
);
//If there is a post, start the loops
if ($pops->have_posts()) {
$pops_content='<div class="shortcode">';
while ($pops->have_posts()){
$pops->the_post();
$pops_content .= '<a href="'.get_the_permalink().'">'.get_the_title().'</a>';
}
$pops_content .= '</div>';
return $pops_content;
}
//Remove the date filter
remove_filter('posts_where', 'filter_where');
wp_reset_postdata();
}
add_shortcode( 'recent-posts', 'weeks_popular' );
```
I used this in a PHP widget before, and it worked fine. Now, there is a problem with it : It affects every other query on the page, including other shortcodes.
I'm resetting the post data after the query has finished, so i don't know what's wrong, since it used to work (and still does work) in a PHP widget. Just doesn't work in shortcode.
Am i missing something? | Note that you're returning from the shortcode's callback with:
```
return $pops_content;
```
before removing the filter's callback with:
```
remove_filter('posts_where', 'filter_where');
```
So it's never called.
That means you're affecting all the later `WP_Query` instances with your filter.
Note that you can use `date_query` in `WP_Query` instead, so you don't need the `posts_where` filtering. |
266,384 | <p>I have created a landing page that is only available to a certain audience. When users visit this page I would like to create a cookie that can be passed on upon completing a booking form on another page. I am using Wordpress and can't figure out how to set a page specific cookie. I am able to set a global cookie through the functions.php. Right now I have tried out a function using the is_page argument to check whether the specific page is being viewed: </p>
<pre><code> add_action( 'init', 'setting_my_first_cookie' );
function setting_my_first_cookie() {
if (is_page('name-of-page')) {
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
}
}
</code></pre>
<p>Any ideas where I am going wrong? Or maybe using a cookie is a totally incorrect approach. In that case I would appreciate a hint, how I could handle such a problem. Many thanks for your help! </p>
| [
{
"answer_id": 266386,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": true,
"text": "<p>WordPress doesn't know if it's a page yet, <code>init</code> fires before the query is run. You need to hook a later action, like <code>wp</code>. Have a look at <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_a_Typical_Request\" rel=\"nofollow noreferrer\">Action Reference</a> to see the order of actions during a request.</p>\n"
},
{
"answer_id": 266388,
"author": "Nathaniel Flick",
"author_id": 87226,
"author_profile": "https://wordpress.stackexchange.com/users/87226",
"pm_score": 0,
"selected": false,
"text": "<p>You can always use Session intead of cookie and run it with jQuery, set it in a function:</p>\n\n<pre><code>$(function() {\n // set landingPage to 1 to set the session to \"True\"\n // or check for not landingPage (!sessionStorage.landingPage)\n // to do something if it's not set\n sessionStorage.landingPage = 1;\n}); \n</code></pre>\n\n<p>And then you can see if the user has that session and act on that on all other pages (for vice a versa switch the else actions around):</p>\n\n<pre><code>$(function() {\n // if landingPage session is not set:\n if (sessionStorage.landingPage) {\n // do something here if landingPage is set to 1\n } else {\n // do nothing, or set landingPage to 1 for next time\n }\n});\n</code></pre>\n"
}
]
| 2017/05/09 | [
"https://wordpress.stackexchange.com/questions/266384",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115021/"
]
| I have created a landing page that is only available to a certain audience. When users visit this page I would like to create a cookie that can be passed on upon completing a booking form on another page. I am using Wordpress and can't figure out how to set a page specific cookie. I am able to set a global cookie through the functions.php. Right now I have tried out a function using the is\_page argument to check whether the specific page is being viewed:
```
add_action( 'init', 'setting_my_first_cookie' );
function setting_my_first_cookie() {
if (is_page('name-of-page')) {
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
}
}
```
Any ideas where I am going wrong? Or maybe using a cookie is a totally incorrect approach. In that case I would appreciate a hint, how I could handle such a problem. Many thanks for your help! | WordPress doesn't know if it's a page yet, `init` fires before the query is run. You need to hook a later action, like `wp`. Have a look at [Action Reference](https://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_a_Typical_Request) to see the order of actions during a request. |
266,401 | <p>Coders. I'm really new in WP Coding, I have zero knowledge, here we are.
I created a plugin (actually found it, but I did some modifications) which update all my wp posts.</p>
<p>Let's show you the code,</p>
<pre><code>if ( ! class_exists( 'MyPlugin_BulkUpdatePosts' ) ) :
class MyPlugin_BulkUpdatePosts
{
public function __construct()
{
register_activation_hook( __FILE__, array( $this, 'do_post_bulk_update' ) ); //Run this code only on activation
}
//Put your code in this function
public function do_post_bulk_update()
{
$posts_to_update = get_posts('numberposts=-1'); //numberposts for post query, "-1" for all posts.
foreach ( $posts_to_update as $update_this_post ):
//update query goes here
endforeach;
}
}
endif;
</code></pre>
<p>As you can see, it makes a query to the all posts, The main problem is I have 10k+ posts, But when I use this my server gets crashed, It gives a "503 Unavailable". But When I use 50-60 posts, it's works.</p>
<p>How can I make this work by less resources ?</p>
| [
{
"answer_id": 266403,
"author": "Picard",
"author_id": 118566,
"author_profile": "https://wordpress.stackexchange.com/users/118566",
"pm_score": 0,
"selected": false,
"text": "<p>10k+ updates must take time. Depending what you need you could operate on the Wordpress tables like <code>wp_posts</code> using raw SQL queries but I don't think it would speed up things substantially.</p>\n\n<p>Because the problem is I think time - if that is a one time operation - you could solve the problem by changing the <code>max_execution_time</code> in php.ini giving the scripts much more time for the updates. For this you'd need to have access to the server's configuration. If you don't you could install a server pack (like XAMPP) on your local machine, there do the update operation and then move the updated DB to you production server.</p>\n\n<p>There are <a href=\"https://stackoverflow.com/questions/7739870/increase-max-execution-time-for-php#answer-14290695\">other solutions</a> for changing that variable on remote servers but they are usually turned off the by admins.</p>\n"
},
{
"answer_id": 266405,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 2,
"selected": false,
"text": "<p>One implementation detail of how WP works with database is that it always drags <em>all</em> query results into PHP values and memory space. In other words it is highly unlikely to throw any heavy query at WP and not have it collapse. Notably any plugins that deal with large queries (such as database backup ones) often write their database access layer from scratch instead of using WP API.</p>\n\n<p>So implementing bulk operations has to be a little more elaborate. Querying should be split into smaller batches and they should be processed sequentially. You would need to write that logic yourself or find an existing solution. I think there are some around, but I hadn't used any generic ones.</p>\n\n<p>The alternate approach, in some cases, is to hook update logic to <em>access</em> of individual posts. If giant one-time complete update of everything is not required, updates can be spread over time in such fashion with no need for throwaway update code and no concern about resource impact.</p>\n"
}
]
| 2017/05/09 | [
"https://wordpress.stackexchange.com/questions/266401",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/116204/"
]
| Coders. I'm really new in WP Coding, I have zero knowledge, here we are.
I created a plugin (actually found it, but I did some modifications) which update all my wp posts.
Let's show you the code,
```
if ( ! class_exists( 'MyPlugin_BulkUpdatePosts' ) ) :
class MyPlugin_BulkUpdatePosts
{
public function __construct()
{
register_activation_hook( __FILE__, array( $this, 'do_post_bulk_update' ) ); //Run this code only on activation
}
//Put your code in this function
public function do_post_bulk_update()
{
$posts_to_update = get_posts('numberposts=-1'); //numberposts for post query, "-1" for all posts.
foreach ( $posts_to_update as $update_this_post ):
//update query goes here
endforeach;
}
}
endif;
```
As you can see, it makes a query to the all posts, The main problem is I have 10k+ posts, But when I use this my server gets crashed, It gives a "503 Unavailable". But When I use 50-60 posts, it's works.
How can I make this work by less resources ? | One implementation detail of how WP works with database is that it always drags *all* query results into PHP values and memory space. In other words it is highly unlikely to throw any heavy query at WP and not have it collapse. Notably any plugins that deal with large queries (such as database backup ones) often write their database access layer from scratch instead of using WP API.
So implementing bulk operations has to be a little more elaborate. Querying should be split into smaller batches and they should be processed sequentially. You would need to write that logic yourself or find an existing solution. I think there are some around, but I hadn't used any generic ones.
The alternate approach, in some cases, is to hook update logic to *access* of individual posts. If giant one-time complete update of everything is not required, updates can be spread over time in such fashion with no need for throwaway update code and no concern about resource impact. |
266,423 | <p>When I go through the database of a fresh Wordpress 4 install I find, for example:</p>
<pre><code>wp_posts
wp_terms
wp_users
</code></pre>
<p>Yet I didn't find `wp_pages'. Where is it?</p>
| [
{
"answer_id": 266424,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I entered to wp_posts and it seems all pages are inside there.</p>\n"
},
{
"answer_id": 266426,
"author": "Amine Faiz",
"author_id": 66813,
"author_profile": "https://wordpress.stackexchange.com/users/66813",
"pm_score": 5,
"selected": true,
"text": "<p>the wp_posts include all post types (post, page, custom post..), and to differentiate between them there is a field called post_type used to specify the name of the current entry whether it's a page, post or a custom post.</p>\n<p>Query below will get list of pages</p>\n<pre><code>SELECT * FROM wp_posts where post_type = 'page';\n</code></pre>\n"
}
]
| 2017/05/09 | [
"https://wordpress.stackexchange.com/questions/266423",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
]
| When I go through the database of a fresh Wordpress 4 install I find, for example:
```
wp_posts
wp_terms
wp_users
```
Yet I didn't find `wp\_pages'. Where is it? | the wp\_posts include all post types (post, page, custom post..), and to differentiate between them there is a field called post\_type used to specify the name of the current entry whether it's a page, post or a custom post.
Query below will get list of pages
```
SELECT * FROM wp_posts where post_type = 'page';
``` |
266,429 | <p>The author section of my first <strong>WordPress theme</strong> is currently <strong>hard coded in HTML</strong>. </p>
<p>See the live website <a href="http://codepen.trafficopedia.com/site01/8/" rel="nofollow noreferrer">here</a>. </p>
<p><a href="https://www.screencast.com/t/j7ZZxDUFsac" rel="nofollow noreferrer">This One.</a></p>
<p>These <strong>social media Icons</strong> and the link associated with them are not provided in the backend author dashboard by default and they need to be coded.<a href="https://i.stack.imgur.com/fvZSk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fvZSk.png" alt="enter image description here"></a></p>
<p>Can someone guide me how to?</p>
<p>Is this feature will also come under meta category?</p>
<hr>
<p>Sir, I have one more confusion which part of the code you have written will be used for actually printing the social media URL's that we have saved in the author's dashboard in the backend.</p>
<p>For the sake of simplifying my query, I am putting here my author's code to be displayed on the front end →</p>
<pre><code><div class="author-box">
<div class="author-image">
<img src="http://blog.blogeto.com/html/images/author_profile.png" alt="">
</div>
<div class="author-description">
<h2>
<!-- AUTHORS NAME --> <?php the_author(); ?>
<!-- <a href="<?php get_author_posts_url(); ?>"><?php the_author() ?></a> -->
<a href=""><i class="fa fa-home" aria-hidden="true"></i></a>
<a href=""><i class="fa fa-home" aria-hidden="true"></i></a>
<a href=""><i class="fa fa-facebook" aria-hidden="true"></i></a>
<a href=""><i class="fa fa-twitter" aria-hidden="true"></i></a>
<a href=""><i class="fa fa-linkedin" aria-hidden="true"></i></a>
<a href=""><i class="fa fa-youtube" aria-hidden="true"></i></a>
</h2>
<p> Lorem Ipsum is simply dummy text.<a href="#">Read More</a> </p>
</div>
<div class="author-category">
<ul>
<li><a href="">CATEGORY 1</a></li>
<li><a href="">CATEGORY 2</a></li>
<li><a href="">CATEGORY 3</a></li>
<li><a href="">CATEGORY 4</a></li>
<li><a href="">CATEGORY 5</a></li>
</ul>
</div>
</div>
</code></pre>
| [
{
"answer_id": 266436,
"author": "Aniruddha Gawade",
"author_id": 101818,
"author_profile": "https://wordpress.stackexchange.com/users/101818",
"pm_score": 1,
"selected": false,
"text": "<p>Yes, those fields will be user meta. And for storing social links of a user you'll have to add custom user meta.</p>\n\n<p>Here's developer's documentation for your reference: <a href=\"https://developer.wordpress.org/plugins/users/working-with-user-metadata/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/plugins/users/working-with-user-metadata/</a></p>\n\n<p>Note: See example code for better understanding.</p>\n"
},
{
"answer_id": 266438,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 3,
"selected": true,
"text": "<p>Add user contact methods using the <code>user_contactmethods</code> filter in your theme's <code>functions.php</code> or via a plugin:</p>\n\n<p>User contact method entries are stored in the <code>wp_usermeta</code> table. The URL field is special; it's stored in the <code>user_url</code> field in the <code>wp_users</code> table.</p>\n\n<pre><code>// Add user contact methods\nadd_filter( 'user_contactmethods','wpse_user_contactmethods', 10, 1 );\nfunction wpse_user_contactmethods( $contact_methods ) {\n $contact_methods['facebook'] = __( 'Facebook URL', 'text_domain' );\n $contact_methods['twitter'] = __( 'Twitter URL', 'text_domain' );\n $contact_methods['linkedin'] = __( 'LinkedIn URL', 'text_domain' );\n $contact_methods['youtube'] = __( 'YouTube URL', 'text_domain' );\n\n return $contact_methods;\n}\n</code></pre>\n\n<p>Output the links in your template file:</p>\n\n<pre><code><div class=\"author-box\">\n <div class=\"author-image\">\n <img src=\"http://blog.blogeto.com/html/images/author_profile.png\" alt=\"\">\n </div>\n\n <div class=\"author-description\">\n <h2>\n <!-- AUTHORS NAME --> <?php the_author(); ?>\n <!-- <a href=\"<?php echo get_author_posts_url( get_the_author_meta( 'ID' ) ); ?>\"><?php the_author() ?></a> -->\n <?php \n // Get the id of the post's author.\n $author_id = get_the_author_meta( 'ID' );\n\n // Get WP_User object for the author.\n $author_userdata = get_userdata( $author_id );\n\n // Get the author's website. It's stored in the wp_users table in the user_url field.\n $author_website = $author_userdata->data->user_url;\n\n // Get the rest of the author links. These are stored in the \n // wp_usermeta table by the key assigned in wpse_user_contactmethods()\n $author_facebook = get_the_author_meta( 'facebook', $author_id );\n $author_twitter = get_the_author_meta( 'twitter', $author_id );\n $author_linkedin = get_the_author_meta( 'linkedin', $author_id );\n $author_youtube = get_the_author_meta( 'youtube', $author_id );\n\n // Output the user's social links if they have values.\n if ( $author_website ) {\n printf( '<a href=\"%s\"><i class=\"fa fa-home\" aria-hidden=\"true\"></i></a>',\n esc_url( $author_website )\n );\n }\n\n if ( $author_facebook ) {\n printf( '<a href=\"%s\"><i class=\"fa fa-facebook\" aria-hidden=\"true\"></i></a>',\n esc_url( $author_facebook )\n );\n }\n\n if ( $author_twitter ) {\n printf( '<a href=\"%s\"><i class=\"fa fa-twitter\" aria-hidden=\"true\"></i></a>',\n esc_url( $author_twitter )\n );\n }\n\n if ( $author_linkedin ) {\n printf( '<a href=\"%s\"><i class=\"fa fa-linkedin\" aria-hidden=\"true\"></i></a>',\n esc_url( $author_linkedin )\n );\n }\n\n if ( $author_youtube ) {\n printf( '<a href=\"%s\"><i class=\"fa fa-youtube\" aria-hidden=\"true\"></i></a>',\n esc_url( $author_youtube )\n );\n }\n ?>\n </h2>\n <p> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.Lorem Ipsum is simply dummy text. <a href=\"#\">Read More</a> </p>\n </div>\n <div class=\"author-category\">\n <ul>\n <li><a href=\"\">CATEGORY 1</a></li>\n <li><a href=\"\">CATEGORY 2</a></li>\n <li><a href=\"\">CATEGORY 3</a></li>\n <li><a href=\"\">CATEGORY 4</a></li>\n <li><a href=\"\">CATEGORY 5</a></li>\n </ul>\n </div>\n</div>\n</code></pre>\n"
}
]
| 2017/05/10 | [
"https://wordpress.stackexchange.com/questions/266429",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105791/"
]
| The author section of my first **WordPress theme** is currently **hard coded in HTML**.
See the live website [here](http://codepen.trafficopedia.com/site01/8/).
[This One.](https://www.screencast.com/t/j7ZZxDUFsac)
These **social media Icons** and the link associated with them are not provided in the backend author dashboard by default and they need to be coded.[](https://i.stack.imgur.com/fvZSk.png)
Can someone guide me how to?
Is this feature will also come under meta category?
---
Sir, I have one more confusion which part of the code you have written will be used for actually printing the social media URL's that we have saved in the author's dashboard in the backend.
For the sake of simplifying my query, I am putting here my author's code to be displayed on the front end →
```
<div class="author-box">
<div class="author-image">
<img src="http://blog.blogeto.com/html/images/author_profile.png" alt="">
</div>
<div class="author-description">
<h2>
<!-- AUTHORS NAME --> <?php the_author(); ?>
<!-- <a href="<?php get_author_posts_url(); ?>"><?php the_author() ?></a> -->
<a href=""><i class="fa fa-home" aria-hidden="true"></i></a>
<a href=""><i class="fa fa-home" aria-hidden="true"></i></a>
<a href=""><i class="fa fa-facebook" aria-hidden="true"></i></a>
<a href=""><i class="fa fa-twitter" aria-hidden="true"></i></a>
<a href=""><i class="fa fa-linkedin" aria-hidden="true"></i></a>
<a href=""><i class="fa fa-youtube" aria-hidden="true"></i></a>
</h2>
<p> Lorem Ipsum is simply dummy text.<a href="#">Read More</a> </p>
</div>
<div class="author-category">
<ul>
<li><a href="">CATEGORY 1</a></li>
<li><a href="">CATEGORY 2</a></li>
<li><a href="">CATEGORY 3</a></li>
<li><a href="">CATEGORY 4</a></li>
<li><a href="">CATEGORY 5</a></li>
</ul>
</div>
</div>
``` | Add user contact methods using the `user_contactmethods` filter in your theme's `functions.php` or via a plugin:
User contact method entries are stored in the `wp_usermeta` table. The URL field is special; it's stored in the `user_url` field in the `wp_users` table.
```
// Add user contact methods
add_filter( 'user_contactmethods','wpse_user_contactmethods', 10, 1 );
function wpse_user_contactmethods( $contact_methods ) {
$contact_methods['facebook'] = __( 'Facebook URL', 'text_domain' );
$contact_methods['twitter'] = __( 'Twitter URL', 'text_domain' );
$contact_methods['linkedin'] = __( 'LinkedIn URL', 'text_domain' );
$contact_methods['youtube'] = __( 'YouTube URL', 'text_domain' );
return $contact_methods;
}
```
Output the links in your template file:
```
<div class="author-box">
<div class="author-image">
<img src="http://blog.blogeto.com/html/images/author_profile.png" alt="">
</div>
<div class="author-description">
<h2>
<!-- AUTHORS NAME --> <?php the_author(); ?>
<!-- <a href="<?php echo get_author_posts_url( get_the_author_meta( 'ID' ) ); ?>"><?php the_author() ?></a> -->
<?php
// Get the id of the post's author.
$author_id = get_the_author_meta( 'ID' );
// Get WP_User object for the author.
$author_userdata = get_userdata( $author_id );
// Get the author's website. It's stored in the wp_users table in the user_url field.
$author_website = $author_userdata->data->user_url;
// Get the rest of the author links. These are stored in the
// wp_usermeta table by the key assigned in wpse_user_contactmethods()
$author_facebook = get_the_author_meta( 'facebook', $author_id );
$author_twitter = get_the_author_meta( 'twitter', $author_id );
$author_linkedin = get_the_author_meta( 'linkedin', $author_id );
$author_youtube = get_the_author_meta( 'youtube', $author_id );
// Output the user's social links if they have values.
if ( $author_website ) {
printf( '<a href="%s"><i class="fa fa-home" aria-hidden="true"></i></a>',
esc_url( $author_website )
);
}
if ( $author_facebook ) {
printf( '<a href="%s"><i class="fa fa-facebook" aria-hidden="true"></i></a>',
esc_url( $author_facebook )
);
}
if ( $author_twitter ) {
printf( '<a href="%s"><i class="fa fa-twitter" aria-hidden="true"></i></a>',
esc_url( $author_twitter )
);
}
if ( $author_linkedin ) {
printf( '<a href="%s"><i class="fa fa-linkedin" aria-hidden="true"></i></a>',
esc_url( $author_linkedin )
);
}
if ( $author_youtube ) {
printf( '<a href="%s"><i class="fa fa-youtube" aria-hidden="true"></i></a>',
esc_url( $author_youtube )
);
}
?>
</h2>
<p> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.Lorem Ipsum is simply dummy text. <a href="#">Read More</a> </p>
</div>
<div class="author-category">
<ul>
<li><a href="">CATEGORY 1</a></li>
<li><a href="">CATEGORY 2</a></li>
<li><a href="">CATEGORY 3</a></li>
<li><a href="">CATEGORY 4</a></li>
<li><a href="">CATEGORY 5</a></li>
</ul>
</div>
</div>
``` |
266,432 | <p>I have added a message button on my site (I'm using a plugin which enables private messaging) by adding the plugin's shortcode to my footer.php:</p>
<pre><code><div class="msgshort"><?php echo do_shortcode('[ultimatemember_message_button user_id=1]'); ?></div>
</code></pre>
<p>Here is a screenshot of how it looks on my site: <a href="https://ibb.co/hLTkmQ" rel="nofollow noreferrer">https://ibb.co/hLTkmQ</a></p>
<p>Here is the code behind this shortcode:</p>
<pre><code>/***
*** @shortcode
***/
function ultimatemember_message_button( $args = array() ) {
global $ultimatemember, $um_messaging;
$defaults = array(
'user_id' => 0
);
$args = wp_parse_args( $args, $defaults );
extract( $args );
$current_url = $ultimatemember->permalinks->get_current_url();
if( um_get_core_page('user') ){
do_action("um_messaging_button_in_profile", $current_url, $user_id );
}
if ( !is_user_logged_in() ) {
$redirect = um_get_core_page('login');
$redirect = add_query_arg('redirect_to', $current_url, $redirect );
$btn = '<a href="' . $redirect . '" class="um-login-to-msg-btn um-message-btn um-button" data-message_to="'.$user_id.'">'. __('Message','um-messaging'). '</a>';
return $btn;
} else if ( $user_id != get_current_user_id() ) {
if ( $um_messaging->api->can_message( $user_id ) ) {
$btn = '<a href="#" class="um-message-btn um-button" data-message_to="'.$user_id.'"><span>'. __('Message','um-messaging'). '</span></a>';
return $btn;
}
}
}
</code></pre>
<p>This button is coded so that the button text is "Message". This button already appears on my user profile pages, but now that I have also added it to my footer I want to change the text that says "Message" in my footer but not when on the user profile template area. </p>
<p>So, I am using this code to rename the text of the message button on my site:</p>
<pre><code>//rename messagetxt
function um_rename_messagetxt( $translated_text, $text, $text_domain ) {
if ( 'Message' === $text ) {
$translated_text = 'Contact Us';
}
return $translated_text;
}
add_filter ( 'gettext', 'um_rename_messagetxt', 10, 3);
</code></pre>
<p>Of course, this changes the button text for all of my buttons that say originally say "Message" (so both the footer.php message button I added with the shortcode and the message button in the user profile template changes). </p>
<p>I just need to change the text for the button that I added via shortcode into my footer.php file. How can I isolate the text translation so that I am only translating the text of a specific element? For instance, is there a way I can only translate "Message" when it's found in footer.php and if so, how would I write it? I would really appreciate any help on this!</p>
<p>Side note: I am a premium member of this plugin and have already contacted their paid support, which they have said they weren't sure about how to do this and directed me to use Poedit... I don't think Poedit is an appropriate solution for this. Thanks so much to Dave Romsey who has tried to help me despite my php skill deficit :)</p>
| [
{
"answer_id": 266435,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 2,
"selected": true,
"text": "<p>WordPress provides the <a href=\"https://developer.wordpress.org/reference/functions/_x/\" rel=\"nofollow noreferrer\"><code>_x()</code></a> function which is just like <a href=\"https://developer.wordpress.org/reference/functions/__/\" rel=\"nofollow noreferrer\"><code>__()</code></a>, but it adds the <code>$context</code> parameter which is used to differentiate between identical strings.</p>\n\n<p>In the example below, some output is generated in the footer. The translatable string is <code>Message</code> is used in both cases, but in the first instance, <code>Message</code> is given the context <code>for use in footer text</code>.</p>\n\n<p>Next, we use the <code>gettext_with_context</code> and <code>gettext</code> filters respectively to translate each of the strings independently.</p>\n\n<pre><code>// Generate output for our example.\nadd_action( 'wp_footer', 'wpse_example_strings' );\nfunction wpse_example_strings() {\n // Note that concatenating strings is not translation friendly. It's done here for simplicity.\n echo 'Message string with context: ' . _x( 'Message', 'for use in footer text', 'text_domain' ) . '<br>';\n echo 'Message string without context: ' . __( 'Message', 'text_domain' ) . '<br>';\n}\n\n/**\n * Translate text with context.\n *\n * https://codex.wordpress.org/Plugin_API/Filter_Reference/gettext_with_context\n *\n * @param string $translation Translated text.\n * @param string $text Text to translate.\n * @param string $context Context information for the translators.\n * @param string $domain Text domain. Unique identifier for retrieving translated strings.\n *\n * @return string\n */\nadd_filter( 'gettext_with_context', 'wpse_gettext_with_context', 10, 4 );\nfunction wpse_gettext_with_context( $translation, $text, $context, $domain ) {\n if ( 'text_domain' === $domain ) {\n if ( 'Message' === $text && 'for use in footer text' === $context ) {\n $translation = 'Message Us';\n }\n }\n\n return $translation;\n}\n\n/**\n * Translate text without context.\n *\n * @param string $translation Translated text.\n * @param string $text Text to translate.\n * @param string $domain Text domain. Unique identifier for retrieving translated strings.\n *\n * @return string\n */\nadd_filter( 'gettext', 'um_rename_messagetxt', 10, 3);\nfunction um_rename_messagetxt( $translation, $text, $domain ) {\n if ( 'text_domain' === $domain ) {\n if ( 'Message' === $text ) {\n $translation = 'Contact Us';\n }\n }\n\n return $translation;\n}\n</code></pre>\n\n<h2>Edit: Ultimate Member Messaging Button customization</h2>\n\n<p>I've taken a close look at this, and unfortunately the plugin authors have not made it very easy to change the button text.</p>\n\n<p>Here's a solution that will replace the default Ultimate Member Message Button's shortcode with our own forked version. Note that we can recycle the <code>ultimatemember_message_button</code> name. I would suggest making a plugin out of this code:</p>\n\n<pre><code><?php\n/*\nPlugin Name: Ulimate Member Custom Message Button Shortcode\nPlugin URI: \nDescription: \nVersion: 0.0.1\nAuthor:\nAuthor URI:\nLicense: GPL2/Creative Commons\n*/\n\n/**\n * Remove the default UM Message shortcode and wire up our forked version.\n */ \nadd_action( 'init', 'wpse_ultimatemember_message_button_custom' );\nfunction wpse_ultimatemember_message_button_custom() {\n global $um_messaging;\n remove_shortcode( 'ultimatemember_message_button', [ $um_messaging->shortcode, 'ultimatemember_message_button' ] );\n add_shortcode( 'ultimatemember_message_button', 'wpse_ultimatemember_message_button' );\n}\n\n/**\n * Customized version of ultimatemember_message_button shortcode, which allows\n * for the button's label to be specified using the 'label' parameter.\n */\nfunction wpse_ultimatemember_message_button( $args = array() ) {\n global $ultimatemember, $um_messaging;\n\n $defaults = array(\n 'user_id' => 0,\n 'label' => __( 'Message','um-messaging' ),\n );\n $args = wp_parse_args( $args, $defaults );\n extract( $args );\n\n $current_url = $ultimatemember->permalinks->get_current_url();\n\n if( um_get_core_page('user') ){\n do_action(\"um_messaging_button_in_profile\", $current_url, $user_id );\n }\n\n if ( !is_user_logged_in() ) {\n $redirect = um_get_core_page('login');\n $redirect = add_query_arg('redirect_to', $current_url, $redirect );\n $btn = '<a href=\"' . $redirect . '\" class=\"um-login-to-msg-btn um-message-btn um-button\" data-message_to=\"'.$user_id.'\">'. $label .'</a>';\n return $btn;\n } else if ( $user_id != get_current_user_id() ) {\n\n if ( $um_messaging->api->can_message( $user_id ) ) {\n $btn = '<a href=\"#\" class=\"um-message-btn um-button\" data-message_to=\"'.$user_id.'\"><span>'. $label .'</span></a>';\n return $btn;\n }\n\n }\n\n}\n</code></pre>\n\n<p>Update your template to call the <code>ultimatemember_message_button</code> shortcode with our new <code>label</code> parameter like this:</p>\n\n<pre><code><div class=\"msgshort\">\n <?php echo do_shortcode('[ultimatemember_message_button user_id=2 label=\"Contact US\"]'); ?>\n</div>\n</code></pre>\n\n<p>This isn't really the greatest solution, but our options are limited by the way that the plugin is implemented. I would suggest making a feature request for the <code>label</code> parameter to be added.</p>\n"
},
{
"answer_id": 266447,
"author": "kosmicbird",
"author_id": 104629,
"author_profile": "https://wordpress.stackexchange.com/users/104629",
"pm_score": 0,
"selected": false,
"text": "<p>Well, I have become hopeless so I have resolved this in an alternate way (this method is not ideal but at least it gets the job done)</p>\n\n<p>I just added a second shortcode function to the plugin's shortcode.php file and changed the \"Message\" to \"Contact Us\" in the new function:</p>\n\n<pre><code>/***\n*** @shortcode\n***/\nfunction ultimatemember_message_button2( $args = array() ) {\n global $ultimatemember, $um_messaging;\n\n $defaults = array(\n 'user_id' => 0\n );\n $args = wp_parse_args( $args, $defaults );\n extract( $args );\n\n $current_url = $ultimatemember->permalinks->get_current_url();\n\n if( um_get_core_page('user') ){\n do_action(\"um_messaging_button_in_profile\", $current_url, $user_id );\n }\n\n if ( !is_user_logged_in() ) {\n $redirect = um_get_core_page('login');\n $redirect = add_query_arg('redirect_to', $current_url, $redirect );\n $btn = '<a href=\"' . $redirect . '\" class=\"um-login-to-msg-btn um-message-btn um-button\" data-message_to=\"'.$user_id.'\">'. __('Contact Us','um-messaging'). '</a>';\n return $btn;\n } else if ( $user_id != get_current_user_id() ) {\n\n if ( $um_messaging->api->can_message( $user_id ) ) {\n $btn = '<a href=\"#\" class=\"um-message-btn um-button\" data-message_to=\"'.$user_id.'\"><span>'. __('Contact Us','um-messaging'). '</span></a>';\n return $btn;\n }\n\n }\n\n}\n</code></pre>\n\n<p>Then I just called the \"new\" shortcode in my footer.php file:</p>\n\n<pre><code><div class=\"msgshort\"><?php echo do_shortcode('[ultimatemember_message_button2 user_id=1]'); ?></div>\n</code></pre>\n\n<p>This isn't exactly great because I wanted to use translation and add to my child theme's function.php file so I won't lose the modifications when I update... so I would still appreciate a better solution if anyone has one. Thanks again for the help!</p>\n"
}
]
| 2017/05/10 | [
"https://wordpress.stackexchange.com/questions/266432",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104629/"
]
| I have added a message button on my site (I'm using a plugin which enables private messaging) by adding the plugin's shortcode to my footer.php:
```
<div class="msgshort"><?php echo do_shortcode('[ultimatemember_message_button user_id=1]'); ?></div>
```
Here is a screenshot of how it looks on my site: <https://ibb.co/hLTkmQ>
Here is the code behind this shortcode:
```
/***
*** @shortcode
***/
function ultimatemember_message_button( $args = array() ) {
global $ultimatemember, $um_messaging;
$defaults = array(
'user_id' => 0
);
$args = wp_parse_args( $args, $defaults );
extract( $args );
$current_url = $ultimatemember->permalinks->get_current_url();
if( um_get_core_page('user') ){
do_action("um_messaging_button_in_profile", $current_url, $user_id );
}
if ( !is_user_logged_in() ) {
$redirect = um_get_core_page('login');
$redirect = add_query_arg('redirect_to', $current_url, $redirect );
$btn = '<a href="' . $redirect . '" class="um-login-to-msg-btn um-message-btn um-button" data-message_to="'.$user_id.'">'. __('Message','um-messaging'). '</a>';
return $btn;
} else if ( $user_id != get_current_user_id() ) {
if ( $um_messaging->api->can_message( $user_id ) ) {
$btn = '<a href="#" class="um-message-btn um-button" data-message_to="'.$user_id.'"><span>'. __('Message','um-messaging'). '</span></a>';
return $btn;
}
}
}
```
This button is coded so that the button text is "Message". This button already appears on my user profile pages, but now that I have also added it to my footer I want to change the text that says "Message" in my footer but not when on the user profile template area.
So, I am using this code to rename the text of the message button on my site:
```
//rename messagetxt
function um_rename_messagetxt( $translated_text, $text, $text_domain ) {
if ( 'Message' === $text ) {
$translated_text = 'Contact Us';
}
return $translated_text;
}
add_filter ( 'gettext', 'um_rename_messagetxt', 10, 3);
```
Of course, this changes the button text for all of my buttons that say originally say "Message" (so both the footer.php message button I added with the shortcode and the message button in the user profile template changes).
I just need to change the text for the button that I added via shortcode into my footer.php file. How can I isolate the text translation so that I am only translating the text of a specific element? For instance, is there a way I can only translate "Message" when it's found in footer.php and if so, how would I write it? I would really appreciate any help on this!
Side note: I am a premium member of this plugin and have already contacted their paid support, which they have said they weren't sure about how to do this and directed me to use Poedit... I don't think Poedit is an appropriate solution for this. Thanks so much to Dave Romsey who has tried to help me despite my php skill deficit :) | WordPress provides the [`_x()`](https://developer.wordpress.org/reference/functions/_x/) function which is just like [`__()`](https://developer.wordpress.org/reference/functions/__/), but it adds the `$context` parameter which is used to differentiate between identical strings.
In the example below, some output is generated in the footer. The translatable string is `Message` is used in both cases, but in the first instance, `Message` is given the context `for use in footer text`.
Next, we use the `gettext_with_context` and `gettext` filters respectively to translate each of the strings independently.
```
// Generate output for our example.
add_action( 'wp_footer', 'wpse_example_strings' );
function wpse_example_strings() {
// Note that concatenating strings is not translation friendly. It's done here for simplicity.
echo 'Message string with context: ' . _x( 'Message', 'for use in footer text', 'text_domain' ) . '<br>';
echo 'Message string without context: ' . __( 'Message', 'text_domain' ) . '<br>';
}
/**
* Translate text with context.
*
* https://codex.wordpress.org/Plugin_API/Filter_Reference/gettext_with_context
*
* @param string $translation Translated text.
* @param string $text Text to translate.
* @param string $context Context information for the translators.
* @param string $domain Text domain. Unique identifier for retrieving translated strings.
*
* @return string
*/
add_filter( 'gettext_with_context', 'wpse_gettext_with_context', 10, 4 );
function wpse_gettext_with_context( $translation, $text, $context, $domain ) {
if ( 'text_domain' === $domain ) {
if ( 'Message' === $text && 'for use in footer text' === $context ) {
$translation = 'Message Us';
}
}
return $translation;
}
/**
* Translate text without context.
*
* @param string $translation Translated text.
* @param string $text Text to translate.
* @param string $domain Text domain. Unique identifier for retrieving translated strings.
*
* @return string
*/
add_filter( 'gettext', 'um_rename_messagetxt', 10, 3);
function um_rename_messagetxt( $translation, $text, $domain ) {
if ( 'text_domain' === $domain ) {
if ( 'Message' === $text ) {
$translation = 'Contact Us';
}
}
return $translation;
}
```
Edit: Ultimate Member Messaging Button customization
----------------------------------------------------
I've taken a close look at this, and unfortunately the plugin authors have not made it very easy to change the button text.
Here's a solution that will replace the default Ultimate Member Message Button's shortcode with our own forked version. Note that we can recycle the `ultimatemember_message_button` name. I would suggest making a plugin out of this code:
```
<?php
/*
Plugin Name: Ulimate Member Custom Message Button Shortcode
Plugin URI:
Description:
Version: 0.0.1
Author:
Author URI:
License: GPL2/Creative Commons
*/
/**
* Remove the default UM Message shortcode and wire up our forked version.
*/
add_action( 'init', 'wpse_ultimatemember_message_button_custom' );
function wpse_ultimatemember_message_button_custom() {
global $um_messaging;
remove_shortcode( 'ultimatemember_message_button', [ $um_messaging->shortcode, 'ultimatemember_message_button' ] );
add_shortcode( 'ultimatemember_message_button', 'wpse_ultimatemember_message_button' );
}
/**
* Customized version of ultimatemember_message_button shortcode, which allows
* for the button's label to be specified using the 'label' parameter.
*/
function wpse_ultimatemember_message_button( $args = array() ) {
global $ultimatemember, $um_messaging;
$defaults = array(
'user_id' => 0,
'label' => __( 'Message','um-messaging' ),
);
$args = wp_parse_args( $args, $defaults );
extract( $args );
$current_url = $ultimatemember->permalinks->get_current_url();
if( um_get_core_page('user') ){
do_action("um_messaging_button_in_profile", $current_url, $user_id );
}
if ( !is_user_logged_in() ) {
$redirect = um_get_core_page('login');
$redirect = add_query_arg('redirect_to', $current_url, $redirect );
$btn = '<a href="' . $redirect . '" class="um-login-to-msg-btn um-message-btn um-button" data-message_to="'.$user_id.'">'. $label .'</a>';
return $btn;
} else if ( $user_id != get_current_user_id() ) {
if ( $um_messaging->api->can_message( $user_id ) ) {
$btn = '<a href="#" class="um-message-btn um-button" data-message_to="'.$user_id.'"><span>'. $label .'</span></a>';
return $btn;
}
}
}
```
Update your template to call the `ultimatemember_message_button` shortcode with our new `label` parameter like this:
```
<div class="msgshort">
<?php echo do_shortcode('[ultimatemember_message_button user_id=2 label="Contact US"]'); ?>
</div>
```
This isn't really the greatest solution, but our options are limited by the way that the plugin is implemented. I would suggest making a feature request for the `label` parameter to be added. |
266,461 | <p>For miskate i change the url of my wordpress on settings -> general. In order to revert this i changed the wp-config.php file and add this too config.php </p>
<pre><code>define('WP_HOME','localhost/wordpress');
define('WP_SITEURL','localhost/wordpress');
</code></pre>
<p>Then i restarted the apache and i hope i could enter again on my admin panel. But everytime i u use the localhost/wordpress/wp-login.php i receive a 404 not found</p>
<p>ideas?</p>
| [
{
"answer_id": 266464,
"author": "bynicolas",
"author_id": 99217,
"author_profile": "https://wordpress.stackexchange.com/users/99217",
"pm_score": 2,
"selected": false,
"text": "<p>Don't edit your <code>wp-config.php</code> file directly.</p>\n\n<p>Instead, with PHPMyAdmin, access your database and check for the table <code>_options</code>. You should see entries there for <code>site_url</code> and <code>home_url</code> change those values back to what you need</p>\n"
},
{
"answer_id": 291341,
"author": "user25225",
"author_id": 25225,
"author_profile": "https://wordpress.stackexchange.com/users/25225",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to edit it form wp-config.php \nthen use </p>\n\n<p>define('WP_HOME','<a href=\"http://example.com\" rel=\"nofollow noreferrer\">http://example.com</a>');\ndefine('WP_SITEURL','<a href=\"http://example.com\" rel=\"nofollow noreferrer\">http://example.com</a>');</p>\n"
},
{
"answer_id": 333707,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Try this\n1. Clean Cookies and Caches in the Browser\n2. rename \".htaccess\" file to .htaccess _backup in the \"wordpress\" folder\n3. Open your phpmyadmin then click on your database, select table \"options\"\n4. Edit siteurl and type correct url in option_value field.\n<a href=\"https://i.stack.imgur.com/WFXCB.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/WFXCB.png\" alt=\"enter image description here\"></a></p>\n\n<p>Save.</p>\n\n<p>if not working, try rename all plugin folder to disable it at /wp-content/plugins/</p>\n\n<p>Good luck</p>\n"
}
]
| 2017/05/10 | [
"https://wordpress.stackexchange.com/questions/266461",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/119378/"
]
| For miskate i change the url of my wordpress on settings -> general. In order to revert this i changed the wp-config.php file and add this too config.php
```
define('WP_HOME','localhost/wordpress');
define('WP_SITEURL','localhost/wordpress');
```
Then i restarted the apache and i hope i could enter again on my admin panel. But everytime i u use the localhost/wordpress/wp-login.php i receive a 404 not found
ideas? | Don't edit your `wp-config.php` file directly.
Instead, with PHPMyAdmin, access your database and check for the table `_options`. You should see entries there for `site_url` and `home_url` change those values back to what you need |
266,476 | <p>I have installed a wordpress server locally in mi pc, recentlly I have some issues uploading files using <code>wordpress media</code>. </p>
<p>I got some errors like</p>
<pre><code>Wordpress cannot create directory `wp-content/uploads/2017/05`. Check permissions in the above directory.
</code></pre>
<p>I checked directory permissions, and I set up to 777 the entire <code>wp-content</code> directory. Also I used <code>chwon www-data:www-data</code> to assign properly php user. </p>
<p>I checked php7-fpm conf, and php user is <code>www-data:www-data</code>. </p>
<p>I'm using Wordpress 4.7.3 version.</p>
<p>I think I'm missing something, but I don't know what is. Any help would be appreciated. </p>
<p>Thanks,</p>
<p>Ismael. </p>
| [
{
"answer_id": 266477,
"author": "JItendra Rana",
"author_id": 87433,
"author_profile": "https://wordpress.stackexchange.com/users/87433",
"pm_score": 0,
"selected": false,
"text": "<p>I have had similar problem in past. Try adding following to your wp-config.php </p>\n\n<pre><code>define('FSMETHOD', 'direct');\nputenv('TMPDIR='.iniget('uploadstmp_dir'));\n</code></pre>\n\n<p>Let me know if it Helps.</p>\n"
},
{
"answer_id": 266482,
"author": "erginduran",
"author_id": 119384,
"author_profile": "https://wordpress.stackexchange.com/users/119384",
"pm_score": 2,
"selected": false,
"text": "<p>add this below line to your <strong><em>wp-config.php</em></strong> (if you did not add it yet)</p>\n\n<pre><code>define('FS_METHOD', 'direct');\n</code></pre>\n\n<p>Check which user run your servers too (not only php7-fpm).</p>\n\n<blockquote>\n <p>ps aux|grep nginx</p>\n \n <p>ps aux|grep apache</p>\n</blockquote>\n\n<p>if your server works on www-data then,</p>\n\n<pre><code>cd ../your_wordpress_dir/\nsudo find . -type f -exec chmod 664 {} +\nsudo find . -type d -exec chmod 775 {} +\nsudo chmod 640 wp-config.php\n</code></pre>\n\n<p>if you are still getting same error, try a clean installation again with above permissions.</p>\n"
}
]
| 2017/05/10 | [
"https://wordpress.stackexchange.com/questions/266476",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102360/"
]
| I have installed a wordpress server locally in mi pc, recentlly I have some issues uploading files using `wordpress media`.
I got some errors like
```
Wordpress cannot create directory `wp-content/uploads/2017/05`. Check permissions in the above directory.
```
I checked directory permissions, and I set up to 777 the entire `wp-content` directory. Also I used `chwon www-data:www-data` to assign properly php user.
I checked php7-fpm conf, and php user is `www-data:www-data`.
I'm using Wordpress 4.7.3 version.
I think I'm missing something, but I don't know what is. Any help would be appreciated.
Thanks,
Ismael. | add this below line to your ***wp-config.php*** (if you did not add it yet)
```
define('FS_METHOD', 'direct');
```
Check which user run your servers too (not only php7-fpm).
>
> ps aux|grep nginx
>
>
> ps aux|grep apache
>
>
>
if your server works on www-data then,
```
cd ../your_wordpress_dir/
sudo find . -type f -exec chmod 664 {} +
sudo find . -type d -exec chmod 775 {} +
sudo chmod 640 wp-config.php
```
if you are still getting same error, try a clean installation again with above permissions. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.