INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Post URL duplication adds numerical value
I thought that belonging to these different categories url naming posts the same would be treated as distinct.
Categories:
* Home
* Hotel
Posts:
* street
* street
URL generated:
1. www.my.com.br/casa/street-a
2. www.my.com.br/hotel/street-a-2
> I wonder how to solve this, I imagine that it affects> SEO <.
What is the solution to set that House and Hotel BELONG the same street to avoid being added this numerical value 2? | Posts have a slug (that's the last part of the URL), and it must be distinct, even if posts are in different categories.
If your only worry is SEO, don't worry. Google sees the URLs as distinct, and Google is used to dealing with URLs that have a suffix on them, and has no problems with it. The keywords in the URL are still the same and have the same value.
If you still want to change this, you could manually change the slug when you create the post, or you could hook into save_post and change the slug to be street-casa. But there is no need. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, urls, seo"
} |
Override plugin localization
Is it possible to override the localization files provided (or not provided) by a 3rd party plugin? A plugin that I'm using now doesn't have any language files but I want to avoid having a future update to the plugin overwrite the translation files that I've created. | From what you are saying you have translated your plugin and now you want to be sure the future update won' be overwritten. So to avoid that happening you can always put your po/mo translation files (if provided) in global languages folder that is located on your server in wp-content/languages/plugins folder.
If plugin have language file name for example someplugin.pot, from there you can generate someplugin-en_US.po and someplugin-en_US.mo files and put them in folder I mentioned before. Note that I put language code en_US just as an example you will add your language code.
Or you can just not update the plugin (but not recommended). There is also a plugin that disables plugin from auto update here.
Also for all kind of translations I would recommend using you LOCO TRANSLATE which you can use and automatically put your po/mo files generated from plugin .pot to global languages folder.
I hope this helps.
Kind regards,
Usce | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 4,
"tags": "plugins, plugin development, localization"
} |
After plugin activation hook
Does it **OK** , to send email (to me) after user activate my plugin?
Does it a right way to do that (< with hook?
thanks | In the context of official plugin repository this is very explicitly forbidden by the guidelines (emphasis mine):
> 7\. No "phoning home" without user's informed consent. This seemingly simple rule actually covers several different aspects:
>
> * No unauthorized collection of user data. **For example, sending the admin's email address back to your own servers without permission of the user is not allowed** ; but asking the user for an email address and collecting if they choose to submit it is fine.
>
>
> <
Other than that it will risk you reputation (imagine what user will really _like_ discovering you did it?) and might have legal implications. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugin development, hooks"
} |
How can I apply css styling to the current day in the calendar widget
How can I apply css styling to the current day in the calendar widget? It seems there is no css class for the current day. | On my default calendar widget I get:
<td id="today">30</td>
so you could use `#today`.
It uses the `get_calendar()` function where we have the following:
if ( $day == gmdate( 'j', $ts ) &&
$thismonth == gmdate( 'm', $ts ) &&
$thisyear == gmdate( 'Y', $ts ) ) {
$calendar_output .= '<td id="today">';
} else {
$calendar_output .= '<td>';
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "widgets, calendar"
} |
Query with custom taxonomy not working
I have custom post type ' **mix** '. And custom taxonomy ' **meal** '. And categories in custom taxonomy (one of that is with slug: **breakfast** )
_I have problems with making query. My code is :_
$args = array(
'post_type' => 'mix',
'tax_query' => array(
array(
'taxonomy' => 'meal',
'field' => 'breakfast'
)
),
'posts_per_page' => 50
);
$query = new WP_Query( $args );
_My loop is:_
if( $query->have_posts() ):
while( $query->have_posts() ): $query->the_post();
//something here...
endwhile;
endif;
But problem is that nothing show up. | The solution is to use:
'taxonomy' => 'meal',
'field' => 'slug',
'terms' => 'breakfast'
The `taxonomy` and `terms` are obvious, but why does field have to be slug? When you add taxonomy parameters, you can specify what 'breakfast' is-- via the field. It could be the term's ID, the full name, or slug. See the codex on Taxonomy Parameters | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "wp query, custom taxonomy, query posts"
} |
Users are redirected to homepage instead of wp-admin
After migrating my wordpress site users **who are not Admins** are redirected to the site's **homepage after login**. On the old site they were redirected on wp-admin. The Administrator is redirected to wp_admin as it should.
I want the users to be redirected to `wp-admin` after login.
I changed siteurl from the database (`wp_options`), also added this filter in my `functions.php`:
function my_login_redirect( $redirect_to, $request, $user ) {
return admin_url();
}
add_filter( 'login_redirect', 'my_login_redirect', 10, 3 );
Any help please? Thank you and Happy Easter! | Yeeey, I figured it out! Actually my theme had a redirect like this one in `functions.php`:
// Block Access to /wp-admin for non admins.
function custom_blockusers_init() {
if ( is_user_logged_in() && is_admin() && !current_user_can( 'administrator' ) ) {
wp_redirect( home_url() );
exit;
}
}
add_action( 'init', 'custom_blockusers_init' ); // Hook into 'init'
All you have to do is add your own role capability, for example: `!current_user_can( 'manage-reports' )`
This helped me a lot. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "wp admin, redirect, login"
} |
Login user using wp_signon and WP_User object
The problem is that `wp_signon` function requires password as plain text. Where `WP_User` object returns user password as hashed.
There is any way to safety login using user WP_User object? Something like this:
$user = new WP_User(1);
wp_signon([
'user_login' => $user->user_login,
'user_password' => $user->user_pass,
'remember' => true,
]); | You need `wp_set_auth_cookie`:
wp_set_auth_cookie( $user_id, ( bool ) $remember ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "login"
} |
wp query error while paging the posts
i am new to wordpress and i am learning paging the posts but the code below isnt working and i cant find whats wrong. please help.
**the code:**
<?php
$temp = $wp_query;
$wp_query= null;
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$wp_query = new WP_Query( 'posts_per_page=2&paged='.$paged );
while ( $wp_query->have_posts() ) : $wp_query->the_post();
?>
<h2>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</h2>
<?php the_excerpt(); ?>
<?php endwhile; ?>
<div class="navigation">
<div class="alignleft"><?php previous_posts_link( '« Previous' ); ?></div>
<div class="alignright"><?php next_posts_link( 'More »' ); ?></div>
</div>
<?php
$wp_query = null;
$wp_query = $temp;
?>
**the error**
> Call to a member function get() on null in /var/www/html/wordpress/wp-includes/query.php on line 28 | You are setting `null` to `$wp_query` then querying `get_query_var( 'paged' )` this is expected that you will get this error!
First query `get_query_var( 'paged' )` then set the original `$wp_query` to `null`
Example:-
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
global $wp_query;
$temp = $wp_query;
$wp_query = new WP_Query( 'posts_per_page=2&paged='.$paged );
while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?>
<h2>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</h2>
<?php the_excerpt(); ?>
<?php endwhile; ?>
<div class="navigation">
<div class="alignleft"><?php previous_posts_link( '« Previous' ); ?></div>
<div class="alignright"><?php next_posts_link( 'More »' ); ?></div>
</div><?php
wp_reset_postdata();
$wp_query = $temp;
> NOTE: Do not forgot to add `wp_reset_postdata()` after loop. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wp query, pagination"
} |
Can I transfer a mysql database to another site?
I've been playing around with WP for about 2 years so I know my way around, but I'm kinda new to working with databases. I've been making sites not relying on a database too much. However, I have a web directory site built on PHPLD which is staring to look outdated so I want to move the site over to a WP directory theme. The database contains over 15000 website directory listings and I have no idea how to make the WP theme reflect these. Any ideas? | you can export tables of your database that you want to transfer, and Import to another database, then you should change Prefixes of those . | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "database, mysql"
} |
Outputting Page Title As Tooltip
I'm trying to output the page title via `wp_nav_menu()` as a tooltip (.pop_up). The menu text has been replaced by an icon, and using CSS to hide it.
Any ideas how this could be adapted to output the string name where the text "MENU LINK" is shown? Is this actually possible?
wp_nav_menu( array(
'menu' => 'Main Menu',
'after' => '<div class="pop_up">MENU LINK</div>'
)); | Found a way... instead of using `wp_nav_menu()`
$menu_name = 'main-menu';
if ( ( $locations = get_nav_menu_locations() ) && isset( $locations[ $menu_name ] ) ) {
$menu = wp_get_nav_menu_object( $locations[ $menu_name ] );
$menu_items = wp_get_nav_menu_items($menu->term_id);
$menu_list = '<ul id="menu-main-menu">';
foreach ( (array) $menu_items as $key => $menu_item ) {
$title = $menu_item->title;
$url = $menu_item->url;
$id = $menu_item->ID;
$menu_list .= '<li id="menu-item-' . $id . '"><a href="' . $url . '"></a><div class="pop_up">' . $title . '</div></li>';
}
$menu_list .= '</ul>';
}
echo ($menu_list); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "menus"
} |
How do I routinely extract the thumbnail of the most recent post?
I would like to write a PHP snippet that can communicate with Wordpress.
When a new post is published, a file today.jpg will be generated from the thumbnail url (a custom field) of the most recent post.
Or I can schedule a cronjob to execute daily for this action.
How can I implement this function?
My idea is to do it outside of functions.php so that it won't get executed all the time, while a scheduled update for today.jpg seems more resource friendly.
Any pointer is appreciated. | No need for a routine here - use the WordPress hook system to "attach" a function that will run when a post is published:
//
function wpse_225371_post_published( $post_id, $post ) {
// Do your thang
}
add_action( 'post_published', 'wpse_225371_post_published', 10, 2 ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, functions, customization, images, wp cron"
} |
Is it possible to place custom post type files inside a folder in theme directory?
I have created a custom post type called `customtype`. From my understanding the template file for it would be `single-customtype.php` which is placed inside `wp-content/themes/mytheme`.
Can I place the `single-customtype.php` file inside a custom folder in the theme directory? It's not critical but would help with theme files organization.
This is what I want to achieve: `wp-content/themes/mytheme/customtype/single-customtype.php` | You may want to look at the TwentySixteen theme, which does it this way:
In `single.php`:
`get_template_part( 'template-parts/content', 'single' );`
Several templates are grouped in the 'template-parts' folder. You could use a similar logic for your custom post type.
It seems that the technique comes from _underscores. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom post types, theme development, themes, directory"
} |
Cannot Find Hook that is changing the_content()
I am working with a wordpress theme that is using Foundationpress as it's starter theme. When I use `the_content()` all `img` tags have there css class replaced with `image`. This is overwriting the ability for the editors to use there own classes.
While debugging if I `die(get_the_content())` I see the original classes. I have been going through the entire project trying to find where that logic could be overwriting these classes. Has anyone seen this before ?
So far i have checked:
1. Functions.php
2. All javascript
3. Library directory that comes with foundationpress.
Anywhere I could be overlooking? | It's unusual for `the_content` to be rewriting image classes like this; it sounds like it could be a plugin (or theme function) which is doing this. Have you disabled all plugins just to check?
Having said that, most of the functions in core that hook into `the_content` are located in `wp-includes/default-filters.php` (apart from the oembed functions).
You can remove any of them by adding the following to your theme's `functions.php`, eg. to remove the `wpautop` function:
remove_filter("the_content", "wpautop");
However none of these should be messing with these classes. The `wp_make_content_images_responsive` function _will_ be messing with image tags, but it should only be checking the classes, not changing them, which is why it sounds like these changes could be happening in a plugin. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "the content"
} |
Best db table structure for users with many records
I want to allow users to have 1000+ records in my WordPress system.
I was wondering is it best to have just one table for all users and their records or one table per user?
Keep in mind that I could have 1000 users.
A user columns for records would look like:
User_client_name | User_id | User_post_id | etc...
Each user might have 1000+ records in the database of their contacts. If I put all users in one table, I would have to show each of my users their records separated by User_id.
I was wondering is it better to create a new table per new user I signup for? Or stick to one table of users and their records? | Personaly I would go with one table for all users. Having more tables with the same columns seems like a strange idea to me. The database will be a complete mess after you gwt more users.
Make sure that the `user_id` is an index for the table and all your select/update/delete will be fine. The insert might have a very short but unsignificant delay after the table gets bigger, but I guess this might not be the most used opperation. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -1,
"tags": "database"
} |
Link to Download Latest WordPress PLUGIN Version
I use the following code in my PHP script to automatically download the latest version of WordPress...
$wordpress_zip_file_url = '
file_put_contents("wordpress.zip", file_get_contents($wordpress_zip_file_url));
Does this work for plugins the same way? For example, I'd like to automatically download the latest backupwordpress plugin version --> <
Is there a generic link to download the latest version of a plugin? | `
The structure should be the same for all WordPress.org plugins and the link you're looking for is:
`
You can see an example here on how this might be used.
* * *
To update plugins through WP-CLI:
wp plugin update backupwordpress | stackexchange-wordpress | {
"answer_score": 14,
"question_score": 7,
"tags": "plugins"
} |
Replace content via rest api only?
I am not really looking for code as answer but just the idea.
How can i replace content in posts or pages without using short codes or plugins via the recent rest API? In template engines you'd have variable place holders filled later by whatever but I'd like to get exactly around writing extra wp code (short codes, hooking into events, etc...)
However, I can't obviously just drop my custom markup in the content because it would be displayed to users as well. Eventually there is a trick over CSS but I'd love to hear the experts first.
thanks a lot, g | You can use filter for replace text in all post and all pages. add this code to theme function.php
add_filter( 'the_content', 'filter_content_for_replace_text' );
function filter_content_for_replace_text($content){
$content=str_replace("find","replace with",$content);
return $content;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "rest api"
} |
Add post/page ID to inserted links within the_content
Within the main content editor of posts and pages, we can insert multiple links to other posts/pages:
<a href=" World</a>
What I am trying to do is get Wordpress to automatically add the ID of, in this case, the Hello World post to the link. To try and clearly explain what I'm wanting, imagine I'm writing a new blog post and I put a link within the new blog post to my existing Hello World post.
<a id="4" href=" World</a>
Where in the above example our Hello World post has the ID of 4. I have been studying this answer to a different question but I haven't quite figured out how to get the ID of the post/page I am linking to and add it to the anchor element. Incase we have more than one link pointing to the same post/page it might be safer to use the rel attribute instead:
<a href=" rel="4">Hello World</a> | This is the solution I arrived at with thanks to the pointer from @bravokeyl
So, to be clear **it does not add the ID's to links** but by using the link slug I'm able to get the ID which is a solution for what I need. I'm using JS to pass the URL into this function and then stripping it down to the slug only which is used within `get_page_by_path` which then returns the ID for that post.
It's part of what I'm working on to build an Ajax powered theme. This approach also solves the issue of having multiple links with the same ID's.
function local_post_init() {
/** Get post ID from slug **/
$page_slug = $_POST['id'];
$page_data = get_page_by_path(basename( untrailingslashit( $page_slug ) ) , OBJECT, 'post');
$page_id = $page_data->ID;
/** $page_id holds our ID which we then use in our query */
$args = array( 'p' => $page_id );
$theme_query = new \WP_Query( $args );
post_template($theme_query);
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 3,
"tags": "filters, the content"
} |
What goes into wp_postmeta and why?
we are using WordPress in a site that has Places and eventsOn running, however we notice that sometimes the newly inserted place data goes into the wp_postmeta table others it doesn't... Searched for more information about this table schema and no result, can anyone shed a light on this and give me a better insight ?
Thanks, | Like several other tables it is just matching a key to value, when is this specific case they key is composed of the post id number and a string.
It is usually used to store additional information about the post that is not part of the content. In you case probably the place location or event time.
The reason to do such a thing, instead of just inserting it in the content, is to be able to run DB queries based on those values, for example find all posts that are related to event that happen at Christmas at NYC. This is something that is much harder to do when the information is in a free textual format as part of the text.
When does it actually being used by plugin X? depends on the code of the plugin, there are no rules that are being enforced about that. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins"
} |
How to display parent category name and link for custom breadcrumb
I'm currently trying to figure out how to display a categories parent / grand parents name and url for a custom breadcrumb I'm working on.
I simply need to know how to show the parent categories information on a child category page.
**For example**
if parent
blog
else if child
blog > parent_category
else if grandchild
blog > grand_parent_category > parent_category | You can use `get_ancestors`:
<?php
if ( $term_ids = get_ancestors( get_queried_object_id(), 'category', 'taxonomy' ) ) {
$crumbs = [];
foreach ( $term_ids as $term_id ) {
$term = get_term( $term_id, 'category' );
if ( $term && ! is_wp_error( $term ) ) {
$crumbs[] = sprintf( '<a href="%s">%s</a>', esc_url( get_term_link( $term ) ), esc_html( $term->name ) );
}
}
echo implode( ' > ', array_reverse( $crumbs ) );
} | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 2,
"tags": "categories, breadcrumb"
} |
Query does not filter duplicate _sku numbers
I need to find ALL the post_id in table `wp_postmeta` that has duplicate sku numbers. I did this with following sql query but the query is not complete. Now I get the full list of all products as result. The field post_id is missing but I do not know how to set filter on it if count(post_id > 1) Is there someone of you who can modify the query and add the missing part to filter only the duplicate sku? Would be very helpful for me. Thanks in advance.
SELECT * FROM `wp_postmeta`
WHERE `meta_key` LIKE '%sku%' | I haven't tested this, but this should give you the count of skus for each post_id:
SELECT post_id, COUNT(`post_id`) AS sku_count FROM `wp_postmeta`
WHERE `meta_key` LIKE '%sku%'
GROUP BY `post_id`
To have it return only rows where the count is greater than one is trickier. Off the top of my head I'd probably use the above as a subquery:
SELECT * from (< insert the above query >) AS counts where counts.sku_count > 1
Might need some tweaking.
If you can avoid using `LIKE`, or at least get rid to one of the `%` wildcards, you will improve performance | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "mysql"
} |
pass query string on url to filter media
I have an author page which shows all uploaded media by that author. Each media can have tag1, tag2 or tag3. I would like to add an option where I can show on that same page only tag1 media without have to setup a new site structure. So I can up with the idea of using query strings.
My idea: passing a query string like http....url.../author/name?MediaTag=tag1
And use this in my query like `<?php query_posts('cat=1&author=' . $post->post_author . '&order=DESC&tag=' . $tag1 .'&posts_per_page=12' . '&paged=' . get_query_var('paged')); ?>`
and a check if there is no query string, it uses the one I'm using right now `<?php query_posts('cat=1&author=' . $post->post_author . '&order=DESC&posts_per_page=12' . '&paged=' . get_query_var('paged')); ?>`
Do I need to do anything else? Like catch the query string? Is this going to work? But never used this and any help is more than welcome. Maybe there is another way. | As per the given url `http....url.../author/name?MediaTag=tag1`, below code may helpful...
if(isset($_GET['MediaTag'])) //It will check the value of MediaTag (from address bar after ?)
{
$tag1 = $_GET['MediaTag']; //Assigning value of MediaTag to the variable
if($tag1) //Checking if variable have some value or not
{
query_posts('cat=1&author=' . $post->post_author . '&order=DESC&tag=' . $tag1 .'&posts_per_page=12' . '&paged=' . get_query_var('paged'));
} else {
query_posts('cat=1&author=' . $post->post_author . '&order=DESC&posts_per_page=12' . '&paged=' . get_query_var('paged'));
}} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "query posts, media, author template, query string"
} |
Make a plugin page out of influence of the theme's style
I have to make several change to my style to be with what i want, when i export a project to a wordpress plugins :
Based on this :
 );
foreach ($results as $result) {
echo '<p>' .$result->id. '</p>';
} ?>
But it does not work. When I changed the table name to one word for testing, then it works:
<?php
$results = $wpdb->get_results( $wpdb->prepare("SELECT * FROM test") );
foreach ($results as $result) {
echo '<p>' .$result->tester. '</p>';
} ?>
Why does the `sparte-bogensport` table name doesn't work?
This query should be shown over a page. I used the plugin "PHP Code For Posts" but this don't support WordPress varaibles. Do you have an alternative for me?
Regards Peronia | Try putting the table name inside quotes, like this
SELECT * FROM `sparte-bogensport`
**Edit**
More info on why this happens: < | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "database, sql"
} |
How do you get parent and grandparent categories
I'm wondering how you can receive a categories parent name and link for a breadcrumb I've written.
I basically want to have the following structure
if child category
blog > parent_category
else if grandchild category
blog > grand_parent_category > parent_category | This query will help you
global $wpdb;
$cat_id = 65;
// this query will get parent relationships from term_taxonomy table and get category names from terms table
$category = $wpdb->get_row(
"SELECT t4.term_id as parent_id, t4.name as parent_name, t5.term_id as grandparent_id, t5.name as grandparent_name FROM `{$wpdb->prefix}term_taxonomy` t1
left join `{$wpdb->prefix}term_taxonomy` t2 on t2.term_id = t1.parent
left join `{$wpdb->prefix}term_taxonomy` t3 on t3.term_id = t2.parent
left join `{$wpdb->prefix}terms` t4 on t4.term_id = t2.term_id
left join `{$wpdb->prefix}terms` t5 on t5.term_id = t3.term_id
where t1.term_id={$cat_id}"
);
if ($category->grandparent_id) {
echo "blog > {$category->grandparent_name} > {$category->parent_name}";
} else if ($category->parent_id) {
echo "blog > {$category->parent_name}";
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -2,
"tags": "categories"
} |
jQuery append only works if I select html in admin section
The following jQuery code works as expected, in that it inserts the specified html after the closing tag.
$( "html" ).append( "<div id='bf_rsvp_note_display'></div>" );
However, that's a clunky place to insert it. Ideally, I'd like to append it to , but using any other element stops it working.
$( "body" ).append( "<div id='bf_rsvp_note_display'></div>" );
and
$( ".exampleclass" ).append( "<div id='bf_rsvp_note_display'></div>" );
both do nothing - no errors, no anything.
Why is this? | These three lines work as expected , There is a problem maybe with other code before these lines that prevent the execution of your script;
In case just fire the browser console in this page and try them here
$( "html" ).append( "<div id='bf_rsvp_note_display'></div>" );
$( "body" ).append( "<div id='bf_rsvp_note_display'></div>" );
$( ".topbar" ).append( "<div id='bf_rsvp_note_display'></div>" ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "jquery, javascript"
} |
Get all terms assigned to a post from different taxonomies
There are different taxonomies. I have assigned different tags from these taxonomies to different posts. Can anyone help me to get all the terms which are assigned to a post. (Different terms from different taxonomies are assigned to a post) | WordPress tracks which object types taxonomy applies to. This can be established on taxonomy registration or at some point after, so you shouldn't be trying to do this too early.
The approach would be to retrieve the list of taxonomies for the native `post` type and use it with lower level function, which supports multiple taxonomies:
$terms = wp_get_object_terms( $post_id, get_object_taxonomies('post') );
Of course if you interested in a list of _specific_ taxonomies you can just hardcode that as input. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "custom post types, custom taxonomy, terms"
} |
I need to hook and change language of facebook sdk
I need to hook into this function to change language to from en to french facebook sdk.
$facebook_sdk_src = apply_filters( 'bimber_facebook_sdk_src', '//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.5' );
So I only need to change this url on second, and I need to add or apply some filter. So how can I change this url part `//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.5` | Check the documentation of `add_filter()` first argument is name of filter and second one is callback function name. (both are required)
See the example for your case:-
add_filter('bimber_facebook_sdk_src', 'change_fb_sdk_url');
function change_fb_sdk_url($current_url) {
// Variable $current_url hold the current value of URL
// You can manipulate what you want
// Or simply return your URL
return '//url_you_want';
}
Please note:- filter callback function must return the value! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "filters, hooks"
} |
Enque Typekit Fonts - Not Found
I'm trying to enqueue a typekit on my WP site in a function using code below:
/**
* TypeKit Fonts
*
* @since Theme 1.0
*/
function theme_typekit() {
wp_enqueue_script( 'theme_typekit', '//use.typekit.net/xxxxxxx.js');
}
add_action( 'wp_enqueue_scripts', 'theme_typekit' );
function theme_typekit_inline() {
if ( wp_script_is( 'theme_typekit', 'done' ) ) { ?>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<?php }
}
add_action( 'wp_head', 'theme_typekit_inline' );
Code appears to be working fine, however when url called on frontend it's showing 404 in console for link, `
Any idea why not found? Note, I'm using a valid typekit code on my end. | As mentioned in the comments, your code snippet is working fine. Nevertheless the font kit has to be published within the _Kit Editor_ :
1. Login to your Typekit account
2. Locate the _Kit Editor_ (see:
3. Click the _Publish_ button (bottom right)
You may also consider using the new embed code provided by Typekit:
<script>try{Typekit.load({ async: true });}catch(e){}</script> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "wp enqueue script"
} |
Get Meta from Custom Field of Image URL
I have a custom field that is an Image and the return value of the field is Image URL.
I have custom page templates where I render these image fields. Is there a way to get the meta info for the image through the image url. I do not want to change the return value to Image Object or Image ID. | I needed the code in functions.php so that I could re-use it. Here's my solution below:
function get_img_alt($attachment) {
$post = get_post();
$image_id = get_post_meta( $post->ID, $attachment, true );
$image_alt = get_post_meta($image_id, '_wp_attachment_image_alt', true);
print $image_alt;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom field, images, page template"
} |
How to create an optionally available stylesheet for visually impared users?
I have a WP website that I would like to make easily accessible for visually impaired users. I don't want to modify the default stylesheet, nor I would like to use any plugins, so I am looking for a solution with button or link that would turn on/off a specially designed stylesheet.
My questions... Is it possible to create an alternative stylesheet for a WP site that can be turned on by user request at all? What do you think is the best way to implement it? | Easy to setup a button trigger/toggle with a bit of jQuery. Here's a working example I made for you: <
The Code:
**HTML:**
<button id="impaired-button">Impaired Button</button>
**jQuery**
$('#impaired-button').click(function() {
$('body').toggleClass('impaired');
});
**CSS**
.impaired h1 {
font-size: 50px;
}
Just add .impaired before any css that you want specifically styled for impaired users. This will be shown when the button is clicked. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "css, accessibility"
} |
Hook added to the_content seems to be called multiple times
I have the following code running in a plugin:
add_filter('the_content','thousand_pay');
//Callback function
function thousand_pay($content)
{
echo $content;
if( !in_category( 'Stories') )
{
return;
}
?>
<hr></hr>
[Some HTML]
<?php
return
}
For some reason, on individual posts' pages the HTML gets printed multiple times:
 and is_main_query(), so it would look like `if(!in_category('Stories') || !is_singular() || !is_main_query()`, but that just seems to stop the HTML getting printed at all on a post page. Any ideas? | It is normal for content to be accessed multiple times. For example SEO plugins need to do this to access it and generate meta data from.
Also it is a _filter_ hook. Filters should never echo anything to the page, they are meant to modify passed value and return it.
If you do want to do something at that point, but only within the loop then `in_the_loop()` is condition you need. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 5,
"tags": "filters, the content"
} |
Option for pages order in backend
Can someone tell me what is this ordering in pages list in backend and how does it affect anything? Searching for wordpress pages order doesn't give me meaningfull results
`.
By default, this will output all of your pages firstly by their order, then by their title if the orders match.
This makes it simple to avoid the extra step entirely of configuring a menu, which is great for small sites - while still having the ability to get things in the right order.
Even on a site with menus defined, it can be nice to have the pages in the order one would expect to find them in, to make management easier. eg. I usually give the home page an order of -100 so it always appears at the top, and a Contact Page an order of 900 so it usually appears at the bottom. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "pages, order"
} |
How to filter out shortcode when displaying the_excerpt() in the loop?
I'm using `the_excerpt()` in my template loop to display post excerpt on the front page.
It's currently displaying unwanted shortcode directly on the front page
eg.
`[box]post content[/box]`
`[alert]post content[/alert]`
How can I filter out these shortcode only while keeping the actual content? | try this
add_filter( 'get_the_excerpt', 'strip_shortcodes', 20 );
or try this edit
echo strip_shortcodes( get_the_excerpt() );
if shortcode is not register with wordpress function add_shortcode
add_filter( 'the_excerpt', 'remove_shortcodes_in_excerpt', 20 );
function remove_shortcodes_in_excerpt( $content){
$content = strip_shortcodes($content);
$tagnames = array('box', 'alert'); // add shortcode tag name [box]content[/box] tagname = box
$content = do_shortcodes_in_html_tags( $content, true, $tagnames );
$pattern = get_shortcode_regex( $tagnames );
$content = preg_replace_callback( "/$pattern/", 'strip_shortcode_tag', $content );
return $content;
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "functions, filters, excerpt, regex"
} |
$update is always true in save_post
I'm trying to fire some code only when a document type is created using save_post, but $update is always true, even when first publishing it.
I assume this is because there's an autodraft created first. Is there any way around this? | So appreciate this is a bit late but I was having the exact same issue, the $update parameter is almost completely useless if you want to check whether it is a new post or not.
The way I got around this was to compare the `$post->post_date` with `$post->post_modified`. Full code snippet below.
add_action( 'save_post', 'save_post_callback', 10, 3 );
function save_post_callback($post_id, $post, $update) {
$is_new = $post->post_date === $post->post_modified;
if ( $is_new ) {
// first publish
} else {
// an update
}
}
Hope that helps anybody else finding this. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 5,
"tags": "save post"
} |
Custom script file enqueue has "?ver=4.5.1" when loading and doesn't update
I'm loading a custom script file using an enqueue and here's the output:
`<script type='text/javascript' src='.../wp-content/themes/enfold-child/js/custom_script.js?ver=4.5.1'></script>`
curious why it's appending that "?ver=4.5.1" at end. When I remove in console file loads fine, but when it's there blank file. Not sure if that's a caching thing or I should be loading some other way. Here's my enqueue code:
add_action('wp_enqueue_scripts','enqueue_our_required_stylesheets');
function my_scripts_method() {
wp_enqueue_script(
'custom-script',
get_stylesheet_directory_uri() . '/js/custom_script.js',
array( 'jquery' )
);
}
add_action( 'wp_enqueue_scripts', 'my_scripts_method' ); | I agree with @Mark Kaplun - what you're describing is an odd behavior though. Try this markup to override the `$ver` param.
`wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js', array ( 'jquery' ), null, true);`
<
Alternatively, to work around the version cache try this markup which will generate a unique version with each page load.
`wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js', array ( 'jquery' ), rand(1, 100), true);` | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 0,
"tags": "wp enqueue script, wp head"
} |
Add version query tag to all images
I want caching all images on my site and prevent the browser download the images all times, so I would like add an version query tag to all images (for example: `?v=20160505`)
How can I add this for image urls? Now I use this code to show images in my theme:
echo get_the_post_thumbnail( $thumbnail->ID, 'thumbnail' ); | Don't know why you want to do it when there's `update_post_thumbnail_cache()` in WordPress and set expire headers on server side. But you can try this in your `functions.php`:
add_filter('wp_get_attachment_image_src', function($img, $id, $size, $icon) {
$img[0] = $img[0] . '?v={$some_version}';
return $img;
}, PHP_INT_MAX, 4); | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 1,
"tags": "plugin development, thumbnails"
} |
Pass a parameter to a menu walker
Is there any way to pass a parameter to a menu walker? I'm trying to write a BEM-style walker, and I'd like to be able to pass a class to apply to the menu links via the walker. Something like:
<?php
wp_nav_menu(array(
"container" => false,
"depth" => 3,
"items_wrap" => "%3\$s",
"theme_location" => "primary",
"walker" => new BEMwalker("mobile"),
));
?> | As @toscho said, you can call the walker class with parameters as you did:
new BEMwalker( 'mobile' )
The constructor of `BEMwalker` will take the arguments (like any other function or method in PHP) so you can access the parameter(s) via `$this`:
class BEMwalker extends Walker_Nav_Menu {
private $classes;
public function __construct( $classes = '' ) {
$this->classes = $classes;
}
public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
$output .= sprintf( "<li class=\"%s\"><a href=\"%s\">%s</a></li>",
$this->classes,
$item->url,
$item->title
);
}
}
Further reading: There's also a GitHub repository called WordPress BEM Menu which might help you to implement a BEM-like syntax. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "menus, walker"
} |
Shortcodes in RSS excerpts
I am developing a plugin that uses shortcodes. I wanted to enable users to use shortcodes in excerpts, so I added the line
add_filter('the_excerpt', 'do_shortcode');
which worked fine.However, in my RSS feed, the excerpt is still a shortcode. I tried all of the following:
add_filter('get_the_excerpt', 'do_shortcode');
add_filter('the_excerpt_rss', 'do_shortcode');
add_filter('the_content_rss', 'do_shortcode');
But it does not work still. Can someone point me to the right filter so the excerpt would be processed correctly in the feed as well?
Please note that those are manually edited excerpts, not automatically generated ones. | I tested following code and it worked just fine for me:
function my_name_shortcode( $atts ) {
return "<h3>PRASAD</h3>";
}
add_shortcode( 'name', 'my_name_shortcode' );
add_filter( "the_excerpt_rss", "do_shortcode" );
The result can be seen in below screenshot.
;
define( 'WP_MAX_MEMORY_LIMIT', '256M' );
Please help. | Try adding to `wp-includes/default-constants.php` You'll probably see the default values of `40M` starting around line #20, change these values. My setup is as follows:
// set memory limits
if ( !defined('WP_MEMORY_LIMIT') ) {
if ( is_multisite() ) {
define('WP_MEMORY_LIMIT', '256M');
} else {
define('WP_MEMORY_LIMIT', '256M');
}
} | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 0,
"tags": "installation, memory"
} |
Problem with loading images from child theme CSS file with relevant path
I am getting an issue with loading relevant images within CSS file from a child theme directory. I placed -
> Sites: example.com OR sub-domain.example.com
body{
background-image: url(/wp-content/themes/child-theme-name/images/some-image.png);
}
Now the above works fine when the site is in the root folder ( _or sub-domains_ ) but the path breaks when the site is from a sub-directory installation.
> Site: example.com/sub-folder
I tried with
body{
background-image: url(../wp-content/themes/child-theme-name/images/some-image.png);
}
Now it works in sub-folders but again breaks in the root or sub-domain.
How to write the correct file path which will work in both root or sub-directory site where the images will be loaded from a child theme folder ( _say **images** folder_) | There's no need for the `wp-content/themes` path - both themes sit in the same directory, so you can just traverse up one and then back down to child theme:
background-image: url(../child-theme-name/images/some-image.png);
**Update:** Regarding your answer to "where is the CSS file stored", you inferred that the stylesheet resides in the child theme folder - in which case you are _massively_ overcomplicating things and can just use (as @Rishabh suggested):
background-image: url(images/some-image.png);
Relative paths in a stylesheet are **relative to the stylesheet itself** \- not the document, the parent theme, or anything else for that matter. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "images, child theme, subdomains, paths"
} |
How to filter or search the posts using postmeta tables custom meta fields with wordpress REST API
I'm new to wordpress and also working with WP REST API for mobile application development for the wordpress website. Here I want get data's filter & search based post meta custom fields.
I've tried for this example but getting all results not belongs property_featured=1
Kindly find my postmeta table structure for example.
meta id post id meta key meta value
---------------------------------------------
2548 1000 property_featured
3068 1078 property_featured 1
3619 1124 property_featured 1
Here i want to get the post based on property_featured=1 only. Pls help to me fix on this. | You will need to add custom query vars:
add_filter('rest_query_vars', 'wpse225850_add_rest_query_vars');
function wpse225850_add_rest_query_vars($query_vars) {
$query_vars = array_merge( $query_vars, array('meta_key', 'meta_value', 'meta_compare') );
return $query_vars;
}
Now, get your posts at `example.com/wp-json/wp/v2/posts?filter[meta_key]=property_featured&filter[meta_value]=1`.
You can follow this ticket for more info. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "custom field, wp api, rest api"
} |
How to get all posts belongs to a user between a certain date
I am writing a plugin for my company so I need to get all posts belongs to a user between a certain date which is given by another user.
Then I want to count words for each post and finally add them up to a variable and save that value to the database.
There are two main questions:
1- How to get all posts belongs to a user between a certain date?
2- How to get word count for each post?
thanks. | Check out the WP_Query reference.
For parameters.
Date Parameters.
$args = array(
'author' => 123 ,
'date_query' => array(
array(
'after' => 'January 1st, 2013',
'before' => array(
'year' => 2013,
'month' => 2,
'day' => 28,
),
'inclusive' => true,
),
),
'posts_per_page' => -1,
);
$query = new WP_Query( $args );
For the word count check out this post. It has a quick way of doing it by using explode get the post content and then using explode and count. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, posts, plugin development, users"
} |
Surviving Wordpress and plugin updates
In the phase of developing a new wordpress-based site, I'm evaluating also future pitfalls such as upgrades. Unfortunately, there's no guarantee that a third party plugin will not be discontinued. But that's how it works! There are two possible options:
1) Develop a tight robust site, with no future updates, and cross your fingers (hackers)
2) struggle to keep updated the site, and cross your fingers (what if plugin support is dropped?)
Is there a third option? | 3) Relax. You will have to update WP core anyway, so some work is inevitable. If a plugin is discontinued there usually will be an alternative. The most important thing is not to use plugins that require shortcodes in individual posts, because if these are discontinued that will really break your site.
Apart from plugins you will also have to worry about your theme, which may use functions that will be deprecated in future version of WP core. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, updates"
} |
Login to wordpress with filezilla client
I'm trying to login WordPress by using a Filezilla client, but I'm not sure if my log in details are correct because I'm using the login details that I use to login my website as admin, but maybe I need to put the login I use in the hosting service? | You need to use FTP login details( Filezilla is FTP client) to log in.Get the details from your hosting provider.
WordPress login details don't work.
Also hosting login details are different to FTP login details. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -2,
"tags": "login, ftp"
} |
How to setting up the custom size thumbnail for wp_get_attachment_thumb_url()?
I made a line of code to display a product category thumbnail on WordPress. The problem is, the size of my thumbnail is 150x150. I need to set in higher dimension. Try to apply thumbnail size but have no result, the thumbnail still 150x150 pixel.
Here my code:
$cat_thumb_id = get_woocommerce_term_meta( $cat->term_id, 'thumbnail_id', true );
$cat_thumb_url = wp_get_attachment_thumb_url( $cat_thumb_id );
?><img src="<?php if ( $cat_thumb_url ) {
echo $cat_thumb_url ;
} else {
echo mytheme_catch_that_image();
}
?>" alt="<?php echo $cat->name; ?>"/> | I meant you should use `wp_get_attachment_image_src()` with your `$cat_thumb_id`. Try this:
$cat_thumb_id = get_woocommerce_term_meta($cat->term_id, 'thumbnail_id', true);
$cat_thumb = wp_get_attachment_image_src($cat_thumb_id, 'medium_large');
$cat_thumb_src = $cat_thumb[0] ? esc_url($cat_thumb[0]) : mytheme_catch_that_image();
?><img src="<?php echo $cat_thumb_src; ?>" alt="<?php echo $cat->name; ?>"/> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "images"
} |
Special characters in tag get removed for comparison on save
Is there a list of characters, that are not allowed / are allowed in Tags? Or are there some more complex rules?
I first ran into the issue, that some tags are ok with a `*`-prefix, like: `*BLA-BL-BLA` but others are not `*BLA-BL-BLA blah`.
But after doing more testing, i found out, that i can not add a tag like `+BLA-BL-BLA blah` after `*BLA-BL-BLA blah`. The other way round also does not work.
It seems like the special chars get removed before a comparison and then the string matches an existing tag... | Basically, when you add a new term, WordPress will use `term_exists()` to validate term before add it to database.
1. `term_exists()` uses `sanitize_title()` which uses `remove_accents()` and `sanitize_title_with_dashes()` to sanitize term.
2. `remove_accents()` will converts all accent characters to ASCII characters and `sanitize_title_with_dashes()` will limits the output to alphanumeric characters, underscore (_) and dash (-), whitespaces will be converted to dashes, uppercase characters will be converted to lowercase characters.
3. WordPress also doesn't allow to create terms which have the same term slug at the same level of a taxonomy hierarchy.
**So, every characters which don't output the same term slug at the same level of a taxonomy hierarchy after passed through`sanitize_title()` function are allowed characters.** | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "tags"
} |
I have a CPT that have menu_order enabled, how can I make the menu_order values unique so it won't have duplicates
I have a CPT named **homeslider**. I have **menu_order** page-attribute enabled, how can I make the menu_order values unique so it won't have duplicates when assigning values to it? | You can interfere with `save_post` action then change `menu_order` to `post_ID`:
add_action('save_post', function($post_id, $post, $update) {
if ($post->menu_order === $post_id) {
return $post_id;
} else {
global $wpdb;
$q = "UPDATE $wpdb->posts SET menu_order=%d WHERE ID=%d";
$wpdb->query( $wpdb->prepare($q, [$post_id, $post_id]) );
return $post_id;
}
}, 9, 3); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "custom post types"
} |
Wordpress Request Post All Post ID in a Loop?
I would like to ask if there's a way on WordPress to get fetch all of the page's Field?... I am using a Advance Custom Field Plugin and would like to fetch data's from fields inputted over those fields from different pages..
So i have found a way to this already using this:
<?php
for ($x = 0; $x <= 1000; $x++) {
$rows = get_field('about_hotel', $x);
if($rows)
{
echo '<ul>';
foreach($rows as $row)
{
echo '<h1> ' . $row['hotel_name'] . '</h1><br/>'.'<p>' . $row['hotel_description'] . '</p>';
}
echo '</ul>';
}}
?>
But This way is quite unorthodox or is a very bad habit to use... can someone help me with this?
It would be very much appreciated.. Thank You... | Currently from your code I can see you are looping for post IDs from 1 to 1000 that isn't good. WordPress have lot of functions by which you can fetch post IDs, content and other information. One of them (according to your need) is `get_pages()`
Check the documentation of `get_pages()` there are lot of examples.
See the Example from above code:-
$all_pages = get_pages(array(
'number' => -1
));
foreach ($all_pages as $page) {
$rows = get_field('about_hotel', $page->ID);
if($rows) {
echo '<ul>';
foreach($rows as $row)
{
echo '<h1> ' . $row['hotel_name'] . '</h1><br/>'.'<p>' . $row['hotel_description'] . '</p>';
}
echo '</ul>';
}
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, loop, advanced custom fields"
} |
how to merge a WPQuery array with a PHP array and use the Loop to Output the result
I have a mostly normal `WP_Query` (getting 3 post types) for use on a Blog page. This works great.
Client wants the Instagram images to be included and ordered by date. I have all the instagram code setup and working fine creating an separate array. The caveat is that I need to format this Instagram posts array into an array with similar keys for fields like published.
I would like to Merge these arrays and use the WP Loop to output. seems like a stretch but figured I would ask. | Technically you _can_ merge things into loop, by manipulating its `posts` field (such as `$wp_query->posts` for main query). WP has it in `public` for visibility and access, as it tends to.
However it's not that common technique, less so if you are considering injecting something that is _not_ actually posts.
It is more common for such output to check and output additional data _within_ the loop iterations. The most typical example is accessing `$wp_query->current_post` counter to do things like "output after every third post". But it's up to you really what to check and what logic to incorporate. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "wp query, loop"
} |
Detect if WP is running under WP-CLI
I use the wonderful WP-CLI tool. Due to dependence on Apache environment variables for a specific use case, I need to enable a bit of code to run only when running under WP-CLI. **How can I detect if WP is running under WP-CLI?**
In this specific case I _could_ check for the presence of the Apache environment variables in question. However, I would like to know the more general, canonical method to check. Thank you. | Within the `php/wp-cli.php` we find these lines:
// Can be used by plugins/themes to check if WP-CLI is running or not
define( 'WP_CLI', true );
define( 'WP_CLI_VERSION', trim( file_get_contents( WP_CLI_ROOT . '/VERSION' ) ) );
define( 'WP_CLI_START_MICROTIME', microtime( true ) );
so you could check if `WP_CLI` or `WP_CLI_VERSION` are defined. | stackexchange-wordpress | {
"answer_score": 35,
"question_score": 27,
"tags": "wp cli"
} |
Can't run database query
I am writing a function to query some information from a custom table in the database. It seems that I am unable to query the database on the field I need.
function ch_details_from_id($id) {
global $wpdb;
$details = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "ch_guests WHERE key = '" . $id . "'", ARRAY_A);
return $details;
}
$id is currently '001'. If I search on any other field in the table, I get the expected results, but on this field nothing is returned.
If I run exactly the same query in phpMyAdmin, it works fine. | Here issue with the column name. You are using column **key** in the query which is the default keyword/index in mysql.
For resolving this kind of issue just use the "Grave accent(`)' symbol in the query for the column name, No need to change the column name. So in your case the right query is
$details = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "ch_guests WHERE `key` = '" . $id . "'", ARRAY_A);
Run the above query, This is working for me, so i believe will work for you as well. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "mysql, wpdb"
} |
Visual Composer - not working after update
a site has being updated to Wordpress 2.5.2 . Since the update Visual Composer does not load, see screenshot below. I've updated the Theme and all the plugins, including Visual Composer to the latest version.
` . So I just read about that there is if statement that can be used to check if post is even modified that looks like this:
if (get_the_modified_time() != get_the_time())
So I put this in my template where the time itself is being displayed so it looks like this now:
if (get_the_modified_time() != get_the_time()){
echo 'Last updated:' . the_modified_time();
}
And it is not showing at all. So obviously I am missing something here. | Loosely what you have should work already. However few things are off.
1. Calling these function without time format will produce values like `1:36 pm` (depending on your site's settings), which are not exactly comparable.
2. Post modified time can be _less_ than published in some cases, like scheduled posts.
So I would write it along the lines of:
if ( get_the_modified_time( 'U' ) > get_the_time( 'U' ) ) {
echo 'Last updated:' . get_the_modified_time();
}
`U` format stands for a numeric Unix timestamp, which is comparison–friendly. | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 4,
"tags": "functions, loop, hooks, date time"
} |
remove initial wysiwyg editor from cms page edit
So I have successfully installed and implemented the Advanced Custom Fields plugin from: <
I have applied a set of custom fields to a custom page template, successfully.
What Im trying to do now is remove the initial text input field from the page, but I haven't a clue where to start, here is what I mean...
 simply are not working.
I tried a force DB upgrade, still no joy.
Looking at `wp_terms` there's a category with `term_id` of 0. This is mighty strange and if I delete it, I'm then able to add a category via wp-admin. However, subsequent categories then fail with the **"Could not insert term into the database"** message and re-checking `wp_terms` shows the freshly added category as id 0! This seems to suggest WP is assigning the cat a `term_id` of 0 every time.
Has anyone seen this? Any ideas on a fix? The database in question is pretty huge, so a rebuild would not be a pretty thing. | OK. There where multiple issues here;
`wp_terms`, `wp_termmeta` and `wp_term_taxonomy` all had their ID's set not to `AUTO_INCREMENT`.
Changing these and removing the `0` values from each table seems to have resolved this - very odd though.
Big thanks to @N00b for helping! | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 6,
"tags": "categories, taxonomy"
} |
How to limit number of images being printer out in "Set Featured Image" pop up?
I have wordpress web site which contains over 150 000 images and when you click on "Set Featured Image" whole server slows down. Another thing is that it take a really long time to load images.
Is there any filter/action/hook to add pager or to just show last 10 images.
Another question is how to optimize whole thing (maybe images sort by subfolders with some plugin) so it can work | ### Update 1:
After dived into core AJAX call, this filter will only happen on `post.php` page:
add_filter('ajax_query_attachments_args', function($query){
if ( isset($_POST['post_id']) && !empty($_POST['post_id']) ) {
$query['posts_per_page'] = 10; // output 10 images only.
}
return $query;
});
* * *
1. You can use `ajax_query_attachments_args` filter:
add_filter('ajax_query_attachments_args', function($query){
$query['posts_per_page'] = 10; // output 10 images only.
return $query;
});
2. Because of querying attachments happens in core and using AJAX, I don't think we can optimize the whole thing. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 4,
"tags": "images, post thumbnails"
} |
How do I remove the product thumbnail link from a specific div in Woocommerce?
I have a section on my front page that displays the top 4 most popular products from my Woocommerce shop. I is located within a div as such:
<div id="trending">
<p class="trending-title">Trending Products</p>
<?php echo do_shortcode('[best_selling_products per_page="4"]'); ?>
</div>
I want to remove the fact that the thumbnail image is clickable. I don't mean removing the 'add to basket' button but the thumbnail image is clickable and takes you to the individual product page. I initially though to edit the product-image.php file but I don't want to affect this feature across the entire site just in that div 'trending'. Does anyone know of how I can accomplish this? Thank you in advance for any answers and suggestions! | Yes you can for example target the link itself inside the trending id with CSS and remove the action with CSS itself, in your place it would be something like this:
#trending > li.product > a {
pointer-events: none;
cursor: default;
}
Note that this is CSS scheme, not exact CSS, that deppends on classes you have (I would be more specific if you provided link). But the point is you are targeting `<li>` inside `#trending` id and link inside `<li>` itself and you are disabling any events, so that will do the job.
I hope this helps. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "php, woocommerce offtopic, html"
} |
Echo multiple tasks if a common function exists
How can I echo multiple tasks if a common WordPress function exists.
For example, I want to reduce the following:
<?php if (function_exists ('pluginName')) echo someName (1); ?>
<?php if (function_exists ('pluginName')) echo someName (2); ?>
<?php if (function_exists ('pluginName')) echo someName (3); ?>
<?php if (function_exists ('pluginName')) echo someName (4); ?>
into a single query like this:
<?php if (function_exists ('pluginName')) echo someName (1); someName (2); someName (3); someName (4); ?>
What is the right way to do it? | As @Howdy_McGee mentioned in the comments, you can just wrapped the multiple commands you want to run within curly brackets like this:
<?php if (function_exists ('pluginName')) { echo someName (7); echo someName (8); echo someName (9); } ?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, functions, query"
} |
How can I show custom fields in the loop only to specific user roles?
I've inserted this code in the loop (in single.php):
<span style="font-size:16px">
<strong>Currently reading:</strong> <?php the_field('book_name'); ?> (<?php the_field('book_year'); ?>)<br/>
<strong>Currently seeing:</strong> <?php the_field('movie_name'); ?>"><br/>
</span>
Anyway, that's only an example. It is successfully showing in the individual post.
How can I restrain that information to be shown only if a user is logged in with specific roles? (Author, editor and administrator).
Thanks in advance. | You can use `current_user_can()` and `is_user_logged_in()` to validate current user:
<?php if ( is_user_logged_in() && current_user_can('role') ) : ?>
<span style="font-size:16px">
<strong>Currently reading:</strong> <?php the_field('book_name'); ?> (<?php the_field('book_year'); ?>)<br/>
<strong>Currently seeing:</strong> <?php the_field('movie_name'); ?>"><br/>
</span>
<?php endif; ?>
Make sure to change `role` to your preference and take a look at Codex for more info. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom field, loop"
} |
Change users.php WP_User_Query
A client has requested to have two kinds of custom user roles, and have those users displayed in an Admin Menu Page of its own. So far, I've achieved that using `WP_List_Table` with success.
Now, the next request is to not display those users with those custom roles in `users.php`. So far, I haven't been able to accomplish this because I can't seem to find documentation about customizing the `users.php` User Query that runs in that page, or a filter that allows me to do so programatically. Not even a plugin.
Where can I get some info or documentation about this? Or should I reimplement `users.php`? | `pre_get_users` is the action that is fired before a user query is run. You need to check the context of the action to make sure you're on the main users screen. You can then alter the query with any parameters accepted by `WP_User_Query`.
A quick example:
function wpd_filter_users( $query ) {
$screen = get_current_screen();
if( is_admin() && 'users' == $screen->base ){
$query->set( 'role', 'Subscriber' );
}
}
add_action( 'pre_get_users', 'wpd_filter_users' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp admin, user roles, admin menu, wp user query"
} |
orderby in WP_QUERY - Use the order from the Dashboard
I'm using the **Anything Order Plugin** to order custom post types in my dashboard.
For a `wp_query`, I'd like the output to order the posts in the same order as I have them in the dashboard.
What would I use for the "orderby" parameter? | Figured this out.
`'order' => 'ASC'` (or `DESC` \- however you'd like) and `'orderby' => 'menu_order'` solves this. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query, query, order"
} |
Get Attachment Category Name
How can I call the name of an attachment category?
Something that would look like `<?php get_attachment_category_name ?>` or `$attachment->category_name`
This would simply output the name of the category, which was created using the below function:
function add_categories_to_attachments() {
register_taxonomy_for_object_type( 'category', 'attachment' );
}
add_action( 'init' , 'add_categories_to_attachments' ); | The answer was found here: <
For my purposes, I needed to define the category function and then call it by name-only inside the `php echo`:
<?php
$category = get_the_category($attachment->ID);
echo 'html goes here';
echo ''.$category[0]->cat_name.';
?>
Additionally, to help eliminate space or punctuation in the category name, it can display the slug instead:
<?php
$category = get_the_category($attachment->ID);
echo 'html goes here';
echo ''.$category[0]->slug.';
?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, custom taxonomy, attachments, categories"
} |
How to replace the default domain on wp get shortlink
<?php echo wp_get_shortlink(); ?>
When using this line you will get **mydomain.com/?p=1**. I was wondering if I can change my domain like **myalternatedomain.com/?p=1** while using this code? | You can filter the link returned by `wp_get_shortlink()` using `get_shortlink` filter.
add_filter( 'get_shortlink', 'cyb_replace_domain_shortlink' );
function cyb_replace_domain_shortlink( $shortlink ) {
return str_replace( 'mydomain.com', 'myalternatedomain.com', $shortlink );
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php"
} |
lostpassword_redirect filter is not used
I'm trying to redirect a user after they have reset their password. I'm using the following code, based on an example from the wordpress docs.
add_filter( 'lostpassword_redirect', 'my_redirect_home' );
function my_redirect_home( $lostpassword_redirect ) {
return home_url() . '/my-account/';
}
As far as I can tell, the filter is never hit. I've tried replacing the return with an `exit;` but nothing changes. This seems pretty straight forward. Am I missing something?
**Edit:** To clarify, I want to redirect them after they have entered their new password and it has been accepted. I want to redirect them to the login form so that they can use the password they've just set up. | I was missing something. Woocommerce accounts are different from normal Wordpress accounts. The code that I was looking for was:
function woocommerce_new_pass_redirect( $user ) {
wp_redirect( get_permalink(woocommerce_get_page_id('myaccount')));
exit;
}
add_action( 'woocommerce_customer_reset_password', 'woocommerce_new_pass_redirect' );
I found it on stackoverflow. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "password"
} |
Remove inline linking tool
I'm not a big fan of the inline linking tool published with WP 4.5. Is there a way to disable it? | So, I may or may not go to hell for this, but I made a quickfix plugin that bypasses the inline part and just opens the link editor.
You can find it here.
I didn't spend much time testing it, if you find problems make issues in github and I will see if I can fix it.
The way it works is that I removed wplink as a plugin from tinyMCE, then added wplinkc, which I made by copying wplink and removing most of the code.
Edit: I was made aware of this other solution later today, and it looks a bit cleaner and definitely looks less hacky than mine.
<
I havent tried it though.
Edit #2: An actual proper plugin exists now, found here, that gets the job done. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 16,
"tags": "visual editor, wp editor, post editor"
} |
user can login from single account detail from multiple locations(computer) at the same time
I want user can login to an account from multiple computer at the same time, i want concurrent login in word-press. is there any plug-in or custom code for concurrent login ?. | This is already possible meaning two people can logon using the same credentials on different computers. No additional plugins or code are required for this. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -4,
"tags": "plugin development, users, login"
} |
Is there a WP-Plugin to convert PNG to GIF?
I want to upload PNG-files, which convert wordpress in GIF-files. Is there a WP-Plugin to convert PNG to GIF? Thank you | There is no plugin for that as far as I know. The best solution for this would simply be to convert your pngs to gifs somewhere online, you have a lot of converters, and also bulk converters that may help you. Try this one
I hope this helps. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "plugins, uploads"
} |
Object gets unwanted width and height
Is it possible to stop WordPress adding a width and height to an object when you pate it in to the source view?
When I paste in
<a href="#"><object data="grid-linked-in.svg" type="image/svg+xml"></object></a>
WP changes it to
<a href="#"><object width="300" height="150" type="image/svg+xml" data="grid-linked-in.svg"></object></a> | You can try this:
add_filter( 'media_send_to_editor', 'remove_width_height_attribute', 10 );
function remove_width_height_attribute( $html ) {
$html = preg_replace( '/(width|height)="\d*"\s/', "", $html );
return $html;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 3,
"tags": "pages"
} |
Widget text color change
hello i have this site and in the footer section there is the recent posts widget with the grey colored text. I wish to change it to white, i tried adding some custom css code in the theme child with no success. | This CSS will make your grey text in some else you want:
.widget_posts_wrap .latest-posts .col-md-12 a span {color:#your-hex-code !Important;}
This is for subtitles in this widget where you have latest post.
And this is for titles:
.widget_posts_wrap .latest-posts .col-md-12 h3 a {color: #your-hex-code !important;}
Also just note to change `#your-hex-code` part with actual hex code.
I hope this helps. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "widgets, css, child theme"
} |
What WP folder can I use to write files to?
I am working on a theme that uses dynamic in head CSS and gives admin an option to also place the same in a file. Problem is that I am not sure what WP folder is always writable. I originally added the CSS file creation to `themename/css/` dir but since WP deletes the theme on update this has become an issue.
What do you think is the best way to approach this and what is the safest writable WP folder that I could use for this feature? | Best place is the `uploads` directory - it'll be writable by the server, and it's the defacto directory for storing any user-generated/uploaded files:
$dirs = wp_upload_dir();
$path = $dirs['basedir']; // /path/to/wordpress/wp-content/uploads | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 6,
"tags": "theme development, themes, theme options, directory"
} |
How to add an image from web-link?
I currently have this code from a plugin.
[imdbi meta_name=poster]
This cache an Image Link, and it simply display the link, I want it to display it as an image. Is this possible? | This is some specific shortcode to some plugin, that if you just want to paste an image in wordpress editor isn't necessary. (Also there is not enough info about what this shortcode is about).
So there is simple HTML that will simply display link you want as an image, following:
<img src=" />
Make sure you put the url in between the quotations as mentioned in this tag, and that you put actual link in there. Also make sure you paste this in wordpress text editor(tab next to visual editor) and when you publish your post/page it will be there :) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, images, links"
} |
Styling the date format with date_i18n
I'm in wordpress, I am trying to format the date output. This code use to call the end of the sales promotion:
<?php $thepostid = get_the_ID();
$sale_price_dates_to = ( $date = get_post_meta( $thepostid, '_sale_price_dates_to', true ) ) ? date_i18n( 'M j Y', $date ) : '';
echo '<div class="endsale">' .'<span>'.'Promo end ' . '</span>'.$sale_price_dates_to .'</div>';
?>
It's output looks like this: `JAN 21 2016`
I need to style the date and need to give div or span to M, j and Y.
I'm not familiar PHP to get things working.
Can anyone help me?
Thank for any kind of help. | Just use `date_i18n` in multiple places with PHP `date` arguments just for what you need:
if ( $date = get_post_meta( $thepostid, '_sale_price_dates_to', true ) ) {
$sale_price_dates_to =
'<span class="m">' . date_i18n( 'M', $date ) . '</span> ' .
'<span class="d">' . date_i18n( 'j', $date ) . '</span> ' .
'<span class="y">' . date_i18n( 'Y', $date ) . '</span>';
} else {
$sale_price_dates_to = '';
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "date, date time"
} |
My child theme doesn't work Error: "The parent theme is missing. Please install your parent theme"
I am using the Pricerr theme. In my parent theme I have a CSS folder with a few css files in it, a `rtl.css` and a `style.css`.
What should be the code to put in the functions folder so that I can pull the info from the parents theme? And am i on the right track for identifying this as the error when they say "The parent theme is missing. Please install your parent theme?"
I've checked and my parent theme is under `Appearance > Themes` hence it is definitely loaded. | There are three things to check:
1. Is your parent theme complete and what is the exact spelling of the parent theme's name in its `style.css`. Uppercase and lowercase are important.
2. Is the child theme directory named `parentname-child`. It should be in the themes directory, not in a subdirectory of the parent theme.
3. Does the child theme's `style.css` have the line `Template: parentname` in its header. Beware: NOT `Template: parentname-child`.
Strictly speaking you don't need a `functions.php` file for your child theme, but you will probably want to load the parent theme's `style.css` as well. Read more about that here. | stackexchange-wordpress | {
"answer_score": 16,
"question_score": 7,
"tags": "theme development, themes, child theme, parent theme"
} |
Bulk image rotation
I have just uploaded around 70 photos from Windows 10 into wordpress. While all of those photos in Windows are presented correctly Wordpress does not recognize their proper rotation. I may use wordpress media library to rotate each image one by one but this would take hours.
Do you know any plugin or way to insert fast rotate link into media library allowing rotation of multiple images at once? | Yes, this is a known problem between ios devices and Wordpress. It's a real issue due to the high numbers of iPhone/ipad users who also use Wordpress, and I'm surprised it hasn't been addressed in the Wordpress core. Looks like it's still being debated/ worked on here.
It's a question that's been asked before here. As that answer notes, there are plugins for this job, including ios images fixer and image rotation repair (not updated for a while) and Image Rotation Fixer although I'm not sure if they apply to existing images or only new uploads. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "images, media library"
} |
Multiple custom post types under one admin menu
I'm not sure where to start with this one.
I want to have 4 custom post types (Gigs, Venues, Holidays and Potentials) listed under a main heading of Events Manager, but don't want Events Manager to be a custom post type.
Thanks in advance to anyone who can help. | Just create a "placeholder" menu that you can then assign all your post types to:
function wpse_226690_admin_menu() {
add_menu_page(
'Events Manager',
'Events Manager',
'read',
'events-manager',
'', // Callback, leave empty
'dashicons-calendar',
1 // Position
);
}
add_action( 'admin_menu', 'wpse_226690_admin_menu' );
And then in your `register_post_type` calls:
'show_in_menu' => 'events-manager',
Tada! | stackexchange-wordpress | {
"answer_score": 16,
"question_score": 9,
"tags": "custom post types, admin"
} |
Is there a way to read or list wp_head() contents?
I am working on a CSS and JS compiler and need to find a way to list the contents of `wp_head()`
I am trying to get a list of all CSS/JS files and inline CSS on any give page.
Hooking on the wp_head action does not do anything
I was hoping that something like this would work
function head_content($list){
print_r($list);
}
add_action('wp_head', 'head_content');
any help is appreciated.
**UPDATE** :
got something working
function head_content($list){
print_r($list);
return $list;
}
add_filter('print_styles_array', 'head_content');
add_filter('print_script_array', 'head_content');
this lists all css/js files handles | I wanted to search-and-replace in the header, but Neither @majick or @Samuel Elh answers worked for me directly. So, combining their answers I got what eventually works:
function start_wp_head_buffer() {
ob_start();
}
add_action('wp_head','start_wp_head_buffer',0);
function end_wp_head_buffer() {
$in = ob_get_clean();
// here do whatever you want with the header code
echo $in; // output the result unless you want to remove it
}
add_action('wp_head','end_wp_head_buffer', PHP_INT_MAX); //PHP_INT_MAX will ensure this action is called after all other actions that can modify head
It was added to `functions.php` of my child theme. | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 7,
"tags": "wp head"
} |
Relationship field problem: Uninitialized string offset: 0 in
My code is:
<?php
$posts = get_field('designer');
if ( $posts ): ?>
<?php foreach( $posts as $post ): ?>
<?php setup_postdata($post); ?>
<div class="design">
<h4><?php _e("[:tr]Tasarım[:][:en]Design[:]","qtranslate-x"); ?></h4>
<a href="<?php the_permalink(); ?>">
<h5><?php the_title(); ?></h5>
</a>
<?php if( get_field('profile_image') ): ?>
<img src="<?php the_field('profile_image'); ?>" width="200" class="img-responsive">
<?php endif; ?>
<p>
<?php the_excerpt(); ?>
</p>
</div>
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
<?php endif; ?>
This results in this error message:
Notice: Uninitialized string offset: 0
in /Applications/MAMP/htdocs/addo/wp-includes/query.php
on line 3920 | `setup_postdata()`requires a post object such what you would get by using the `global $post`. You are using a custom field, presumably from ACF, and calling it $post. The problem is that it is not an object.
You can use the field `$designer` in a customised post loop like so:
<?php
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
$designer = get_field('designer');
if($designer){
the_field('designer');
}
}
}
Another way to solve this might be to make sure the designer custom field returns a post object. To see the value of `get_field('designer')` you can do something like:
$designer = get_field('designer');
var_dump($designer);
A post object will contain all the relevant information (title, content, etc.). | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "advanced custom fields"
} |
Add post meta based on another post meta value before publish post
I want to add a meta value to my post , which will be based on another meta value , before publish post . This is what I have tried
add_action('save_post_my_custom_post', 'add_custom_field_automatically' );
function add_custom_field_automatically($post_ID) {
$new_meta_value = get_post_meta($post_ID,'_my_meta_key',TRUE).'to ' .' something new';
add_post_meta($post_ID, '_my_new_meta_key', $new_meta_value, true);
}
But it doesn't work . The hook fired properly , it saves only "to something new" , but what I expect the value should be "my meta value to something new" | The solution is using `added_post_meta` and `updated_post_meta` hook .
Here is the working code .
add_action( 'added_post_meta', 'add_custom_field_automatically', 10, 4 );
add_action( 'updated_post_meta', 'add_custom_field_automatically', 10, 4 );
function add_custom_field_automatically( $meta_id, $post_id, $meta_key, $meta_value )
{
if ( '_my_meta_key' == $meta_key ) {
add_post_meta($post_id, '_my_new_meta_key', $meta_value.'to something new', true);
}
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "post meta, save post"
} |
Admin page repeatable fields
I have a submenu page set up and I want to add repeatable fields to it.
The submenu page is to add staff holidays (fields will be Start Date, End Date and a multi select to pick the staff members name). Setting up the first lot of fields is not a problem, however, I want a button that each time I click it, it will another set of the above mentioned fields.
I'm aware there will be some Javascript involved and have googled this a few times, but cannot find what I want.
Can somebody help please? | Try this one <
and use array so input should be something like this
<input type="text" name="data[1][time][start]">
<input type="text" name="data[1][time][end]">
<input type="text" name="data[2][time][start]">
<input type="text" name="data[2][time][end]">
....
then save data as array
update_post_meta($post_id, 'field_name', $_POST['data']); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "admin menu, options"
} |
Is sanitize_text_field() is enough to save to DB?
So here is the situation. We allow users to enter input data, i.e. user_first_name and user_additional_comments. Then we use sanitize_text_field() , which is named as save.
But after this filter:
`Thomas' OR SELECT * FROM wp_user`
Is still save into DATABASE as full text. And `'` char is not escaped as `'` or `\'`.
I use `$wpdb->query("INSERT INTO A (a,b,c) VALUES ('{$a}', '{$b}', '{$c}')");` So $a has to be a valid value here, which can be inserted into db. I have reasons not to use insert(), prepare() etc. specific functions, so I need to be sure that $a is VALID and SECURE. How to ensure that for text data like last name, or comment.
So is this brokes the security? | You can use wpdb insert function. It's better in every way.
It can care about data's escapeing itself and it's shorter.
You can use your own query anyway but I would recommended this article for reading < | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 6,
"tags": "database, security, sanitization"
} |
*wpupdateuser* user_login in my WordPress database
Recently, I've started to notice a **wpupdateuser** user_login in my WordPress databases. Is this correct, or a compromise? | **wpupdateuser** does not appear correct. Is it a compromise? Possibly not if you are allowing user registrations. A Google search for wpupdateuser reveals numerous sites where this username appears. Make sure WP and plugins are up to date. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "users"
} |
How I can made a custom post type to page templates?
In my site, I created a `custom post type` called: "Pictures"
add_action( 'init', 'create_post_type' );
function create_post_type() {
register_post_type( 'Pictures',
array(
'labels' => array(
'name' => __( 'Pictures' ),
'singular_name' => __( 'Pictures' )
),
'public' => true,
'has_archive' => true,
)
);
}
In my site, I want to have two pages: Index and Pictures
->Index: It had posts only of text ->Pictures: It had posts only of pictures
In Dashboard -> Posts. All posts that I did go straight to the index.
I wonder how I can access the Dashboard-> Pictures-> Add New . And each post I do, fall into the "Pictures" page.
How I can do this? | You need to add:
'supports' => array('title', 'editor','page-attributes','thumbnail')
add this to your array after 'singular name' => 'pictures'.
The thumbnail adds the featured image option to your post type.
You can access the post type archive: yoursite/archive-pictures, this will use your themes archive.php file if it exists.
Or you can create a custom post type archive template with a custom loop: archive-pictures.php.
Or you can create a custom page template and apply it to a page.
Both the post-type archive and custom page template would contain similar code: a custom post type loop like this:
$args = array( 'post_type' => 'pictures', 'posts_per_page' => 10 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
the_title();
echo '<div class="entry-content">';
the_content();
the_post_thumbnail("medium");
echo '</div>';
endwhile; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, posts"
} |
Wordpress Add javascript:void(0); to menu link item?
I want to add `javascript:void(0);` to menu link item instead of `#` but it is not accepting any JavaScript. Now i am thing to replace `#` with `javascript:void(0);` using filters, but could not find the appropriate filter for the task.
Can any one tell me which filter can be used for this task.
Note. I know this could be done with javascript/jQuery but this is for SEO purposes so have to do it with PHP on server side and render the correct html for google Spider, to avoid duplicate URL issue. | > I am not sure how it does effect the SEO but just to answer this question:-
You can not save menu item with `javascript:void(0);` because WordPress filter the URL using function `esc_url()` thus removing bad values. And it all happens in Nav Walker class. So you need to alter the URL when WordPress done with filtering and returning final safe HTML.
You can use filter `walker_nav_menu_start_el` if your theme does not have custom nav menu walker class OR does have this filter in walker class.
Example:-
add_filter('walker_nav_menu_start_el', 'wpse_226884_replace_hash', 999);
/**
* Replace # with js
* @param string $menu_item item HTML
* @return string item HTML
*/
function wpse_226884_replace_hash($menu_item) {
if (strpos($menu_item, 'href="#"') !== false) {
$menu_item = str_replace('href="#"', 'href="javascript:void(0);"', $menu_item);
}
return $menu_item;
} | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "menus, themes"
} |
Getting a Page via its post-name using WP REST API v2 and Postman
Using Postman as a Chrome extension I have had success accessing Pages(not posts as I don't use them) from my WP website.
Having trouble pulling data using the post-name url that I set way back in the Permalinks.
Here is what I have:
* < (Actual ID page for 2012 Happy Days SUCCESS)
* < (The permalink "post-name" doesn't work FAILURE. The page "happy-days" is the post-name permalink set up for that page) | You need to use the `slug` argument: `/wp-json/wp/v2/pages?slug=happy-days` | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, api, rest api"
} |
Add custom HTML to posts page
I want to add a header image via some custom HTML to the posts page but can't edit it with the pages menu in Wordpress. Is there a way to add the HTML in the specific PHP-File and which PHP do I have to pick? | If you want to modify the main `<header>` output take a look at `header.php`. This file will be called before the other templates.
If you want to modify the template that is used to display your latest blog posts, `index.php` would be the file of choice.
`Index.php` is also the fallback template for any post object so you might want to let it as it is to avoid the special content being displayed on any other site.
You could conditionally hook into `pre_get_posts` and do your modifications there. You could create your own action hooks and fire them conditionally. There are many ways to achive modifications.
For Conditionals see
* < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "php, images, html, headers"
} |
link to JS library using wp_enqueue_scripts not working
I've added the following code to `functions.php` of my activated child theme:
function fullpagejs() {
$slimscroll = get_stylesheet_directory_uri() . '/library/fullPage.js-master/vendors/jquery.slimscroll.min.js' ;
wp_register_script('fullpage-slimscroll', $slimscroll, false, null);
//some more files will be added here later
}
add_action("wp_enqueue_scripts", "fullpagejs");
However when I check the page source, I can't find the script `jquery.slimscroll.min.js` registered. | You must not only register the script, but also enqueue it after that, like this:
wp_enqueue_script('fullpage-slimscroll'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp enqueue script"
} |
I can't write in my DB using $wpdb->insert
Building a plugin I'm trying to insert something in my DB but isn't works!
My code is like that:
global $wpdb;
$table_name = $wpdb->prefix."mytable";
$wpdb->insert(
$table_name,
array(
'name'=>"'".$_POST["name"]."'"
),
array(
'%s'
)
);
I have a string in my $_POST["name"] and my database only have 2 columns: id, who is AUTO_INCREMENT and Name.
I don't know if I need do something more than the $wpdb->insert('xxxxxxx') but: Wordpress don't send me any error in PHP or SQL and don't insert anything in my database. | I would say the problem is first array. Change it to
array(
'name' => $_POST['name']
),
You can also use wpdb->show_error() or wpdb->print_error()
To Samuel Elh: wpdb->insert() can escape value itself | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, wpdb, sql"
} |
How to set the default embed image size
When a user adds media to the WYSIWYG, is there a way to set the default image size to large?
It defaults to medium, I'd like this to be "large" without the user having to change the value.
 {
// Set default values for the upload media box
update_option('image_default_align', 'center' );
update_option('image_default_size', 'large' );
}
add_action('after_setup_theme', 'custom_image_size');
You can update the options as you need. | stackexchange-wordpress | {
"answer_score": 11,
"question_score": 5,
"tags": "images, media, wysiwyg"
} |
Change plugin main file name (that is currently in the repo)
Thought I'd ask before I give it a shot and break my plugin.
Is it possible to update a plugin's main file name that IS CURRENTLY in the repo?
It was the first plugin I ever made, and the file name is SUPER long...
Thanks! | If you actually mean a main _file_ (the one with header data) inside the plugin you can rename it freely. I think the only thing would happen is that it will deactivate on update and will need to be activated again by user.
But if you mean plugin slug in the repository (the one in URL) — those are fixed in stone (or at least SVN) and cannot be changed. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, plugin development"
} |
Set spesific size of featured images
I am trying to reduce the loading speed of my webpage. Google PageSpeed Insights tells me to optimize my images. In the following code, how can I set an image size so that if the uploaded image is 99999x99999px the rendered image is maximum 427px wide?
<?php
if ( has_post_thumbnail() ) {
echo '<a href="' . get_permalink($post->ID) . '" >';
the_post_thumbnail();
echo '</a>';
} else {
echo '<a href="' . get_permalink($post->ID) . '" ><img src="'. get_stylesheet_directory_uri() . '/img/fallback-featured-image.jpg" /></a>';}
?>
I would like Wordpress to handle this automatically so that I do not have to worry about cropping my images before I upload. It is also always nice to have the original size, but We do not want the user to wait for such a large image to load. | In your functions.php you want to issue a call to set_post_thumbnail_size()
<
As with add_image_size, you provide the target width, height & whether you want the image hard cropped to these dimensions. So, for example,
set_post_thumbnail_size(427, 427, true);
will crop all your thumbnails to be a maximum of 427px high or wide, depending on aspect ratio of the original.
If you use
set_post_thumbnail_size(427, 9999);
then your images will be scaled to 427px wide without being cropped. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "functions, images, post thumbnails, media"
} |
Show only posts from todays date
<?php if ( have_posts() ) : ?>
<?php
// Start the loop.
while ( have_posts() ) : the_post();
get_template_part( 'content', get_post_format() );
// End the loop.
endwhile;
else :
get_template_part( 'content', 'none' );
endif;
?>
A simple loop her eon my index page. I am using the No Future Posts plugin to publish posts with dates in the future but the most relevant ones are today.
I have been doing a ton of cutting and pasting code from around the net trying to find a way to get just todays posts to show but nothing is sticking. I'm sure I need to check for todays date then put it into the loop but I have no idea how to do that, I know very little php, I usually just copy and paste other peoples code.
If any of the experts on here could maybe point me in the right direction it would be appreciated.! | If you just want posts from today, it's super easy and right in the WP codex:
<?php
$today = getdate();
$args = array(
'date_query' => array(
array(
'year' => $today['year'],
'month' => $today['mon'],
'day' => $today['mday'],
),
),
);
$custom_query = new WP_Query( $args );
?>
<?php if ($custom_query->have_posts()) : while ($custom_query->have_posts()) : $custom_query->the_post(); ?>
<?php get_template_part( 'content', get_post_format() ); ?>
<?php endwhile; endif; // end of custom loop ?>
<?php wp_reset_postdata(); ?> | stackexchange-wordpress | {
"answer_score": 7,
"question_score": -1,
"tags": "loop"
} |
Is Post-Author-Id shortocde
How difficult would it be to create a shortcode based on the following code:
<?php if($post->post_author == '8'): ?>
Yes This Post Is By Author Id 8
<?php endif; ?>
The shortcode then would be something like [post author="8"] Text Here [/post-author]
I am ok with creating simple shortcodes but when it gets to using parameters I get a little lost. | This is pretty straightforward as far as shortcodes go:
function wpse_226998_post_author( $atts, $text ) {
if ( ! empty( $atts['id'] ) && $atts['id'] == get_the_author_meta( 'ID' ) )
return $text;
}
add_shortcode( 'post_author', 'wpse_226998_post_author' );
And in practice:
[post_author id="8"]This post is by author ID 8[/post_author] | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "shortcode"
} |
What is this file: wp-config-wpe.php?
I just have been given access to an unmaintained Wordpress site. I have access to the Wordpress admin site, and also to the filesystem tree and PhpMyAdmin site through the host admin site.
I'm trying to setup a developer environment for this site. What I found is that there is no `wp-config.php` file, but there is a `wp-config-wpe.php` instead.
How is it even possible that the site is running in production? Where in the Wordpress tree is configured the path to that config file? | `wp-config.php` file do not have to be at the root directory, it can also be at the directory above it (that way they are not easily accessible from the web even if php interpreter malfunctions). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "wp config"
} |
Is it possible to set a variable for get_post_meta?
I have a lot of places within my templates where I get custom post meta set up with CMB2 and I was wondering if it's possible to set
get_post_meta( get_the_ID() )
to a variable like
$service_meta = get_post_meta( get_the_ID() )
and then use some sort of shorthand to get my items out of the array?
I've spent some time looking around the internet but haven't managed to find anything so would be great if someone could advice or suggest a better option for outputting my meta data. | In answer to my question (and in case anyone is interested), this seems to be the best solution:
<?php
$service_name = $post->_cmb2_service_name;
?>
<p><?php echo $service_name; ?></p> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development, post meta"
} |
How to get submenu of admin menu?
I user `global $menu` in one of my plugins to get the list of menu items. But i would like to get the list of of items from a submenu for example from `Posts` i would like to get Add new, All, Edit category etc. with slugs or other something unique.
How can i get this? | You can use the global variable `$submenu`.
Example to list the child menu of parent post menu:-
function admin_init_callback() {
global $submenu;
$sumenu_list = $submenu['edit.php'];
var_dump($sumenu_list); //array of submenu
}
add_action('admin_init', 'admin_init_callback', 999);
**Profi660 EDIT:**
Not needed to be used with `admin_init` hook.
I used this in my plugin page and worked very well. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "menus, admin, sub menu, globals"
} |
How to Move the Comments Bubble to the Right Side of the Toolbar
In the admin section, the commments bubble is on the left side of the toolbar. I know how to remove the bubble. What I can't figure out is how to move it to the right hand side of the toolbar (next to 'Howdy, [username]).
Any ideas? | After you have removed the comments bubble, you add it again. The trick is that in the `$args` of `add_node` you have to set `parent` to `top-secondary`.
So it will look like this:
add_action( 'admin_bar_menu', 'wpse227079_toolbar_link_to_bubble', 999 );
function wpse227079_toolbar_link_to_bubble ( $wp_admin_bar ) {
$args = array(
'id' => 'wp-admin-bar-comments',
'parent'=> 'top-secondary',
'title' => 'QQ',
'href' => 'QQ',
'meta' => array( 'class' => 'QQ' )
);
$wp_admin_bar->add_node( $args );
}
Title needs the full html of the bubble, href the link where it is going and meta the class for the list item. You'll have to delve into the source code of the admin bar to find the right QQ's for the bubble. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugin development, admin, admin bar"
} |
How to get the number of child categories a specific parent category has?
How do we count the number of child categories of a parent category? I am using a custom taxonomy, called: "authors".
I found this code, which does count the number of child categories, but only globally, not of one specific parent.
$num_cats = wp_count_terms('authors');
$num_parent_cats=count(get_categories('parent=0&hide_empty=0'));
$num_child_cats = $num_cats-$num_parent_cats;
echo '<p>number of child categories: ' . $num_child_cats . '</p>';
Source: < | Use get_term_children()
$term_id = 2; // use get_queried_object()->term_id; to get the current term id
$taxonomy_name = 'mypages'; // use use get_queried_object()->taxonomy; to get the current taxonomy name
$countchildren = count (get_term_children( $term_id, $taxonomy_name ));
echo $countchildren; | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "categories, custom taxonomy, taxonomy, count"
} |
Add a meta value if admin , editor or any other user have open a post in edit mode
In my application user can publish a custom post from front end . And later admin or capable user can update or delete the post . What I want to do , is to determine if that post is seen by admin or capable user from a dashboard . A post meta "is_seen" is attached to my post , by default it is false . I want to make it true if admin or capable user open the post in edit mode . In short I want to do something when "Edit" link is clicked. | I have found a solution . If someone click a on "Edit" link or change anything of the post . A new meta field which meta key is "_edit_lock" is added . Thus we can do something when "Edit" link is clicked by
add_action( 'added_post_meta', 'add_custom_field_automatically', 10, 4 );
add_action( 'updated_post_meta', 'add_custom_field_automatically', 10, 4 );
function add_custom_field_automatically( $meta_id, $post_id, $meta_key, $meta_value )
{
if ( '_edit_lock' == $meta_key ) {
//do something
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "post meta"
} |
Correct procedure for fixing broken WP sites after WP version update
What is the correct procedure for fixing a WP site that has broken due to a recent update to the latest WP version. Assuming there are no backups both locally or via the web host.
Is it a case of switching off plugins and switching themes to see if it is restored? | I'm afraid reverting would depend on how major the upgrade was. A WP upgrade can change the database structure as well as the core code.
Your first step though should be to disable all plugins and see if the site runs without them. If so, enable them one by one until you find the problem one.
Same goes for your theme. Try one of the default themes to rule out a conflict with your own theme.
Make sure that your plugins and themes are on their latest versions too.
When I've had sites white-screen after an upgrade, those steps are usually enough to get to a fix.
If not, turn on PHP error display or logging and see where the problem apparently lies. This can be a mixed blessing as it may report a core file problem when really the issue is within a plugin or theme, hence the elimination of those earlier on. What you might see though is a compatibility issue with your hosting and the new version of WP. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "updates, automatic updates"
} |
Extension preview disapeared since WP 4.5.2
Since the last Wordpress update, I can't read new version notes when trying to update a plugin in my dashboard. ![enter image description here](
The same thing happens when I try to read an plugin's details.
How can I fix that ?
**Edit:**
Here's what I get from my browser's console when trying to view a plugin's details:
![enter image description here]( | Thanks for your answer @rarst. The issue came from my nginx configuration.
I just had to change `add_header X-Frame-Options deny;` to `add_header X-Frame-Options "SAMEORIGIN" always;` | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "plugins, dashboard"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.