INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
action future_post returns wrong date
Hi I am using a `future_post` hook to capture when a scheduled post is updated like so :
add_action('future_post', 'on_post_scheduled');
Then I want to send the new post date to a database, however `$post->post_date` returns the date prior to updating the post. I have to update the post again to get the correct new date.
Within the `on_post_scheduled` function I am using the `global $post` to access the post date, is this the cause? | function on_post_scheduled( $post_id, $post ) {
// If this is just a revision, don't do anything.
if ( wp_is_post_revision( $post_id ) )
return;
// If this is a 'post' post and post status is future.
if ( ('post' == $post->post_type) && ('future' == $post->post_status)) {
// do the thing zhu li!
wp_die('<pre>'.print_r($post,true).'</pre>');
}
}
add_action( 'save_post', 'on_post_scheduled', 10, 2 );
it's best to add action on save_post like this... and just check the post type and post status... | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "actions"
} |
How to Customize the category list page
i use evolve theme for my site. here is the screenshot of category list
!enter image description here
the page display the raw code of the page content which contains a gallery.
How can i customize the category display? | WordPress determines which template file to use from its Template Hierarchy. It might be further customized by extensions and themes might be using different files for same things, depending on what they do.
There are helper plugins for simpler cases (for example What The File), but it might require involved debug with more complex themes. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "categories"
} |
Dynamically send pdf attached to post with contact form 7
I'm trying to send a dynamic pdf that is attached to a post via the plugin contact form 7.
I assume I need to use the hook:
add_action('wpcf7_before_send_mail','send_pdf');
As it's been the hook I've seen used most commonly when looking for a solution.
Here's what I have, I've just been trying with a test pdf with an absolute url first:
function send_pdf( $cf7 ) {
if ($cf7->id==741){
$cf7->uploaded_files = array ( 'pdf' => get_template_directory().'/test.pdf' );
}
}
Now if I understand this correctly, if the contact form id is correct, and I have `[pdf]` in the mail2 "file attachment" field, then that pdf should send via email to the person who has submitted their details?
For me though this isn't working, I get the email but with no attachment.
Is there something I'm missing here or perhaps know of another method that works? | Try this instead. There was some internal restructuring in CF7 3.9.
`add_action('wpcf7_before_send_mail','send_pdf');`
function send_pdf( $cf7 ) {
$id = $cf7->id();
if ($id==741){
$submission = WPCF7_Submission::get_instance();
$submission->add_uploaded_file('pdf', get_template_directory().'/test.pdf');
}
}
This should work. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 1,
"tags": "email, plugin contact form 7"
} |
Dynamically populate Cascading Dropdown from MySQL using JQuery/AJAX
What I'd like to achieve is managing tables in the front-end of a WordPress page the same way as MS Access does. So, I'd like to show dependent cascading dropdown which are related by foreign key and then click on some buttons for executing my insert/update query.
I honestly find it very strange that there is nothing out there (not even a premium plugin) for doing such operations since they are really useful and used by nearly every business. | You might want to take a look at CRED plugin and see if it gets you anywhere near what you need. I've worked with it back when it was three different plugins (Types, Views and Access).
For as much as I can remember they used to keep a testing environment where you could take plugins for a spin in a clean site on their server before you bought it, you should ask them about that. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "jquery, ajax, mysql, front end, dropdown"
} |
How to access $wp_query object from array of posts given by get_posts?
I have a simple custom query driven by `get_posts`:
<ul>
<?php
$args = array('post_type' => 'event', 'numberposts' => 6 );
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post);
echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
endforeach;
wp_reset_postdata();
?>
</ul>
However, there's a need to access this custom loop's query object - the one which is accessible by default if you do custom loops using `new WP_Query` method. (This is needed to get connected posts of other CPTs, mechanism driven by the excellent Posts2Posts plugin's `each_connected`.) Is it possible to get to the query object from `get_posts`? Or the only way to do this is to remake the loop in the `new WP_Query` style? | You can filter any WP query using `pre_get_posts()`. The (sometimes) tricky part is that it is run against all queries of WP so you need to pinpoint your query using WP conditionals (`is_admin()`, `is_page()`, `is_archive()`, etc... ).
You'll find a few useful examples on that page, too. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query, loop, get posts"
} |
How to customize the_archive_title()?
In my child theme's `archive.php`, I have the following code for displaying the title of my archive pages:
<?php
the_archive_title( '<h1 class="page-title">', '</h1>' );
?>
But that displays my titles as "Category: _Category Title_ " instead of simply the title without the prepended "Category: ".
My first instinct was to override `get_the_archive_title()` from `wp-includes/general-template`. But from what I've read, apparently I'm not supposed to ever alter wordpress core stuff, even with overrides from a child theme.
So what is the best-practice way to control the output of `the_archive_title()`? | If you look at the source code of `get_the_archive_title()`, you will see that there is a filter supplied, called `get_the_archive_title`, through which you can filter the output from the function.
You can use the following to change the output on a category page
add_filter( 'get_the_archive_title', function ( $title ) {
if( is_category() ) {
$title = single_cat_title( '', false );
}
return $title;
}); | stackexchange-wordpress | {
"answer_score": 52,
"question_score": 49,
"tags": "functions, child theme"
} |
Categories list into registration form
I'm trying to create a custom user registration form used for Educational website.
Is it possible to automatically retrieve categories of posts (custom posts) in the registration form.
The form should be:
username : password : first name: last name :
optional
(category list) (courses list)
if user choose it will automatically show related sub-categories example:
(course1)
\- (sub-course-1)
\- (lesson 1)
\- (lesson 2)
\- (sub-course-2)
\- (lesson 1)
\- (lesson 2)
Is there a way to do such thing into registration form? | The best way to add extra fields to the wordpress user registration form that I know of is to use the related registration form filters:
1. register_form \- This is used to add your fields to the registration form
2. registration_errors \- This is used to validate your fields
3. user_register \- This is used to add your custom user_meta data to the system
4. and maybe register_post \- This can be used to do other things pre-validation | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "posts, categories, custom field, user registration"
} |
wordpress multisite, https for whole site or just admin?
I have a wp multiste with a subdomain structure and a wildcard SSL cert. My multiste has enabled registration for anyone t create a site.
I know how to do both:
1\. just the admin to have have https
or
2\. https everywhere (frontend and admin).
I'm not sure what one to choose.
Wordpress.com have https everywhere on all their users sites, and to my knowledge google announced in 2014 they give an improved ranking for sites that use https. Seems good reasons to have https everywhere.
But of course https, may slow the website down.
So is there much benefit to have https everywhere.
Also why would you have https on the frontend? Usually you only need it when users fill in forms/giving away personal details where security is needed. What benefit would there be in having https everywhere.
Thanks in advance | Once you have https for admin users you need to have https on the front end as wellat least for the logged-in users as their authentication cookies will be sent in clear text when they access the front end and 3rd parties will be able to duplicate them and use them to get into the admin area for that user.
This do not require https everywhere but it is just the mentally easier option, and you don't need to worry about some bug in some badly coded plugin or theme exposing your user's cookies. For the option of SSL only for logged in users take a look at < couldn't find anything more recent so you should use it as starting point for investigation. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "multisite, https"
} |
Why are no posts showing despite my apparently correct DB restoration?
I restored a backup to MySQL using the phpMyAdmin Import feature. When I browse the DB in phpMyAdmin, I see that my posts are there. But in Wordpress, I only see the default out-of-the-box welcome post. Even the WordPress admin shows no signs of the info in the database. (I checked that this is the correct database.)
How can I fix this? | Check all credentials in `wp-config.php`. And don't forget about table prefix. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "database, wp admin, mysql, backup"
} |
How to hide sidebar widgets in all pages except Hompage?
im using a sidebar widget in homepage for an extra gallery. sadly it appears in every pages ._. thanks in advance | Simple, quick option: use a plugin called "dynamic widgets"; it provides an interface the where you can specify the conditions under which each of your widgets should appear.
Slightly more involved option is to edit your theme, so that it has two sidebars, both registered as widget areas, and include one of them only on the `front-page.php` (if you have a static front page), or `home.php` (if you have a blogfeed front page). | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "widgets, sidebar"
} |
How to get all possible arguments for a wordpress function
I'm trying to get all arguments for function `get_the_author_meta()` or `the_author_meta()` because I have custom profile fields such as "parent name" and so, not only the normal arguments which is in Function_Reference/the_author_meta
I tried php `func_get_args()` but I can't make it work
any suggestions ? | I think you are confusing function arguments with author (user) meta fields. To get all user meta fields you can use `get_user_meta()` with empty `$key` parameter. For example, for user with ID 45:
$user_meta = get_user_meta( 45 );
`$user_meta` will be an array with all meta fields for the user with ID = 45. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "author, profiles"
} |
Merge custom plugins in one folder
I've made some plugins to print some text with php from the database. I use them in pages via shortcodes. If I put all the code in only one folder, so just one plugin, only one shortcode works,the one in the file with the same name of the plugin. How can I put all files in only one folder and have all shortcodes working? | Choose one file to be the main file of the plugin. From it, use
require_once( plugin_dir_path( __FILE__ ) . 'another-file.php' );
for each of the other files you want to include.
This means the rest of the files no longer need the plugin comment header, just the actual code that does whatever you need it to. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, plugin development"
} |
Is it still only possible to do multisite domain mapping with a plugin in WordPress 4.1?
If I have a multisite subdomain install e.g. `mysite.co.uk` and I want to map another domain e.g. `mysite2.co.uk` to a new site in the same multisite install, is this only possible using a plugin or manually editing the database? When adding a new site to the network I only have the option to add `subdomain.mysite.co.uk`
This old question is relevant but I'm wondering if there have been more recent developments. | The short answer is yes. But it seems that the WordPress team are moving toward encouraging the creation of networks of sites rather than simply using Multisite. I watched this video:
<
Which gives a good insight into creating a Network of sites. Each Network can have a different domain.
I'm therefore going to install WP Multi Network
A slightly longer answer is yes and no. Once you have created a new site in a subdomain (in my use case) you can then go and edit the site and change the domain completely. Checkout the video for more details on what is going under the hood in the `wp_site`, `wp_blogs` and `wp_sitemeta` tables | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 3,
"tags": "multisite, domain mapping"
} |
How to create plugin list groups?
How do I create more of these? !enter image description here
so that i can create proper plugins categories in the network plugin dashboard of wordpress. | solved with the plugin: "plugin categories" .
Edited to explain how it works:
there are no hooks for the screenshot I posted, therefore the only solution is to offer a way to store categories relations into the database.
The plugin uses options table to store the data, ad saves through ajax.
Hooks into the columns display of the plugin page and offers an action link to edit the categories.
I added a bulk action to append categories to a group of plugins through default wordpress checkboxes.
To display only plugins belonging to different categories the plugin filters the view-all table eliminating the excluded ones. | stackexchange-wordpress | {
"answer_score": -2,
"question_score": 0,
"tags": "plugins, admin, dashboard, lists"
} |
How to replace URL protocol using PHP?
I'm using HTTPS everywhere in my website but I have problems with sharing buttons for Pinterest and Tumblr. For example, when I try to share image on Pinterest I get this error: "Sorry we could not fetch the image."
To make it work, I think I need to change image source URL protocols to HTTP only for my sharing buttons.
This is how I get thumbnail source:
$share_image_src = wp_get_attachment_image_src( get_post_thumbnail_id(), 'large' );
I need to change this: ** www.example.com/wp-content/uploads/example-image.jpg
to this: ** www.example.com/wp-content/uploads/example-image.jpg | Simply use `set_url_scheme()` function.
$share_image_src = wp_get_attachment_image_src( get_post_thumbnail_id(), 'large' );
$share_image_src = set_url_scheme( $share_image_src, 'http' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, post thumbnails, social sharing"
} |
Generate thumbnails like 500px.com
I tried but couldn't get thumbnails like these, in wordpress. Please check this url <
If you notice, there is no cropping. Its just zoomed-out or whatever you call it. Tumblr also uses such technique of thumbnails. The image is shown full but in small size. Width is custom, say 300px and the height of thumbnail is variable, so the thumbnail does not look awkward.
What I did, unchecked the Crop checkbox in Media settings and set dimensions for thumbnail but it wasn't generating the same as on the 500px site.
Any idea or suggestions? | I have gotten something similar working in WordPress by incorporating the Masonry script (or isotope if you want filtering)
Here they are:
masonry -> <
isotope -> <
I am assuming you are comfortable with javascript and jQuery so I won't tell you how to use it (the site has tutorials if you get stuck) - but getting it to work in wordpress is just a matter of enqueueing and targeting correctly - though to get it to work with featured images for posts would take a little bit more work.
Hope this is helpful. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "thumbnails"
} |
get_page_by_title() doesn't retrieve my post
I have a CPT called "patchwork" and I created a post of this type entitled "Patchwork 01". The following code should retrieve this post, but it doesn't.
$patchwork = get_page_by_title( 'Patchwork 01', 'patchwork' );
echo $patchwork->ID;
What's the problem? | The second parameter for `get_page_by_title()` is `$output`, with the third being `$post_type`.
This should solve your porblem -
$patchwork = get_page_by_title( 'Patchwork 01', OBJECT, 'patchwork' );
echo $patchwork->ID;
Please have a look at the Function Reference for `get_page_by_title()` for more information. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "custom post types"
} |
Add #anchor to next/previous_post_link
I have tried to figure out to change the `previous_post_link` by following the Codex but I can't figure it out. Same for the `next_post_link`.
I just want to have a simple link but with an `#anchor` tag added.
All I get is a changed LinkName - the url stays untouched.
I could do it with javascript, but this isn't the way I want to do it - I would like to know how to do it with WordPress tools.
Any hint would be great. | This seems to do the trick:
add_filter( 'next_post_link', 'wpse_post_link', 10, 4 );
add_filter( 'previous_post_link', 'wpse_post_link', 10, 4 );
function wpse_post_link( $output, $format, $link, $post )
{
if( $url = get_permalink( $post ) )
$output = str_replace( $url, $url . '#anchor', $output );
return $output;
}
i.e. appending the `#anchor` to the previous/next permalinks.
ps: I removed the `WP_Rewrite::using_permalink()` check, since we actually don't need it, `example.tld?p=123#anchor` should work as well. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "next post link, previous post link"
} |
Add attribute to link tag that's generated through wp_register_style?
My original question was answered here: Google Fonts giving: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Is there a way to add the data-noprefix attribute to my Google Fonts link tag?
My functions.php looks like this:
wp_register_script( 'prefixfree', get_template_directory_uri().'/js/prefixfree.min.js', array( 'jquery' ) );
wp_enqueue_script( 'prefixfree' );
wp_register_style( 'google-fonts', ' '', '', 'all' );
wp_enqueue_style( 'google-fonts' );
Answer, with the help of Birgire:
add_filter( 'style_loader_tag', 'add_noprefix_attribute', 10, 2 );
function add_noprefix_attribute($link, $handle) {
if( $handle === 'google-fonts' ) {
$link = str_replace( '/>', 'data-noprefix />', $link );
}
return $link;
} | Looking at the `WP_Style` class, we find the `style_loader_tag` filter, that might be useful.
Try for example:
add_filter( 'style_loader_tag', function( $link, $handle )
{
if( 'google-fonts' === $handle )
{
$link = str_replace( '/>', ' data-noprefix />', $link );
}
return $link;
}, 10, 2 ); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "functions, css"
} |
Same menu for different taxonomies to reach different content
I'm using a "location" taxonomy to show the same website for 4 different locations. Each of them will have the same categories which I want to display in a menu.
Is there anyway to create the same menu to show posts filtered by category but which also takes into account the current taxonomy the user is in? Can I do it directly using the wordpress panel or would I need to create a specific theme for it?
Basically, the site would have an index with 4 options, for example:
* London
* Cambridge
* Manchester
* Briton
Once the user click in any of them, a new menu will appear:
* Cars
* Tvs
* Trains
* Ships
So if I click in first in "Briton" and then in "Cars", the page should only show the posts with the category "cars" which are also inside the taxonomy "Briton". | How about creating those categories Cars, Tvs, Trains and Ships as sub categories of locations?
Then you could have a navigation menu containing parent categories i.e Briton, Manchester etc.
Once a parent category is navigated to you could have a menu that uses the get_terms() function with the `parent` argument set to the current location term ID that lists all sub categories of the current location. Something like this.
$tax = get_query_var('taxonomy' );
$current_location_id = get_term_by( 'slug', get_query_var( 'term' ), $tax );
$terms = get_terms( $tax, array(
'parent' => $current_location_id
) ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, custom taxonomy, menus, taxonomy"
} |
Where is search.php?
I've got a site on Wordpress 4.0.1, and I can't find search.php.
A database batch process has applied a template to the default search results page, but I now can't find the page to change it back.
How can I change the template of this page?
Would creating a new "search.php" in my theme help? If so, what should this file contain? | Normally, copying index.php file for the theme as search.php will let you have a new base template to work off of with the same styles and look as your theme, assuming the theme implemented index.php decently.
That would give you a solid start to be able to make changes to provided nothing is using a hook such as template_redirect to hijack the search results and use some other template to display them. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "templates, search"
} |
Custom capability for a single user
I have this complex scenario:
1) I'll have multiple admin users.
2) Only one admin can 'see_encrypted_pass'
Now, I want to assign custom 'see_encrypted_pass' capability to only one admin (say, John). I have a restricted page containing encrypted password. I want to use this on that page-
if(current_user_can('see_encrypted_pass')){
//show encrypted password
}
How do I do that? | I solved it myself :) I just added custom capability to the user-
$user = new WP_User(1); //1 is the admin ID
$user->add_cap( 'see_encrypted_pass' );
Then checked-
if(current_user_can('see_encrypted_pass')){
//encrypted password
}
It works!! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "users, capabilities"
} |
update_post_meta is Updating with two page id
I am writing a code to count the number of views of post. For that I am using update_post_meta and passing appropriate parameter.
I am calling a function on add_action('wp', 'function_name'); in functions.php.
My problem is, whenever I am loading the page in Chrome, it works fine. But when I am loading the page in Mozilla Firefox, it is updating the page view counts for two/three page's id in wp_postmeta table.
Should I use some other action hook?? If yes, which one? Can anyone tell me, what the issue is??
Thanks | It's probably Firefox prefetching pages, which it can do based on the `rel` attribute of links (see < You could alter these links to remove eg `rel="next"`, or you could detect Firefox prefetching by checking the headers sent:
if ( ! isset( $_SERVER['HTTP_X_MOZ'] ) || $_SERVER['HTTP_X_MOZ'] != 'prefetch' ) {
add_action( 'wp', 'function_name' );
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, hooks"
} |
Create a page template with No Footer
I want to create a page template that doesn't use footer. Removing `get_footer()` will not work in this case. Because my theme adds the stylesheets and scrtipts after the footer (before /body) and if I remove `get_footer()` all the scripts and styles are not loaded which will mess up css styling on the page.
I tried to create a separate file footer-none.php without footer area elements and used `get_footer(none);`. But this is not working.
Can you please help me with this?
Thanks. | The correct way to load footer-none.php is:
get_footer("none");
Anyway, I think it can be better to use `wp_footer()` (required function on any frontend page) directly in the page template file so you don't need to load any empty footer template (assuming you load all required HTML tags in the page template, for example closing body and html).
If you are going to use the custom footer template in more than one page, then it would be better to maintain a separated custom footer template. It is up to your preference. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "page template, footer"
} |
add_rewrite_rule() not working
I need to pass a property reference the last part of a URL to search the database for an entry, eg,
> <
I need to pass the G638 into an array for my plugin. What I have below is calling the cottage-details page, but removing the last part of the URL and showing an empty page, rather than the information I wish to retrieve from the server. If I use
> <
it works perfectly.
/**
* Rewrite tags for plugin
*/
function dcc_rewrite_tags() {
add_rewrite_tag('%propref%', '([^&]+)');
}
add_action('init', 'dcc_rewrite_tags', 10, 0);
/**
* Rewrite rules for plugin
*/
function dcc_rewrite_rules() {
add_rewrite_rule('^[^/]*/([^/]*)/?','index.php?p=2&propref=$matches[1]','top');
}
add_action('init', 'dcc_rewrite_rules', 10, 0);
What’s going on? | You rewrite rule is quite broad and will most likely generate a lot of conflicts.
add_action('init', 'dcc_rewrite_tags');
function dcc_rewrite_tags() {
add_rewrite_tag('%propref%', '([^&]+)');
}
add_action('init', 'dcc_rewrite_rules');
function dcc_rewrite_rules() {
add_rewrite_rule('^cottage-details/(.+)/?$','index.php?page_id=2&propref=$matches[1]','top');
}
Then you can access to `propref` query var like:
$propref = get_query_var( 'propref' );
And remember to flush the rewrite rules; you can do it by going to Settings -> Permalinks and clicking on save button.
**Note** : changed `p` query var to `page_id` because, as you said in the comments, you are using a page, not a standard post. | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 2,
"tags": "rewrite rules"
} |
Confused by the behaviour of "front page" / "home" templates
I stumbled upon a confusing issue while trying to customize the appearance of the front page of my blog (`blog.example.com`) without changing the behaviour of the other blog posts index pages (`blog.example.com/page/3`).
The problem is that I can't seem to find a way to add a template for the front page that doesn't affect the other list pages:
* according to wphierarchy.com and to the rather confusingly worded codex entry, it looks like `front-page.php` is what I'm after, but if I provide that, the blog posts index pages are affected by it as well!
* if I modify `home.php`, both the home page and the index pages are affected, as correctly documented
* adding a custom page template and setting the front page to use a page with that template set doesn't work either! the index pages still end up calling the `page-foo.php` template
What am I doing wrong? | You have this all wrong :-)
* `blog.example.com` is page one
* `blog.example.com/page/3` is page number 3 of `blog.example.com`
So this not a new page, but a paged page. By default, this all pages in a paged sequence will use the same template as the first page | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development, templates, frontpage"
} |
WP redirect rule doesn't work
I'm trying to redirect the page ` to `
I have tried the following:
add_rewrite_rule('newsletter/unsubscribe.html$', 'newsletter/unsubscribe', 'top');
If I `var_dump` the **global** `wp_rewrite` i see the following rule added:
...
public 'non_wp_rules' =>
array (size=1)
'newsletter/unsubscribe.html$' => string 'newsletter/unsubscribe' (length=20)
...
Does anyone know what I am missing? | The short answer is: that's not how rewrite rules work. You can see how they work in the examples section of the codex page.
It sounds like what you're trying to do is setup a redirect. I would suggest using a plugin to do that. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "url rewriting, rewrite rules"
} |
Display Custom Taxonomy Terns ordered by meta_value
I got stuck with ordering custom taxonomy. I've created a hierarchical custom taxonomy called **Brand** and created some meta tags including one called **position**. Now I would like to display my terms ordered by **position** meta tag. I tried doing this:
<?php
$taxonomy = 'brand';
$term_args=array(
'hide_empty' => false,
'orderby' => 'meta_value_num',
'meta_key' => 'position',
'parent' => 0,
);
?>
<?php $tax_terms = get_terms($taxonomy, $
<?php foreach ( $tax_terms as $tax_term ) : ?>
<h2><?php echo $tax_term->name; ?></h2>
<?php endforeach; ?>
But as I can see `get_terms()` doesn't support `'orderby' = 'meta_value_num'` and terms are ordered by name. Is there any way to display them ordered by position?
Thanks for your help! Patryk | Assuming the position field is filled with numbers to give order: have a look at `ksort`.
<?php
$terms = get_terms('brands');
// Let's create our own array and then reorder it
$order_terms = array();
foreach( $terms as $term ) {
$position = set_up_the_position_meta_here;
$order_terms[$position] ='<h2>'.$term->name.'</h2>';
}
// now lets reorder the array based on keys (position)
ksort($order_terms);
// time to display
foreach( $order_terms as $order_term ) {
echo $order_term;
}
?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom taxonomy, order, terms"
} |
Why are featured images sometimes cropped, and sometimes not
I am developing a website using Wordpress CMS, in particular Hatch theme. I noticed that in some posts, featured image is displayed full size (like here) but in others, featured image has a smaller size, cropping the original image,!small featured image !enter image description here I don't think it is about image starting size, because some of the images displayed correctly are way bigger than the one it shows as cropped. Both of them are made with cameras. Moreover, if I change the freshly updated photo with another one that i recently uploaded, it shows as cropped, while changing it with older photos shows it full size
Do you know why it behaves like this, and how I can fix it? Can it be an extension issue (even though they both are JPEGs)?
Thanks | Image sizes are generated when the original is uploaded. If you add an image size after files have already been uploaded, those old images won't have the new sizes, and will default to displaying the original. If you search the WordPress Plugin repository for "regenerate images" you'll find some plugins that will simplify fixing this. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "images"
} |
page.php not displaying content
I am using a page.php template I have used on about 400 Wordpress websites, and all of a sudden the loop decides it doesn't want to display any content.
Code is:
<div class="text-content">
<?php if (have_posts()) : while (have_posts()) : the_post();?>
<h1><?php the_title(); ?></h1>
<?php the_content(); ?>
<?php endwhile; endif; ?>
</div>
Page title displays fine so loop is fine, content remains blank.
Any advice? Never seen this before. Thanks | OK, sorted, re-uploaded my pre-developed functions.php file, in which I had only removed a function for breadcrumbs and one for pagination, but this must have some how affected page content, so anyway this is back, thanks for your time. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "page template, the content"
} |
$args numberposts variable
$args = array( 'numberposts' => '10', 'post_type' => 'newposttype');
$recent_posts = wp_get_recent_posts( $args );
I know it's not a simple thing to ask but how could I set the numberposts depending on the screen width?
That is: for a desktop visitor I show 10 posts and for a mobile visitor I show 3 posts. | Yes, there is no way to get screen size with PHP, because it runs on _server_ , while the screen is something related to client (browser).
However, in OP you say:
> for a **desktop** visitor I show 10 posts and for a **mobile** visitor I show 3 posts
and even if you can't get the screen size, you can understand if the request comes from a mobile device, thanks to `wp_is_mobile()`:
$number = 10;
if (wp_is_mobile()) {
$number = 3;
}
$args = array( 'numberposts' => $number, 'post_type' => 'newposttype');
$recent_posts = wp_get_recent_posts( $args );
There are PHP libraries like Mobile Detect that gives you more control, e.g. you can differentiate tablets form phones.
So if post number choice may depend on device being mobile / non-mobile, than it can be easily done as explained above, if the choice must depend on real screen width than the only solution is AJAX.
Search this site (start here) to find guidance on how to get posts using AJAX. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "query, mobile"
} |
Other than save_post any other actions on add / edit post screen?
When the add post or edit post screens load, is there an action other than save_post which I can hook on to? I need to make an API request before a user starts adding / editing posts. Basically when the add or edit post screen loads I need my API call to be made. I know that `save_post` first when those pages are loaded, i'm just wondering if there is an earlier action I can hook on to? I've looked at < and do not see any useful other than `save_post`
Thanks | you can use `load-{page-hook}`. It is called prior to the admin screen loading.
add_action( 'load-post-new.php', 'post_listing_page' );
function post_listing_page() {
// 'add new' page, you may have to check post type..
}
* {page-hook} on the 'add new' page of any post type, it is post-new.php
* {page-hook} on the edit page of any post type, it is post.php | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "admin, actions"
} |
Website displays old version of page
So I'm working on a website for a company and everytime I edit a page/post I have to manually go in to the database and remove the old versions (which isn't something that I'd like to do since it's pretty good to have) just so the website can update the front-end to be the same as the back-ends current version.
Is this caused by WordPress (v 4.0) or is it some kind of cache? (No cache-plugin installed however). | I have faced similar issue while working for a client. The issue may cause due to following reasons.
* Check server configuration and server cache. ( This happens if you are using specialized wordpress hosting; the server admin configured some cache mechanism to increase performance) In this case you have to wait till the sever refresh its cache. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "database, cache"
} |
Wordpress Thumbnail compression depends on the server?
Different image weights were generated in different servers when Uploading images to Media.
For instance, an original image of 2.1Mb uploaded to a server generated a 700Kb image, for the medium size, which is too big. The same image uploaded to my local server, generated a 70Kb image for the medium size, which looks horrible.
Does anyone know what it may be due to? What parameters affect the image compression rate? | This depends on two things
* the image library WP uses
* the settings of your WP install
# Image Library: ImageMagick vs GD
Since WP 3.5 ImageMagick is the default, but if this isn't available WP will fall back to GD.
ImageMagick generally does have better quality which is why it is preferred.
# Settings
There are some filter to change the quality WP uses to resize images, the main one being this one:
add_filter( 'wp_editor_set_quality', 'wpse_176452_custom_image_quality' );
function wpse_176452_custom_image_quality( $quality ) {
return 96;
}
More details can be found at the announcement I linked to above.
* * *
So you need to check if your install differs in any of those factors. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "uploads, thumbnails"
} |
Why are default comments deprecated?
I am developing a theme and, after calling comments_template(), noticed that "Theme without comments.php is deprecated since version 3.0".
I created a comments.php in the root of my theme and copied the default wp-includes/theme-compat/comments.php inside, which is perfectly fine for me. This core file will be removed in future versions of wordpress.
I am not sure if this is a good practice for theme development, though, as it is a complex bunch of code and it does not belong to the website development core features. I prefer wordpress to provide a default comments template.
I could deliver the theme without the ability to enable comments, but that is even worse.
I can be called lazy, but apart from that, shouldn't there be a standard/default comments template? | You shouldn't copy _that_ file, precisely because it is too bulky. About half of it is implementation of submission form, which was entirely replaced with `comment_form()` function around that time.
So the answer why was it deprecated is roughly:
1. Newer code is more compact
2. Markup belongs in theme
For better and more relevant `comments.php` example look at core themes, such as `twentyfifteen/comments.php`. | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 3,
"tags": "comments, comment form"
} |
Create a Page template selector page
I'm running around with an idea in my head that I would like to make but I don't really know how or where to start.
In a custom theme I had to make serveral templates for one of my clients. I noticed that I had around 20 possible templates for my client (because he wanted to have "multiple" options)
You can imagine that the dropdown list for the templates was immense. So I was wondering how I can replace the default dropdown with a new screen or a pop-up to create a visual reference to the possible templates.
It would be even cooler if there are thumbnails of templates generated based on how the template looks. (like Google used to do a while ago) But this is part two. First I would like to know how to even replace the dropdown.
Any thoughts/ideas?
I found this but.... well I don't know. | You could develop your own metabox for the page (with custom styling, probably) that allows selection of the template. I don't know that generating screenshots is feasible, but you could definitely have it pull from some sort of associated file (eg: template name is template-name.php, screenshot is template-name.png).
With the replacement selection method generated, you can then just use `remove_meta_box()` to remove the default input box (see: Get List of Registered Meta Boxes and Removing Them) and you should be set! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "customization, themes, templates, core"
} |
Failed media upload: "The uploaded file was only partially uploaded."
I am running Linux CentOS 5.8 and I have my web pages using WordPress 4.0.
I am trying to uplad jpg photos to server via WordPress, but it randomly fails. I uploaded few photos, and then I get errors like:
“4.JPG” has failed to upload due to an error
The uploaded file was only partially uploaded.
Then I try again and again and again until it is successfuly uploaded. Very frustrating.
How can I debug this? Is there a log file? Where to look for? | I managed to resolve this problem with changing Apache server configuration: there is a KeepAlive flag which needs to be turned Off.
More about this flag:
Apache Optimization: KeepAlive On or Off? | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 4,
"tags": "php, uploads, media"
} |
Can I install a theme on only one site of a multi-site network install?
I'd like to install a theme on only one site of a multi-site network install. Is there a way to do that? | Yes, you can enable a theme for a single site (as opposed to enabling it for your entire Multisite network).
Go to the site's **Edit Site** backend page and select the **Themes** tab. The URL should be something like `example.com/wp-admin/network/site-themes.php?id=[site ID]`. You'll need Super Admin privileges on the Multisite network.
Enable the theme(s) you'd like to allow on the site. Once that's done, administrators in the site will be able to use the selected theme(s).
**Edited to add:** You shouldn't need to know the site's ID to do this. Once you're logged in, go to the site's Dashboard. You'll see the site's name in the top bar. Mouse over it and select **Edit Site** from the dropdown:
!Edit Site dropdown
Then select the **Themes** tab:
!Themes tab | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 4,
"tags": "multisite, themes"
} |
Move theme templates to subfolder without losing page associations
I'm aware that templates can reside in a subfolder of a theme since 3.4.
My theme has been about for a while and all our templates reside in the theme directory. I'd like to tidy this up by adding them to subfolders, but simply moving them will result in all the pages losing their templates. Which would be a pain to rectify for 40 templated pages or so...
Is there a wordpress filter, hook or other method that could be used for checking template location? Which I can use to check for missing templates? google is turning up nothing useful.
Does anyone have any other wordpress based ideas?
(I'm aware I could try running a query to update template locations, but I'd rather not modify the DB directly if I can avoid it.)
Thanks! | You could hook the `page_template` filter and check if the current page has a `_wp_page_template` meta key. If it does, you can check if `file_exists` in the new templates location, then `update_post_meta` to append the new directory name. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "theme development, templates"
} |
How to add Post Tags to a new <meta> element in header.php?
How to add Post Tags inside a new element in header.php?
I'm probably overlooking an obvious function in the WordPress Codex.
I have tried adding these to header.php:
<meta name="page-tags" content="<?php the_tags(); ?>">
=> produces some unwanted html (I do not want to change core in the wp-includes folder
and
<meta name="post-tags-here" content="<?php get_the_tag_list(); ?>" >
=> doesn't print
and
<meta name="post-tags-here" content="<?php tag_description(); ?>" >
=> doesn't print
Any clues? | Use `get_the_tags()` instead of `the_tags()`, `get_the_tags()` does the following for you:
> Returns an array of objects, one object for each tag assigned to the post.
with which you can work with to achieve what you want. See the examples on the codex page for more information. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, tags, headers"
} |
Custom url for a single page
Created a page and the link is like the following
need to be like the following
I need this structure only for this page .So i don't want to change the current permalink structure.Is there any other option to achieve this?
Can anyone help please. | Read on htaccess. You can try this,
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^phones$ /?page_id=1081 [L]
</IfModule> | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "permalinks, htaccess"
} |
Creating a one click demo importer
edit: I've re-written this because it is unclear, apologies it was written rushed on a Friday afternoon.
Wordpress has import/export functionality for posts within wordpress, I am a theme developer trying to export demo content with my theme, I would like users to be able to click a button within my plugin and then that will load in all the demo content.
The problem is Wordpress's native functionality only handles posts and media images, it does not handle things like site options (I would like to set the front page post) and widgets + their locations, my question is how can I write something that would import my widget settings and some site options | I believe that if you are not going to do a massive sql insert (which I think is likely just as efficient) that you need to go ahead and utilize the plugin api and at the time of the button being pressed, create them. I think it's pretty clear your choice is either to create the widgets on the fly, or to import through an sql insert.
< should point you in the right direction if you'd prefer to avoid the SQL insert. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "widgets, import, export, options"
} |
Show div only if post is in specific category
In my list of blog posts, I would like to show a div which labels the post as a "Press Release" if the post is tagged with the "Press" category.
I have added the following chunk into my loop:
<?php if (is_category( 'press' )) : ?><div class="category">Press Release</div><?php endif;?>
I have also tried replacing `press` with the category ID, but neither seem to work. Is this how I should be implementing this? | `is_category()` does this:
> (...) Checks if a Category archive page is being displayed. (...)
One line below on the codex page you find:
> To test if a post is in a category use `in_category()`.
So just use the latter. | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 4,
"tags": "categories, loop"
} |
RSS Feed Sticky Post?
My latest RSS feed shows 20 posts for example, but I want to include a certain category no matter how old the post is (for example, my 'featured' post category), and also just get 1 latest post from this category.
I've been trying to look for plugins, but I'm not exactly sure what it would be called. Any help would be appreciated. | You can try the following:
/**
* A sticky feed post from a given category
*
* @see
*/
add_filter( 'the_posts', function( $posts )
{
if( is_feed()
&& $tmp = get_posts( array( 'category_name' => 'feed', 'posts_per_page' => 1 ) )
)
$posts = array_merge(
$tmp,
wp_list_filter( $posts, array( 'ID' => $tmp[0]->ID ), 'NOT' )
);
return $posts;
} );
where we prepend a given category post to the feed. Here you have to adjust the `feed` category slug to your needs. We also make sure that the sticky post isn't duplicated. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "rss"
} |
How can I remove the Static Front Page option from the Customizer
In Wordpress 4.1's Theme Customizer there's a **Static Front Page** option. I've set up my theme to have a custom front page (via `front-page.php` in the theme) so I don't want this option to be available here.
!enter image description here
How can I remove it? | This code will do the job.
add_action('customize_register', 'themename_customize_register');
function themename_customize_register($wp_customize) {
$wp_customize->remove_section( 'static_front_page' );
}
It will remove Static Front Page option.
Details here | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 2,
"tags": "theme development, customization"
} |
Warn user that data may be lost for custom pages
When you edit a builtin field in Wordpress like the title and don't save the cahnges, and attempt to go to another link, a warning alert box comes up stating that "changes may be lost if you navigate ...".
How can I make that same box appear for my own pages?
Thanks! | you have to make a javascript code similar to this...
jQuery(function ($) {
name = $('#name').val();
$('#name').data('old_value',name);
window.onbeforeunload = function () {
if ($('#name').data('old_value') !== $('#name').val())
return 'You have unsaved changes!';
}
});
here's a demo page... try closing the page after changing the value of the textbox there... | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom field, options, validation, plugin options"
} |
How can the user place a custom text string as a placeholder for a plugin
ex: like a user adds {{my-new-plugin}} somewhere in their post, the plugin will read it and add arbitrary text.
I just need help finding the name for this. I can't find this the proper words to put in a search engine. | I believe what you are looking or are short codes.
Check the codex for more details on them:
* Shortcode API
* Builtin Short Codes and Overview
Hopefully that gets you going. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "tags"
} |
Get the ID of category page with or without any posts
Is there a better way to get the category ID that may or may not have any posts assigned to it?
Currently im using the following code that resorts to parsing the page url, and getting the category ID from its slug. Doesn't feel like the best way to do it.
$current_url = rtrim($_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"], "/");
$arr_current_url = split("/", $current_url);
$thecategory = get_category_by_slug( end($arr_current_url) );
$catid = $thecategory->term_id; | Make use of `get_queried_object_id()` in your category page. This will return the ID of the category.
This is really useful little function. It will return the the:
* author ID on an author archive page
* term ID on a taxonomy, tag and category archive pages
* post ID on a single post page
* page ID of a page
## EDIT
From your answer, you can simplify your code to something like this
if ( is_category() ) {
$catid = get_queried_object_id();
} elseif ( is_single() ) {
$cats = wp_get_post_terms( get_queried_object_id(), 'category', array( 'fields' => 'ids' ) ); // category object
$catid = $cats[0];
}
The above code is faster and is more reliable :-) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "terms"
} |
Parallax WordPress theme without hardcoding - possible?
I want to develop my first Parallax WordPress theme, just for the fun of learning this stuff.
I found this snippet: <
It lets the user click on a menu item and the website will scroll to that page. I want to know if it's possible to do this when developing a theme - to somehow get the pages of each menu item on the same front page, and being able to jump straight to it.
This of course means it will have to be functional no matter what page it is from the menu, as I want to distribute the theme to the theme repository.
I hope this makes sense. | One option would be to load all items in the nav menu into the page when it is being generated using wp_get_nav_menu_items( $menu_name, $args )
Another possible way to do that would be to use ajax to grab the page in question and append it to the end of the current content before the scroll action is fired.
However, there are a few possible problems with the latter idea, particularly the fact that normal wordpress themes use templates to show an entire page ... and getting just the content you want to append would require a little more work than simply receiving query data, using query_posts() to stomp all of the globals (finally, a use for that function!), opening a buffer, loading the appropriate template, and returning the content.
Of course, you could write a custom function to grab and format posts in a particular way and then use that to return the proper code to be appended to the post list. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "themes"
} |
Do I need "wordpress hosting" to host wordpress?
I am a beginning wordpress user and am unsure about wordpress hosting. Some hosting sites (for example, Godaddy) have hosting plans and then they have _wordpress hosting_ plans. do I _need_ the special wordpress hosting? Is it possible to host a wordpress site without having special wordpress hosting? | You don't need WordPress-specific hosting, just a hosting package that meets the requirements.
> PHP 5.4 or greater
>
> MySQL 5.5 or greater
>
> The mod_rewrite Apache module (to enable Pretty Permalinks) | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "hosting"
} |
What exactly is an advanced object cache?
I'm reading this article about fragment caching. It seems self explanatory except for this line:
> based on the assumption that you have an advanced object cache available.
What exactly is an advanced object cache, and how can I check for one/implement if not already available? | An advanced object cache is a cache mechanism that can store data that persists beyond a single request. A couple of popular object caches for WordPress are APC and Memcached. The `WP_Object_Cache` class Codex page has a list of links with more info on advanced cache options. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 5,
"tags": "cache"
} |
Varnish with Wordpress
I have moved my Wordpress site (a small blog) onto a hosting platform with Varnish at its front. Varnish, rightly, won't cache when cookies exist.
It looks like Wordpress starts the session, even if it doesn't need it. As such, it sets the `PHPSESSID` cookie, even though a `var_dump()` of `$_SESSION` is empty (when done at the end of index.php).
Is there a way to stop Wordpress doing this? Perhaps with an existing or, indeed, custom plugin?
**EDIT:** Looking at it again, does the session get used for anything useful on the frontend of the site? Posting a comment seems to set other cookies. Can I just exclude `PHPSESSID` from Varnish?
I know W3 Total Cache works with Varnish but it's a massive plugin and, despite spending a lot of time configuring it, performance was worse and things occasionally broke. | I gave it a punt and it seems to be OK. Below is my VCL. It basically unsets all cookies unless it's wp-admin. This will only work for a very simple site.
# Specific to my.website.com
if (bereq.http.host == "my.website.com") {
# Strip all cookies (the only one should be PHPSESSID) if not admin
if ( ! bereq.url ~ "^/wp-admin/") {
unset beresp.http.Set-Cookie;
}
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "varnish"
} |
Getting version number of latest Wordpress release
I want to find out the latest version of WordPress that is officially released. If possible, I'd like to get that version language specific for at least English and German.
I could try and parse the website < but it doesn't have the version number in a specific place. I also know I could download the latest package (< but I don't need the whole package, just the version number.
Is there a reliable, stable way to just get the latest stable version number of WordPress?
This question is _not_ about getting the version number of my WordPress installation. Actually I want to compare my installed version against the latest version by a script. | WordPress.org offers an api that includes a version checker. That version checker can return a json response (or a serialized string if that's your thing).
**Example usage**
$url = '
$response = wp_remote_get($url);
$json = $response['body'];
$obj = json_decode($json);
The resulting `$obj` will contain an offers array, whose first element is an object that contains the information you want.
$upgrade = $obj->offers[0];
echo $upgrade->version;
`$upgrade` will also contain a lot of other useful information including the locale, where to download the current version, etc.
If you're going to be running this in a plugin, I'd recommend caching it with a transient that expires every 12 hours or something and not spamming the poor api on every page load.
_Edit_ : Variable name spelling fail. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 5,
"tags": "wordpress version"
} |
Adding a translation phrase to Wordpress Theme
I'm creating a custom Wordpress theme and I'm using exactly 3 phrases that I need to be translated according to the site language selected. I've digged a little bit through the Internet, but couldn't find an easy solution to add those phrases, so I could translate them through admin panel on my site.
I'm wondering if there is any way to add those phrases (f.e. in `functions.php` file) without using any PO/MO/POT files? | Here is an idea or two that you can pursue here: ( _CAVEAT: Untested_ )
## OPTION 1
In your template file (use a child theme if this is not your own theme), use `get_locale` in a conditional statement to check which language is set in `WPLANG` and then dish up the text according to the locale
## OPTION 2
Create yourself a function (which will be the ideal solution and what you are actually asking) using the `gettext` or `gettext_with_context` filter depending on your string context.
In conjuction with `get_locale()` you can then get and transalte and serve the correct translated string according to the language set | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "translation"
} |
Strip category base from URL?
Where I Place This Code Or How Can I Use This?
function wpa_alter_cat_links( $termlink, $term, $taxonomy ){
if( 'category' != $taxonomy ) return $termlink;
return str_replace( '/category', '', $termlink );
}
add_filter( 'term_link', 'wpa_alter_cat_links', 10, 3 );
You'll probably want to test this thoroughly for any side-effects, use at your own risk!
**EDIT** \- altering just top level category links:
function wpa_alter_cat_links( $termlink, $term, $taxonomy ){
if( 'category' == $taxonomy && 0 == $term->parent ){
return str_replace( '/category', '', $termlink );
}
return $termlink;
}
add_filter( 'term_link', 'wpa_alter_cat_links', 10, 3 );
**Original Source:Force Wordpress to Show Pages Instead of Category** | You would place this code inside your theme's functions.php file. It shouldn't really matter where in the file that you place it. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "permalinks, archives"
} |
Question mark on special chars
Yesterday i was working on a file when notepad++ crashed. I then went in the backup folder of the program to restore the file. After the restoration, special chars (such as `€` or accented letters) are displayed as a question mark in a black diamod. What is strange is that this happen only in this page, the other pages in the whole WP are displayed correctly! I trashed the file and wrote a new file with the same name and the same shortcode but the problem persist! How can i fix this? | WordPress sends all HTML content encoded as UTF-8. If you save a file in a single-byte encoding, like Windows-1252¹, you create invalid characters for UTF-8. These are displayed with a replacement character, usually (but not necessary) as a question mark in a black diamond.
Always use UTF-8 for everything. Do not use a BOM (byte order mark), because this is treated as a printable character by PHP, and you will get the famous _Headers already sent_ error.
¹ **ANSI** is not a real encoding. It resolves to your operating system’s locale encoding. This term should be forbidden in all text editors. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "encoding"
} |
Some doubts about gallery shortcode in Wordpress
I'm using Jetpack with Wordpress and creating a gallery. The thing is that I don't want all the images from that gallery to be shown, only the last 50 of them. Is there any solution to this using just the shortcode?
If not, is there any other solution?
Also, I have another doubt about the usage of galleries in Wordpress, is it possible to assign a name (or ID) to the gallery and call it in the code? For example
<?php echo do_shortcode("[gallery name='my_gallery']"); ?>
Thanks in advance! | If you want to display the _attached_ image gallery, from another post, you can use:
[gallery id="123"]
where the custom `id` attribute is the post ID.
If you want limit the number of items in a gallery, there seems to be a plugin available on wordpress.org called Limit parameter for gallery shortcode (no affiliation). It uses the `pre_get_posts` filter to change the `posts_per_page` and `offset` attributes of the `get_posts()` or `get_children()` calls in the gallery shortcode callback.
Example:
[gallery id="4" limit="3" offset="1"] | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "shortcode, gallery"
} |
How to put forward a blog post
I would know if I can put forward a blog post natively using Wordpress ?
For example, I have created 20 posts, but I only show 5 on my homepage. Then imagine that I want to put the 18th at the first place ? By default Wordpress order by publication date. I was thinking about creating a custom field called for example 'highlighting' with a boolean value and order by this new field, but it has its limit if there is more than one post to 'highlight'.
So my exact question is: There is a native way to this with Wordpress ?
Thank you in advance. | You can do this with Sticky Posts feature in WordPress.
When you make a post sticky, it shows up above your new posts. As name suggests, that particular post will stick at top, first in the row for as long as you want.
> Sticky Posts is a feature introduced with Version 2.7. A check box is included on the Administration > Posts > Add New Screen (In the Publish panel under Visibility. Click edit to see the checkbox). If checked, the post will be placed at the top of the front page of posts, keeping it there until new posts are published. Please notice that this feature is only available for the built-in post type post and not for custom post types. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom field, query posts"
} |
Gallery with shortcode not showing
I've created a gallery in a static page of my wordpress site, like this:
[gallery type="rectangular" ids="129,13,126,34,130"]
This page has ID=63, so I'm trying to display this gallery in my homepage with this line of code:
<?php echo do_shortcode("[gallery id='63']"); ?>
But nothing is shown...Am I missing anything?
Thanks in advance! | While gallery shortcode does have `id` arguments, it won't do what you think.
If that argument is present WP will try to look for _child attachments_ of that post, using `get_children()`. It won't take content of the post and shortcodes in it into account.
If the gallery is _only_ content of that page you could try the following (not tested):
echo do_shortcode( get_post_field( 'post_content', 63 ) ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "images, shortcode, gallery"
} |
WP_Query by post ID doesn't work if post is in custom post_status
I want to display a single post by its ID using WP_Query(). To do this, I use the following argument:
$args = array(
'p' => 61202);
That should work, but does not seem to work **if** the post is in a custom `post_status`.
To fix this, I tried the following:
$args = array(
'p' => 61202, // id of post
'post_type' => 'any', // apply to all post types
'post_status' => 'my_custom_status' // the custom post status
);
But this still does not work. **Why?!**
Is there a known bug? I am running this code in the wp-admin area. It works fine if the post is in any of the WP core post statuses. | `WP_Query` has a bug (#29167) when you try to fetch posts with (almost?) any other status than `publish`. This bug seems to be fixed in trunk. I haven’t tested it, so I cannot tell if it covers your use case. Try it, and give feedback there if it doesn’t.
There are two workarounds:
1. Use `get_post( $post_id )`. This runs its own query and isn’t affected by this bug.
2. Use a custom DB query if you don’t know the post IDs:
$sql = "SELECT * FROM $wpdb->posts WHERE post_status = %s AND post_type = %s";
$prepared = $wpdb->prepare( $sql, $status, $post_type );
$posts = $wpdb->get_results( $sql ); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 5,
"tags": "wp query, post status"
} |
Conditional functions.php on page template
I am creating a new page template (which essentially i am taking bits and pieces from a new theme). I have called this `template-flat.php`
Now in `functions.php` I am looking for a conditional statement to load some new js and css only for `template-flat.php` instead of the ones loaded by the old theme.
Is there a way I can do this? | You can make use of the conditional tag `is_page_template()`
> This Conditional Tag allows you to determine if you are in any page template. Optionally checks if a specific Page Template is being used in a Page. This is a boolean function, meaning it returns either TRUE or FALSE.
You can try something like
if( is_page_template( 'template-flat.php' ) ) {
//Do something if the current template is template-flat.php
}else{
//Do something else if the current template is not template-flat.php
} | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 0,
"tags": "functions"
} |
Is it possible to get an exported WP site in a zipped folder up and running?
Our old webmaster abandoned us and stopped hosting our website. All he gave us to work with was a zipped folder of the website. It contains the wp-admin, wp-content, and wp-includes folders, index.php, and 26 other php files in the root of the folder. We don't have any access to the server it was installed on, but we do still own the domain name. Is it possible to get this up and running, or is this just junk now? | It's not junk, but it's not complete. You should also have the database, normally an `.sql` (can also be zipped).
You should buy hosting, change the DNS to point to your new host. Than you want to upload the files he gave you to the new server and import the contents of your old database into the new one. If all goes well, your site will be up and running by this time.
You should, however, have someone familiar with WordPress do this. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "migration, export"
} |
Disable wordpress from including jQuery in the head section
I need to make Wordpress not include jQuery in the `<head>` section of every page. The reason I need this - is because I am already including jQuery at the very bottom of the document.
I tried this: `wp_deregister_script('jquery')` but it **doesn't work.**
How does one remove jQuery from the `<head>` section? | the following may work
function wpdocs_dequeue_script() {
wp_dequeue_script( 'jquery' );
}
add_action( 'wp_print_scripts', 'wpdocs_dequeue_script', 100 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "plugins, jquery, wp head"
} |
Can I have multiple database users within WordPress?
I want to use more than one database user to overcome the 7500 query database limit. How can I do that using `wp-config.php`?
I want all the users to have the same password. | Just set a random user in your `wp-config.php` for each request:
$db_users = array(
'user_1',
'user_2',
'user_3',
);
define( 'DB_USER', $db_users[ array_rand( $db_users ) ] ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "database, wp config"
} |
Get Image tag from content of post
I have create a custom sidebar, and want to show only posts images in that sidebar. I have add a post with some text and choose image from gallery in the content of that post. Now i want to get only image tag from post by loop.
Any suggestions? | You can either make use of `get_children` or `get_posts` or even `WP_Query` to get the the attached image ID's to the current post
You can then use those ID's to gt the attached image with `wp_get_attachment_image()`
Here is a basic idea that you can use in a widget or sidebar. ( _CAVEAT: Untested_ )
$args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => null,
'post_parent' => get_queried_object_id()
);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
echo '<li>';
echo wp_get_attachment_image( $attachment->ID, 'full' );
echo '<p>'; echo apply_filters( 'the_title', $attachment->post_title );
echo '</p></li>';
}
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "posts, loop, attachments"
} |
List of child pages fetch next results at link click
I have a list of child pages which are getting displayed as links to those pages. Im displaying it in a certain div with a maximum of 6 results. What I want is I have a "a href" which is called more... so when clicked I want to fetch and display the next 6 results (so the first 6 are replaced by the next). A button that does it is fine also, how would I do this? What I have so far in a have_posts loop is:
$subs = new WP_Query( array( 'posts_per_page'=>6, 'post_parent' => $pid, 'post_type' => 'page', 'orderby' => 'menu_order title' ));
if( $subs->have_posts() ) : while( $subs->have_posts() ) : $subs->the_post();
if ($link==get_permalink()) echo '<li><h1><a href="'. get_permalink() .'">'. get_the_title() .'</a></h1></li>';
else echo '<li><h2><a href="'. get_permalink() .'">'. get_the_title() .'</a></h2></li>';
endwhile; endif; wp_reset_postdata(); | Why don't you just use the build in features to page your results
* `WP_Query` Pagination Parameters
* `next_posts_link()`
* `previous_posts_link`
Just simply add the `paged` parameter to your query arguments, and don't forget to set the `$max_pages` parameter in `next_posts_link()` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, posts, wp query, pages, child pages"
} |
How do I enable the text view of the side admin bar
When I logged in today evening, I found that all the text in the admin bar had disappeared and only the icons were visible as shown below
!enter image description here
How do I enable the text again | At the very bottom there should be an icon that looks like a play button:
!Icon to toggle menu with
Click it! ;) | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "admin bar"
} |
It's possible to hide body copy box for a custom post type?
I'm using Wordpress Types for create and manage Custom Post Types (CPT) at my blog and it works perfectly. I have created a CPT called _Espacio Publicitario_ and I added also some custom fields (see image below). I need to hide **body copy box** since on this CPT is useless, can I do that? How? It will be hide just for this CPT not for the rest of the post, pages and so on
!enter image description here | There is a built in WordPress function for this, **remove_post_type_support** < .
In your case you could use something like
add_action( 'init', 'my_custom_init' );
function my_custom_init() {
remove_post_type_support( 'custom_post_type_name', 'editor' );
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "custom post types, custom field, wp admin, plugin types"
} |
Permissions error
I am completely new to WordPress. I just installed it and wanted to change the theme of my website and I get following error:
Installing Theme: Klasik 0.7.5
Downloading install package from
Unpacking the package…
Could not create directory.
I really don't know what to do from that point. My permissions are ubuntu www-data ( I am running this on lxc ). Please, please tell me what I have to do!! I tried to get wp working on Windows and everything worked. Now on Linux its just not working and I could destroy my monitor at the moment.... -.- | This is more server config question than WordPress.
Make sure the www-data group has write permissions in the directory you're running WordPress from. Assuming it's in /var/www/ then `sudo chmod -R g+rwxs /var/www/` should do the trick. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "themes, permissions"
} |
Can a plugin be used to contain all custom functions to extend other plugins
I am very new to Plugin development and I have used my themes functions.php file to modify functionality as needed to date.
As a result of conversation with a customer I was asked if it is possible to create a super plugin that could manage all of their customization to existing plugins and I wasn't sure. So I wanted to ask about other devs experience or how you would handle this situation.
The goal is to protect against having to customize a plugin and then losing that functionality when a new version of the plugin is released. | If your plugin customise functionaity of other plugins through hooks (actions and filters) the answer is **Yes**. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugin development, upgrade"
} |
Strange iframes added in wordpress 4.1 localhost
I have a strange iframes added in my code, that you can see in the images below. I disabled all the plugins but this iframes still appeared. I tried to track where this code is in the project, but no result. I am on localhost which is strage too. Any idea how to remove this iframes. They make couple requests and try to load 412.html. In the request preview is this url cloudfront.net, I don't know if it matters. Thank you very much!
| This is not a WordPress issue. A Google search for `boostsaves.com` reveals it is a browser add-on that injects iframes into the page source of whatever you're viewing.
Use Google to find instructions on how to remove it from whatever browser you're using. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "html"
} |
Restrict access to options-*.php pages
I have a custom role named `manager` with `manage_options` and `read` capabilities , i want to restrict him not to access Settings menu, you may say remove `manage_options` capability but that's not the case as i need that cap (am using Settings API which posts to options.php).
I can hide those pages by using `remove_menu_page()` but still we can access by directly typing url. | A quick and dirty way of doing this is by adding a `.htaccess` file to the wp-admin directory, with the following content.
<FilesMatch "^options-(.*)\.php$">
Order Allow,Deny
Deny from all
</FilesMatch> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "settings api, user roles"
} |
Sorting posts by ACF field
I am trying to sort posts by the 'prempost' ACF field, but it's not working (just shows default order). Can anyone see where I'm going wrong? ACF support suggested that I use http_build_query, which I've done below, but still no cigar:/
<?php
$meta_query = array(
'relation' => 'OR',
array(
'key' => 'prempost',
'compare' => 'IN'
),
array(
'key' => 'prempost',
'compare' => 'NOT IN'
)
);
$args = array(
'meta_query' => $meta_query,
'orderby' => 'meta_value',
'meta_key' => 'prempost',
'order' => 'ASC',
);?>
<?php $new_args = http_build_query($args); ?>
<?php $posts = query_posts($query_string.'&'.$new_args); ?>
//begin loop
<?php if (have_posts()) : while (have_posts()) : the_post(); ?> | You are not going to this in one query, you will need to do two queries. The first query will hold the posts which will hold the meta key, the second will be the posts without the meta key.
( _Just a note: **never** use `query_posts` unless you intentionally wants to break things_)
You can try something like this
$args1 = array(
'orderby' => 'meta_value',
'meta_key' => 'prempost',
'order' => 'ASC',
);
$query1 = new WP_Query($args1);
//Do your stuff here
$args2 = array(
'meta_key' => 'prempost',
'compare' => 'NOT IN'
'order' => 'ASC',
);
$query2 = new WP_Query($args2);
//Do your stuff here
You can also maybe try to get all the posts at once and then sorting them with php using `usort()` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "meta query"
} |
Simple plugin don't display content
Trying to learn WP plugin development.
Followed all the instructions.
`plugins/e4-test-1` directory.
Main php file (`e4-test-1.php`):
<?php
/**
* Plugin Name: Test 1
* Plugin URI:
* Description: xxxxxxxxxxxxxxxxxx
* Version: 1.0.0
* Author: xxxxxxx
* Author URI:
* License: GPL2
*/
My one an only php file with code (`testhook.php`):
<?php
function testhook() {
echo 'SOULISSSSSSSSSSSS';
}
add_action( "wp_head", "testhook" );
It simply does nothing. View Source doesnot contain the string anywhere.
Of course I have activated the plugin, cleared caches e.t.c
Obviously my noobness stops me from finding the mistake | You need to call your custom file into your main plugin file. Without doing that, your custom file will not get called. Think of your main plugin file as your themes `functions.php` file and your custom file like a custom file that also holds functions
By default, Wordpress will only read your functions.php, and not your custom functions file. For wordpress to know to load that functions inside the custom file, you need to tell wordpress that there is a custom file with functions it should load. Normally, in a theme, you would use `include` or `require_once`. Here we would do the same, except, your path will differ from themes
So you can try the following in your main plugin file
require_once(dirname(__FILE__) . '/testhook.php'); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development"
} |
WP_Query custom order and pagination
I am seeing some strange behaviour when combining a custom order with pagination when using `WP_Query`. The arguments for my query are as follows:
$args = array(
'post_type' => 'news',
'posts_per_page' => 10,
'meta_key' => 'news_date',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'paged' => $my_page
);
The variable `$my_page` contains the current page number as extracted from the URL or set to 1 if not defined in the URL.
This query returns the correct number of results but the order is incorrect. Removing the `paged` parameter results in the correct order being achieved but obviously breaks my pagination.
Is there something I am doing wrong? Thanks. | You want to orderby 'date' not by 'meta_value_num' because it is to order numerically. So if you were ordering items by their price, then you would want to use 'meta_value_num'. The meta_key 'news_date' is most likely in date format.
You should also cast the meta_value to DATE using 'meta_type' => 'DATE'.
$args = array(
'post_type' => 'news',
'posts_per_page' => 10,
'meta_key' => 'news_date',
'meta_type' => 'DATE'
'orderby' => 'meta_value',
'order' => 'DESC',
'paged' => (int)$my_page
);
If your getting the correct order, you could always calculate the offset yourself by multiplying paged * posts_per_page. Also make sure that your $paged variable is an integer if you grab it from a query string then it is not an Integer. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query, pagination, query, order"
} |
Display only current page -> posts tags in page
I am having one page for example sample page. I am displaying 3 posts in that page. All 3 posts having 2 tags so total 6 tags.
Now I want to display all those 6 tags in sample page , I have tried below code :
<?php echo wp_get_post_tags(1 , $args ) ?>
But above code printing **Array** instead of post tag actual name. Above 1 is my post id. Also I want to know that how I can pass all post ids of which tags I want to retrieve. | First you've to know what you want to retrieve, you will have to find something identical for that group of post you want to retrieve. Use the following code to retrieve the post, where `$args` is the variable what contains the arguments to select the right post ids.
$posts = get_posts($args);
$terms=array();
foreach($posts as $post) {
//Get all terms for the retrieved post IDs
$terms[]=wp_get_post_tags($post->ID);
}
foreach($terms as $term) {
for($i=0;$i<=count($term);$i++;) {
print $term[$i]->name; //the output
}
}
I didn't test the code yet, but this is basically what you need. It will output names of all the tags.
1. Get to know of which posts their tags have to be shown.
2. Store the IDs and use them to retrieve the tags of the specific posts.
3. Put it all in one array and iterate through it. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, pages, tags"
} |
Current User In Custom Menu Item URL
I'm using S2Member + Buddypress on a compatible template. I have 8 menu items and am using the "Menu Items Visibility Control" to limit the 7th for view only to `current_user_is(s2member_level1) | in_array('administrator', $GLOBALS['current_user']->roles)` This visibility is working correctly.
I'm in need of a way to create a custom menu item that will link to a page containing the following structure:
I don't know how to incorporate the current user name into the URL. I've come across this post:.
*There must be an easy fix, if I leave a custom menu item's URL blank..can I specify the url elsewhere in my code? | Congrats on figuring it out. Perhaps this would also work:
function change_menu($items){
foreach($items as $item){
if ($item-> post_name == 'the-slug')/*replace "the-slug" with menu item post_name */
$item->url = bp_loggedin_user_domain() . '/events/my-events/?action=edit';
}
return $items;
}
add_filter('wp_nav_menu_objects', 'change_menu'); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "menus, buddypress, s2member"
} |
Enqueue Style in Functions.php
This doesn't work for me in `functions.php`:
if( is_page_template( 'template-flat.php' ) ) {
function flatsome_scripts() {
wp_enqueue_style( 'flatsome-style', get_template_directory_uri() .'/flatash/css/foundation.css', array(), '2.1', 'all');
}
add_action( 'wp_enqueue_scripts', 'flatsome_scripts' );
}
However, if I include the style manually in the header of `template-flat.php` like this it works.
<link rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>/flatash/css/foundation.css" type="text/css" />
Why is my functions code not working? | Your problem is that you have wrapped your complete function and your action inside your conditional check. Your conditional check for your page template should be in your function.
Page templates gets set quite late, too late for your action.
Your function should look like this
function flatsome_scripts()
{
if( is_page_template( 'template-flat.php' ) ) {
wp_enqueue_style( 'flatsome-style', get_template_directory_uri() .'/flatash/css/foundation.css', array(), '2.1', 'all');
}
}
add_action( 'wp_enqueue_scripts', 'flatsome_scripts' ); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "functions"
} |
Conditional Page Template not working
I am using this code in `functions.php` to conditionally load some shortcodes but it doesn't work. The shortcodes are still loaded on `template-flat.php`. Any ideas what's wrong here?
if( is_page_template( 'template-flat.php' ) ) {
// other code
}else{
require_once(functions . '/shortcodes.php');
}
I think it's because the page call happens after the functions call in the wordpress actions order? | You need to run this code in an action hook rather than directly in the functions.php file. Take a look at the Action Reference page in the Codex and determine at which point you want this script to run. Whatever action you choose will end up looking something like this:
add_filter( 'template_include', 'check_page_template', 99 );
function check_page_template( $template ) {
if( is_page_template( 'template-flat.php' ) ) {
// other code
} else {
require_once(functions . '/shortcodes.php');
}
return $template;
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "functions"
} |
Wordpress equivalent to Drupal Views?
**Is there a Wordpress plugin that provides a subset of the functionality found in Drupal Views?**
Specifically, I'm looking for the ability to use a Views-like plugin to pull in fields of content based on criteria like date, title, etc. and place them in a block-like area on particular pages.
I'm aware of this question thread (How to replicate some of Drupal Views functionality in WordPress?), but it is from over 4 years ago, so I'm wondering if there are any new solutions.
Thanks. | Its not identical to Drupal Views, but i think WP Views is the closest you will get to Drupal Views.
I am a Drupal guy, and i use WP Views for every Wordpress project i create. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "customization, conditional content"
} |
Template for child pages / subpages
I'm trying to build a template file for my custom post type that is different for the parent, child, and child's child post.
The best I've been able to find is the following code:
if( $post->post_parent !== 0 ) {
get_template_part('content', 'child');
} else {
get_template_part('content');
}
Only issue with this is that it only works for Parent > Child.
Is there any way to make this work for Parent > Child > Child? | Here is a basic idea:
Any page where the page parent (`$post->post_parent`) is `0`, it means the page is a top level page. If any other value exists, the page is a child of another page. This value is the ID of the page that the specific page is a child to.
With the above information, we can calculate if the page is a child or a granchild using `get_post` and the returned `WP_Post` properties.
You can try the following: ( _CAVEAT: Untested_ )
if ($post->post_parent === 0) {
//Do something for post parent
} else {
$q = get_post($post->post_parent);
if ($q->post_parent === 0) {
//Do something for direct child
} else {
// Do something for grand child
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "pages, templates"
} |
How do I understand which page of my theme is being loaded?
Inside my theme there are tons of pages: page-nosidebar.php pages.php content.php
How can I track which is actually loaded? | If it's just for your understanding, then install the Query Monitor plugin, which gives you a lot of information about what's going on under the hood | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "themes"
} |
How to get current page name in my wordpress plugin
I am creating a custom wordpress plugin.
Where for some pages like
<
<
i will append my template code from my plugin folder. Which mean i will include my custom template not even related to wordpress theme.
my code will look like this inside my wordpress plugin page.
if ( $wp->query_vars('pagename')=="clinic"){
include(MYPLUGINPATH . '/template/clinic.php');
die();
}else if($wp->query_vars('pagename')=="pharmacy"){
include(MYPLUGINPATH . '/template/clinic.php');
die();
}
But $wp-query_vars('pagename') return null.is there a way to get the current loading wordpress pagename inside the plugin code. | Use the `$pagename` global variable or pull it from the url
$slug = basename(get_permalink());
or grab the title before the loop starts:
$page_title = $wp_query->post->post_title; | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "plugin development"
} |
Iterate through users and display users meta info at front-page
I have a meta field in user called `columnista-destacado` I need to iterate through Wordpress users and if that field has valued set (lets said equal 1) then I need to display user meta info at front-page. Should be 6 users at maximum, how I can do that? | Sometimes it is more useful to look at the task outside of the WordPress field, but from true programming. You can use custom SQL query to get your users ids and then do what you want with them.
Place the code below into `functions.php`
function wpse_177536_get_user_ids(){
global $wpdb;
$sql = "SELECT user_id FROM $wpdb->usermeta WHERE meta_key='columnista-destacado' AND meta_value = '1' LIMIT 6";
$user_ids = $wpdb->get_col($sql);
return $user_ids;
}
Now anywhere, for example, in `front-page.php` you can call this function like this:
$user_ids = wpse_177536_get_user_ids(); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom field, users"
} |
Using esc_url_raw with protocols properly
I'm trying to build up my own function to sanitize a URL before saving it to my WP database. However I cannot get esc_url_raw to trigger against unwanted protocols. The function below is letting all protocols through.
function scientifik_sanitize_url($url){
$prots = array('http', 'https');
$item = $url;
$sanitized = esc_url_raw( $item, $prots );
if ( is_wp_error( $sanitized ) ) {
return 'funny';
die();
}
return $item;
};
I appreciate anyone's experience with this function in advance. | You are execpeting a WP Error object if the URL has a non-valid protocol but `esc_url_raw` returns an empty string in that case (see codex), not a WP Error object. So, `is_wp_error( $escaped )` never verifies. Also, you are checking an undefined `$escaped` variable (note that the value of `esc_url_raw` is stored in `$sanitized` variable):
function scientifik_sanitize_url($url){
$prots = array('http', 'https');
$item = $url;
$escaped = esc_url_raw( $item, $prots );
if ( empty( $escaped ) ) {
return 'funny';
die();
}
return $item;
}; | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "urls, sanitization"
} |
Remove action working on functions.php but not in a plugin. Why?
I am trying to remove an action from Woothemes' Sensei plugin.
If I do on the functions.php:
global $woothemes_sensei;
remove_action('sensei_lesson_video', array($woothemes_sensei->frontend, 'sensei_lesson_video'));
I can remove the action.
But if I do the same on a plugin, I can't.
Actually, the problem is that after var_dumping $woothemes_sensei on a plugin a get NULL.
Why is that?
EDIT: Well, here is the answer. I should put the code inside a function and hooked it to `init`or `after_setup_theme`. But I found a Sensei hook, that runs before the loop (`sensei_before_main_content`). So I did:
add_action('sensei_before_main_content', 'trib_s2sensei');
function trib_s2sensei() {
global $woothemes_sensei;
remove_action('sensei_lesson_video', array($woothemes_sensei->frontend, 'sensei_lesson_video'));
} | The include of custom code via theme is different from the including via plugin. It is important, that you add a hook to include your custom source inside the plugin, like `after_setup_theme`, maybe with a low priority, after the default theme init his code. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, actions"
} |
No results searching custom post type in admin panel
So I have a custom post type `action` and when I search in the admin panel I don't get any results. I think I figured out why, but not sure how to fix it. When I enter a search term and then click "Search actions" it takes me to this url:
It shows no results, and I see why, but I don't understand where all those extra query vars are coming from? I disabled all plugins, emptied out my `functions.php` and still it takes me there, showing no results.
I can make it work if I manually change the url to:
The above will show any actions containing "foobaz".
Any ideas where do I begin to fix this? | The problem in this case is the name of the post type, `action`. WordPress core uses the query var `action` for its own purposes, so this has created a conflict somewhere within the code. The solution is to rename the post type to something unique to remove the conflict. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, admin, search"
} |
Shown icon if old
I have this code
<?php if( date('U') - get_the_time('U', $post->ID) < 24*60*60 ) : ?>New Post<?php endif; ?>
for posts that are under 24 hours old I want to alter the code for it to display Old Post if it's over 24 hours | Just flip the "less than" `<` to "greater than" `>`:
<?php if ( date( 'U' ) - get_the_time( 'U', $post->ID ) > DAY_IN_SECONDS ) : ?>Old Post<?php endif ?>
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "icon"
} |
WordPress login page logo customization
For some reason the first code works. But the second does not. And I can't figure out what is wrong with my syntax.
background-image: url("/wp-content/themes/flawless-v1-17-child-01/images/Logo-B-Classic.jpg") !important;
background-image:url('.get_stylesheet_directory_uri().'/images/Logo-B-Classic.jpg) !important; | **_get_stylesheet_directory_uri()_** is a PHP function, you must use it in a PHP file instead of your CSS file.
In your functions.php you can paste this code and change depends on your needs:
function my_login_logo() { ?>
<style type="text/css">
body.login div#login h1 a {
background-image: url(<?php echo get_stylesheet_directory_uri(); ?>/images/Logo-B-Classic.jpg);
}
</style>
<?php }
add_action( 'login_enqueue_scripts', 'my_login_logo' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "images, login, paths, logo"
} |
Show image if a post is featured
I know that posts that are sticky show on top but I want to add an image to show that is featured is there any code I could use | You can use the conditional tag, `is_sticky()` to check whether or not a specific post is a sticky post or not.
You can try the following **inside** your loop
if( is_sticky() ) {
//Display your desired image
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "sticky post, featured post"
} |
How to restrict the amount of categories/post tags/terms for a post type post
I'm in need of a solution that allows me to restrict the user/author to only use maximum of two categories per new post. One post can only have one or two categories.
The only similar solution that I have found is when you make the categories as radio buttons instead of check boxes. But that will restrict the user to choose only one category. Only one category per post
Any idea have to solve this? | Thanks the the replies. I solved my problem with jQuery.
Here is the code:
jQuery(document).ready(function ($) {
$("#category-tabs li.hide-if-no-js").hide(); //Hides Most Used tab
$("#category-all input:checkbox").change(function () {
var max = 2; // Max allowed cats
var count = $("#category-all input:checked").length; //counts selected cats
if (count > max) {
$(this).prop("checked", "");
alert('You are only allowed to select ' + max + ' categories.'); //alert message when user tries to select a third cat
}
});
}); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, metabox, users"
} |
Is it possible to pass variables to WordPress externally?
I would like to know if it is possible to pass json variables from a form which is located outside WordPress? This is the situation: The user fills a form located on x server. Then his answers are sent to the WordPress site located in Y server in which depending upon his answer he will get an offer. I´ve been Googling to see if I can find an example but cant find none.
Could you please guide me?
Thanks | It is possible and there are a number of ways to go about doing this, all of them requiring that you can write code or find someone willing to write it for you.
One option would be to send your content via ajax to admin-ajax.php along with any wanted authentication tokens ... and then listen on admin-ajax.php and process accordingly.
Another would be to create your own endpoint that checks for particular post data and then, if it looks correct, loads wordpress and adds what you need. For this you might search for bootstrapping wordpress or look at index.php in the wordpress root directory and see how it loads wordpress ... then do the same when needed.
There are probably a lot of other methods as well, but those two are relatively simple to implement and would do what you want to do.
Also, you might check out wp-api.org, which I just stumbled on via a post from kaiser on a different thread here. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "forms, variables, json"
} |
Is there a general way to get a themes primary colour?
I'm writing a plugin and I'd like it to play nicely with wordpress themes by adopting the themes colour schemes. To be specific, not just use a HTML element that was incidentally styled by a themes CSS but to actually get at the themes colour scheme to, for example, set a border colour on a custom element to follow the themes primary colour.
Is this possible, or do all themes save their config differently?
I seen mention of get_theme_mod($propertyName) - but is that propertyName defined by the theme author? I've seen other plugins advertised to follow a themes style - how do they do that? | The easiest way to follow the "theme style" is not to add CSS of your own.
There is really no such thing as "theme color scheme" and if there was, it might be hard coded. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, theme development"
} |
Move two independent sites to network
I have two independent sites, both have contents and plugins and themes. I know from docs how to convert one to a network but how do I import the second one on this network? By import I mean at DB level since I'll use directory approach for the network, any advice or help? | It's a good idea to search WP DEV before you post a new question: <
And Google is a good try, too:
The WordPress Codex is a good place to start: <
> Since Version 3.0, WordPress includes new multisite features, meaning that it can run many blogs, even with their own separate domains, on one WordPress installation. This tutorial explains how to migrate multiple WordPress installations into one new WordPress multisite. You can migrate sites that are using their own domain, as well as sites using a subdomain on your main domain. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "multisite, network admin"
} |
How to update global header and footer
I have a problem with the global header and footer in multisite. When I change the root's header and footer, the subsites (all other blogs) don't update.
This is my code:
global $switched;
switch_to_blog(1);
get_header();
restore_current_blog();
switch_to_blog(1);
get_footer();
restore_current_blog(); | Resolved using this code:
global $switched;
switch_to_blog(1);
//get_header();
$root = realpath($_SERVER["DOCUMENT_ROOT"]);
include ($root.'/wp-content/themes/themename/header.php');
restore_current_blog();
global $switched;
switch_to_blog(1);
//get_footer();
$root = realpath($_SERVER["DOCUMENT_ROOT"]);
include ($root.'/wp-content/themes/themename/footer.php');
restore_current_blog(); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "switch to blog"
} |
No Error Log File, no debug info
My error when writing a plugin for uploads
and yes, I can debug. But it just jumps directly from this line to `destruct`
!enter image description here
the end of my `wp-config.php` **EDIT:**
// Enable WP_DEBUG mode
define('WP_DEBUG', true);
// Enable Debug logging to the /wp-content/debug.log file
define('WP_DEBUG_LOG', true);
/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');
(yes i did restart)
My webcontent folder
!enter image description here
So now what?
How do I find out what is the problem?
**EDIT** it's not file permission as I can do `error_log("errrorrrr ", 3 , "..../debug.log")`
In my plugin I wrote the line
`throw new \Exception("foo");`
I want to get to see the error in my debug.log file | Insert this into your wp-config.php
// Enable WP_DEBUG mode
define('WP_DEBUG', true);
// Enable Debug logging to the /wp-content/debug.log file
define('WP_DEBUG_LOG', true);
// Disable display of errors and warnings
define('WP_DEBUG_DISPLAY', false);
@ini_set('display_errors',0);
Before
`/* That's all, stop editing! Happy blogging. */` | stackexchange-wordpress | {
"answer_score": 12,
"question_score": 13,
"tags": "plugin development, errors, customization"
} |
Sort search results by post type
I need to sort my search results by custom post type. the problem: the order is custom.
I do have 5 different post types and i got the order like so:
1. artist
2. artwork
3. page
4. post
5. publication
I'd like the order to be like this:
1. artist
2. post
3. artwork
4. publication
5. page
Here is what I have so far, the elements are grouped by their post type and get sorted by title. Wonderful. Now all I need is the custom ordering.
Any hint?
add_filter( 'posts_orderby', 'order_search_by_posttype', 10, 2 );
function order_search_by_posttype( $orderby ){
global $wpdb;
if( ! is_admin() && is_search() ) :
$orderby = "{$wpdb->prefix}posts.post_type ASC, {$wpdb->prefix}posts.post_title ASC";
endif;
return $orderby;
} | I found the key: SQL CASE Expression
function order_search_by_posttype($orderby){
if (!is_admin() && is_search()) :
global $wpdb;
$orderby =
"
CASE WHEN {$wpdb->prefix}posts.post_type = 'artist' THEN '1'
WHEN {$wpdb->prefix}posts.post_type = 'post' THEN '2'
WHEN {$wpdb->prefix}posts.post_type = 'artwork' THEN '3'
WHEN {$wpdb->prefix}posts.post_type = 'publication' THEN '4'
ELSE {$wpdb->prefix}posts.post_type END ASC,
{$wpdb->prefix}posts.post_title ASC";
endif;
return $orderby;
}
add_filter('posts_orderby', 'order_search_by_posttype'); | stackexchange-wordpress | {
"answer_score": 22,
"question_score": 8,
"tags": "custom post types, functions, filters"
} |
Add custom list menu on Posts page in admin panel
How can i add custom_list as shown in attached screen-shot. I want to list posts having some meta_value . Is there any way of adding this. I am not looking to edit the core files. Please guide me in right way.
!Add custom list menu on Posts page in admin panel | You can use the `views_{$this->screen->id}` filter in `WP_List_Table::views()`, where screen ID in this case is `edit-post`:
function wpse_177655_views( $views ) {
$custom = sprintf( '<a href="%s"', esc_url( 'edit.php?post_type=post&custom=foobar' ) );
if ( ! empty( $_GET['custom'] ) && $_GET['custom'] == 'foobar' )
$custom .= ' class="current"';
$custom .= '>Custom</a>';
$views['custom'] = $custom;
return $views;
}
add_filter( 'views_edit-post', 'wpse_177655_views' );
Obviously this is more of an example than an exact solution. You'll also need to hook onto `pre_get_posts` to add the relevant meta query args. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "wp admin"
} |
ACF no print data
I've a problem with Advanced Custom Fields Plugin
I create a custom field named: `bgcolor`
I want to print the value in `category.php`, this is my code:
$color = get_field('bgcolor', 'category_'.the_category_ID( $echo ).'');
echo $color;
What its wrong?
Thanks | I assume you want the field for the current category archive, not the category of the post inside the loop? Try `get_queried_object_id()` instead of `the_category_ID( $echo )`.
In `single.php`, you just need a slightly different iteration of your original attempt:
if ( $terms = get_the_category() )
the_field( 'bgcolor', 'category_' . $terms[0]->term_id ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, custom field, advanced custom fields"
} |
add_action in the loop hooks
I have the following structure:
add_action('my_content', 'standard_loop');
function standard_loop() {
if (have_posts()) :
while (have_posts()) :
the_post();
do_action('loop_entry_before');
do_action('loop_entry');
do_action('loop_entry_after');
endwhile;
endif;
}
add_action('loop_entry_before', 'do_entry', 1);
function do_entry() {
if ( get_the_title() ) {
add_action('loop_entry_before', 'function_that_adds_h2_structure');
}
add_action('loop_entry_entry', 'function_that_adds_content_structure');
}
The issue is that all post display the function_that_adds_h2_structure even if is only empty html and the post has no title. This is just an example for using login in the do_entry();
Thanks | Once a fucntion has been hooked to an action, the function will be executed every time the action is called (with `do_action`). To stop this, the action should be removed. See `remove_action`:
function do_entry() {
if ( get_the_title() ) {
add_action('loop_entry_before', 'function_that_adds_h2_structure');
} else {
remove_action('loop_entry_before', 'function_that_adds_h2_structure');
}
add_action('loop_entry_entry', 'function_that_adds_content_structure');
}
In your case, I think that the actions hook approach is not very good and it can be better to do direct function calls:
function do_entry() {
if ( get_the_title() ) {
function_that_adds_h2_structure();
}
add_action('loop_entry_entry', 'function_that_adds_content_structure');
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "loop, hooks, actions"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.