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 getti... | 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' );\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' );\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 si... | 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, an... | 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, an... | 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, an... | 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 Front... | 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\... | 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\... | 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 ... | 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 ... | 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/referenc... | 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/referenc... | 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/referenc... | 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... | 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 Cha... | 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.... | 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.... | 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 ... | 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 ... | 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> (ak... | 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/... | 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/... | 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-controlle... | 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, ... | 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 nore... | 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 nore... | 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,... | 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,... | 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,... | 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>RewriteC... | 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_u... | 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>... | 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 d... | 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 ... | 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=\"nofol... | 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 ... | 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 ... | 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 objec... | 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 function... | 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. ... | 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 i... | 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.... | 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.... | 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 perma... | 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 tr... | 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</cod... | 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</cod... | 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 ... | 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... | 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 y... | 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 y... | 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 Pos... | 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://su... | 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 th... | 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 th... | 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</... | 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... | 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... | 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 ... | 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 ... | 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 al... | 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 follow... | 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(... | 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 de... | 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 de... | 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... | 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> butto... | 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 co... | 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 co... | 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 co... | 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.... | 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.... | 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.wor... | 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, th... | 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/\" ... | 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 mo... | 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": ... | 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... | 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 ... | 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 support... | 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 support... | 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 i... | 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 i... | 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 i... | 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 a... | 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 a... | 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<pr... | 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>... | 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>... | 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>... | 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... | 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 late... | 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... | 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,
"auth... | 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 cus... | 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 no... | 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 d... | 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>defin... | 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. |