INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Custom CSS is not working?
I have put the following custom CSS in my WP site's additional CSS setting:-
.et_pb_row_2 {
height:100vh !important;
background-color: red !important;
}
.et_pb_section_2 {
height:100vh !important;
background-color: #ff0000 !important;
}
The classes are for a section and row that I created using the Divi theme. You can view this live here.
Am I missing something here? | There's no et_pb_row_2 classes being used on that page only et_pb_row_1. Same thing applies to the class et_pb_section_2. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "css, html"
} |
Filtering a list of objects with 'OR' on the same field
I'm trying to use `wp_filter_object_list` to get tags with the slug (for example) "cat" OR "dog" from an array of tags.
My code looks like this:
$post_tags = wp_get_object_terms( $post_ids, 'post_tag' );
wp_filter_object_list( $post_tags, array('slug' => 'cat', 'slug' => 'dog'), 'or' );
I would expect this to return all tags with the slug "cat" or "dog", but it seems to only be returning the tag with "dog". If I switch the order, I only get "cat". How can I filter the list of tags for both? | the function `wp_filter_object_list` can only filter one value.
for your filter try that :
$post_tags = array_filter($post_tags, function ($e) {
return in_array($e->slug, ["dog", "cat"]);
}); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "filters, tags"
} |
get_template_directory_uri() providing wrong path for img
I've recently uploaded my wordpress project to my web hosting and images arent showing properly, the source for the images is adding a %20 suffix to my theme directory.
this is the error thats thrown in console
GET 404 (Not Found)
it should be
in my php file it is written as
<img class="mobile-image-full" src="<?php echo get_template_directory_uri(); ?>/img/slideshow1.jpg"> </img>
I cannot figure out what the issue is, if anyone could help i would be grateful. | There's a space after the word "shapely". You must remove that, spaces and special characters are encoded when used in URL's. Most probably this space is in the directory name, rename it and it will solve the problem | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php, permalinks, links"
} |
Is using register_activation_hook required?
I'm building my first plugin and it's very basic. I created my `init` class that is used for enqueue styles.. etc. It also has the `register_activation_hook` and `register_deactivation_hook` hooks but I don't know what to do with those!
My question is this.. Put yourself in my position, that you want to create a basic plugin that adds small features like related posts, maybe some small widgets... etc, and you don't want to do anything on activation/deactivation or uninstall.. Would you..
* Remove those hooks?
* Keep the hooks and leave the callback functions empty or return null...?
* Do something else that any plugin should do when activate or deactivate or uninstall?
Thank you! | You don't have to use the `register_activation_hook` or `register_deactivation_hook` hook, they are optional. As their name suggests, they are hooks planned to run a task on plugin's activation/deactivation, such as updating the status of all users for some purpose.
So, if your plugin doesn't require such tasks, then simply don't use them. If you want to register new post types and taxonomies, you can use the `init` hook instead. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "plugin development"
} |
Change the user_login at registration
I use a third party plugin that adds Social Login option to my blog. It works very well, but I dislike that **when users choose to login by their social accounts** the user login names (`user_login` in database) are saved in this format - " _First-Second_ ", so the first letter of the each part are capitals. My own `user_login` will be "Iurie-Malai", but I would like "iurie-malai".
I know that WordPress usernames are case-insensitive, but I want that user logins to be only in lowercase. How can I do this? | You can hook into the `user_register` action hook and lower case the strings manually, by using the `wp_update_user` function. Here's a quick example:
add_action( 'user_register', 'callback_function', 10, 1 );
function callback_function( $user_id ) {
// Get the user by their ID
$user = get_user_by( 'id', $user_id );
// Update their user_login
wp_update_user(
array(
'ID' => $user_id,
'user_login' => strtolower( $user->user_login )
)
);
}
## Using the `pre_user_login` filter
You can use the above filter to filter the user's login before its added to the database, as follows:
add_filter( 'pre_user_login', 'callback_function' );
function callback_function( $login ) {
return strtolower( $login );
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "users, login"
} |
append code after the_content not working
**Goal:**
Add pagination below single post pages.
**Code**
function add_pagin( $content ) {
if ( is_singular('post') ) {
$content .= previous_post_link() . next_post_link();
}
return $content;
}
add_filter( 'the_content', 'add_pagin' );
**Result**
Pagination added to the top of `the_content`, not below it. If I change `$content.=` to echo a simple string it works, but not with those two wprdpress functions.
I appreciate the help with this. | `previous_post_link` and `next_post_link` both output the link directly, which won't work in your case because you're trying to assign the result to a variable. Use `get_previous_post_link()` and `get_next_post_link()` instead-
function add_pagin( $content ) {
if ( is_singular('post') ) {
$content .= get_previous_post_link() . get_next_post_link();
}
return $content;
}
add_filter( 'the_content', 'add_pagin' ); | stackexchange-wordpress | {
"answer_score": 5,
"question_score": -1,
"tags": "plugin development, theme development, filters, the content"
} |
How to fetch all the movie details from IMDB
I am working on wordpress website and want to fetch all movies/tv data from imdb by using movie/tv id E.G tt2527336. I wanna fetch everything, i mean Director, Stars, Release Date, genre, storyline, country, feature post and language. Is there way that all data will add in post by adding imdb post id? | Pat J is right but even so, I think there's an unofficial API that provides that kind of feature: < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -3,
"tags": "feed"
} |
Customizer JS API: Adding a "dropdown-pages" control
What is a proper way to add a list of pages (`type: dropdown-pages`) using Customizer JS API?
Currently, I have this code but it does not display a control:
api.control.add( new api.Control( 'custom-control', {
type: 'dropdown-pages',
section: 'custom-section',
setting: new wp.customize.Setting( 'custom-control', '0' ),
label: 'Select Page'
} ) );
If I change the type to, for example, `text` then the control is shown in the section. | You're right, that doesn't work… yet. We didn't add support for the `dropdown-pages` control in #30738 because we wanted to leverage the REST API for this control to fetch the pages. So in 4.9 this is the only base control that requires server-side rendering in core. However, in 4.9 it is easy to provide our own implementation of a content template for the `dropdown-pages` control.
I've written a standalone example plugin which includes control template for the `dropdown-pages` control type. With that template included, you can create controls in the same way you are doing here. Follow #42272 for upcoming core implementation.
Alternatively, you may want to consider the Customize Object Selector plugin, as it provides a control which uses Select2 to provide a searchable interface for selecting one or more pages. See example usage in the Customize Posts plugin. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "javascript, theme customizer, api"
} |
Customizer JS API: Defining control settings
I am trying to create Customizer controls using JS API. What is a proper way to define control settings?
Here is my current code:
var mySetting = new api.Setting( 'section_title', 'Hello World!' );
api.add( mySetting );
api.control.add( new api.Control( 'section_title', {
type: 'text',
section: 'custom-section',
setting: mySetting,
label: 'Enter your custom title'
} ) );
When I try to save my changes, the Customizer shows an error: "Setting does not exist or is unrecognized." | Settings must be registered in PHP one way or another. If you don't register them statically via `$wp_customize->add_setting()` calls, you will have to register dynamic recognition of them via the `customize_dynamic_setting_args` filter. Why? In order for a setting to be safely stored it must be sanitized and validated by the server. Relying on client-side sanitization and validation is dangerous. Additionally, the Customizer setting is what gets persisted into the DB and actually applies a change to the site. This means that WordPress needs to know what a setting is for, how to preview it, and how to save it. So you may freely create settings in JS, but you must create a `customize_dynamic_setting_args` filter. You use this filter to match a given setting ID against a certain pattern you define. Examples of this can be found in core for widgets and nav menu items. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, theme customizer, api"
} |
custom url rewrite for wordpress
Can we rewrite bellow url in wordpress site?
I want to hit the following wordpress url:
test/test-post/index.shtml
with this url "custom" is my folder at root path and custom.php file
custom/custom.php?cat=1
Any help would be greatly appreciated, I've been struggling with this. Thanks in advance! | This will do it:
RewriteEngine on
RewriteRule ^test/test-post/index.shtml$ custom/custom.php?cat=1 [L,R]
The `[L]` flag causes mod_rewrite to stop processing the rule set.
Use of the `[R]` flag causes an HTTP redirect to be issued to the browser. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "php, customization, htaccess, rewrite rules"
} |
Hierarchical Custom Post Types - Show only parent on tax archive?
I have a cpt of Accommodation
Taxonomy of Region
Regions are then added like USA, Canada etc
Then for the posts:
I create a post for a whatever Resort and a child posts of whatever Hotel in that resort ( Hierarchical ) and assign it to a tax term like USA
All good and working 100% perfect
Question: when I go and view say USA
I see all the posts, both parent and child
How can I only show the parent post and not the children on these taxonomy archives?
Figured a simple pre_get_posts would do the trick, but tried like 20 variations with no luck
Suggestions appreciated | > Figured a simple pre_get_posts would do the trick,
It will, you just need to query posts that have a parent of `0`.
Assuming your taxonomy slug/name is literally just `region`:
function wpse_286405_parents_only( $query ) {
if ( ! is_admin() && $query->is_tax( 'region' ) ) {
$query->set( 'post_parent', 0 );
}
}
add_action( 'pre_get_posts', 'wpse_286405_parents_only' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom post types, taxonomy, archives, hierarchical"
} |
posts_per_page returning only one post
function blog_post_home_shortcode() {
$query = new WP_Query( array(
'post_type' => 'post',
'order' => 'DESC',
'post_status' => ' publish',
'posts_per_page' => 3
));
while ($query->have_posts()): $query->the_post();
$blog = get_the_title();
return $blog;
endwhile;
wp_reset_postdata();
}
add_shortcode('blogs_home', 'blog_post_home_shortcode');
returns only one title while in WP_Query I have set `posts_per_page => 3` I want to display all 3 title of last published posts. | You may please update your code as follows
function blog_post_home_shortcode() {
$query = new WP_Query( array(
'post_type' => 'post',
'order' => 'DESC',
'post_status' => ' publish',
'posts_per_page' => 3
));
while ($query->have_posts()): $query->the_post();
$blog = get_the_title();
echo $blog;
endwhile;
wp_reset_postdata();
}
add_shortcode('blogs_home', 'blog_post_home_shortcode');
Please check the above code and let me know if it works for you. | stackexchange-wordpress | {
"answer_score": -2,
"question_score": 0,
"tags": "posts, wp query"
} |
Sending comment notifications to different recipients depending on taxonomy terms
I try to add a filter to the comment notification recipients function, for adding different recipients/moderators depending on the taxonomy terms of each post.
This is my code so far, but it doesn't work:
function se_comment_moderation_recipients( $emails, $comment_id ) {
$emails = array( '[email protected]' );
if ( has_term('myterm','mytaxonomy') )
return $emails;
}
add_filter( 'comment_moderation_recipients', 'se_comment_moderation_recipients', 11, 2 );
add_filter( 'comment_notification_recipients', 'se_comment_moderation_recipients', 11, 2 );
Any help would be really really appreciate. | Finally I found the right code, if it can be usefull to someone:
function sp_comment_moderation_recipients( $emails, $comment_id ) {
$comment = get_comment( $comment_id );
$post = get_post( $comment->comment_post_ID );
if ( has_term('myterm','mytaxonomy', $post->ID) ) {
return array( '[email protected]' );
}
return $emails;
}
add_filter( 'comment_moderation_recipients', 'sp_comment_moderation_recipients', 10, 2 );
add_filter( 'comment_notification_recipients', 'sp_comment_moderation_recipients', 10, 2 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "comments, terms, notifications, moderation"
} |
How to send user data from one website to another
I need to send user data (some parts of `user` and `user_meta`), from Website A to Website B (both are Wordpress Websites) over a secure Protocol, after clicking on a button. According to this post, a secure method would be the ssl protocol (https).
Or in other words, **I need the user data of Website A also on Website B** (different Server). I have full access to both sites.
What are the **best practice** and are there already some tools to do that? Where to find good documentation for this task?
In my research I could find only Client to Server communication like here: developer.mozilla.org/Sending_and_retrieving_form_data.
But I'm looking actually for ways to send data to another website (on another server). I guess my case is **server-to-server** communication?
Thanks in advance for your help! | I just found a possible solution for my question.
The technology I was looking for is `curl`. Look at this posts for more Informations:
* stackoverflow.com/transfer-php-variables-from-one-server-to-another
* stackoverflow.com/sending-data-across-websites-using-from-http-and-receiving-in-https
Also I this Blog Article quite useful:< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "ssl, https, curl"
} |
How to find a post id using the post_excerpt?
I know how to find the post_excerpt using the post ID, but is it possible to find a post ID using an excerpt? Every time I search for this, all that comes up is how to find the post_excerpt from the ID. Thanks for any help. | You can get the post ID from the excerpt, but as far as I can tell, `WP_Query` doesn't support this (very well), so you need to write a custom WPDB query.
function get_post_id_by_excerpt($excerpt) {
global $wpdb;
$result = $wpdb->get_row(
$wpdb->prepare("SELECT ID FROM {$wpdb->prefix}posts WHERE post_excerpt LIKE %s", $excerpt)
);
return $result;
}
For this to work, you need to pass the exact excerpt (incl. HTML) to the function | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "wp query, excerpt"
} |
Dashboard : remove Safari navigator message
Everytime when i login to wordpress backoffice with safari (only with safari navigator). I got the message on the picture below :
 {
remove_meta_box( 'dashboard_browser_nag', 'dashboard', 'normal' );
}
add_action( 'wp_dashboard_setup', 'wcs_disable_browser_upgrade_warning' );
I would tell your client the risks that might be comming with this - just to make sure that you won't be responsible if anything happens.
Hope the code works - I couldn't test for my browsers are updated ;) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp admin, admin, metabox, dashboard"
} |
How to get total count for each star rating?
I'm using Woocommerce and I'm trying to get the total for each star rating using the post id (just like in the image below). Each rating is stored on my database as a number from 1 - 5 I just don't know how to go about retrieving the total count for each rating.
Any help will be greatly appreciated.
!rating system | You can use the function `get_rating_count()` by specifying on each call the value needed. For example :
global $product;
$rating_1 = $product->get_rating_count(1);
$rating_2 = $product->get_rating_count(2);
$rating_3 = $product->get_rating_count(3);
$rating_4 = $product->get_rating_count(4);
$rating_5 = $product->get_rating_count(5);
You can read more about the function | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "woocommerce offtopic, rating"
} |
Shotcode argument issues
function some_function_bbb() {
ob_start();
extract( shortcode_atts( array(
'hexabexa' => 0
), $atts )
);
$args = array(
'hexabexa' => $hexabexa
);
?>
<div class="newsletter <?php echo $args['hexabexa']==1 ? 'newsletter2' : '' ?>">
<h2>Plugin Works!</h2>
</div>
<?php
return ob_get_clean();
}
add_shortcode('some_function_bbb', 'some_function_bbb');
Shortcode →
[some_function_bbb hexebexa="1"] →
still the class newsletter2 is not printing. where am i wrong? | You need to pass `$atts` as parameter to the function. Also you don't need to use `extract()` function and better you avoid this `extract` function as much as you can. So your whole code block will be-
function some_function_bbb( $atts ) {
$atts = shortcode_atts(
array(
'hexabexa' => 0
),
$atts
);
ob_start();
?>
<div class="newsletter <?php echo $atts['hexabexa'] == 1 ? 'newsletter2' : '' ?>">
<h2>Plugin Works!</h2>
</div>
<?php
return ob_get_clean();
}
add_shortcode('some_function_bbb', 'some_function_bbb');
// Call it like [some_function_bbb hexabexa=1]
And lastly you are passing your shortcode attribute wrong. You declared your attribute as `hexabexa` and passing the attribute as `hexebexa`. The _e_ should be _a_ in your shortcode. So fix this typo also.
Hope that helps. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "functions, shortcode"
} |
using conditionals on enqueue styles
I want to run my css code on a specific page in admin area. What is the best approach please?
A:
function register_style() {
if (is_page..something) {
wp_enqueue_style('style', PLUGIN_URL . 'style.css');
}
}
add_action('admin_enqueue_scripts', 'register_style');
B:
function register_style() {
wp_enqueue_style('style', PLUGIN_URL . 'style.css');
}
if (is_page..something) {
add_action('admin_enqueue_scripts', 'register_style');
} | I'd go for A) (but give that function another name to avoid collisions), because you can be absolutely sure that all manipulation of the request is over once `admin_enqueue_scripts` is fired. You cannot be sure if you just put it into the functions.php (or where ever this code will live).
I don't really see a (non-edge-case where somebody is doing something strange) scenario where B) will get you in trouble, but A) is much cleaner imho. A) might (theoretically; humans won't notice until we evolve quite a bit or you go back down to ancient CPUs) a tiny bit heavier since both the conditional and the action have to be run if the conditional returns false. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "wp enqueue script, conditional tags, wp enqueue style"
} |
Customize WooCommerce my account dashboard through plugin
I am making a plugin that adds some functionality to woocommerce. I dislike the bland default woocommerce "my account dashboard" page and I would like to change the way the dashboard looks. I have been looking online and it seems the only way to do this would be to modify the theme or the template inside of woocommerce plugin itself.
I want to make my plugin as portable as possible therefore, I would like for my plugin to modify the my account dashboard page, and not the PHP code of the template or the woocommerce plugin. Is there a way to do this as a plugin? | I ended up doing it in what I would consider a sloppy way. On the `init` hook I check the WooCommerce template against my custom template and if the WooCommerce template does not match my template then I replace the WooCommerce template with my template.
add_action( 'init', 'run_inital' );
function run_inital(){
$wooThemePath = $woocommerce->plugin_path()."/templates/myaccount/dashboard.php";
$myThemeFile = file_get_contents(plugin_dir_path( __FILE__ )."/WooCommerce/dashboard.php");
$WooThemeFile = file_get_contents($wooThemePath);
if($myThemeFile != $WooThemeFile){
$Woo_Theme = fopen($wooThemePath, "w");
fwrite($Woo_Theme, $myThemeFile);
}
}
If you wanted to make this snippet better you should check to see if the file sizes are different instead of comparing the contents. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugin development, woocommerce offtopic"
} |
Function not working at one place
function some_function() {
$template_options = get_post_meta(get_the_ID(), 'the_s_t_l_id', true);
if ('layout_7' === $template_options || 'layout_8' === $template_options || 'layout_9' === $template_options){
echo 'displaynone';
}
}
Class →
.displaynone {display:none;}
But when I am calling function it doesnt work here →
<aside class="sidebar <?php some_function(); ?>">
However, if I call this function somewhere else, and if the logic is true then it does print the anticipated class.
what is the reason that it is not working in the desirable place then? | This is because you have functions that work only inside of the WordPress Loop like `get_the_id()`. This will return the correct value inside the WP Loop in template files, but when called in other places does not return the correct value and check fails.
See this for more information on the WordPress loop
<
When outside the loop you can either use the global `$post` object to get the id like this
global $post
$id = $post->ID;
Alternately you can try this
$id = get_queried_object_id(); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "php, functions"
} |
Strange custom post type issue
I previously had a custom post type called "Business" however the client needed this changed to "Listing", which I did (before we started adding a load of posts, luckily).
We now have over 100 posts under the "Listing" post type, however when I use the default loop on the archive-listing.php template as
$i = 0;
if (have_posts()) : while (have_posts()) : the_post();
echo $i++ . " ";
endwhile; endif;
I only see 50 posts returned. More strange is that when I view the posts within Wordpress (by clicking "Listing" on the left hand menu), I see 50 posts on the first page (of 9 pages), even though I have set `Screen settings > Number of items...` to just `10`.
I have visited and saved the permalinks page, so it's not that. Is this perhaps related to the name change of the custom post type early on, and if so, how do I resolve this at this late stage? | I suggest you to debug first that whether the loop is carrying all posts or not. You may use print_r() and die combination. If it carries all posts fine then you may move to further steps of debugging.
Add pagination code. Because, if your loop do have all the posts with it then probably due to no pagination, you are missing other posts.
If still it doesn't show anything. Then, you need to share a screenshot of both the pages admin and frontend. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types"
} |
Category links break the https
I have asked my hosting company to active the https for my web site. Now, when I write the URL in my browser and go to my web site it is https (I can see the green lock). I have some Menu items which direct to some pages I have created, all works fine. However, links which direct to example.com/category/holidays etc. breaks the https. Any idea why this could be? | With the new or not so new move to the https side of thing, there are rising numbers of questions about the mixed content warning for https.
## First check the sites URLS:
* Settings > Permalinks and save. This will refresh the urls.
* Also change WordPress Address (URL) and Site Address (URL) so it includes the **https** ://yourawesomewebsite.com).
* As a final step clear cache and cookies
## Steps to verifying:
* Open the developer tools( Chrome/Firefox F12)
* Navigate to console and see the complete error/warning | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "https"
} |
Bulk append URL (add word to slug)
Is there a way to bulk add one word at the end of each URL for posts? I have around 3500 posts and it would be time consuming to add to each one.
For example URL's are
www.example.com/my-post/
www.examle.com/new-post/
And I want to add one word to end of URL
www.example.com/my-post-word/
www.examle.com/new-post-word/
Is there MySql script to do such thing? | Here is your code:
if ( isset($_GET['slug-update']) ) {
$posts = get_posts();
foreach($posts as $singlepost) {
if($singlepost->post_status === 'publish'){
$post_id = $singlepost->ID;
$current_slug = $singlepost->post_name;
$updated_slug = $current_slug . '-word';
}
wp_update_post( array(
'ID' => $post_id,
'post_name' => $updated_slug ) );
}
die('Slug Updated');
}
Add this to your theme's function.php. Then run this with `www.example.com/?slug-update`
P.S. this will only update the default post type 'post' (backup the database to be secure)
Let me know if this helped. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "permalinks, url rewriting, mysql, urls, slug"
} |
How to add onclick event to widget image
I have added a custom url to the widget image in the new WP 4.9. Now I want to add an onclick event to the link.
The a tag looks like this
<a href=" class="" rel="" target=""></a>
And I want to have it like this
<a href=" onclick="ga('send', 'event', 'Sidebar Image', 'Promo Image', 'Clicked');"></a>
How can I do this? | I would use the Google Tag Manager firing options:
Or
Old school jQuery solution:
function($){
$('.widget_class').click(function() {
ga('send', 'event', 'Sidebar Image', 'Promo Image', 'Clicked');
});
})(jQuery);
Now you just add a class name to your links. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "images, widgets, events, google analytics"
} |
How to replace values in Wordpress DB using phpMyAdmin
I am trying to save a value in a cg_option row/field using phpmyadmin, however data is not stored correctly and when loaded again after saving, only part of data appears. Do I need to use a conversion function within phpmyadmin?
The row is theme_mods_[theme-name]
This is a sample of data contained in the field:
`s:19:"thim_my_text_option" s:0:"" s:30:"thim_display_login_menu_mobile" b:0 s:25:"thim_body_secondary_color" s:7:"#4caf50" s:24:"thim_remove_query_string" b:0 s:21:"thim_google_analytics"` | The data is serialized.
In order to edit it, you need to unserialize it, edit, then serialize again, and save.
You can do that with PHP.
Check serialize and unserialize.
You can check this tool as well: serializededitor.com | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "database, phpmyadmin"
} |
When changing pages to posts, how do you set up 301 redirects for the page URLs?
I recently found that an older, now disabled plugin that made scheduled posts was creating new posts as pages. I went into the database and changed `post_type` to `post`.
The urls then changed to the permalink structure I have for posts:
> <
Whereas the page URL was:
> <
My old page URLs, which were shared on social media already, are now generating 404 errors. Most tutorials I find online discuss setting up redirects when the permalink settings themselves are changed and the whole site is affected. I just want to mitigate these few page-to-post URLs. | If it's just a few pages, then you could set redirects explicitly for these pages in your .htaccess file (it's located in your WP install root folder), just add following lines on top of the file (you will need to write a rule for every page you want to redirect):
Redirect 301 /this-is-the-page /default-category/this-is-the-post
Redirect 301 /this-is-another-page /default-category/this-is-another-post
as you see the pattern is really simple:
Redirect 301 /old-page-path /new-page-path | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, permalinks, pages, redirect"
} |
REQUIRED: get_bloginfo('template_url') was found in the file search.php. Use get_template_directory_uri() instead
Theme Check error →
REQUIRED: get_bloginfo('template_url') was found in the file search.php. Use get_template_directory_uri() instead.
Line 21: <img src='<?php echo get_bloginfo('template_url') ?>/img/no_results_found.png'/>
I acted and made the changes, but the image is now not coming in live webpage →
<img src='<?php echo get_template_directory_uri() ?>/img/no_results_found.png'/>
Is there any mistake in the above? | Is the image in a child theme? If so, use `get_stylesheet_directory_uri()` instead as it will grab the child theme URL. `get_template_directory_uri()` grabs the parent theme.
Depending on your PHP version adding a semicolon also might make a difference, and typically image src uses double quotes rather than single.
<img src="<?php echo get_stylesheet_directory_uri(); ?>/img/no_results_found.png" /> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php, functions, codex"
} |
Limit search form to 4 custom post types only
I'm able to limit the search to one post type which works like a charm.
This code works: `<input type="hidden" name="post_type" value="videos"/>`
However, how do I limit the search to be performed in 4 custom post types instead of just one.
The post types are "videos, e-courses, e-books and white-papers".
Any help is really appreciated.
Thanks | You have to change the input with 4 inputs like this :
<input type="hidden" name="post_type[]" value="videos" />
<input type="hidden" name="post_type[]" value="e-courses" />
<input type="hidden" name="post_type[]" value="e-books" />
<input type="hidden" name="post_type[]" value="white-papers" />
You may get more detail about a complete code in this article | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "custom post types, search"
} |
How to display author meta in a sidebar widget
I am trying to display author meta data (username, email) in a custom sidebar widget and I cannot figure it out.
I can display the info on a template page (using php) just fine but that wont work for what I need. I have also figured out how to call the meta data by manually specifying the user id.
I have tried using the same code that works on the template page in my widget code but it wont work (I am not using the WP widget section).
How can I display the meta data (username and email) in the sidebar widget? Is there a way to pull the user id of a post with php? Or is there a better/different way to pull the user meta by php? I am guessing the widget doesn't have access to the same post information that the normal page does? | I figured it out, completely accidentally. I had already tried the solutions posted but they did not work for me, most likely due to the theme I am using (TravelTour).
For me, to get the user meta to display I had to call wp_reset_query before it. I have no idea why.
Example:
wp_reset_query();
// then
echo get_the_author_meta('user_email'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "widgets, author, user meta"
} |
Warning on my WordPress site
Domain showing an alert message of " Deceptive site ahead ". How can I resolve this issue, please help. I have attached the screenshot showing error.
.
There there is a tab that shows this activity and telling next steps to resolve it.
> This warning may be up a time after you resolve the issues because it should be recrawled and verified, a process that requires time and manual action.
Also removing only the files didn't mean you are safe. Backdoors exist also in the **Database**. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "warnings"
} |
Problem after renaming wordpress template file
After renaming the files of my templates and inside the file with php, it is looking for the old templates. The dropdown is no longer available. Why is this happening and how to fix that?
The only files i modified is the `template-parts` folder inside the child theme. I did not touch the `class-wp-theme.php` where it is the warning.
 {
if ( ! in_array( $current_screen->base, array( 'post', 'edit', 'theme-editor' ), true ) ) {
return;
}
$theme = wp_get_theme();
if ( ! $theme ) {
return;
}
$cache_hash = md5( $theme->get_theme_root() . '/' . $theme->get_stylesheet() );
$label = sanitize_key( 'files_' . $cache_hash . '-' . $theme->get( 'Version' ) );
$transient_key = substr( $label, 0, 29 ) . md5( $label );
delete_transient( $transient_key );
}
add_action( 'current_screen', 'fix_template_caching' );
Reference: Fix for theme template file caching
Hope this helps!
:) | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "themes, page template"
} |
How to prevent a style sheet to affect a header.php or footer.php?
I crated a footer.php and a corresponding customFooter.php. It looked great until I added header.php and customHeader.css. Now the 2 custom css files are overlaping. For example: some of the `<img>` are not aligned properly, due to the alignment of the pther css file. Is it possible to restrict certain css file only to a specific pphp file?? | You can define specific stylesheets for specific PHP files.
If you are using a Child Theme, use the functions.php of the Child.
**You should use something like:**
function my_custom_css() {
wp_register_style( 'stylesheet_name', get_stylesheet_directory_uri() . '/stylesheet.css' );
}
add_action( 'init', 'my_custom_css' );
function my_custom_css_enqueue() {
// only enqueue on product-services page slug
if ( is_page( 'my-page' ) ) {
wp_enqueue_style( 'stylesheet_name' );
}
}
add_action( 'wp_enqueue_scripts', 'my_custom_css_enqueue' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "headers, css, footer"
} |
Function for when new custom post type is created should do something
I've been searching in the codex from wordpress and search through google but didn't find any function or any code that can help me.
I want to build a conditional that when there is a new custom post type should do something automatically(in one case specific create a marker in a map).
Any suggestion?
Thanks | You can do something on a post creation with the action `save_post_`...
$customPostType = "custom";
add_action("save_post_" . $customPostType, function ($post_ID, \WP_Post $post, $update) {
if (!$update) {
// creation of the custom post
// ...
return;
}
// updating of the custom post
// ...
}, 10, 3); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, functions, codex"
} |
Multisite configuration for multiple domains
I have a multisite installation running fine with two sites. I can access both of them with no problems using the urls mydomain.com/site1 and mydomain.com/site2.
The problem is that I need to configure my site1 to be accessed from an url of another domain, ex: anotherdomain.com
How can I achieve this? I changed my site's URL on the Network dashboard to anotherdomain.com and it's dns pointing to mydomain.com. It didn't work, my main site is displayed. | WordPress supports **Domain Mapping**.
WordPress multisite subsites may be mapped to a non-network top-level domain. This means a site created as subsite1.networkdomain.com, can be mapped to show as domain.com. This also works for subdirectory sites, so networkdomain.com/subsite1 can also appear at domain.com. Before setting up domain mapping, make sure your network has been correctly set up, and subsites can be created without issues.
Before WordPress 4.5, domain mapping requires a domain mapping plugin like WordPress MU Domain Mapping.
In WordPress 4.5+, domain mapping is a native feature.
* * *
Full details and tutorial can be find here: < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "multisite, domain"
} |
get_permalink() of page the enclosing page not posts
I have spent the last hour googling and trying different methods but nothing works the way I want it to.
Within the loop of the posts, I need to get the permalink of the main page.
## Example
You have a portfolio custom post type and then a page where you show all of your work `archive-portfolio.php`, I need to get the link to the main portfolio page/archive-page within the loop.
The latest I have tried is getting the ID of the page outside of the loop and setting it to a variable then calling it later on in the loop.
$page_id = get_the_ID();
but because i am using an `archive-{post-type}.php` it is not working, correctly.
Is there another solution other than changing over to `page-{template`} and implementing that method? | I think you need the `get_post_type_archive_link` function. It requires a post type as a parameter, but since you're already on the archive page you should be able to use it in combination with `get_post_type`, which gets the current post type by default:
$permalink = get_post_type_archive_link( get_post_type() );
See more on the Codex. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, plugin development, loop, templates, custom post type archives"
} |
get post id from wp_insert_post for get_template_part
This is my code:
$my_post = array(
'post_type' => 'theposttt',
'post_title' => 'test',
'post_content' => '',
'post_status' => 'publish',
'post_author' => 1
);
$data = wp_insert_post($my_post);
ob_start();
get_template_part( 'template/the', 'post' );
$data = ob_get_clean();
$resp = array(
'success' => true,
'msg' => 'success',
'data' => $data
);
I want to get the post id of the new post from wp_insert_post to using it inside the template the-post.php that I get it by using the get_template_part function. | Declare `$my_post_id` as global in your code. Declare `$my_post_id` as global in `the-post.php` template. Your code:
global $my_post_id;
$my_post = array(
'post_type' => 'theposttt',
'post_title' => 'test',
'post_content' => '',
'post_status' => 'publish',
'post_author' => 1
);
$my_post_id = wp_insert_post($my_post);
if(is_wp_error($my_post_id))
$my_post_id = 0;
Now, you can use `$my_post_id` in `the-post.php` template. Possible values: 0 ( failure ), post id ( success ). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, posts, functions, wp insert post"
} |
Adding shortcode closing tag after a loop
I'm using a shortcode for accordion. I would like to put a loop inside this shortcode. However the closing tag seems to be unparsed.
<?php echo do_shortcode('[su_accordion]');?>
<?php
if ( have_posts() ) :
while ( have_posts() ) : the_post();
echo '<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">';
echo do_shortcode('[su_spoiler title="'.get_the_title().'" open="no" style="default" icon="plus" anchor="" class=""]'.get_the_content().'[/su_spoiler]');
echo '</div>';
endwhile;
else :
echo wpautop( 'Sorry, no posts were found' );
endif;
?>
<?php echo do_shortcode('[/su_accordion]');?>
The last part of the shortcode is displayed as simple text.
Any solution? | Collect all of the loop's output in a variable, wrap it in the accordion shortcode, then pass that through do_shortcode:
$output = '';
if ( have_posts() ) :
while ( have_posts() ) : the_post();
$output .= '<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">';
$output .= do_shortcode('[su_spoiler title="'.get_the_title().'" open="no" style="default" icon="plus" anchor="" class=""]'.get_the_content().'[/su_spoiler]');
$output .= '</div>';
endwhile;
else :
$output = wpautop( 'Sorry, no posts were found' );
endif;
echo do_shortcode( '[su_accordion]' . $output . '[/su_accordion]' );
I've tested this with a couple of enclosing Shortcodes and got the expected output. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "loop, shortcode"
} |
Customizer doesn't recognise sidebar
I have registered a sidebar and I use it on all of my pages. For some reason the customizer doesn't recognise it.
Have I done something wrong?
Here's my code:
**functions.php**
function registerSidebar() {
register_sidebar( array(
'name' => 'Main sidebar',
'id' => 'main-sidebar',
'description' => 'Main sidebar on the left.',
'before_widget' => '<div id="%1$s" class="widget flex-column %2$s">',
'after_widget' => '</div>',
'before_title' => '<h5 class="widgettitle font-weight-bold">',
'after_title' => '</h5>'
) );
}
add_action( 'widgets_init', 'registerSidebar' );
**sidebar.php**
dynamic_sidebar( 'main-sidebar' );
Then I just include my sidebar in the **header.php** file, like this:
get_sidebar();
Here's an image of the message I get:
 {
wp_enqueue_script( 'my-great-script', get_template_directory_uri() . '/js/my-great-script.js', array( 'jquery' ), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'my_theme_scripts' );
See more on this page. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "sidebar, theme customizer"
} |
WPCLI - update plugins, themes, and core, all in one row, instead 3 rows?
Is there a way to update plugins, themes, and core, all in one row, instead 3 rows, in WPCLI?
This is the current code I use in the `crontab` and that I'd like to improve:
0 0 * * * for dir in /var/www/html/*/; do cd "$dir" && /usr/local/bin/wp plugin update --all --allow-root; done
0 0 * * * for dir in /var/www/html/*/; do cd "$dir" && /usr/local/bin/wp core update --allow-root; done
0 0 * * * for dir in /var/www/html/*/; do cd "$dir" && /usr/local/bin/wp theme update --all --allow-root; done | Run a script instead:
0 0 * * * for dir in /var/www/html/*/; do cd "$dir" && ./updatewp.sh; done
In `updatewp.sh`:
wp core update --all --allow-root
wp plugin update --all --allow-root
wp theme update --all --allow-root | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "wp cli"
} |
Let custom text widget use the same font as the theme
On this page, I have created a text widget. I don't know how to match this up with the font on the rest of the site. The theme uses the Playfair Display font. I don't have extensive knowledge of Wordpress yet so apologies if this is a frustrating question. Here is the link < | UPDATE: You just have to put this code in your custom-css area in the wordpress customizer:
.wpb_wrapper {font-family: playfair display;}
But this will affect all items on your site with the CSS-Class ".wpb_wrapper" so maybe you should look for a way to specifice the CSS-Classes and CSS-IDs for single elements of your page if you have to, so that you're able to specify your CSS-Code, when you need some like now, to point just at the one specified Element. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "themes, formatting, widget text, fonts"
} |
How to use the php if statement
//The textarea is displayed when the if clause evaluates to false. // What do I need to change?
<?php
if ( 1==2)
?>
<textarea>
"Add multiple lines of text here and watch the scrollbars grow.">
</textarea> | You may do it this way using open/close bracket **{}**
<?php
if ( 1==2) {
?>
<textarea>
"Add multiple lines of text here and watch the scrollbars grow.">
</textarea>
<?php } ?>
In general rules you need to enclose all the `if else` statement using php tag and the html outside it. You may also use echo.
* * *
<?php if ( condition ) { ?>
<!-- your html goes here -->
<?php } else { ?>
<!-- another html goes here -->
<?php } ?>
Example with the use of echo (using ony one php tag to open/close the block)
<?php if ( condition ) {
echo "<p>Some text content</p>";
} else {
echo "<p>Another text content</p>";
} ?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "php, javascript"
} |
Minimum version for Wordpress Backbone
How do I find the minimum Wordpress version required if I want to use Backbone on a plugin? I'm building a Wordpress plugin, and I can't find documentation online that records when Wordpress first used Backbone. | It was introduced in 3.5 for the media library, but it's been periodically updated since then. Honestly, it's been around long enough that you're almost certainly using something else that has a more recent requirement. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "wp admin, backbone"
} |
How to pass variable to get_search_form()?
Is it possible to pass variable to `get_search_form()`?
I'm using it in two places: one in header and on the search page in the content. The latter must have additional class, e.g. `search--full`. I've tried to use `is_search()` but while it works well on other pages, on search page both forms have `search--full` class. | You can pass custom args to get_search_form() when calling it:
get_search_form(array('test' => 'hello'))
Then in **searchform.php** it all will be available under $args variable
echo($args['test']); // Will print "hello"
Just be aware in your searchform.php file that this file is called everywhere get_search_form() is used so you most likely want to check that such key exists first
if(array_key_exists('test', $args)){
echo($args['test']);
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "search"
} |
Change conditionally a variable value for different feeds
I need to change conditionally a variable value for different feeds. I can't find a function for this. These are my custom feeds:
function my_custom_rss_init(){
add_feed('fc_md', 'my_custom_rss');
add_feed('fc_ro', 'my_custom_rss');
add_feed('fc_ua', 'my_custom_rss');
}
And I need something like this:
if( is_feed_name_fun( 'fc_md' ) ) $country = 'MD';
if( is_feed_name_fun( 'fc_ro' ) ) $country = 'RO';
if( is_feed_name_fun( 'fc_ua' ) ) $country = 'UA';
Is this possible? How can I accomplish it?
**UPDATE**
The last three code lines will be in a feed template. | The feed name will be stored in the query var `feed`-
$feed_name = get_query_var('feed');
if( 'fc_md' == $feed_name ) $country == 'MD'; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "feed"
} |
How does one insert a variable value into a "myCRED plugin shortcode
Example:
[mycred_exchange from="mycred_default" to="mycred_usd" min= "0.00001" rate="8127"]
In this instance I would like to link the exchange rate (`rate="8127"`) to the actual market value of Bitcoin.
I have gone through a few articles but just can't seem to get it to work. | You can create the shortcode as a string like this :
$rate = 2587.36;
$code = "[mycred_exchange from=\"mycred_default\" to=\"mycred_usd\" min=\"0.00001\" rate=\"$rate\"]";
and then, to execute the code
echo do_shortcode($code); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "shortcode"
} |
remove blank space where sidebar was
I have been working on a website using WordPress < there are some pages that I didn't want to have the sidebar on, so I made a template and removed get_sidebar
Now I have just a blank area where the sidebar was, which I want to remove and allow the main content div fill the space.
The pictures below show the empty space
With Sidebar
Without Sidebar
How can I fill the empty space where the sidebar was?
Thanks
Links to page.php and style.css are below < < | You may add this code to your custom CSS :
.page-template-pageWithOutSidebar .entry-header, .page-template-pageWithOutSidebar .entry-content {
padding-right: 0;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, css"
} |
Search in multiple specific post types
I want search in specific multiple custom post types. I using second code to determine post types:
function custom_search_filter($query) {
if ( !is_admin() && $query->is_main_query() ) {
if ($query->is_search) {
$query->set('post_type', array('post','product'));
}
}
}
add_action('pre_get_posts','custom_search_filter');
I can not search for woocommerce products, if in array post_type is more than only 'product' cpt. If is only 'product' then this post type is findable.
In my search.php file code is:
<?php if ( have_posts() ) : ?>
<?php
while ( have_posts() ) : the_post(); ?>
founded
<? endwhile;
endif;
?>
If in array('post','page'), all is working good too, posts and pages are findable. | I recently had a similar problem and it had something to do with the query's `posts_per_page` parameter. Try setting it explicitly, like so:
function custom_search_filter($query) {
if ( !is_admin() && $query->is_main_query() ) {
if ($query->is_search) {
$query->set('posts_per_page', 10 ); // Try setting it to the number you've set in the Wordpress admin (Settings > Reading).
$query->set('post_type', array('post','product'));
}
}
}
add_action('pre_get_posts','custom_search_filter');
Hope this helps! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, woocommerce offtopic, search"
} |
Move product attributes after summary on single product page
I must say i don't know coding or programming. I did copy paste this code, inside my functions and it is working perfect. The code shows all the woocommerce product attributes after the product description summary.
add_action ( 'woocommerce_product_meta_start', 'show_attributes', 25 );
function show_attributes() {
global $product;
$product->list_attributes();
}
But inside the debug_log this lines are appearing:
PHP Notice: WC_Product::list_attributes is deprecated since version 3.0! Use wc_display_product_attributes instead. in /home/public_html/domain.com/wp-includes/functions.php on line 3837
So i tried changing this line:
**$product->list_attributes();**
to this
**$product->wc_display_product_attributes();**
But it didn't work. It breaks all my frontpage with multiple lines of code errors.
So i am here for help. Thanks in advance! | The `list_attributes` is a method of `WC_Product` class called with `->` operator and the `wc_display_product_attributes` is a simple function.
This will fix the issue:
add_action ( 'woocommerce_product_meta_start', 'show_attributes', 25 );
function show_attributes() {
global $product;
wc_display_product_attributes( $product );
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions, woocommerce offtopic, debug"
} |
Get users that likes the post
I have an ajax like posts system when a user like a post the system added a post meta to the post and it's named (post_liked_users). Example of post_likes_users meta value: `a:1:{s:6:"user-1";i:1;}`
Now how can get the users that like the post?
Note: I can't use foreach only like Jack Johansson answer I must use WP_User_Query or WP_Query because I want to use offest and number. | It appears that you are storing the data in the post's meta, not user's meta. Therefore, you need to retrieve it by directly getting the meta for that post, not by doing a user query.
Let's say your post's ID is `$post_id`:
First, retrieve the meta by `get_post_meta()`:
$users = get_post_meta ( $post_id, 'post_liked_users', false );
I assumed that you are storing the data as multiple serialized ( based on your question ), so I set the last parameter of the above function to false, which will retrieve every meta, and we will try to extract the array:
if ( $users ) {
foreach ( $users as $user ) {
// $user[0] is the user-1 string here, and
// $user[1] is the integer ( their ID )
echo get_user_by( 'id', $user[1] )->display_name;
}
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "php, wp query, functions, users, wp user query"
} |
Use the_title_attribute() for the WHERE parameter in a page template
**Goal** : Create a page template that queries that database based on page title. This allows for "dynamic" pages based off of the title.
I've got the page template set up and working when I hard code the id, when I try and use the_title_attribute() it's not working. This is what I'm attempting.
$id = the_title_attribute();
$sql = "SELECT * FROM <databasename>.<tablename> WHERE name = '". $id."'";
$results = $wpdb->get_results($sql, OBJECT);
The issue with this is that the_title_attribtue() doesn't populate in time for my query because it's populating later for the page to be rendered. So I'm trying to figure out how to pull page title so I can use it in SQL select statements to generate content for my page.
Any help is appreciated. | Answer provided by @Howdy_McGee who commented on the question. Using the prepare statement allowed the results to be pulled at the correct time and using %s is for strings and %d would be for a decimal or number value.
$sql = $wpdb->prepare("SELECT * FROM <databaseName>.<tableName> WHERE name = '%s'", get_the_title());
$results = $wpdb->get_results($sql, OBJECT); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "page template"
} |
Can I clone WP to another directory on the same server?
I want to do some changes on WP for a friend but I don't want to do it live. So I was thinking of cloning the current WP to another directory on the same server and then do work on that version (www.myfriendswp.com -> www.myfriendswp.com/testing) and, when done, clone the changes back to main directory.
Is this possible or will there be some problems? Most tutorials and plugins are talking about cloning to a different server. | I would recommend to clone it on a subdomain. Something like "testing.myfriendswp.com". I have tried this approach and it works fine. If you have a cpanel, you will see an option to create a subdomain in it. create a subdomain and point it to a folder inside public_html. So, for example, your subdomain "testing.myfriendswp.com" will be pointed to a directory "public_html/testing". Once you have the subdomain created:
1. copy the WP files from the main domain to subdomain
2. create a new database and import tables from the main DB to it.
3. set appropriate DB credentials in wp-config.php file
4. change the domain name in the wp-options table in the new DB.
5. boot up WP on the subdomain and refresh the permalink settings.
6. Run a search replace script on DB to replace main domain to the subdomain.
For extra security, add a robots.txt file on your subdomain to prevent the instance from being crawled by Search Engine Robots.
Thanks | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "installation, clone site"
} |
Getting rid of role="navigation" in the Home Page Pagination
For the Pagination on the front page ort the Homepage I am using this one →
<?php the_posts_pagination( array( 'mid_size' => 2 ) ); ?>
Codex Reference #1
Codex Reference #2
In the actual Browser, it generated a div like this →
<nav class="navigation pagination" role="navigation">
W3C Validation is throwing this error →
> Warning: The navigation role is unnecessary for element nav.
>
> From line 301, column 2; to line 301, column 54 `↩ <nav class="navigation pagination" role="navigation">↩ <h2`
**Question →**
Is there a method to get rid of this →
role="navigation" | `navigation` is the default value for `role` attribute in `nav` elements. So, if the browser/technology understands HTML5 and is fully standard compliant, then it is unnecessary, but what if not? I don't get the advantage of removing it; it just make sure that any technology reading the document knows what the element is used for.
Anyway, if you want to remove it, you can filter the navigation markup template:
add_filter( 'navigation_markup_template', 'cyb_navigation_template' );
function cyb_navigation_template( $template ) {
$template = '
<nav class="navigation %1$s">
<h2 class="screen-reader-text">%2$s</h2>
<div class="nav-links">%3$s</div>
</nav>';
return $template;
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "php, functions, pagination"
} |
Displaying POST content with HTML tags and all
The following code allows me to display the post TITLE and content fine, but the content is not displaying as I see it on POST EDITOR.
Here's the webpage where the PHP is rendered: <
Here's the PHP code:
<?php
$post_id = 2292; // Define the ID of the page
$queriedPost = get_post($post_id); // Load contents of the page
$field_contents = get_post_meta($queriedPost->ID, $field_slug, true); // Load the contents of the custom field
$post_object = get_post( $post_id );
echo '<h3>' . $queriedPost->post_title . '</h3>';
echo $post_object->post_content;
?>
And here's the post itself: <
So, how can I use this PHP code with the style that my end-users use? I can't have them edit the code and include
tags, for example. Well... I _could_ , but then again......
Thanks so much! | First, be sure that you text, in the editor, don't have any code from where you are copying it. Use the HTML tab to check that. In the link you provided, the text has paragraph, with span inside, with more span inside that span. Is kinda weird.
Beside that, you have to use CSS to style every detail of the text, like to 'foresee' what the user will use. Create style for paragraph, headers, span, bold, italic, whatever you need. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, posts, functions, get posts, css"
} |
Add Password Generator on password protected page
I'm looking for add a password generator with 14 characters on the protected pages like in the picture. I search something like what is used when you create users but for page password.
 when you click the _Password protected_ radio button.
$('#visibility-radio-password').click(function () {
// If there is no password
var $password = $('#post_password')
if ( !$password.val() ) {
$password.val(Math.random().toString(36).slice(2));
}
});
Here you can learn how to correctly add JS scripts to admin pages - < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugin development, pages, password, publish, core modifications"
} |
Adding padding above menu
I am not sure why but after I done some editing the menu now has no space from the type of the page. How do I create this ?
< | This forum is specific to WordPress internal workaround and your question is regarding element styling which does not belong here. Please try to use specific sites according to your question.
For your problem, add the following lines in your theme's stylesheet and it should be fixed.
#masthead #cms-header.header-ontop {
padding-top:15px;
}
#masthead #cms-header.header-sticky {
padding-top:0;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -3,
"tags": "menus, css, formatting"
} |
WordPress Logout Only If User Click Logout or If User Delete Browser History
This is the main requirements of my project.
After a user login, logout should be done only if user click logout button or if user delete browser history.
When browser closing, then machine restarting, changing IP address **should NOT logout the User**.
Is this possible with WordPress? Is there any filter, action hook? | You can use the `auth_cookie_expiration` filter to change the expiration time of the cookie WordPress sets to remember you. The user won't be logged out unless they change browser or clear their cookies (normally part of clearing history).
The problem is that you can't set a cookie to never expire, so you have to set a date in the far future. The furthest you can go is 19th January 2038, because of the Year 2038 problem.
The value of the `auth_cookie_expiration` filter is added to `time()` so if you want to set the longest possible time for the cookie, you need to get the maximum value (`2147483647` according to this) and subtract `time()`:
function wpse_287104_cookie_expiration( $length ) {
return time() - 2147483647;
}
add_filter( 'auth_cookie_expiration', 'wpse_287104_cookie_expiration' ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "security"
} |
Display tags for current post in sidebar
I'm looking for a way to list all the tags associated with the current post as a bulleted list in the sidebar, ideally with a CSS class for custom styling. All the plugins and code snippets I've found either display all tags site-wide, or display it as a tag cloud. My hunch is that it would involve calling `get_the_tag_list` outside of the loop somehow, but I'm a complete novice to WordPress development and am not sure how to get that working without guidance.
Any help would be greatly appreciated!
Thanks so much in advance,
Julian | You can use `get_the_tag_list()`, you just need to set the 4th argument, `$id` to `get_queried_object_id()` which gets the ID of the main queried post/page outside of the loop. You'll want to check `is_singlar()` too though, in case the queried object is a tag/category with the same ID as a post:
<?php
if ( is_singular() ) :
echo get_the_tag_list(
'<ul class="my-tags-list"><li>',
'</li><li>',
'</li></ul>',
get_queried_object_id()
);
endif;
?>
The first 3 arguments are the HTML before the list, separating each list item, and after the list. The configuration I have there wraps the whole thing in an unordered list and all items in list item tags. The list has the class `my-tags-list` that can be used for styling. You can change that to whatever you want. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "tags, sidebar"
} |
WooCommerce product prices not showing up correctly
For my website I simply wanted to display products with prices below. This was all working fine until I opened up the website yesterday and every price on the website was set to **0,00$** , instead of it's regular **$9,95**.
Does or did anyone have the same problem? Please help :) | Did you install any new plugin? If so, try to deactivate that plugin first.
What version of WooCommerce are you using? If you are using an outdated one, try updating it to the latest version.
Can you try to add a dummy product and add a price on it? If the price still did not display try to deactivate and reactivate the woocommerce plugin. | stackexchange-wordpress | {
"answer_score": -1,
"question_score": -1,
"tags": "plugins, woocommerce offtopic, e commerce"
} |
How to make a sticky footer?
The footer does not stay on the bottom.
footer {
padding:2em;
bottom:0;
clear:both;
background-color:black;
color:white;
position:absolute;
}
does not work and neither does `postion:relative;`.. What do I do? | I think I figured out the answer. In your footer.php file add a div like that goes outside the footer and assign your footer class to it. For example,
`<div class="sticky-footer"> <footer id="colophon" class="site-footer"> <div class="site-info"> <?php /* translators: 1: Theme name, 2: Theme author. */ printf( esc_html__( 'Theme: %1$s by %2$s.', 'best' ), 'best', '<a href=" ); ?> </div><!-- .site-info --> </footer><!-- #colophon --> </div><!-- #page --> </div>`
And the correct style is :
.sticky-footer {
padding:2em;
bottom:0;
clear:both;
background-color:black;
color:white;
position:static;
width:100%;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -2,
"tags": "theme development"
} |
WP_Query - Exclude Posts
we have a custom WP_QUERY with these args: <
$args = [
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => $post_number + 1,
'paged' => ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1,
'tax_query' => [
[
'taxonomy' => $taxonomy,
'field' => 'term_id',
'terms' => $category_id,
'include_children' => false
],
],
];
We'd like to exclude those post which are also assigned to a child category.
I mean, we have some terms:
\-- Parent 1
\-- Parent 2
\------ Child 1
\-- Parent 3
We'd like to get posts in Parent 2 but **not** those are also assigned to Child 1.
Is it possible? Have you got any suggests?
Thanks | You'll need a second tax query for posts not in the child categories of the given category. To do that you'll need to get the IDs of the children. This is possible with `get_term_children()`:
$args = [
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => $post_number + 1,
'paged' => ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1,
'tax_query' => [
[
'taxonomy' => $taxonomy,
'field' => 'term_id',
'terms' => $category_id,
'include_children' => false
],
[
'taxonomy' => $taxonomy,
'field' => 'term_id',
'terms' => get_term_children( $category_id, $taxonomy ),
'operator' => 'NOT IN'
],
],
]; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "wp query"
} |
Why deleting/removing cookies in WordPress does not log me out from admin?
I am really curious and I haven't found satisfactory answer in similar questions.
When deleting all of my cookies, I am still perfectly able to access my admin dashboard - why am I not returned back to login page and required to authenticate again? Why is it different in WordPress than in most other CMSs that deleting cookies still keeps my admin session valid somehow? Can someone explain to me in more details how and why this works this way?
To add additional explanation, when I clear cookies, top user/admin bar is no longer there (this is expected). However, if I directly access some wp-admin page (via bookmark, for example), then the bar is back and I can do anything I normally do as logged-in admin user.
Thank you | Well, for those who are curious, and to the best of my knowledge/investigation: it turns out this was a strange bug/issue of Chrome Portable* version 47* I was using on my older laptop. It does not happen in other browsers and regular Chrome installation.
* (with Windows XP, because of EOL support) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "login, cookies, logout"
} |
media_sideload_image results in http error (500)
I want to import a external image with media_sideload_image, but I get the HTTP-Code 500.
What is wrong with my code?
function test() {
media_sideload_image(" 1261, null, "id");
}
add_action("init", "test");
I want to import a external Image and generate the image sizes | The `media_sideload_image()` function is only available in the admin by default, and `init` runs on all page loads.
See the Codex article:
> If you want to use this function outside of the context of /wp-admin/ (typically if you are writing a more advanced custom importer script) you need to include media.php and depending includes:
>
>
> require_once(ABSPATH . 'wp-admin/includes/media.php');
> require_once(ABSPATH . 'wp-admin/includes/file.php');
> require_once(ABSPATH . 'wp-admin/includes/image.php');
> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "uploads, media"
} |
Disable the "Skip to Toolbar" tabbing accessibility feature
Is there a WordPress setting or hook that I can use to disable the WordPress "Skip to Toolbar" accessibility feature?
I'm referring to the small popup that appears when tabbing through form controls:
, preferably without having to change the `tabindex` for any/all of the form elements on my page. | It's not possible without JavaScript. The HTML for it is output in the `WP_Admin_Bar` in a private and protected method with no filter.
You can remove them after the page has loaded with JS like so:
function wpse_287259_remove_skip_link() {
echo "<script>jQuery( '.screen-reader-shortcut' ).remove();</script>";
}
add_action( 'wp_after_admin_bar_render', 'wpse_287259_remove_skip_link' );
I hope it goes without saying that this is something you should do just for yourself and not do for unsuspecting users who might need or want the accessibility benefits. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "admin, forms, admin bar, tabs"
} |
Twenty Fourteen: Shrinking header while scrolling down
I am using the Twenty Fourteen theme. Normally the header has a heigth of 48 px. I made the logo bigger with the following code:
.header-main {
min-height: 108px;
}
That works well so far. Now I would like to shrink the header while scrolling down, in such way that the the header will get a height of 48 px and be fixed. The logo within the header should be replaced by a smaller logo that fits to 48 px height.
Unfortunately I have insufficient experience to implement this function. Can someone help me please ? | Ok, Pradhana. This is going to be around about solution to your question, but the first thing that I believe that you would need to do is create a child theme. Go over to WordPress.org and do a little studying on how to create a child theme.
Then you'll have to add a javascript file that is referenced from the functions.php file in the child theme. Once you get to this point, then you can start experimenting with Jquery to adjust the height of your logo. I would do a specific search on using Jquery to adjust the height of your logo.
I just googled "jquery to resize header logo on scroll down." and got a nice list of options. Those jquery solutions is would go in the Javascript file that you add to your child theme. This should get you off into the right direction. Good luck! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "css, headers, logo, theme twenty fourteen"
} |
Create a custom search for Estate Agency Wordpress site
I'm currently working on an Estate Agency website. Built the custom post type and some custom taxonomies.
I need to build a custom search where a user can select options from the custom taxonomies to display the search results.
Example: Search by location & min-max price & number of bedrooms.
I tried a couple of plugins for Real Estate but they don't allow me enough control over the display of the output in the frontend of the website, therefore I need to build my own "simple" custom search.
Can anybody point me in the direction of a tutorial, or how to do this. I don't want to use a plugin as I can't find one that isn't overkill or gives me enough space to output what I need.
Hoping somebody can help
Thanks in advance
Dan | I ended up using the Search and Filter plugin. My PHP isn't strong enough to build such a thing, when I was pushed for a deadline by the client. In the end, I had to use the plugin which works great, rather than trying to build my own.
Thanks for the help though guys, really appreciate it! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "customization, search"
} |
Storing data to database and user registration
The project that I'm working with have a quote form. When someone submit the quote request, the information should be stored into a new table in the database and also prompt the user to register an account (Register as a WordPress subscriber) in that website. When they register, the user Id must be passed into the lead information table such as user id so that we can track the leads per user.
Here is what I completed. All the lead info are stored into the database. Then prompt the user to register and it works fine as well. The only thing which I'm not sure how to do is - collecting the user id after user registration and storing it into the corresponding row in the lead info table.
Any suggestions? | Look like you need used hook user_register
it's return to you user id, after that you can save it in DB. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "user meta, user registration, users"
} |
Am I able to change the name of /wp-admin/options-general.php?
I'm asking this question because I am coding a Wordpress plugin, and I want to be able to detect when WP-Admin is using options-general.php. Currently, I'm just checking the URL directly to see if it ends with options-general.php, but if Wordpress allows installations to change the filenames of this file, then my plugin may not work on certain installations. | No, you can't, though I would rely on the Screen object, not the URL
< | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wp admin, backbone"
} |
Load page in customizer preview on panel click?
I'm trying to extend customizer with some functionality but documentation is lacking for cases that are non-control related.
E.g. I’d like to load some url in preview after clicking the panel.
My two issues are:
1. I can’t attach events to panels and fields because regular click and change don’t work because panels seem to be loaded not immediately.
2. How would one then send a custom message to preview section? | I've documented how to do this in my post Navigating to a URL in the Customizer Preview when a Section is Expanded, though naturally you'd just use panels instead of sections.
This should get you what you want:
(function ( api ) {
api.panel( 'my_panel_id', function( panel ) {
panel.expanded.bind( function( isExpanded ) {
if ( isExpanded ) {
api.previewer.previewUrl.set( panelPreviewUrl );
}
} );
} );
} ( wp.customize ) );
You'd replace the `panelPreviewUrl` variable with whatever you want to navigate the preview to. And then you'd replace `'my_panel_id'` with whatever the ID is for your panel. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "javascript, theme customizer"
} |
How to find out what "Blog pages show at most" is set to
Under **Settings** > **Reading** , there is a field called **Blog pages show at most __ posts**. Since all of my queries are based off of the main query, I need to find out what's stored in that field. How would I do that, especially outside of the loop? | You can get that value with
get_option('posts_per_page'); | stackexchange-wordpress | {
"answer_score": 11,
"question_score": 3,
"tags": "wp query, query posts, get posts"
} |
disable wp admin bar for customers logged in
I have a wordpress website, where i am providing customers with user name and password to access my shop.
When a customer logs in, he can see the top wordpress admin bar as well. I dont want users added as "customers" through users>add new to see that bar.
How should i disable this? | If you look at user profile in WordPress administration you would see that there is an option: **Show Toolbar when viewing site**. If you uncheck this option user will not see an admin bar.
This option is checked by default when user is registering to your store. You can disable it using `user_register` filter.
function wpse_278096_disable_admin_bar( $user_id ) {
update_user_meta($user_id, 'show_admin_bar_front', false);
}
add_action( 'user_register', 'wpse_278096_disable_admin_bar', 10, 1 ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "admin bar"
} |
Which action fire in front-end single post only
I need to add an action in the following situation : When it load a single page post in the frontend, before anything is displayed. I looked the 'the_post' action, but it's triggered at several areas, including admin.
There are probably a lot of way to do this, but I'm fairly new in wordpress developpment, and can't find the answer. | You can use `the_content` filter if you need to modify the content:
add_filter( 'the_content', 'cyb_content_filter_callback' );
function cyb_content_filter_callback( $content ) {
// Only for singular post views and for posts of main loop
if( is_singular( 'post' ) && in_the_loop() ) {
// modify $content here
}
return $content;
}
If you need an action that runs before the post is displayed, maybe `loop_start` is what you are looking for (not sure without knowing what exactly you need to do, but this action is the one that fires just before the post data is setup when the loop starts):
add_action( 'loop_start', 'cyb_loop_start_action_callback' );
function cyb_loop_start_action_callback( $wp_query ) {
// Only for singular post views and for posts of main loop
if( is_singular( 'post' ) && in_the_loop() ) {
// do something
}
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "actions, single"
} |
Using ACF to display data on all pages
I have installed Advanced Custom Fielts, and I have created custom fields such as email, phone etc. I put those in my footer.php, and the data is displayed only on the homepage. Can I use ACF to create global variables? My rule for that custom field is `'If Post Type is equal to post';`
I get that data in footer.php like this
$phone_number = get_field('phone_number');
and Im displaying it like
<?php echo $phone_number; ?>
So basically when Im on my homepage, it is displayed correctly, when I go to other page(which has that same footer), data is not displayed. What can I do to display it on all pages? | You Need to use ACF Options Page plugin as well.
_**This Plugin has been deleted from the repository. Now you can use the function without the plugin.**_
The options page feature provides a set of functions to add extra admin pages and all data saved on an options page is **global**.
Sea the plugin overview
After installing plugin you have to add the following to your `functions.php`
if( function_exists('acf_add_options_page') ) {
acf_add_options_page();
}
and the " _Options_ " label will be visible in your admin area.
then you just need to create acf fields with the rule like `'If Options Page is equal to Options'`
Finally to display the field:
echo get_field('phone_number', 'option'); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "plugins, advanced custom fields"
} |
The cart, checkout, and shop links not getting removed
I uninstalled woocommerce plugin but yet the shop, checkout and cart links in navigation bar is persistent. The theme I'm using is Compass. But whatever theme I choose those three links do not vanish. I want to create a simple blogging website for myself. Any suggestion is welcomed. | Oops, my bad. I'm new to wordpress so I did not know that the pages created my plugins persists even when they are uninstalled. I had to delete cart, shop, and checkout from pages. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "menus, woocommerce offtopic, navigation, links"
} |
Child Theme not working - CSS gone
I'm using the Twentyeleven theme for my new site. I created a child-theme so I can modify the theme and not have my changes overwritten. But once I activate my child-theme the whole styling is gone. I guess the issue lies in the functions.php. Maybe I did something wrong. Can anyone point me in the right direction?
This is my functions.php in my child-theme:
<?php
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function theme_enqueue_styles() {
wp_enqueue_style( 'parent-style', get_stylesheet_directory_uri() . '/style.css' );
} | You will want to use `get_template_directory_uri()` to load files from the parent theme. `get_stylesheet_directory_uri()` is for the current theme, which is your child theme. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "functions, child theme"
} |
Wordpress ajax-action failing because of newline in response
When I'm using the dashboard, for example, adding a category. The request returns valid XML as expected, but it is prepended with a newline character, causing the `DOMParser()` to fail.
I'm not sure where to proceed for debugging, it happens on one site and not another (different server, different theme). I've checked, none of the theme's php files have any characters proceeding `<?php` and none end with `?>`
Any suggestions? | Found a plugin ending with ?> with a newline after it | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php, ajax, wp admin, xml"
} |
How the redirect_to parameter is added to wp_login.php when trying to access wp-admin?
I have noticed that a `redirect_to` parameter is added to `wp-login.php` URL when trying to access `wp-admin`, so from where does it come? I have tried to search into the wp-admin folder but lost. | Redirect parameter is created at `auth_redirect` function:
<
and it is added at `wp_login_url` function:
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development"
} |
Can I have a Wordpress site stored on a subdomain of another website owned by me?
I have a website developed by a different program (wix) and I own the web domain to the site. Can I store my Wordpress site on a subdomain of that site? For example my site is website.com - and I want my wordpress site to be located in mysite.website.com . | Is it possible? Absolutely; the how depends on your setup though. It will be slightly different depending on where the site is installed (VPS, shared host, ect.) Without more information I can't give you anymore than just the general steps that need to be taken. That said here they are.
Generally the steps are:
1) Install WordPress on your host.
2) Go to your DNS settings on your domain registrars dashboard and add an A record with the hostname set to the subdomain & address/value set to the IP address of the server WP is installed on. This tells clients which IP address to go to when they look up the domain name.
3) Configure your server software (Apache, Nginx, ect..) to serve up the site whenever mysite.website.com is requested.
You don't have to have the subdomain on the same server as you're main site. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "subdomains"
} |
Changing permalink structure for Posts
I'm just a beginner with wordpress and I wanted to know, if I can change the permalink structure for my posts (I already have about 10 or more Posts) from
**< => < without losing the redirects to my 'old' posts. Thank you in advance, really appreciate it. | You can change your permalink structure from settings->permalinks option in wp-admin.
Please check below screenshot.
?
I am creating custom tables from a plugin. Foreign keys are required. To be safe, I'm want turn off `foreign_keys_check` before issuing `maybe_create_table()`.
This codes is what I have to check variable's initial status, make the change and, and show the result:
echo $wpdb->query( "SHOW VARIABLES LIKE '%foreign%'" );
$wpdb->query( 'SET foreign_key_checks=0' );
echo $wpdb->query( "SHOW VARIABLES LIKE '%foreign%'" );
I expected the output to be `10` reflecting that the `SET` succeeded. Instead, I get `11` indicating the `foreign_key_checks` variable remains `true`.
What is the proper way to programmatically set a MySQL variable from inside WordPress? | `$wpdb->query()` doesn't return the data but the rows affected, use `$wpdb->get_var()`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, mysql, variables"
} |
Fetching latest posts from 2 different WP installations
I have three WordPress installations (cannot use multisite; cannot use RSS/Atom feeds) and I am trying to display a date-sorted list of the latest 10 posts from each of the two sub-sites on the main site home page. The site is organized thus:
<
<
<
These are three separate installations of WordPress, however sharing the same database (with different db prefixes, of course).
I have tried creating a loop calling the wp-load.php function, but I cannot seem to get it to reset; instead, the second iteration simply re-displays the posts from the first loop (in this case, from ./editorials/wp-load.php).
I have tried to place all the posts in separate arrays, for later combining and sorting by date, i.e., $content1 and $content2, but I haven't gotten that far since I cannot fetch posts from the second instance.
Here is code:
<
Thanks in advance! -Brian | I'd use the REST API to get the latest 10 posts from each install, then combine the two arrays, sort them by the date, and then only use the latest 10 results.
$editorials = wp_remote_get( ' );
$news = wp_remote_get( ' );
$editorials = json_decode( $editorials[ 'body' ] );
$news = json_decode( $news[ 'body' ] );
$all = array_merge( $editorials, $news );
//* The spaceship operator requires PHP > 7.0
usort( $all, function( $a, $b ) { return $a->date <=> $b->date; } );
$all = array_slice( $all, 0, 10 );
//* Do something useful with the combined array of posts | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp load.php"
} |
WPCLI search and replace in a particlar site dir effect another site-dir
In /var/www/html I have a site dir. I've duplicated that site's dir and db into a new site dir and db by the name of "test" (without quote marks), and changed `wp-config.php` accordingly.
I Navigated into this new site dir in console (`cd /var/www/html/test`), and ran:
wp search-replace ' '
The site itself goes up and its internal links become based on `test`, but 2 problems occur:
1. All css is jumbeled up.
2. The original site's CSS is also jumbeled up (this is quite wired, I must say).
While I can reverse the result, I admit I don't understand what's going on (because I do everything in the new dir and not in the original dir).
## Update
I was wrong, the db wasn't changed to `test` in `wp-config.php`... It seems my sed operation failed:
sed -i 's/${domain}/test'/g /var/www/html/test/wp-config.php | The problem was due to some conflict between variable values (I don't recall the exact details).
The solution AFAIR, was to just use another Bash session, without any predefined variables (I just newly defined any variable I needed this time):
$ bash | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "database, mysql, wp cli, backup, customization"
} |
WPCLI doesn't recognize the site
When navigating into a certain site dir in `/var/www/html/mysite`, I get the following WPCLI error:
> Error: The site you have requested is not installed.
But the site is basically working and surfable... So what may cause WPCLI to miss the fact it's there?...
WPCLI doesn't miss other sites, so it's a bit wired. | There is only one function in wp-cli which will return this error and it is `wp_not_installed`
wp_not_installed definition.
as you see function is checking if your site is installed by calling function from WordPress core `is_blog_installed`.
is_blog_installed definition.
It is hard to tell what is happening exactly with your site but I would try to debug this two functions. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp cli"
} |
How to allow .bin files upload?
How can I allow .bin files upload in media library?
I have found couple codes online but none of them actually work. | This code would allow you to upload `.bin` files.
/**
* Allow upload bin mime type
*/
add_filter( 'upload_mimes', 'wpse_287673_allow_upload_bin_mime_type', 1, 1 );
function wpse_287673_allow_upload_bin_mime_type( $mime_types ) {
$mime_types['bin'] = 'application/octet-stream';
return $mime_types;
}
This code is tested and is working for me, but it might be some differences for you since we are allowing files to be uploaded by extension and mime type and mime type of your file is defined by webserver. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "uploads, media library, customization"
} |
Why is my menu not ordered properly?
I am using the Avant theme, but I don't know if this is a fault of the theme or of WP. My main menu looks like below in the WP designer, with `Home` the first menu item.
)) {
// code
}
But once I use a template for the page this does not work anymore. Where I need to check the id, so I can display local nav?
It is not convenient to do it in the templates because the website has too many pages. | You can also check if you are on page template with is_page_template function:
if(is_page(array(18,52,22,20)) || is_page_template( 'blog.php' )) {
//do your stuff
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "functions, pages, templates"
} |
get_children() not working properly – Only on one post?
Client wants to show how many images await the reader in a post. I say: easy peazy. Now I realize: I lied.
The system only uses galleries, even for single pictures.
$images = get_children(array(
"post_parent" => $post->ID, // $post->ID gives the right ID.
"post_status" => "any",
"post_type" => "attachment",
"post_mime_type" => "image"
));
count($images); // only post with id 12 shows correctly 14 entries
In one post (ID 12, an eaaarly test entry) `$images` is filled with the correct amount of entries. In every other post I tested `$images` is wrongfully empty.
I even copied the exact same text (from the "Text"-Tab of TinyMCE, not "Visual") to post with ID 298. Still empty `$images`. Same custom fields. Both have a thumbnail (even if I delete it, no change) – Same taxonomy-settings.. | The `get_children` function retrieves posts (an upoaded image is also a post) that are dependent on the post with a certain ID. An image becomes a child of a post when it is uploaded while editing that post. It does not become a child of a post when it is reused.
So if you are writing post A and upload image B, B will become a child of A. If you then write post C and include image B in a gallery, B will not become a child of C. If you use `get_children` on C, you will find nothing.
What you are looking for is `get_post_galleries`. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "images, get posts, children, get children"
} |
Display custom field value into content with hyperlink
The following code helped me to display the "Custom Field" value in the `the_content` section.
But I need a help to make it to show as a hyperlink.
Here is the code:
function wpa_content_filter( $content ) {
global $post;
if( $meta = get_post_meta( $post->ID, 'demo_link', true ) ) {
return $content . $meta;
}
return $content;
}
add_filter( 'the_content', 'wpa_content_filter', 10 );
For example:
If I give the following custom field value:
demo_link =
The code result would be like
But I need the link to be clickable.
Can anyone please help on this?
Thanks. | I think this is what you're looking for...
function wpa_content_filter( $content ) {
global $post;
if( $meta = get_post_meta( $post->ID, 'demo_link', true ) ) {
return $content.' <a href="'.$meta.'">'.$meta.'</a>';
}
return $content;
}
add_filter( 'the_content', 'wpa_content_filter', 10 ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -1,
"tags": "custom field, metabox"
} |
User / membership Plugin
I would like to know if there is any plugin that can do the following:
1) Every registered user will have a personal agent assigned. The user can contact via messages only with the assigned agent.
2) Every agent (there will be 4-5 agents in total) can see only the users assigned to him by the administrator.
3) The administrator can see all the users (including the agents).
Thank you. | I don't know a plugin like this. But, my personal solution for this project would be like this :
* create a custom post type for agents
* create users role for agents (and users if you want)
* attach a custom field to users to store the assigned agent (maybe with Advanced custom fields plugin)
Create a page to show the chat or whatever. You need to add some specific code to query the data from custom post types from database.
Something like this.
Do you need more infos? | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, users, user roles, user registration, membership"
} |
WooCommerce order created via REST - sending the date_created along
So as the topic hints, I'm trying to get WooCommerce to accept my `date_created` that I'm sending along with the order I'm creating via REST:
POST
{
(order_fields)
...
"date_created": "05-12-2017 13:00:00"
}
The field is readonly sadly, so does anyone know if this is possible?
The reason I need this, is the orders are created in an external system, and the dates need to be the same across both systems. | `date_created` is `read-only` value meaning that you cannot set it over the REST API. What you can do is:
1. Send creation time from your "external system" as `order meta data` (sample PHP code below) and then in WooCommerce trigger the action using custom plug-in which updates order `date_created` according to a meta value.
>
> $json_encode['meta_data'][0]['key'] = 'my_date_created';
> $json_encode['meta_data'][0]['value'] = '05-12-2017 13:00:00';
>
2. Update `date_created` in your "external system" with `date_created` from jSon returned by Woocommerce in order to have values synchronised.
If you just want to pair order records do it over `order ID` returned in jSon by Woocommerce (Woocommerce returns a jSon when the order was created successfully). You will add `order ID` record to your "external system". | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "woocommerce offtopic"
} |
How the Css File is Linked without calling it in header.php?
everytime I analyze free wordpress.org theme, I am not able to find how the css file is linked in the theme. as far as i learned css file should be linked in `header.php` using link tag. but everytime I check themes I didn't see any code in which they link their css through link tag. check example of this theme `header.php` < my question is how they are linking their file, if its not showing in `header.php`? | The correct way to register styles in `Wordpress` is to enque them through `wp_enqueue_style` function in your theme's `functions.php`. You can read and learn how to do it here - wp_enqueue_style
/**
* Proper way to enqueue scripts and styles
*/
function wpdocs_theme_name_scripts() {
wp_enqueue_style( 'style-name', get_stylesheet_uri() );
wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/example.js', array(), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "css, wp enqueue style"
} |
How to display post_content from database in different <p> on template page?
I am storing some long unstyled text post_content, where title is XXX. I am selecting this content:
<?php global $wpdb;
$findContent = $wpdb->get_var("SELECT post_content FROM wp_posts WHERE
post_title = 'XXXX'");
echo $findContent;
?>
It is a requirement that f$indContent is not styles into the database, so I need to put it into paragraphs. How can I do that? | You can simply run it through the_content filter:
$filteredContent = apply_filters('the_content', $findContent);
echo $filteredContent; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, database, css, get posts"
} |
WordPress wp-admin login problem
I want to log into wp admin, but I am getting an unfamiliar login form. Is it normal? Image below.; ?>
I need to replace "[email protected]" with the value of the ACF field `email`.
How can I do it? | You can use php values inside the do_shortcode function In your case it will be like this:
<?php echo do_shortcode( '[contact-form-7 id="983" title="Formulaire de contact 1" destination-email="'.get_field( 'email' ).'"]' ); ?> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "advanced custom fields, plugin contact form 7"
} |
What permissions does wp-content/uploads need?
What is the default wp-content/uploads directory permission? What chmod command do I need to set it correctly? | You'll want directories to have 755 and files to have 644. you can navigate to your www directory and use these 2 commands:
find . -type d -print0 | xargs -0 chmod 0755 # For directories
or
find . -type f -print0 | xargs -0 chmod 0644 # For files
(Obviously don't input the # or anything after it when using the above 2 commands) | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 4,
"tags": "uploads, security, permissions"
} |
Yearly archive page for future year
There are some posts dated on future year. I would like to show them. What have I done so far:
add_filter( 'getarchives_where', 'displayFuturePosts', 10, 2 );
function displayFuturePosts( $text, $r ) {
return "WHERE post_status = 'future' OR post_status = 'publish'";
}
wp_get_archives(array( 'type'=>'yearly' ));
This show three links: 2016 2017 2018
First two opens and shows all the posts, but 2018 redirects to 404. | You need to add future posts to the query.
function add_future_posts($query) {
$query->set('post_status', array('publish', 'future'));
}
add_action('pre_get_posts', 'add_future_posts', 10, 1); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "posts, wp query, archives"
} |
Should I have a single cron job that loops the users, or one for each user?
I'm working on a website which only registered users can access, and they are manually added to the site, since there is no registration enabled. Think of it as a private shop. The number of users is below 1000.
Each of the users can set a couple of events, such as birthday. They usually add less than 10.
I want to inform the user by email about their events, when there is a couple of days remaining to reach that event.
Now the question is, is it performance-wise better to run a single cron job every day at 00:00 and loop through all users and check their events ( stored as metadata ), or should I set a yearly cron job for each event of each user ( which ends up in having a thousand of cron jobs )? | Run a single cron, it's much more manageable and more stable, and performance shouldn't be an issue since you do 99% of the work of selecting which user should be notified in MySQL, which will be extremely fast.
I'd use a table to save each day (and each user on that day) that my cron has successfully run for, to make it more resilient. Plan for failure, not for success, because it **will** fail at some point, and the importance is how bad that failure will be and how much time it will take you to fix the fallout.
Server crashes right before midnight and is rebooted at 00:05? No problem, just run the job manually, or wait till the next day, it'll run two days in one run!
Server crashes while executing the cron? No worries, the next time it runs, it'll pick up right where it stopped last time. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "user meta, wp cron"
} |
Custom permalink with pagination
I have a custom post type called **news** and in order to distinguish _current_ and _old_ news posts I have a custom field where the client can mark a news post as ' _archived_ '.
So my permalink rewrite code looks like this:
function custom_rewrite_rule() {
add_rewrite_rule('^news/archive/?','index.php?post_type=news&news_archive=true','top');
add_rewrite_rule('^news/archive/page/([0-9]+)?/?$','index.php?post_type=news&news_archive=true&paged=$matches[1]','top');
}
add_action('init', 'custom_rewrite_rule', 10, 0);
function add_query_vars_filter( $vars ){
$vars[] = "news_archive";
return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );
The first bit works but the problem is with the pagination. I can access the **_news_archive_** query_var but not the **_paged_** query_var.
What is the correct way to incorporate paged into this permalink rewrite? | The problem is that your first rule is capturing anything that begins with `news/archive/`.
Add the `$` anchor to match _only_ `news/archive/`:
add_rewrite_rule(
'^news/archive/?$',
'index.php?post_type=news&news_archive=true',
'top'
);
Your pagination rule will then begin to work as-is after you flush permalinks. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "custom post types, wp query, permalinks, pagination, query variable"
} |
What is the way to hook all wordpress email
I have a wordpress site that have plugins: Contact form 7, WP Mail SMTP Plugin by Mail Bank, Spartpost...All of these plugins are able to send out email by anyway (wp_mail, smtp, http api)...
I am developing another plugin that will do my custom action on each sent out email by any plugin.
Currently, I can do the custom action on contact form 7 email with:
add_action('wpcf7_before_send_mail', 'my_custom_action', 10, 1);
My question: is there any hook, filter or something that is general to wordpress email? Instead of use action/filter of every plugins?
Thank you. | Every WordPress email usually uses `wp_mail()`. Which is actually a wrapper of PHPMailer. Find out this `wp_mail()` functions documentation and source code, you'll find some hooks there which will be useful to you cases.
> But keep it in mind that, those hooks will be applicable only if the mail is sent by using `wp_mail()`. If any email is send by any other function like the _PHP_ native `mail()` function then the hooks may not work. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, email, smtp"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.