INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Auto crop images in Wordpress
Im brand new to coding in wordpress, usually I use ModX. In ModX there is a plugin called phpthumb which automatically crops images to a specified h and w. How can I achieve this in Wordpress?
Image Code:
<?php
$thumbnail_id = get_post_thumbnail_id($post->ID);
$thumbnail = wp_get_attachment_image_src($thumbnail_id,'featured works');
echo '<div data-src="'.$thumbnail[0].'" alt="[[+name]]"></div>';
?>
Thanks for any insight. | You can use `add_image_size` to create your custom size like this:
add_image_size( 'featured-works', 220, 180, true );
then get it like this:
wp_get_attachment_image_src($thumbnail_id,'featured-works');
take into account how the crop works here | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "php, images"
} |
Eliminate render-blocking JavaScript and CSS in above-the-fold content
I am optimizing speed of my website and fixed all issues except "Eliminate render-blocking JavaScript and CSS in above-the-fold content".I have gone throgh many solutions but not resolved till now.
 and most websites do not defer the CSS because it makes the site render not as nicely and as long as you aren't loading JS from 3rd party API's it won't make much difference anyway (themes should be loading scrips from WP core or the theme so usually it's fine).
Of course if you really want to there are plugins for that or you can use custom code. Here is a good tutorial - < \- just be careful because some themes and plugins purposely add JS to the header because it's needed early on. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "css, javascript, content"
} |
Child theme style repeated
I have create child theme with style.css and functions.css, I edit parts style.css in child theme to get best style. But some page have no effect and style.css from child theme repeated with another version.
style.css
#masthead {
top: 0px;
background: black !important;
border-top: 2px solid rgba(250,105, 0, 1);
border-bottom: 2px solid rgba(250,105,0, 1);
}
functions.php
<?php
function my_theme_enqueue_styles() {
$parent_style = 'parent-style';
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
array( $parent_style ),
wp_get_theme()->get('Version')
);
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
?>
;
function my_theme_enqueue_styles() {
wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
}
?>
Just try it. i hope is useful. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "child theme, wp enqueue style"
} |
Custom Taxonomy not displaying all post
I have created 15 post and assigned to the custom taxonomy. It is not displaying all the 15 post. It shows only 10 post.
Please guide me. Thanks
wp_reset_query();
$args = array(
'tax_query' => array(
array(
'taxonomy' => 'parent_login_gallery',
'field' => 'term_id',
'terms' => array($_REQUEST['term_id']),
'operator' => 'IN',
'public' => true,
'has_archive' => true,
),
)
); | Try this code.
wp_reset_query();
$args = array(
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'parent_login_gallery',
'field' => 'term_id',
'terms' => array($_REQUEST['term_id']),
'operator' => 'IN',
'public' => true,
'has_archive' => true,
),
)
); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, custom taxonomy"
} |
help me to display featured image of specific post by post id
i need to attach an image from a specific post by using post id of custom post type which i created new... how can i..? actually i created a new 5 post type named 'flips'... and meta content areas are website, title back, content back, main title, thumbnail etc.,.
<?php $mypost = get_post(28); echo apply_filters('the_content',$mypost->post_content); ?>
<?php $mypost = get_post(28);
echo apply_filters('website',$mypost->website);
echo apply_filters('titleback',$mypost->titleback);
echo apply_filters('contentback',$mypost->contentback);
?>
i need to add post thumbnail to display here also how can i? | You can use get_the_post_thumbnail like this:
<?php $mypost = get_post(28); echo apply_filters('the_content',$mypost->post_content); ?>
<?php $mypost = get_post(28);
echo apply_filters('website',$mypost->website);
echo apply_filters('titleback',$mypost->titleback);
echo apply_filters('contentback',$mypost->contentback);
echo get_the_post_thumbnail( $mypost->ID, 'thumbnail');
?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types"
} |
Getting Member Data From WhishList Member on Register
I contacted WLM tech support and asked:
> "I'm using the WishList Member API is there a way I could figure out if a new member has been added to Wishlist? I'd like to capture the newest member's name and email address and then use that it in my plugin."
They responded with:
> "You can use wishlistmember_shoppingcart_register (action).
>
> Called when a new member is signed-up via one of the shopping cart integrations. Information about the registration can be found in the $_POST variable."
I'm wondering how to do this... should I use an action?
add_action('wishlistmember_shoppingcart_register', 'get_member_info'));
function get_member_info(){
//get $_POST
// do stuff here
} | Please refer to the link below and read on how to use add_action correctly. <
add_action('wishlistmember_shoppingcart_register', 'get_member_info'));
function get_member_info() {
// Debug $_POST.
echo '<pre>';
var_dump($_POST);
exit;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, plugin development"
} |
Why is file_get_contents returning page source?
I'm trying to write a shortcode in my theme's **functions.php** file that can display the contents of a CSV file on our server.
I'll worry about reading the CSV file into arrays and such later, but for now I just want to make sure I can read a file's contents using **file_get_contents**. However, when I run the shortcode below, the alert contains HTML.
function display_csv_data_func( $atts ) {
$file_contents = file_get_contents("
return "<script>alert('" . $file_contents . "');</script>";
}
add_shortcode( 'display_csv_data', 'display_csv_data_func' );
returns:
alert('
<!doctype html>
<!--[if lt IE 7 ]> <html class="no-js ie6" lang="en-US"
...
Is there something about shortcodes, functions.php or WordPress in general that's interfering with my code? Seems like this should be a fairly simple thing to do... | Aha, I figured it out! You have to use **wp_remote_get()**. I'm not exactly sure why at this point, but here's what the code looks like:
function display_csv_data_func( $atts ) {
$file_path = "
$response = wp_remote_get($file_path);
$response_body = wp_remote_retrieve_body($response);
return "<script>alert('" . $response_body . "');</script>";
}
add_shortcode( 'display_csv_data', 'display_csv_data_func' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "php, shortcode, csv"
} |
PHP syntax error when using wpdb update?
I'm not too good with PHP, so I'm having trouble with some code that is supposed to update the wp_posts table. The problem is that when I try to save it, WP deactivates the plugin saying there's a syntax error in the following bit of code:
global $wpdb;
$dbresult = $wpdb->update($wpdb->post, ['post_title' => 'Test Title', 'post_content' => 'Test Content', 'group_access' => $group_access, 'tag_list' => $tag_list], ['ID' => 12095])) :
if (false === $dbresult) {
echo 'An error occurred wile updating...');$errors = $post_id->get_error_messages();
}
I believe it would work if I could figure out what the syntax error was. | you've got a simple typo, it should read
$dbresult = $wpdb->update($wpdb->posts, ...) ;
that is, `$wpdb->posts` with a 's', instead of `$wpdb->post'. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "php, wpdb"
} |
wordpress not generate thumnails for mp4 videos
i have wordpress installed v4.6 , when i upload videos in media manager it cant generate thumbnails for video, am uploading mp4 videos.
so any idea how to add/configure ffmpeg library for wordpress.
on my Debian 8 server have ffmpeg installed in
/usr/bin/ffmpeg
also which wordpress file is responsible for file uploading so that i may make changes to it. thanks | You can output them on the front end using custom fields like this:
printf( '<a href="%s"><img src="%s" /></a>', get_post_meta( get_the_id(),'video_url', true ), the_post_thumbnail_url() );
Or this if you want to use a different image for your video thumbnail
printf( '<a href="%s"><img src="%s" /></a>', get_post_meta( get_the_id(),'video_url', true ), get_post_meta( get_the_id(),'video_img', true ) ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "media library"
} |
Menu — How to add "current-menu-grand-ancestor" css class
Any tips in order to :
Add the css class `current-menu-grand-ancestor` to an item with the class `current-menu-ancestor` that has a child with also the class `current-menu-ancestor` via functions.php ?
Thank you !
Johan | Something like this will help you filter a menu item and add a custom class conditionally. ( Untested )
function add_nav_class( $classes ) {
if ( class_exists( 'current-menu-ancestor' ) || $item->title == 'blog' ) {
$classes[] = 'current-menu-grand-ancestor';
}
return $classes;
}
add_filter( 'nav_menu_css_class', 'add_nav_class', 10, 2 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "php, functions, menus"
} |
Custom posts don't work
I made a basic custom post type basing on examples from codex but it doesn't work until I modify permalink settings. When I click `view` to preview the post I see `Not found` notification but when I modify permalink settings, click `Save changes` the post works as well as default post type. I mean, without creating special loop queries.
What should I do to avoid this error creating a theme to public use or selling?
Do everyone will have to change permalink settings to be able to use my custom post types? | After custom post type registration, that is `register_post_type()` , try adding function `flash_rewrite_rules();`
This will automatically flush all rewrite rules so you won't need to go to permalink settings each time.
See this page: <
Example:
add_action( 'init', 'my_cpt_init' );
function my_cpt_init() {
register_post_type( ... );
flush_rewrite_rules();
}
As it's said in the docs, it's better to do that on plugin activation. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, plugins, plugin development"
} |
How I Can Delete Custom Post Type URL
i create a Custom Post and i don't want them has a URL.
There is a URL like that = site.com/custom-slug/and-id-or-title  default to the value of `public` (e.g., `show_ui`), show when you set `'public' => false` you often times need to explicitly set those args to true, e.g.
$args = array (
// don't show this CPT on the front-end
'public' => false,
// but do allow it to be managed on the back-end
'show_ui' => true,
// other register_post_type() args
) ;
register_post_type ('my_cpt', $args) ; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom post types"
} |
ACF gallery & bootstrap colls and rows
I've code to display ACF gallery:
<?php
$images = get_field('portfolio');
if( $images ): ?>
<div class="row">
<?php foreach( $images as $image ): ?>
<div class="col-lg-3">
<a href="<?php echo $image['url']; ?>">
<img src="<?php echo $image['sizes']['thumb_front']; ?>" alt="<?php echo $image['alt']; ?>" class="img-responsive"/>
</a>
<p><?php echo $image['caption']; ?></p>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>
And I need to wrap every 4 item `<div class="col-lg-3">` into the `<div class="row">` How can I do this, guys? | The easiest option would be to simply check if you are on every fourth iteration. Please see the following for an illustration, I haven't tested this but see the basic idea.
<?php
$images = get_field('portfolio');
if( $images ): ?>
<?php foreach( $images as $key => $image ):
if (($key + 1) % 4 == 0) { ?>
<div class="row">
<?php } ?>
<div class="col-lg-3">
<a href="<?php echo $image['url']; ?>">
<img src="<?php echo $image['sizes']['thumb_front']; ?>" alt="<?php echo $image['alt']; ?>" class="img-responsive"/>
</a>
<p><?php echo $image['caption']; ?></p>
</div>
<?php
if (($key + 1) % 4 == 0) { ?>
</div>
<?php }
endforeach; ?>
</div> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -2,
"tags": "advanced custom fields, twitter bootstrap"
} |
'the_content' Filter delivers empty string with lengh (608)
I used the 'the_content' filter to check if the content of an page is empty and to set an alternative content:
add_filter( 'the_content', 'my_content' );
function my_content( $content ) {
// check if we the posttype is correct -------------------------------
...
if (strlen($content) == 0) {
return 'new content';
}
return $content;
}
When I open an empty post with the correct posttype I will get an empty $content with string length (608). In this case will show and emtpy page and not the "new content" :(
I included the following debug information:
$temp = trim($content);
var_dump($temp);
if (strlen($content) == 0) {
return 'new content';
}
and get as an result: string(608) " "
Any Idea what is going on and how to fix it? | It was an presentation issue as the content was injected by another plugin and it was an HTML comment "" and this Text will not be shown by an echo or even an print_r() or var_dump() | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "filters"
} |
What does wp_update_post() do that the $wpdb class does not?
I recently had to make direct changes to my `wp_posts` table from a WordPress plugin. I first tried to do this with `wp_update_post()`, thinking that would would do it. Apparently, `wp_update_post()` is only able to edit a predefined set of table fields (presumably the WP default ones). Then I happened upon `$wpdb` class. I thought I read that `wp_update_post()` uses `$wpdb` which is interesting, but then begs the question, why have `wp_update_post()` when you can just use the `$wpdb` class directly? What does `wp_update_post()` do that the `$wpdb` does not? What need is it filling? Or is it more of an administration concern, like resources or security? If that's the case, what are the downsides of using $wpdb directly? | 1. `wp_update_post()` calls some hooks that `$wpdb` doesn't on it's own. You'll have to do it on your own to make it compatible with other plugins.
2. `wp_update_post()` calls some functions related to database entry sanitation, thumbnails, attachments, time (format, zone etc.), comment, taxonomy, meta, cache etc. So if you use `$wpdb`, make sure you handle all of them as appropriate.
3. WordPress will update `wp_update_post()` to always keep it compatible with the current state of Database, core CODE, plugin support etc. Even if you do everything right, future updates will be difficult for you with `$wpdb`.
So if something can be done with `wp_update_post()`, then always use it, only use `$wpdb` if your desired action related to updating post can't be done with it. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wpdb, wp update post"
} |
get_tags() return an empty array after added tags with wp_insert_term()
I added some Tags programmatically with wp_insert_term(), and later I call get_tags() to use them, but it returns an empty array, although they are inserted in the database.
Here is my code:
install.php
$tags = array(
array('name' => 'Beachfront Escapes', 'slug' => 'beachfront-escapes'),
array('name' => 'Group Holidays', 'slug' => 'group-holidays'),
array('name' => 'City Breaks', 'slug' => 'city-breaks')
);
foreach ($tags as $tag) {
if (!term_exists($tag['name'], 'post_tag')) {
wp_insert_term($tag['name'], 'post_tag', array('slug' => $tag['slug']));
}
}
display.php
$tags = get_tags();
var_dump($tags); // empty array()
Am I doing something wrong? | Thanks to @Milo I could fix it. The problem was, that the tags were not assigned to any post.
display.php
$tags = get_tags(array('hide_empty' => false));
The `hide_empty` param do the trick. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "database, tags, array, terms"
} |
Disable a Wordpress site
Hello I plan to disable my wordpress website. I don't plan to permanently delete it from the web. What are the steps I must follow to disable it? | An easy way is to create a file called 'maintenance' and place it in your sites root folder. When WP sees that file, it puts up a 'down for maintenance' type file. You can still get into the admin area, but the 'public' can't see the file.
Another way is to rename the '.htaccess' file (which helps redirect access to the site into WP pages) and create a new index.php/html file (renaming any existing one). That index file would contain an 'under construction' message or something similar. Disadvantage of that would be no access to the admin area.
Which technique you use depends on the length of the downtime. Temporary downtime: I'd use the 'maintenance' file technique. Longer-term: I'd build an 'under construction' page as index.html or index.php (renaming any existing files of that name) and rename the '.htaccess' file. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugins"
} |
How do I resolve obtaining the dashboard features created with CPT UI in localhost onto my live site?
I utilized a great plugin during development called Custom Post Types UI by WebDevStudios. Its an Admin UI for creating post types and custom taxonomies for WordPress dashboard. The problem is the custom post types I created on localhost did not all populate when I added this plugin to the production site. How do I resolve this short of redoing all the custom post types on the live site again? | Have you migrated your database to the server already? | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types"
} |
Add code to a specific post's content
I want to add a button on top of all posts have catogery "music", Here's what I have tried but it does not work at all. Please give me advice.
function add_go_back_btn($content) {
global $post;
$cat = get_the_category();
$post_type = get_post_type();
if($cat === 'music' && $post_type === 'post') {
return '<div><a href="/music">This is a button</a></div>' . $content;
}
else return $content;
}
add_filter( 'the_content', 'add_go_back_btn' ); | Your code is fine, but your logic isn't working because of $cat. $cat is returning an Array with an Object which you're trying to check against. But you can easily just use in_category('music') like this:
function add_go_back_btn($content) {
global $post;
$cat = get_the_category();
$post_type = get_post_type();
if(in_category('music') && $post_type === 'post') {
return '<div><a href="/music">This is a button</a></div>' . $content;
} else return $content;
}
add_filter( 'the_content', 'add_go_back_btn' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, functions"
} |
Pagination for a page created by the shortcode "Product"
My `searchDB` function searches products with the specified keyword, and returns an array of found ids.
Below is my page. How can I add a pagination is this page ?
<div class="product-container">
<?php
$my_products = searchDB($text);
foreach ($my_products as $value) {
echo do_shortcode('[product id="'.$value.'"]');
}
?>
</div>
P.S: searchDB uses $wmdb. | Woocommerce doesn't have pagination optionality by default, you need a plugin or code it by yourself. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "shortcode, pagination, woocommerce offtopic"
} |
Could a higher number of registered image sizes affect performance?
This question is related to this one, but is a bit different.
In the layout (archive page) for a Wordpress project I'm working on right now there's a couple of image sizes that do not appear anywhere else. They are quite (by tens of pixels) close to the sizes that we already have registered — let's say, we have 210x300 already and the new size is 230x300. There's also another new image size which doubles that in height and could be also replaced by an already existing image size.
I know that having a lot of differently sized elements might not be good in terms of design consistency — so that could be one argument against it.
But, looking more from a practical side, are there any performance related concerns in adding more and more image sizes via `add_image_size`? Currently we have 8 custom image sizes, and I'm not sure whether it's optimal to add more of them.
Thanks! | Depends. One argument could be that if the requested page use all sizes then there will be a lot of image calls (slower response, bandwidth etc) but you can bypass that i.e. by loading images with JS. Also more sizes means more disk space usage. I don't think there is any significant performance concern related to back-end, meaning the db calls / queries etc.
Also if the images are compressed from the begging a few pixels down in width or height won't be a difference in performance.
You can have an image with 600x900 dimension and cover a lot of intermediate sizes adjusting with CSS and keep a good aspect ratio and have a good quality for retina monitors. Better to have a bigger, in dimension, image and shrink it than to have a smaller image and scale it up. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "performance, images, optimization, maintenance"
} |
Is there a reset_button()?
After 5 years, is there a `reset_button()`?
If not (yet) there is, in WordPress what is the **best** way for the cleaning of a backend form fields? | You can reuse the submit button code:
print str_replace(
'"submit"',
'"reset"',
get_submit_button( 'Reset' )
);
This should create a button with the regular style for submit buttons. The attributes `name`, `type` and `id` will be set to `reset`. Not tested. :) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "forms"
} |
update custom post type meta from a shortcode
I have the following scenario: I have a custom post type called "tablepress_tables" that is create by the plugin "Wordpress", Tablepress has a shortcode to display the number of rows which is `[table-info id=123 field=number_rows /]` This will give rows number let's say 45 my question is I want to update every 'tablepress_tables" with a meta containing the number of rows that this post have, so the shortcode "id" will need to be changed automatically any idea on how to do that? or where to start? | I hope you will pull the code from here.
Now you have table id
get_option('table_press' .$table_name ."_". $table_id);
so you can chage shortcode id dynamiclly using do_shortcode(). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, plugins, metabox, post meta, table"
} |
Sum a custom field that has a shortcode in it
I have a custom post type called "subjects" it has a custom field called "exams_count" that custom field value is a shortcode that another plugins uses, when the custom field is displayed it show a numerical value lets say 10 or something but the data in the field itself is the shortcode as I mentioned above my quesiton is: I want to sum all the displayed value of that custom field after the shortcode is executed how can I do that? | Without your code it's a bit difficult, so bear with me.
Can you do this:
$x=0;
$x=do_shortcode ('[your_shortcode]'); // say its 10
$valuetoadd = 20; //for example
$exams_count_sum= $x + $valuetoadd;
echo $exams_count_sum; //should equal 30
Or, if you are in a loop, this could be a good starting point:
$examtotal=0;
$examtotal_sum=0;
while ( $the_query->have_posts() ) : $the_query->the_post();
the_content();
$examtotal=do_shortcode ('[your_shortcode]');
$examtotal_sum = $examtotal_sum + $examtotal;
endwhile;
echo 'total is '.$examtotal_sum; //this will be your total | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types"
} |
Does WordPress function replace_hello() exists?
I was looking at this website: < and one of the PHP code solutions in it is nagging at me. The problem is How would you change all the occurrences of “Hello” into “Good Morning” in post/page contents, when viewed before 11AM? The author has an answer that looks like this:
<?php
function replace_hello(){
}
I have Googled this function and the only function I know of that can replace a string is the PHP str_replace() function.
Can anyone confirm the above function is an actual function? In other words is function replace_hello() or function replace_welcome() actually a valid function and where (if at all) in the WordPress Codex or any documentation can I locate to learn more about it? | This is custom function the author uses to show how to use `the_content` filter. If you look at the line after the function `add_filter('the_content', 'replace_hello');` this is saying to call the custom function `replace_hello` when encountering the `the_content` filter | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions"
} |
How can I make that when I clic on one of the menu items, that page shows only posts with the same category?
I have a blog wordpress in localhost. What I want to know before uploading is if it is possible to show just posts with a certain category in an specific page. I mean, to show category articles "cats", for example, in the "cats" page in the menu. | Almost any WP theme will include category archives. If you want to add them to a menu, go to Appearance/Menus, select the Menu you want to edit, and pick the Category you want from the Categories menu to the left. How the Category "page" or archive displays will in turn be determined by your theme template, though a developer can also customize a specific Category template to show anything you want virtually any way that you want. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "theme development, themes"
} |
Set meta_key and meta_value for all registered user in wordpress using sql query
I am trying to add **meta_key** and **meta_value** for the all already registered user in my database via phpmyadmin.
I want: **meta_key = is_activated** and **meta_value = 1** ;
$blogusers = get_users( $args);
foreach($blogusers as $key => $user){
update_user_meta( $user->ID, 'is_activated', 1 );
}
**OR** you can also do this using $wpdb
global $wpdb;
$users = $wpdb->get_results( "SELECT ID FROM $wpdb->users" );
if( $users ) {
foreach ( $users as $user ) {
update_user_meta( $user->ID, 'is_activated', 1 );
}
}
check PHPMyAdmin you will find every user meta_key=is_activated is set to 1. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "mysql, user meta, phpmyadmin"
} |
Fetching values from database for select box
I have created a table named `ic_states` i want to make a select box from the database values using wpdb. I have tried wpdb::get_row but not getting the result. It is showing only value. Can someone help me. I have checked the question if anyone asked before but i didn't found any suitable query for my problem. | You can used below code to get results from the database in wordpress.
global $wpdb, $posts;
$prefix = $wpdb->prefix;
$query = $wpdb->get_results("SELECT * FROM {$prefix}states");
if($query){
echo '<select><option value="select">Select</option>';
foreach ($query as $value) {
echo '<option value="'.$value->ID.'">'.$value->ID.'</option>';
}
echo "</select>";
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "database"
} |
Add a custom class to awating comments
So not sure if i have missed something but awaiting comments dont have a own class, so is there a way to add in a simple way a custom class to comments that are awaiting moderation so that I can style there comments with CSS. | Here's one way to add a custom `.wpse-comment-awaiting-moderation` comment class through the `comment_class` filter:
add_filter( 'comment_class', 'wpse_259326_comment_classes', 10, 5 );
function wpse_259326_comment_classes ( $classes, $class, $comment_ID, $comment, $post_id )
{
if( 'unapproved' === wp_get_comment_status( $comment ) && is_array( $classes ) )
$classes[] = 'wpse-comment-awaiting-moderation';
return $classes;
}
where we used that `wp_get_comment_status( $comment )` returns `'unapproved'` for _unappproved_ comments. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 3,
"tags": "comments"
} |
add_image_size for header_image
How can I add image size for header_image() just like featured image by using add_image_size()
What is the correct way of adding image size for header_image() | This may can help you
add_theme_support( 'post-thumbnails', array( 'post' ,'promotions',
'services', 'counter') );
set_post_thumbnail_size( 200, 200, true );
add_image_size( 'slider-image', true );
Image will resize according to your html code | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "php, images, headers"
} |
Pass parameters to function through an action
I'm trying to pass the value of a variable into do_action and then use it in the resulting function but it's not working. The action is being fired in the woocommerce checkout, so it also passes the $checkout variable as well, which is working fine. Simplified example below:
add_action( 'my_action', 'my_function' );
function my_function( $checkout, $myvar ) {
var_dump ($checkout); //Works fine
var_dump ($myvar); //Returns NULL
}
And then calling the action in the template like so:
$myvar = 1;
do_action( 'my_action', $checkout, $myvar );
I can't access $myvar at all in the function, any help appreciated. | add_action() and add_filter() take 4 params: `string $tag, callable $function_to_add, int $priority = 10, int $accepted_args = 1`.
So, the function you are hooking to takes more than 1 param, then just pass the number of params it accepts as the 4th param to `add_action()`. In your case,
add_action ('my_action', 'my_function', 10, 2) ; | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "functions, woocommerce offtopic, actions"
} |
What and where are the WordPress core-bundled scripts?
I submitted a theme and they rejected the theme because: `Core-bundled scripts: Required to use core-bundled scripts rather than including their own version of that script. For example jQuery.`
Where exactly are these core-bundled scripts? I am not using jQuery but I am using Bootstrap, so I assume that is what they're referring to.
I've searched Google, but it returned nothing at all about the bundled scripts. | You can see every script loaded by core in the `script-loader.php` source file. I don't see Bootstrap in there. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development"
} |
Is it possible to restrict content in wordpress?
I just upload my blog with wordpress in my host. But I want to make some posts restricted to only those who are logged in and in some cases, the ones who pay for some "super premium" content. I have no idea if there's a plugin to do that or maybe another way to do it, but I really need it. It could be perfect to sign up by email, or social media and get those emails later to add them to a newsletter. Thank you so much for your help and guidance! | You should look up membership plugins. There are several options. Some free some paid. Other than that, you can definitely use custom templates and WordPress functions to restrict content to certain users. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, theme development"
} |
WordPress SSL (https) is not working with custom permalink
I have set up SSL on a site and the homepage is working properly.
plus every page and archives are working if the permalink settings are set to default ( Plain )
but its giving a 404 error for all pages and categories if the permalink settings are changed to another option.
I am using woocommerce plugin if that matters? plus my htaccess file looks like below.
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
also Page titles on all pages are not displaying correctly. its printing out domain name instead. | Make sure `mod_rewrite` is enabled as Apache module. It's not needed when _plain_ permalinks are used, but you have the opposite situation.
Also, don't lose any of incoming link juice and redirect with HTTP Status 301 everything and everybody to the HTTPS version of the site. Add to `.htaccess` file before (or inside) the WordPress section:
RewriteEngine On
# The following lines are essential
RewriteCond %{HTTPS} !=on
RewriteRule (.*) [R=301,L]
And don't forget to set up the SSL for `Check Out` pages in the WooCommerce settings. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "url rewriting, htaccess, https"
} |
My style in my child theme loads after the parent theme, but it breaks stuff: How do I load it before the parent theme?
I'm building my child theme, but including materialize css that I want to use, breaks the entire site when enqueued in **functions.php**. How do I change that?
function bla_enqueue_child_theme_styles() {
wp_enqueue_style('cookie-font', '
//wp_enqueue_style('datatables-css', '
wp_enqueue_style('materialize-css', ' 0);
wp_enqueue_style('cake-child-style', get_stylesheet_directory_uri().'/style.css', '', 1, 'all');
wp_enqueue_script('new-jquery', '
wp_enqueue_script('materialize-js', '
//wp_enqueue_script('datatables-js', '
wp_enqueue_script('custom', get_stylesheet_directory_uri() . '/custom.js');
}
add_action( 'wp_enqueue_scripts', 'bla_enqueue_child_theme_styles', -20); | > How do I load it before the parent theme?
I think you are doing it right. If the parent theme is attaching the function responsible for enqueueing its styles to the `wp_enqueue_scripts` hook, then your `bla_enqueue_child_theme_styles()` function must be being executed first (because you passed `-20` as priority) and your styles should be being included first in the page's source code.
The fact that Materialize's CSS rules are overriding the parent theme's may not be related to the order in which the stylesheets are being included, but to the specificity of the selectors being used in those stylesheets.
Cake is likely to be using some kind of CSS framework as well, either one developed by a third party or a custom one. In that case, is very likely that both Cake and Materialize are trying to solve the same problems, but using different methods, creating conflicts in the process. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "wp enqueue style"
} |
Show video as part of the post?
I am doing a post in wordpress, but I want to put a video as part of the post. I mean, I have a paragraph but after the paragraph I want to put a video. I did put it as media, but it just shows a link and if I clic on the link it downloads the file, and I just want to play the video, not to download it. What can I do? Thanks! | When I want to _embed_ a video on a WP post I use the html5 `<video>` tag. It's very simple to put into the html code and is much like the `<img>` tag. W3Schools breaks it down for dummies. Here is their sample code:
<video width="320" height="240" controls>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "theme development, add theme support"
} |
Adding a search form inside a div
I wanted to add a search form inside a div using the code bellow:
`printf( '<div class="entry"><p>%s</p>%s</div>', apply_filters( 'genesis_noposts_text', __( 'Try again below.', 'genesis' ) ), get_search_form() );`
But every time I add the `get_search_form()` it's generated before the div, like the following:
<form></form>
<div class="entry"></div>
The workaround I found was to split the code, but I wanted to know if there is a better solution that works properly.
remove_action( 'genesis_loop_else', 'genesis_do_noposts' );
add_action( 'genesis_loop_else', 'mytheme_do_noposts' );
function mytheme_do_noposts() {
printf( '<div class="entry"><p>%s</p>', apply_filters( 'genesis_noposts_text', __( 'Try again below.', 'genesis' ) ) );
printf( '%s</div>', get_search_form() );
}
* * *
get_search_form | The `get_search_form()` echos so it will always show up before returns. Use:
get_search_form( false ) | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "php, html, genesis theme framework"
} |
Want to Add Custom Fields for Uploading video to WordPress Users from front end
I am trying to an add upload media option for the user profile.Which i was achieved with the help of This Link
By adding the code given in the above link on my theme's functions.php i am able to see the extra added field on user profile section once i logged in with admin screen.
**What I want is** :I want to show the upload media option for the front-end user to add their video. | Use CMB2 library for Custom Field
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, custom field, users, user meta"
} |
How change child theme's boxed layout to fullwidth in genesis?
I'm using LifeStyle Pro Genesis Child theme, that has a boxed layout of width=1140px. I first changed it to 1200px and worked with that layout. Now I want to test some pages with fullwidth-layout, meaning wider than 1200px, not boxed.
In settings of the "Genesis Layout Extra Plugin" I only find 'fullwidth-content'. But using that means just not having the sidebar any more.
So: What code in what file I have to use to get a fullwidth website? Is it possible and recommended to modify a child theme that has boxed layout? | To apply the same width to everything, change the `max-width` of the `.wrap`
.wrap {
max-width: 90%;
}
If you just want to change the width of the content section, add the following code:
.site-inner .wrap {
max-width: 90%;
}
Hope it works for you, good luck. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "child theme"
} |
Duplicated WP site manually, now links redirect wrong
So, I duplicated my website (by just duplicating the VM in Proxmox under another name) so I could use the local duplicate to test settings and develop the site. I have edited the database, changed the site URL from wp-config.php and everything kind of seems to work.
The page address is now just an IP address, but when I click a link on the site, the address "duplicates" itself. If I click a link called "about", the address changes from 127.0.0.1 to 127.0.0.1/127.0.0.1/about. If I click another link on the About page, this causes an infinite loop of redirections. I get
> The 127.0.0.1 page isn’t working. 127.0.0.1 redirected you too many times.
and the page address is an endless loop of the IP and page addresses. I have no idea what causes this, could anyone help? Note: the actual address isn't 127.0.0.1, but an internal network address. I just used that for the sake of the question. | Found the issue: in `wp-config.php`, there was no http:// before the address on the `define('WP_HOME'` line. From Wordpress Codex:
> Add these two lines to your wp-config.php, where "example.com" is the correct location of your site.
>
> `define('WP_SITEURL','
> `define('WP_HOME','
Adding these properly solved the issue. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "redirect"
} |
wp_list_pages shortcode jumps above previous content
I have the following shortcode:
function roofspan_product_childpages() {
$list_p = array(
'sort_column' => 'menu_order, post_title',
'child_of' => '12',
'title_li' => 'Products: '
);
return wp_list_pages( $list_p );
}
add_shortcode( 'product_childpages', 'roofspan_product_childpages' );
In a Wordpress page, I have some paragraph content, and in the last paragraph I have the shortcode `[product_childpages]`.
On the front end, the `[product_childpages]` is rendered before the previous text paragraphs.
How can I ensure `[product_childpages]` stays at the end of the page content? Thanks. | That's because your list is printed immediately.
`wp_list_pages()` has the `echo` parameter, which is `true` by default. Make it false like here:
<?php
function roofspan_product_childpages() {
$list_p = array(
'sort_column' => 'menu_order, post_title',
'child_of' => '12',
'title_li' => 'Products: ',
'echo' => 0 // Note this
);
return wp_list_pages( $list_p );
}
add_shortcode( 'product_childpages', 'roofspan_product_childpages' ); | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 0,
"tags": "shortcode"
} |
Multiple category RSS feeds
Taken from WordPress Feeds:
> You can include posts from one of multiple categories or tags in a feed by comma-separating their values. For example:
>
> <
>
> You can include posts from all of multiple categories or tags in a feed by adding to the end of the link. For example:
>
> <
I understand the 2nd feed will include posts from both cat1 and cat2. The 1st feed looks, to me at least, as though it will do exactly the same. How do these feed URLs differ? |
will include posts belonging to `cat1` _OR_ `cat2`, while
will include posts belonging to both `cat1` _AND_ `cat2` simultaneously. **See the update below!**
In the following example, the first RSS will include all posts, while the second – `Post 3` and `Post 4` only.
Category 1
|- Post 1
|- Post 2
|- Post 3
|- Post 4
Category 2
|- Post 3
|- Post 4
|- Post 5
|- Post 6
**Updated!**
Surprisingly, in spite of WordPress Codex instructions on finding RSS feed URL, the second feed URL shows only the last category mentioned in URL. The right formed URL for `cat1` _AND_ `cat2` will look as follows:
Thanks @birgire for drawing my attention to this. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 3,
"tags": "rss, feed"
} |
Later blog post pages give 404 error
The later blog pages give a 404 error.
For example page 7 works fine: <
Page 8 gives you a 404 error: <
Any suggestions would be appreciated! | First, try rebuilding your permalinks. Go to Settings >> Permalinks and click Save, which will rebuild them. If that doesn't work, go into your Settings >> Reading >> _Blog pages show at most_ setting and try increasing or decreasing that and see how that changes things.
Some themes have a setting that lets you adjust how many posts per page display in the loop that can conflict with the main WordPress setting, so if you can edit your theme options, try ensuring there isn't a setting in there you need to adjust.
One thing I'd also try if none of this works is disabling all of your plugins temporarily and reverting to the default WordPress theme just to isolate the cause of the issue. If it works, then switch back to your current theme. If it still works, you'll know it's plugin-related. If not, you'll know it's theme-related. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "pages, pagination, blog, paginate links"
} |
REST API, get user role?
I'm trying to figure out how to retrieve a user's roles from the API, but I haven't been able to sort it. Is this information not accessible by default?
Can anyone point me in the right direction? | This is totally possible by registering your own rest field into the response.
Here's some documentation on modifying response data. <
Here's how to add roles to the endpoint:
function get_user_roles($object, $field_name, $request) {
return get_userdata($object['id'])->roles;
}
add_action('rest_api_init', function() {
register_rest_field('user', 'roles', array(
'get_callback' => 'get_user_roles',
'update_callback' => null,
'schema' => array(
'type' => 'array'
)
));
});
Specifically, what I'm doing is creating a function called `get_user_roles` that retrieves the user roles, then registering a 'roles' field in the response, and tell it that the data comes from that function.
I also ran into an issue of it not playing nice when the data returned an `array`, so I told the schema to expect it in the `schema` property of the array passed in `register_rest_field` | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 4,
"tags": "user roles, rest api"
} |
Register rest field for specific user
I'm extending Wordpress REST API with a custom plugin, and I'm in the need of adding a new field to the user response.
The problem is that this field has to appear only in base of the user role.
For example I want a field `custom_field` appear in the response only if the user is `administrator` and not `contributor`.
At the moment I'm using the `register_rest_field()` function, but it allows me to chose only the type of object.
Do you know if there is a workaround to this issue? Or do you know better ways to reach the same result?
P.S. I'm using WP 4.7.3 | I found a better workaround using the same filter suggested by @ben-casey in his answer.
Firstly I registered throuhg `register_rest_field` all the custom fields of all the user types I have in the database.
Then in `rest_prepare_user`, insted adding the wanted fields, I removed the unwanted ones. In this way I can still use the same endpoint to update the field.
Below an example of the JSON clean up.
function my_rest_prepare_user( WP_REST_Response $response, WP_User $user, WP_REST_Request $request ){
if( in_array( 'administrator', $user->roles ) ){
$data = $response->get_data();
unset($data['custom_field']);
$response->set_data( $data );
}
return $response;
}
add_filter( 'rest_prepare_user', 'my_rest_prepare_user', 10, 3 ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom field, users, user roles, rest api"
} |
Loading CDN that requires jQuery in Wordpress
According to wpdevsolutions the correct way to load CDN javascripts in Wordpress is like this:
function theme_name_scripts() {
wp_enqueue_script( 'pushy', '//cdnjs.cloudflare.com/ajax/libs/pushy/1.1.0/js/pushy.min.js' );
}
add_action( 'wp_enqueue_scripts', 'theme_name_scripts' );
The question I have is what do I do if the script require jQuery to be loaded?
This does not seem to work.
`wp_enqueue_script( 'pushy', '//cdnjs.cloudflare.com/ajax/libs/pushy/1.1.0/js/pushy.min.js', array(), '', true );`
The console gives me: _Uncaught ReferenceError: jQuery is not defined_
Most of the relevant answers here seem to be fairly outdated or incorrect. | You need to use it with jQuery like this:
wp_enqueue_script( 'pushy', '//cdnjs.cloudflare.com/ajax/libs/pushy/1.1.0/js/pushy.min.js', array( 'jquery' ) ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "functions, jquery, javascript"
} |
What's the difference between "wp" and "wp_loaded"?
What's the difference between `wp` and `wp_loaded`? Which one is earlier? | `wp_loaded` is fired once WordPress, all plugins, and the theme are fully loaded and instantiated.
`wp` runs immediately after the global WP class object is set up.
`wp_loaded` fires before `wp`. See the actions run during a typical request. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "hooks"
} |
Count the number of images uploded on the website
I mention "full website" because I don't need the number of attachments on one post (as answered in many questions). I basically need a function that returns the number of uploaded images (attached and unattached) on the website, excluding non-image files.
I've done some research, but there isn’t any direct function that counts only the images. What is the most simple way to do this? | There's a handy built-in function, namely `wp_count_attachments()`.
We can filter out images with `wp_count_attachments( $mime_type = 'image' )` that returns an object like:
stdClass Object
(
[image/gif] => 9
[image/jpeg] => 121
[image/png] => 20
[image/x-icon] => 6
[trash] => 0
)
So we can use the one-liner:
$count = array_sum( (array) wp_count_attachments( $mime_type = 'image' ) );
for the total number of images. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 4,
"tags": "wp query, images, attachments, count"
} |
Connect to server with SFTP instead of FTP/FTPS within WordPress Backup
I have recently setup a Linode Apache2 Debian server and I am hosting my WordPress site on it. It seems I can only connect to the server with SFTP.
When I attempt to add/update a plugin I am presented with this screen:

Tried:
1) Looking for a setting in Jetpack Infinite Scroll menu - nothing there
2) Adding this code to child functions.php
function twenty_fifteen_infinite_scroll_init() {
add_theme_support( 'infinite-scroll', array(
'posts_per_page' => 10,
) );
}
add_action( 'after_setup_theme', 'twenty_fifteen_infinite_scroll_init' ); | Found the code that works here:
<
/*
* Change the posts_per_page Infinite Scroll setting from 10 to 20
*/
function my_theme_infinite_scroll_settings( $args ) {
if ( is_array( $args ) )
$args['posts_per_page'] = 20;
return $args;
}
add_filter( 'infinite_scroll_settings', 'my_theme_infinite_scroll_settings' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin jetpack, infinite scroll"
} |
Show "Republished" badge when Post Date is manipulated
I am transitioning from Drupal to Wordpress and I love the way Wordpress handles pretty much every aspect.
Although the transition is smooth I have a question. I am using WP-Types plugin to create views and custom post types.
What I want to do is to find a handle that I can use to show a "Republished" badge on a product when an admin manipulates the Post Date.
Any ideas on this one ?
Thank you in advance. | As for determining the case, if `get_the_date()` and `get_the_modified_date` differ, then the post has been modified - updated or republished. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, front end"
} |
WordPress thinks my custom theme is a theme in the public theme repository
I'm currently developing a custom theme for a client, and all of a sudden WordPres tells me there's an update to version 1.4. This is obviously wrong, but WordPress thinks my theme is the same as <
Here's my style.css:
/*
Theme Name: RISA AS 2017
Theme URI:
Author: AD. Moment AS
Author URI:
Description: Nettsidene til RISA AS
Version: 1.0.0
License: GNU General Public License v2 or later
License URI: LICENSE
Text Domain: risa_as
Tags:
*/
I changed the name of the theme and the Text Domain from risa and risa respectively, but WordPress still thinks this is the same theme.
How can I change the name of my theme to not overlap with the one in the public theme repository? | Be sure your own theme folder is not named the same as the theme folder in the WordPress repo. When checking for updates, WordPress scans theme folder names, not the theme title or other meta in the `style.css` file. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "themes"
} |
Enable identical menu on network sites
I want a network of sites in a multisite install to automatically have certain items in the main menu when the user first uses the site.
This seems surprisingly hard to do, and the new REST API doesn't provide ways to interact with menus.
So instead I've created a simple plugin, which creates a menu if it doesn't exist, and adds various items to it.
I now want to make sure that that menu is activated and visible in the primary menu when people come to the site.
I currently can't see a function that activates the menu in a specified location.
Any suggestions how to do it? | Worked it out.
Assuming using a theme which has a menu location called 'primary', and you have just created a menu with an id contained in $menu_id
$menu_locations = get_nav_menu_locations();
$new_menu_locations = array_map( 'absint', ['primary' => $menu_id]);
$menu_locations = array_merge( $menu_locations, $new_menu_locations );
set_theme_mod( 'nav_menu_locations', $menu_locations );
This is pretty much exactly how Wordpress itself saves updated menu locations in `wp-admin/nav-menus.php` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "menus, rest api"
} |
Responsive images in Bootstrap 4 slider
I have a Bootstrap 4 slider in progress at < . When I add images of a 0.75 ratio like 2000x1500 they display and resize well. 3000x2000 works too. This with them being loaded with:
`the_post_thumbnail('post-thumbnail', ['class' => 'img-responsive responsive--full', 'title' => 'Feature image']);`
It seems to show the images the way I cropped them in WordPress or not and then load them with file dimensions that vary from image to image.
When I use `add_image_size( 'b4-slider', 2000, 1500);` or `add_image_size( 'b4-slider', 2000, 1500, true);` because I am like, let's automate setting the proper size for these babies.. they are no longer responsive. They get squashed when I shrink the browser window size.
How is this possible? | Hmm, I figured it out. I changed the thumbnail AND removed the needed class img-responsive to apply responsive dimensions. Once I kept those all was fine. – | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "images, twitter bootstrap, responsive"
} |
How do you use JavaScript to detect the homepage
I have tried is_front_page() but I believe that is the php way of doing it. Perhaps I'm not calling it right because, of course, I'm not getting a response. Maybe I'm just short of my detailed Js ways of accessing the Wordpress classes.
What I'm trying to do is simple. If I am on the front page or home page add this class if I'm not add this other class. Very simple it's just not working. I have even tried a pseudo span tag and add the class to that and it doesn't work. | I just posted an answer to another question about how to do it.
In your case, assuming you used `body_class()` in your theme, your home page should have a `<body>` with class `home` to it.
So in your JS, you can:
if( $('body.home').length ){
// Do stuff
} | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "custom post types, posts, css, javascript"
} |
Why use hierarchical taxonomies instead of many custom taxonomies?
Or vice versa. What reasons are there for choose one over the other?
 not working?
I am new to wordpress, I am trying to develop a theme on localhost, I am trying to load style.css using this code in functions.php
function add_theme_scripts() {
wp_enqueue_style( 'style', get_stylesheet_uri() );
}
add_action( 'wp_enqueue_scripts', 'add_theme_scripts' );
And style.css is
body{background:green;}
But this code is not working
Can someone explain what i am doing wrong here ? | Are you sure you theme is active?
If you see your style.css code it should not have only the CSS code but also the Theme defination at header of your style.css.
Please make sure if your theme is active.
The above code for loading CSS file looks good and should work if your theme is active.
**Update** :
Have you added `wp_head()` and `wp_footer()` in `header.php` and `footer.php` respectively?
`wp_head()` should be added before `</head>` tag in your HTML and `wp_footer()` should be added before `</body>` tag in HTML. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "themes"
} |
Get an array of custom taxonomy with posts inside each items
I want to obtain an array like that for a custom taxonomy (cat-formation) and custom post types (formation) inside each terms :
custom_taxonomy_term_1
custom_post_type_post_1 (taxonomized with term_1)
custom_post_type_post_2 (taxonomized with term_1)
custom_post_type_post_3 (taxonomized with term_1)
custom_taxonomy_term_2
custom_post_type_post_4 (taxonomized with term_2)
custom_post_type_post_5 (taxonomized with term_2)
custom_taxonomy_term_3
custom_post_type_post_6 (taxonomized with term_3)
custom_post_type_post_7 (taxonomized with term_3)
custom_post_type_post_8 (taxonomized with term_3)
...
Is there a way to get this ? Thank you ! | $terms = get_terms( 'custom_taxonomy', array(
'hide_empty' => false,
));
foreach( $terms as $term ) {
$args = [
'post_type' => 'custom_post_type',
'post_status' => 'publish',
'tax_query' => [
[
'taxonomy' => 'custom_taxonomy',
'field' => 'id',
'terms' => $term->term_id,
]
]
];
$posts = new WP_Query( $args );
$result[ $term->term_id ] = $posts->posts;
}
In result you will have associative array with
$result[ TERMID_1 ] = ARRAY( POST_OBJECT_OF_TERMID_1 );
$result[ TERMID_2 ] = ARRAY( POST_OBJECT_OF_TERMID_2 );
$result[ TERMID_3 ] = ARRAY( POST_OBJECT_OF_TERMID_3 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "taxonomy"
} |
Editing pages from dashboard
I keep struggling to understand how and why this happens: in some themes I can modify the content of a page (type page) from the dashboard, in others I can't. For instance, if I activate a default theme, say Twenty Fifteen, I can create and edit pages from dashboard. When I creat a theme from scratch, I can add a new page from dashboard, but the content added there is not showing up in the website so editing isn't possible either (my theme has only few files created: 404, footer, header, functions, index.php and style.css). When I visualize a page in the website (local), it displays the index.php content instead of the content from the dashboard. So what is the difference between the wp default themes and the one I created from zero? Please help me understand this. I didn't find any satisfying explanations on Google and posting here is kind of my last resort. Thanks in advance for any help! | to display page content in custom theme you should use `page.php` template, and call `the_content()` inside the **loop**. You can also create custom template for different pages and assign them in back end. See: < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "pages, dashboard, content"
} |
show number of posts posted today
I need to display the number of posts that were added TODAY
I found this one that will show number of all posts but I need only last day
<?php
$total = wp_count_posts()->publish;
echo 'Total Posts: ' . $total;
?>
I've a felling that it's very easy but I coudn't any script that will work :(
Thank You in advance, Peter | You can use WP_Query like this:
// we get the date for today
$today = getdate();
//we set the variables, i am ignoring sticky posts so they dont get counted
$args = array(
'ignore_sticky_posts' => 1,
'posts_per_page' => -1, //all posts
'date_query' => array(
array(
'year' => $today["year"],
'month' => $today["mon"],
'day' => $today["mday"],
),
),
);
//we create the query
$today_posts = new WP_Query( $args );
//the result already has a property with the number of posts returned
$count = $today_posts->post_count;
//show it
echo $count; | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php"
} |
Backup custom table
In a WordPress site, I have some custom tables _with the correct WordPress prefix_ , created with/for a plugin.
Does standard export function (XML) also save those custom tables? | No it does not, it will only export all of your posts, pages, comments, custom fields, terms, navigation menus, and custom posts.
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "backup"
} |
Wordpress behind Proxy - Mixed Content
My Server Env for a wordpress site is as follows:
---------- --------- -------------
| Client | <-- HTTPS --> | Proxy | <-- HTTP --> | Wordpress |
---------- --------- -------------
The Problem is that the Wordpress Site itself is served internally over HTTP but the Client communicates over HTTPS with the Proxy. Since Wordpress is configured with HTTP it returns links and images-src with " which leads to `mixed-content` errors in the browsers. (Eg. all css / script links generated by wp_head() return http:// urls)
Can i configure Wordpress to generate only " urls, even if it's serverd over HTTP?
Wordpress runs on nginx webserver
The Proxy is also nginx | Please take a look at Administation Over SSL, particularly the "Using a Reverse Proxy" section. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 4,
"tags": "https, nginx, configuration, proxy"
} |
Getting the sub category
I have custom post types that are using sub-categories. I can't figure out how to display the sub-category slug. I am trying to make the sub-category name a class name, but it keeps returning "unrecognized", which isn't right because it is a subcategory. Here's the code:
<?php
$categories = wp_get_post_terms($post->ID, 'menu_category', $cat_args);
$args = array('parent' => $caregory->term_id);
$sub_cats = get_categories( $args );
?>
<div class="menu-item isotope-box-nested <?php foreach($sub_cats as $sub_cat) echo $sub_cat->slug ?>">
Any ideas what I'm doing wrong her? | If you use `post_class()`, it will echo out your classes using just about everything it has on the post.
If you need to manipulate it, `get_post_class()` function can be used. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories, terms"
} |
Slider image issue in wordpress
I am developing a wordpress site using the theme **Enlighten**. For other theme i had used page concept for adding sliders and other contents. But accoding to the documentation provided by the enlighten theme, they are using post concept to add sliders and other contents.
Here i am attaching the documentation link:
<
I have successfully added slider to my website. but i am facing an issue that my slider images are coming as seperate posts. I have attached a screen shot below; ;`) `header-modern.php`, i need to add styles(in `functions.php`) if included this header, how i can do this ?
`if(is_page_template('header-modern.php')){ wp_enqueue_style('landing-style', get_template_directory_uri() . '/css/navbar.css'); }` i need correct condition. | `get_header` has an action hook called, (surprise!) `get_header` which gets a single parameter - the name of the header file. So what we do is check that name and if it matches our name we add a style. So something like this:
add_action( 'get_header', 'wpse_260353_add_css_for_header' );
function wpse_260353_add_css_for_header( $name ){
if( 'modern' === $name ){
wp_enqueue_style('landing-style', get_template_directory_uri() . '/css/navbar.css');
}
} | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 0,
"tags": "conditional tags, headers"
} |
limit how many words show up in the_content on index
I'm having a heck of a time with this! I'm trying to force this page to only show a limited amount of words regardless if they insert a readmore tag.
I was going to use the_excerpt, but it doesn't add a readmore link at the end of the excerpt.
I have my index page pulling my blog roll by using this code:
<div class="entry-content">
<?php
/* translators: %s: Name of current post */
the_content( sprintf(
__( 'more %s <span class="meta-nav">...</span>', 'gateway' ),
the_title( '<span class="screen-reader-text">"', '"</span>', false )
) );
?>
</div>
In my reading settings I have set "For each article in a feed, show" to "summary".
So I guess my question is this: Is there a away to limit the_content() or alternatively add a read more to the_excerpt()? | I couldn't get this resolved with the_content() so i went simple and this works:
the_excerpt();
echo '<a href="' . esc_url( get_the_permalink() ) . '"> more...</a>'; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "the content"
} |
Separate header for static home page and posts page
My custom headers are located in the folder `/parts/header/` and header selection is controlled using theme panel, so I tried write like this in my `header.php` but came out blank header in static front page, please advice.
if (is_front_page() ) {
get_header( '/parts/header/header-style-11.php' );
} else {
/*
* loads the header template set in Theme Panel -> Header area
* the template files are located in ../parts/header
*/
td_api_header_style::_helper_show_header();
do_action('td_wp_booster_after_header'); //used by unique articles
} | You don't specify a path in `get_header()`, but rather a name. So for example:
get_header( 'home' );
This will load `header-home.php` from the main theme directory. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "customization, headers"
} |
do_shortcode for is_page(slug)
iam new with php and wordpress. i try to implement a shortcode which should only work for a specific slug for my website. all other sites should do another shortcode.
i tryed this:
<?php
if( is_page( ( 'azubi');
<?php echo do_shortcode( '[contact-form-7 id="274" title="Bewerbungsformular_beruf" ]' ); ?>
else
<?php echo do_shortcode( '[contact-form-7 id="2741" title="Bewerbungsformular_berufe" ]' ); ?>
<?phpendif ?>
but with this i got an error. i thin php syntax is wrong? works this solution for that i want to have?
best regards tom | In this line `if( is_page( ( 'azubi');` you start but not end the round bracket ["(" OR ")"] and not used semicolon after the if condition used colon like `if( is_page('azubi')):`
<?php
if( is_page('azubi')):
echo do_shortcode( '[contact-form-7 id="274" title="Bewerbungsformular_beruf" ]' );
else:
echo do_shortcode( '[contact-form-7 id="2741" title="Bewerbungsformular_berufe" ]' );
endif;
?>
Check this : <
Enter correct page name.
if( is_page('About Us')):
echo do_shortcode('[contact-form-7 id="263" title="Contact form 1"]');
else:
echo do_shortcode('[contact-form-7 id="264" title="Contact form 1_copy"]');
endif; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "shortcode"
} |
Add pagination to search.php page
When I want to use the_posts_pagination() in my search.php page and I click "2" or "3", it goes on 404 page (this link: mywebsite/page/2/?s=a). How can I add pagination for search.php page?
**SOLVED**
It didn't work because of the query_posts() inside search.php . | Sometimes pagination will break and give unexpected results, redirect you to the wrong page or give you a 404 (page not found) on the "paged" pages. This is usually due to your theme altering (querying) the main loop wrong.
Try updating your .htaccess file by updating the permalink. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "pages, pagination, search, 404 error, links"
} |
remove_query_arg on options.php
I have a normal WordPress settings page. It POSTs to options.php.
In options.php it uses wp_get_referer to redirect back to the page it came from.
I need to use remove_query_arg to remove an argument from the URL. Example:
I need to remove the tab=90 part. How can I do this via options.php? | Ended up using jQuery to do this. There might be a better way, but this works:
jQuery("input[name=_wp_http_referer]").val('admin.php?page=plugin_settings_page') | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp admin, settings api"
} |
undesrtanding get_post_meta function
Is there any way to avoid that when you don’t specify a $key ('') and set $single to true in get_post_meta, it returns all keys still with an array of values, instead of returning a single value only .
$meta = get_post_meta(get_the_ID(), '', true);
print_r($meta);
//This is giving me:
//Array ( [key_1] => Array ( [0] => value_1 ), [key_2] => Array ( [0] => value_2 ) )
//And I will expect:
//Array ( [key_1] => value_1, [key_2] => value_2 )
I know that I can access the data writing array[key_1][0], but I don't understand why, considering that I'm declaring $single as TRUE.
I might be missing something... | `get_post_meta()` calls get_metadata(), the parameter description of which says:
> $single (bool) (Optional) If true, return only the first value of the specified meta_key. This parameter has no effect if meta_key is not specified.
>
> Default value: false
So, since you are passing `''` as the meta_key, the `$single` parameter is ignored.
Does that explain it?
**Edit:**
If you only want the 1st value for each meta key, then just do the following:
array_map ('array_shift', get_post_meta (get_the_ID (), '')) ; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "post meta"
} |
How to add specific meta tags to head of cart and checkout pages in woocommerce?
I am trying to insert this meta information into the cart and checkout page for woocommerce. It will hide a specific plugin on those pages. However i know if i edit the plugin files for woocommerce it will be overwritten on woocommerce update.
How would i do that correctly? Jquery? Or even function.php function?
if (wc_get_page_id( 'cart' ) == get_the_ID()) {
<meta name="yo:active" content="false">
}
or
if !is_page(array('cart', 'checkout')) {
$('#yoHolder').attr("style", "display: none !important");
}
i tried this too to achieve same outcome of hiding it but didnt work.
Thanks for any help! | If your goal is to put it in the `<head>IM INSIDE THE HEAD</head>` tag than just put it inside the head tag in the `theme_header.php` or `header.php` of your theme – if it's not a child theme.
Place this snippet of code directly above the closing `</head>` tag in your header.php file.
<?php
if ( is_checkout() || is_cart() ) {
// Add meta tag here
echo '<meta name="yo:active" content="false">';
}
?>
Should work fine for you. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "php, custom field, javascript, woocommerce offtopic"
} |
What does the raw value for the get_bloginfo's filter argument exactly do?
The `$filter` argument for the `get_bloginfo` function has a default value of `raw` but WordPress' Code Reference didn't mention another allowed values. What this `raw` stands for and what are other possible values if any? | We have the following filters added by default (source)
add_filter( 'bloginfo', 'wptexturize' );
add_filter( 'bloginfo', 'convert_chars' );
add_filter( 'bloginfo', 'esc_html' );
The `bloginfo` filter (source) is applied on the `get_bloginfo()` output, in the `display` mode, except for the _url_ that has it's own `bloginfo_url` filter. The core isn't using that _url_ filter currently and there's a _wontfix_ (see #26803) on escaping the _url_ in display mode.
So the _raw_ mode, skips these filters.
The `bloginfo()` function is a wrapper for `get_bloginfo()` in display mode (source). | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 5,
"tags": "codex"
} |
Theme customizer not working
I am trying to add theme support for custom background using the following code in functions.php file:
function supp_custom_bg() {
$defaults = array(
'default-color' => '',
'default-image' => '',
'wp-head-callback' => '_custom_background_cb',
'admin-head-callback' => '',
'admin-preview-callback' => ''
);
add_theme_support( 'custom-background', $defaults );
}
add_action( 'after_setup_theme', 'supp_custom_bg', 20 );
and the options now are activated in the customizer but no effect on the theme.
Note: The `wp_head` is added to the `<head>` tag | The simplest way to use this feature:
1. Add `add_theme_support( 'custom-background' );` to `functions.php`
2. Use `body_class()` in your `body` tag like this: `<body <?php body_class(); ?>>`
3. use `<?php wp_head(); ?>` in your `head` tag
if you go to the customizer should look like this:

Add `<?php wp_footer(); ?>` to the theme usually in `footer.php` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme customizer"
} |
wordpress post status inquery
I am working on a local server to create wordpress website. I check in database every post which i made after publish its create 2 post in database. One with Inherit post status second with publish status and both have different post ID's.
I need to know its some kind of wordpress function or my mistake. and what is the benefit of Inherit post.
**How to solve it to make only publish post?** | That is called as Revision in Wordpress.
Whenever you update your post, the older content of that post is treated as Revision and a new record for revision is inserted in posts table.
And we can check our revisions from Revision meta box.
More detail : <
For - How to solve it to make only publish post?
You can define the number of revision you want to create and also can disable revision for wp posts by adding below lines in wp-config.php
`define( 'WP_POST_REVISIONS', 3 );` // max 3 revision will be stored.
`define( 'WP_POST_REVISIONS', false );` // disable revision system | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "post status"
} |
background changed after Wordpress update
I recently updated Wordpress, and it seems to have affected the background images on my site. I had them set to take up the whole screen, but now they show up in their actual size (which is too small to cover the screen). The css code seems intact, so I don't know how to fix this. Example: see the background image in the upper left corner of this page. It used to cover the entire background. < And here is the code:
body.page-id-2 { background-image:url(< !important; background-repeat:no-repeat; background-attachment:fixed; } | What version did you update to? The following has only been tested in 4.7.3 (and I never use custom backgrounds in the customizer, so I'm not sure what previous version of WP did there).
In the customizer, when you set the custom background image, there should be an "Image Size" dropdown. You probably have "Original Size" selected in this dropdown. If you change that to either "Fit to Screen" or "Full Screen" you should get what you want.
Which one you choose depends on what you want to achieve. "Fit to Screen" results in the customizer outputing `background-size: contain ;`, while "Full Screen" results in `background-size: cover ;`.
See CSS background-size Property for the difference between `contain` and `cover`. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "css, updates, custom background"
} |
Prevent threading in emails from gravity forms
I'm hosting a WP site using gravity forms for a medical clinic. I'm hoping to add a unique ID of some sort (A timestamp would be enough) to the subject line of emails sent from gravity forms. Occasionally, emails sent from the site can become threaded where replying to one thread will include messages from previous form submissions. Obviously this is not acceptable in a medical context. I can't find any fields or plugins that support this. | You can actually utilize Gravity Forms merge tags in the subject line to do what you're asking.
1. Head to the notification settings for your specific form
2. Click on the admin notification for your form (the one that's sending you the emails)
3. On the subject line field, note the icon at the right of the field, you can click on that to access all the fields from that specific form including date (the date of the form submission).
4. Enter `{date_mdy}` for the date to make it unique for your subject lines.
` through the `sanitize_title` filter at priority 10 (source), so you can replace it with a dash, just before with:
add_filter( 'sanitize_title', function( $title )
{
return str_replace( "'", "-", $title );
}, 9 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "permalinks"
} |
difference between $wp_the_query and $wp_query? & getting the values properly
i have seen `$wp_query` and `$wp_the_query` in many plugins and themes. for me these two are just same thing with no difference. i am not looking to either use or get the values from $GLOBALS.
what is the actual difference between these two objects and when to use them? What is the proper action /filter hook for getting and reading values from `$wp_query` and `$wp_the_query`. | You should read in this answer it explains it in depth.
in short,
* `$wp_query` is the variable that holds a copy of `$wp_the_query` global query that could/can be modified by plugins and themes
* `$wp_the_query` is the variable that holds an unmodified copy of the global query object and used to reset the `$wp_query` object when we call wp_reset_query()
I think you now understand as to why it makes sense to have both available to us. | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 3,
"tags": "wp query"
} |
How can I insert a shortcode in the title tag of another?
//Shortcode which return a name
[get_name]
//A heading of the theme. I need text + shortcode in title=""
[dt_fancy_title title="My name: [get_name]"]
//I tried this but it doesn´t work
[dt_fancy_title title="My name: "][get_name][/dt_fancy_title]
I use many headings or other widgets with different titles. The text is different in every title. | No, you can't do that, as the title argument is passed as a string.
Given the information you provided, I suppose that your `[dt_fancy_title]` shortcode does not actually execute shortcodes.
The syntax for this function should be:
function dt_fancy_title_callback( $params, $content = null ) {
// extract the title argument from the params, setting default value
extract( shortcode_atts( array(
'title' => 'default title'
), $params ) );
// execute your function, whatever it does
// call for shortcodes to be executed within your shortcode
$content = do_shortcode( $content );
// return the content
return $content;
}
add_shortcode( 'dt_fancy_title', 'dt_fancy_title_callback' );
If you do not call the `do_shortcode()` in your callback function, the shortcode texts inside will be interpreted as a string. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "shortcode, title"
} |
Wordpress Plugins vs Traditional PHP membership website
I want to create membership website, as a form of passive income and also a way of improving my skills (I'm a UI/UX designer and front-end developer).
The problem is that in theory, I would like it to grow to an almost 6 figure income per year and I don't have experience making these type of "complex" websites. My main fear is the website security.
I'm good at Wordpress, well to some extent, but I can't write complex PHP websites with all those login and membership systems.
So, in terms of security, would it be better to use an already written Wordpress membership plugin (s2member for example) or take the time and learn how to build a more or less secure system in pure PHP myself? | Even if you're skilled in "complex PHP websites" it's safer to go with something that's already built. If you code it yourself you're very likely to overlook security issues and you'd have to constantly be updating it. It's worth investing a bit of money in plugins up front (if necessary; you may well do fine with free plugins, just do lots of research up front to see how well supported the plugins are, how many active installs, all that type of plugin vetting you should do in any case) so you don't have headaches down the road. And if you're expecting triple-digit income please be sure to find solid managed WP hosting, your own VPS or something similar, so that if things go south you have someone to help immediately. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "membership, s2member"
} |
Can't delete the default jQuery in the theme
In my theme, jQuery is loaded in the header by default. I even dequed it in my `functions.php` but still in the header I have the jquery :
function remove_jquery_migrate( &$scripts){
if(!is_admin()){
$scripts->remove( 'jquery');
$scripts->add( 'jquery', false, array( 'jquery-core' ), '1.2.1' );
}
}
add_filter( 'wp_default_scripts', 'remove_jquery_migrate' );
function wpdocs_dequeue_script() {
wp_dequeue_script( 'jquery' );
}
add_action( 'wp_print_scripts', 'wpdocs_dequeue_script', 100 );
but this is printed in the header:
<script type='text/javascript' src='...wp-includes/js/jquery/jquery.js?ver=1.12.4'></script>
I don't know if a plugin is causing this but I want to remove this as I am already loading the jquery using Google CDN in the footer. | An example on how to deregister a WordPress built-in library and load your own:
function load_custom_scripts() {
wp_deregister_script( 'jquery' );
wp_register_script('jquery', '//code.jquery.com/jquery-2.2.4.min.js', array(), '2.2.4', true); // true will place script in the footer
wp_enqueue_script( 'jquery' );
}
if(!is_admin()) {
add_action('wp_enqueue_scripts', 'load_custom_scripts', 99);
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "jquery, wp enqueue script"
} |
How to Escape Custom Meta Data And Prefix Custom Meta ID
Here is a code snippet where I tried to retrieve a custom meta data from a custom post type.
$p_client_link = get_post_meta( $post->ID, 'client_link', true );
<a href="<?php echo esc_url( $p_client_link); ?>"><?php the_post_thumbnail( 'client_logo' ); ?></a>
My queries are:
1. Q. esc_url( $p_client_link); == right/wrong? esc_url() or esc_attr()?
2. Q. custom meta id client_link. Is it necessary to add prefix with this custom meta id like ‘p_client_link’?
3. Q. Is it right to use esc_url() for any ‘href’ attribute value?
N. B. I have been developing a one page WordPress theme for themeforest submission.
Thanks in advance. :) | 1. esc_url() - The correct option. He will prepare a string for use in attributes. Doc: <
2. Adding a prefix is correct. You will secure your variables from overriding with other plug-ins.
3. yes | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "customization"
} |
add_rewrite_rule no longer working - possible https issue?
I have a redirect rule that is intended to load a custom template file. This worked last week, and is now not working (and loads a 404 page instead). The only change to the site is the entire site is now loaded on https instead of http.
Here is the function:
function event_rewrite() {
add_rewrite_rule('^event/(.*)/?', 'index.php?pagename=event&event_name=$matches[1]', 'top');
}
add_action('init', 'event_rewrite');
Is there anything in the matching that would change with https in the url? Or is there a different problem going on that coincidentally arose when we switched to https? | This _might_ be a permalink issue. Sometimes when things like HTTPS get turned on, you need to flush permalinks to get URL's and rewrites working again.
Head to permalinks (settings > permalinks) and just hit the save button and see if that fixes the issue there. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "page template, rewrite rules"
} |
Is it necessary to prefix every css class in a theme framework?
I'm working on a theme framework, prefix everything include css classes, so 'main-content' is 'framework-main-content', 'header' is 'framework-header', etc.
Recently I took a look at the famous framework Genesis, and I see no prefix for css classes at all, the HTML markup so that looks clean and also the CSS code.
It is no doubt we should prefix everything in PHP code, but is it necessary for css classes of a theme or theme framework? | Prefixes are used to avoid conflicts. If your framework is used to build a theme, the chances are high that there isn't a second theme framework in use at the same time. So there is no conflict, and therefore no need for a prefix.
The exception are CSS classes generated by the WordPress core, for example in the comment form. If you are using the same class names for an entirely different purpose, you need a prefix, or better class names for your use case. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "theme development, css"
} |
Widget outputting JS as plain text
I have made a custom widget that works in a shortcode but when i go to use it as a widget the javascript involved in the output is shown as plain text.
How do i make a widget output javascript as javascript not plain text? | Did you try to put propper `<script>`tags around your code?
So instead of inserting the raw JS code, I suppose you encapsule the code it like this:
<script>
// JS goes here
</script>
This at least works with the common `text` widget. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "widgets, javascript"
} |
Nav menu category links not showing
I am new to wordpress and have a project where I have show nav menu category links like this:
<?php wp_nav_menu(array('theme_location' => 'primary', 'menu_class' => 'menu right'));
After adding a new category in the admin, the new category link is not showing in the menu. What should I do about that? | A `wp_nav_menu` is a manually created menu - WordPress doesn't create it for you. If you want to keep using this function, you can go to either Appearance > Menus or Appearance > Customize > Menus, add links to the menu, and check the "primary" theme location under Display Location.
However - if you're just wanting to show category links, it's better to use one of the built-in options so that you don't have to manually add each category and keep them updated.
Option 1: create a sidebar and use the built-in "Categories" widget.
Option 2: pure code:
<?php
$args = array(
'orderby' => 'name',
'parent' => 0
);
$categories = get_categories( $args );
foreach ( $categories as $category ) {
echo '<a href="' . get_category_link( $category->term_id ) . '">' . $category->name . '</a><br/>';
}
?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "categories, menus"
} |
Switching Theme and back will reset the previous Theme's settings?
Everyone,
I have a Wordpress site on my hands, and I wanted to try a new Theme; I changed the active one and, unsatisfied, I selected again the previous one... and I found the website's appearance to be changed.
Is there a safe way to restore the site's appearance or are the settings lost and I need to recreate them? | Depending on the theme this could happen. It's not great coding, however I have seen that happen. Did you restore to the exact theme though or did you make changes (even a name change will cause reverting to defaults)?
**It may be as easy as once you go activate the original theme, go into it's settings page and click save.**
Some themes in their setup section will have a back up and restore option. If you previously backed up the settings you can restore them there.
If you don't have any of the theme backed up, you can always do an actual database restoration from before the switch and this will revert the changes back to their working state. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "themes, switch theme"
} |
how to delete 30 day old data using PHP
I am mysql beginner, how to delete 30 day old data using php?
This code is not working?
global $wpdb;
$table = $wpdb->prefix . "userinfo";
$delete_rows ="DELETE * FROM $table WHERE timeall <".strtotime('-1 month');
$wpdb->query($table, $delete_rows);
my data photo 1 ,INTERVAL 30 DAY)"
);
`$wpdb->prefix` adds the `wp_` for you. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "php, wpdb, sql"
} |
Add custom attribute to menu item link using Filter
In order to increase my theme's accessibility, I want to add the `aria-current="page"` attribute to the menu item that has the class `.current_page_item`.
As of right now, I am doing this via jQuery using the following:
var currentitem = $( '.current_page_item > a' );
currentitem.attr( 'aria-current', 'page' );
While this does what I want it to do, I would prefer that PHP handles this particular thing.
I know I can do this either with a custom Nav Walker class or with a filter to `nav_menu_link_attributes`. Unfortunately I have not seen any code even remotely near what I want to do.
function my_menu_filter( $atts, $item, $args, $depth ) {
// Select the li.current_page_item element
// Add `aria-current="page"` to child a element
}
add_filet( 'nav_menu_link_attributes', 'my_menu_filter', 10, 3 );
Any help in writing this filter would be appreciated. | You may target the `current_page_item` CSS class or you may target the `current-menu-item` CSS class instead. `current_page_item` class may not be present for all kinds of menu item. Read the answer here to know why.
Whichever CSS class you choose, you may use the CODE like the following to set the attribute:
add_filter( 'nav_menu_link_attributes', 'wpse260933_menu_atts_filter', 10, 3 );
function wpse260933_menu_atts_filter( $atts, $item, $args ) {
if( in_array( 'current-menu-item', $item->classes ) ) {
$atts['aria-current'] = 'page';
}
return $atts;
} | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 5,
"tags": "menus, accessibility"
} |
Speed of the slider images should be increased in wordpress
Iam using **Enlightenment** theme of wordpress, i have added Sliders to my wordpress site by creating a new page in the admin page,
.
The enlightment theme uses a slider called "flexslider". To alter the speed you can go into the flexslider javascript-file and change the slideshowSpeed parameter.
In your theme folder, navigate to the file "jquery.flexslider.js". It is located at "enlightment > core > js". Open the file in a text editor and on line 1073 you'll find the default settings for the slideshow speed:
> slideshowSpeed: 7000, //Integer: Set the speed of the slideshow cycling, in milliseconds
Changing this value should allow you to set your own speed. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "images, homepage"
} |
Suddenly forbidden 403 error on some pages
Suddenly my Wordpress installation is giving 403 error on only some (two) pages. Disabled all plugins (1) and renamed httaccess but error is still there.
Pages was working fine two days ago. Pages a basic articles without custom template.
Any help? | Please check the permissions of files and folders. All folders should have permission set to `755` and files should have `644` . If permissions are different than specified, please try changing the permissions.
You can easily check and change permissions using filezilla.
Let me know if it helps. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "pages, errors"
} |
How to configure PoEdit to pick up translation string?
I need to localise Flash theme, but don't know how to configure PoEdit to pick up such string.
Tried: _nx:1,4c (but this picks up only Reply to ..) but does not find Thoughts on ..
printf( /* translators: 1: number of comments, 2: post title */
_nx(
'%1$s Reply to “%2$s”',
'%1$s Thoughts on “%2$s”',
$comments_number,
'comments title',
'flash'
),
number_format_i18n( $comments_number ),
get_the_title()
);
Thanks! | It should be `_nx:4c,1,2`. There is BTW a nice repository at github for this kind of problems that has a complete keywords list: Blank-WordPress.pot | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "themes, localization"
} |
I can't get blog posts into 'featured areas' on homepage
Forgive the newbie question but i'm starting up a new blog using wordpress and, having installed a template and begun the very initial steps of setting it up, i've got an issue with not being able to configure the 'featured areas' on the homepage to be able to pull in the blog posts.
The URL is <
Have played around and tried to configure this way but not been able to get it to work. Ideally i'd have the most three recent posts in the featured areas and then potentially a couple more below them.
Any tip would be appreciated as i get to grips with configuring WP. | I note you are using the **Minamaze** theme, correct? The problem here is the featured area, is exactly that, an area to manually enter featured content. You cannot automatically add posts to these areas.
To configure them, you need to go into the admin, choose appearance, then customize.
In here, choose Theme Options, then Homepage (Featured) and this will open the section to edit the content of the three areas. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins"
} |
Update my custom WordPress Plugin through my own server
I am working on a WordPress plugin that will be accessible only to a group of a few selected website owners. I have installed my plugin to those sites already. There is active development going on for this plugin. And we need to upload changes to all the sites. Manually uploading the changes in all sites will be a tedious process. So I would prefer to upload changes to all of those websites at the same time.
How is this possible with WordPress? | Yes you can. Check this Repo
<
This is a custom update checker library for WordPress plugins and themes. It lets you add automatic update notifications and one-click upgrades to your WP Plugin. All you need to do is put your plugin/theme details in a JSON file, place the file on your server, and pass the URL to the library. The library periodically checks the URL to see if there's a new version available and displays an update notification to the user if necessary.
You can either manage your update/source code on your own server or you can store them on BitBucket or Github
From the users' perspective, it works just like with plugins and themes hosted on WordPress Repo | stackexchange-wordpress | {
"answer_score": 13,
"question_score": 10,
"tags": "plugins, plugin development"
} |
Set plugin-values when creating post via REST-API
I'm using the wordpress REST-API to create posts via a mobile app (currently testing with postman). To publish my posts to Facebook I'm using the plugin "Facebook Auto Publish" (FBAP) (similar to "Social Media Auto Publish", both from xyzscripts.com)
How can I set the value to publish to Facebook?
In current state every created post is published to Facebook, but I want to have some posts to be published and some only to be created but not published to Facebook.
I've also tried setting different categories for this and only select one category in FBAP. But the post is published, regardless which category I've set.
Anyone knows how to handle this? | I've found the problem, why it's not working with the categories. I don't know why, but when creating a post over the API, the post is published before the category is correctly set.
Now, I'm creating drafts (already with correct category). With a second PUT-Request I set the status to "publish" and publish my posts. Now the category is correctly set and only the expected posts are published to Facebook. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugins, api, facebook, rest api"
} |
What is required in the hosting environment for WordPress to process an image into multiple sizes?
I'm looking for source documentation on what hosting environment prerequisites there are for the hosting environment so that WordPress can process images into multiple sizes.
All the libraries necessary to process images in the way WordPress does are not included in the PHP core of WordPress itself. I'm looking for a list of what additional libraries on which WordPress relies. | WordPress uses Imagemagick for image processing if it's available and falls back to php-gd if it's available. If neither are available, then no image processing is done.
Have a browse through the source code:
* class-wp-image-editor-gd.php
* class-wp-image-editor-imagick.php
* class-wp-image-editor.php | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "images, hosting"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.