INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Secure login without SSL?
I use WordPress to host a blog, so I need to log in to use the Admin Panel. Since I do not have and SSL certificate , is there any way to make the login secure without one?
Note: I don't want to use Let's Encrypt because I don't agree with their privacy policy. | After much research, I figured out that there is no way to do it. I ended up choosing to use Cloudflare, as they proved free HTTPS along with other useful features. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "login"
} |
Is it possible to roll back to a previous customization of Genesis?
Excuse my ignorant question, but couldn't find anything about this anywhere.
I did some changes on a Genesis based site. The site was set to **display last posts** (rather than static page) and I used the _customizer_ to make changes. Now, the site owner told me she doesn't want the changes, and to roll back to what it was.
I exported the site before anything, so I guess I can recover from that. But in my experience, every time I have used the **WP generated Export backup** it duplicated a lot of things, specially menu items.
I would like to know if it's possible to roll back in some way, without importing the file. I only need 3 or 4 lines of text and importing will cause more trouble than writing them (if I had those lines, of course).
If not, is there a way to check on the import file for the way the customization was at the moment I backed it up? | You may find that < may be useful in retrieving a snapshot, or at least being able to take a snapshot before you do work like this again in the future. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "genesis theme framework"
} |
Custom shortcodes not working using __s theme
I'm trying to register a new shortcode on my custom theme.
In functions.php I have created a basic test function as follows
function get_second_image($atts) {
echo ‘test’;
}
And registered it right underneath
add_shortcode( ‘case_study_second_image_sc’, ‘get_second_image’ );
Using the WYSIWYG editor I insert the shortcode [case_study_second_image_sc] but it just displays as the raw code on the page.
I'm calling the page content using
<?php the_content(); ?>
in the template file.
Based on info from another SE question I have searched my theme's files for any add or remove filter functions but there don't appear to be any that would be getting in the way. | Make sure to use straight quotes, e.g. `'` or `"` and not curly quotes `‘`, `’`, `“`, or `”` for strings.
Also, shortcodes should return their output, not echo it.
When WordPress finds a shortcode without a callback, it displays the shortcode tag just as it was entered e.g. `[case_study_second_image_sc]`.
The shortcode tag `‘case_study_second_image_sc’` and the associated callback `‘get_second_image’` will be parsed as constants by PHP. This means we won't have a valid shortcode tag or callback function for our shortcode and WP will just output the shortcode as it was entered by the user.
Turning on error reporting helps to find these tricky errors (sometimes curly quotes appear in copy/pasted code and it can be difficult to differentiate quotes in some editors).
>
> Use of undefined constant ‘case_study_second_image_sc’ - assumed '‘case_study_second_image_sc’'
>
> Use of undefined constant ‘get_second_image’ - assumed '‘get_second_image’'
> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "theme development, shortcode"
} |
How to apply wordpress 'with_front' = false for categories?
I know that how to add add `'with_front' = false` for WordPress custom taxonomy when adding them.
But how to apply WordPress `'with_front' = false` for categories? | The `register_taxonomy_args` filter should do the job intercepting the arguments for the specified taxonomy:
add_filter( 'register_taxonomy_args', 'cyb_modify_category_args', 99, 2 );
function cyb_modify_category_args( $args, $taxonomy ) {
if( 'category' === $taxonomy && is_array( $args ) ) {
$args['rewrite']['with_front'] = false;
}
return $args;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories"
} |
Amend description of menu location in customizer Wordpress
Amend description of menu locations in customizer? I just want to add note that I have limited menu depth. Not really sure how to do it.
I refer to this description under 'Menu Locations'
> Your theme supports 2 menus. Select which menu appears in each location. You can also place menus in widget areas with the “Custom Menu” widget.
or to add description for Menu panel.
I tried like this
$wp_customize->get_setting( 'nav_menus', array(
'description' => esc_html__( 'new description', 'theme_name' ),
) ); | You need to be modifying a _section_ not a _setting_.
Try this:
add_action( 'customize_register', function( $wp_customize ) {
$section = $wp_customize->get_section( 'menu_locations' );
$section->description .= "<p>Custom HTML added.</p>";
}, 12 );
The priority of `12` is used because `\WP_Customize_Nav_Menus::customize_register()` happens at priority `11`, and this is where the section is added. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme customizer"
} |
Changing title of wordpress RSS feed
I need to change the title of the feed that appears in the top in `mywebsite.com/feed`. I have tried editing files in wp-includes and also have tried this code :
function filter_wp_title_rss( $get_wp_title_rss, $deprecated ) {
// make filter magic happen here...
return 'new title';
};
// add the filter
add_filter( 'wp_title_rss', 'filter_wp_title_rss', 10, 2 );
But this does not work. | In _functions.php_ of theme:
add_filter( 'wp_title_rss', 'my_rss_filter', 20, 1 );
function my_rss_filter( $rss_title ) {
$rss_title = 'New Title';
return $rss_title;
}
I added a lower priority of 20, and just ditched the deprecated stuff altogether. You could just return a text string as you have it, of course, but I included the rest for a more complete reference. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "rss"
} |
Can I use REST-API on plain permalink format?
Recently all of my REST-API requests suddenly turned to return a 404 error, Every request (no matter custom endpoint or built-in).
Then I figured it's because of permalink's structure. `/wp-json/` is not accessible under plain permalink, since there is simply no redirect rule available at the moment.
Is it possible to use the REST endpoints in this situation? Both custom and built-in. | Yes you can. Just add the `rest_route` query parameter.
So
<
would become
<
Or ` would become ` to give you a more complete example.
So you're wondering how to decide which one to use? Worry no more, there's a function for that: `get_rest_url()`
Another option is the fact that by default there is a `<link>` in the header that gives you the API root.
<link rel=' href=' />
So in case you need to figure that out from client side JS just use something along the lines of
document.querySelectorAll('link[rel="
* * *
So basically you shouldn't take the `wp-json` part as given (and hardcode it) but always build it dynamically either using `get_rest_url()` or the JS approach mentioned above. | stackexchange-wordpress | {
"answer_score": 20,
"question_score": 12,
"tags": "permalinks, rest api"
} |
Can I restore a plugin that was accidentally deleted? (on localhost)
I did something really stupid and accidentally removed a plugin that I've been working on for weeks, with no backups. (I know! Learning moment!)
**Is there any way I can restore this plugin?** It's not in my Windows recycle bin.
I deleted it through the WordPress wp-admin interface. Going to Plugins and clicking **Delete**.
Any help is greatly appreciated! | Shot answer: It depends.
* If you store your wordpress in a partition which do not contain OS, you get higher chance to recovery it.
* If you has not rebooted your PC, you get higher chance.
* If you've just deleted your plugins, you're likely to be able to recover it.
Try some data recovery softwares (like Recover My Files - Data Recovery) **as soon as posible**. I tried it sometimes in the past and have good result.
Next times, you should use a version control software like `git` and a remote git hosted service like github or bitbucket to save your ass.
Good luck buddy! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, backup"
} |
Multiple pages per post (not pagination)
I'm making a movie database and need to have multiple pages per post: details, cast, recommendations, reviews (something like IMDb). I would prefer to not use any plugins if possible. I'm not new to wordpress but I don't have any clue how to do this. I was looking for help on the internet but every article was about splitting long posts using pagination. So the question is **how to make multiple pages per post?** | You can use a custom post type, e.g. `movies` and then you can have some rewrite rule which will basically render something like this `movies/movieId/ratings` to `movies/movieId/?page=ratings`.
So now you can use `$_GET['page']` to check what data you have to show.
How to rewrite the slug in WordPress? Google it.
Check this answer for rewrite rules. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, posts, pages"
} |
Block Adsense on specific page
**Set-up**
I have the following standard Adsense script inserted in my `header.php` file,
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js">
</script>
<script>
(adsbygoogle = window.adsbygoogle || []).push({
google_ad_client: "ca-pub-********",
enable_page_level_ads: true
});
</script>
This allows me to display ads on all pages instantly without too much hassle.
* * *
**Problem**
I'd like to prevent display of all adsense ads on specific pages of my website.
I'm looking for some 'if' function to stop the display. Anyone knows of such a function? | You can use this function:
<?php if(is_page('your-page-slug')): ?>
//do nothing on selected pages
<?php else: ?>
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js" />
<script>
(adsbygoogle = window.adsbygoogle || []).push({
google_ad_client: "ca-pub-********",
enable_page_level_ads: true
});
</script>
<?php endif; ?>
If you want to disable this on more than one page, just add them like this:
<?php if(is_page('your-page-slug1') || is_page('your-page-slug2')): ?>
Wordpress Developer Resources are very useful (more than codex), so i recommend checking them out first if you don't know how to do something | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "adsense"
} |
create users to site with specific language
We've created a website that has 8 languages, Russian, Spanish or English to name a few. Each language has its own version of the website.
I'm trying to create users that will be able to only modify the site's assigned languages.
For example, if I create a user for the Russian version, that person will be only able to modify the Russian version.
The webdesigner who created the website said it cannot be done but I'm still asking, just in case.
For info, I'm using the module `polylang` | There is actually a plugin that offers this exact functionality: Polylang User Manager:
> Polylang User Manager will work with Polylang WordPress multilingual Plugin, it will allow you to restrict access for editors/shop_manager or other user role based on languages they’re not assigned as Translators or editor. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "wp admin, users, user roles, plugin polylang"
} |
How to print raw query from WP_Query class just like in CodeIgniter
I am struggling with WordPress, and was looking at `WP_Query`. We usually pass an array of arguments to get result against.
$args = array(
'post_type' => 'post',
'post_per_page' => '2',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'ignore_sticky_posts' => true
);
$the_query = new WP_Query( $args );
Is there any way to print out `$the_query` in raw form for testing purpose just like we do in CodeIgniter with `$this->db->last_query();`?
Raw Query Example:
select * from table1 where ...... | The generated SQL is available via the `request` property:
echo $the_query->request;
where `$the_query` is a `\WP_Query` instance.
Check out how it's formed in the class here.
Also available via the `posts_request` filter for _unsuppressed_ filtering. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "plugin development, wp query"
} |
Woocommerce: Get Cart ID
Can i get the cart id and instanciate the cart later?
In another case, is there a unique identifier that I can use to store information from each cart? | Why this question down-voted? I think it is can be very useful. Unfortunately WooCommerce have not feature like this. But you can:
1. Set cookie with unique id, when user added something to cart
2. Create db table with `cookie_cart_id` and items, and update this table when user change items in cart.
3. When user create order - delete cookie | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "woocommerce offtopic"
} |
Function Reference/human time diff for future posts
Right now I've got future posts displayed on my site, and I was using this code on each post to show when it was published.
<?php echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago'; ?>
Naturally it shows a post 2 days from now as 2 days ago. How might I fix it so it says "ago" and maybe "from now" where applicable? | I managed to figure it out
<?php
if ( get_post_status ( $ID ) == 'future' ) {
echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' from
now';
} else {
echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago'; ?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, timestamp"
} |
Advanced Custom Fields - Google Map Won't Render Unless Variable Dumped
I'm trying to display the Google Map object created using the Advanced Custom Field plugin's built-in generator.
I used the stock Javascript/CSS/PHP outlined here as this exactly matches my use case: <
Only problem: The jQuery script seems unable to find the lat/lng html attributes unless the php variable is dumped or echoed in some way.
<div class="map">
<?php
$location = get_field('location');
var_dump($location); <-- Why is this necessary?
?>
<div class="acf-map">
<div class="marker" data-lat="<?php echo $location['lat']; ?>" data-lng="<?php echo $location['lng']; ?>"></div>
</div>
</div>
My knowledge of PHP is clearly inadequate to understand why this might be the case. The Javascript is being included in an inline script tag within the PHP file itself. | Try this code:
<div class="map">
<?php
global $post;
$location = get_field('location', $post->ID);
?>
<div class="acf-map">
<div class="marker" data-lat="<?php echo $location['lat']; ?>" data-lng="<?php echo $location['lng']; ?>"></div>
</div>
</div>
Sometimes in the template you're loading this you don't have the `post` that the field belongs to, so you can try to fetch it in the `global $post` variable. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "advanced custom fields, google maps"
} |
Display a default image for custom-logo
I am switching my Genesis theme over to use Wordpress' 4.5 custom-logo function. It was simple to do:
add_theme_support( 'custom-logo', array(
'width' => 861,
'height' => 130,
'flex-width' => true,
'flex-height' => true,
) );
However, I do not see a way in which to provide a default logo (which would be under `theme/images/header.svg` where `customer-header` had had an option like:
add_theme_support( 'custom-header', array(
'default-image' => get_stylesheet_directory_uri() . '/images/header.png',
...
How can I achieve what I am trying to do? I am willing to edit the child theme, of course. | When you display the custom logo you can check if is set, if not you display another image. You can achieve this with the following code featured in the documentation. I adapted it to suit your needs:
$custom_logo_id = get_theme_mod( 'custom_logo' );
$logo = wp_get_attachment_image_src( $custom_logo_id , 'full' );
if ( has_custom_logo() ) {
echo '<img src="'. esc_url( $logo[0] ) .'">';
} else {
echo '<img src="'. get_stylesheet_directory_uri() . '/images/header.png' .'">';
} | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "customization, genesis theme framework, logo"
} |
Editing Them with Child Theme Basics
I've spent the past 3 hours attempting to edit my theme with little results and would greatly benefit from a few basics.
I'm trying to edit my site, www.yodega.com/sell. I have a child theme created with `style.css` and `functions.php` files.
I'm trying to make some theme alterations - in the photo I've marked a few things I'm trying to edit (with direction on these I'm confident I can use what I learn to apply it to the rest of the edits I need to make).
, then use the developer tools (like Firebug on Firefox; or the native developer tools in FF or Chrome), to inspect the element's CSS. Use the CSS name as shown in the CSS inspector pane in your child theme's `style.css` file to change the 'look' of that element (like background color, margins, padding, etc).
If you are trying to change what WP 'builds' on the page (the generated page source), then you need to dig into the templates that the theme uses by copying a template to your child theme folder, then editing that file.
There are some great tutorials out there for either purpose. Start at a site like www.wpbeginner.com for a tutorial that will help.
More specific questions will get you a more specific answer. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, child theme"
} |
Group several custom global page templates in sub-folder
I have to create several global page templates, and, in order to keep them organized, would like to have them in a subfolder. So far I don't know how to do it, the template-parts/page/... structure is not meant for this purpose.
Any idea or alternative? | You can group them under custom folder "templates" or any other name and it will work | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, page template"
} |
School & class blogs - renaming/archiving post categories?
In a small school we use WP to create class-blog posts, therefore each posts may be assigned to a class-blog category representing the class (Year 1, Year 2, etc). While this was fine until school end, for next year it won't make much sense as students are moving to next-year "classes".
Possible solutions:
1. Delete all last-year class-blog posts
2. Rename old categories to something else such as "2017.18 - Year 1" and create new categories for next year
3. Leave as is
Solution number 2 seems good, but this will make grow the categories list over time and may lead to confusion for teachers creating posts (having to scroll through longer lists of categories)
Your thoughts? | What you can do is, create a new taxonomy `session` and use it with `classes`.
In this way you don't have to create each class again and you will be able to differentiate which session (and class) a blog post is linked to.
Example: Create new blog post. Assign it session `2017-2018` and class `year 1`. Now you can query using session and/or class to get desired results. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "categories"
} |
Why are my frontend theme styles bleeding into the backend?
I'm developing a custom theme. For some reason, some of the styles I define globally in the front-end (like certain styles for headings and such) are affecting the back-end.
I am using the WP-LESS plugin and enqueueing the main stylesheet in the theme's functions.PHP:
wp_enqueue_style( 'mainLESS', get_template_directory_uri() . '/less/index.less');
Is this normal behaviour?
How should I prefix styles to keep them from applying to the backend? I don't seem to be seeing any obvious body classes I could take advantage of. | You're supposed to enqueue on the `wp_enqueue_scripts` event. Placing the function in `functions.php` and immediately running it, will make it run on all pages, including the admin area
Here's an example from the devhub:
/**
* Proper way to enqueue scripts and styles.
*/
function wpdocs_theme_name_scripts() {
wp_enqueue_style( 'style-name', get_stylesheet_uri() );
wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/example.js', array(), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' );
This hook/action/event fires on the frontend. If you would like to add a style or script to the backend, use the `admin_enqueue_scripts` event instead | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 2,
"tags": "wp admin, css, front end"
} |
How to set custom capabilities for custom taxonomies?
I am trying to set some custom capabilities for a custom taxonomy. I am trying the following:
'capabilities' => array(
'manage_terms' => 'manage_'.$types,
'edit_terms' => 'edit_'.$types,
'delete_terms' => 'delete_'.$types,
'assign_terms' => 'assign_'.$types
)
where `$types` is the plural form of the taxonomy slug. This is part of a larger function to programmatically create custom taxonomies.
* * *
I am viewing the capabilities using User Role Editor (and have looked in the `options` table of the DB) and these capabilities are not all created. I can see the caps for `edit_terms` and `delete_terms` but none for `manage_terms` and `assign_terms` which are the ones I actually need.
I am struggling to see what I am doing wrong so any help would be appreciated, thanks! | The array that you pass on taxonomy creation should consist of existing capabilities, it doesn't create them. You'd have to do that manually with `add_cap()` before registering your taxonomy. Unless you need specific capabilities to vary with each of your new taxonomies it's best to pass existing capabilities like `manage_categories` or create one set of capabilities, eg `manage_custom_taxonomies` to cover all of them. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom taxonomy, capabilities"
} |
Demo Import changes terms ids
I am using < to create a one click demo import for my theme, however, when i click the button to import the demo data which i have exported via WordPress, the pages that use the custom post type categories with an ID of 9 stop working because when the demo data get imported the categories change their ID to 20 or something.
There are no other categories with same ID and its done on a fresh WP install.
What can cause this issue where when you import the demo data:
<wp:term>
<wp:term_id><![CDATA[9]]></wp:term_id>
<wp:term_taxonomy><![CDATA[slider_category]]></wp:term_taxonomy>
<wp:term_slug><![CDATA[fullscreen_slider]]></wp:term_slug>
<wp:term_parent><![CDATA[]]></wp:term_parent>
<wp:term_name><![CDATA[fullscreen_slider]]></wp:term_name>
</wp:term>
the terms have their ids changed? | AFAIK, when a new term is imported, it will get an arbitrary ID, similar to posts. If all you need is a term attached to some posts, then it's fine, because WordPress handles that automatically.
However, if you use the term ID somewhere else, like in the Customizer, you can't get the new term ID.
I'd suggest you should not rely on the term ID. Why not using term slug? It's not kind of 100% unique, but in most cases, it remains the same when you import. And you can easily get the term via `get_term_by`. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "theme development, taxonomy, terms"
} |
After installing ssl certificate images won't show
This is my website <
After installing ssl certificate images won't show or show as missing.
I have updated almost all the urls to https but the problem insists.
Any ideas? | I suppose you have Adaptive Images plugin installed?
The author suggests for now:
> Can you check if the urls in your admin Settings > General page do contain the “https” instead of “http”? They should contain the “https” and (sorry about this inconvenience) you need to update your Adaptive Images settings one more time after this.
>
> Also, for a proper and complete migration from HTTP to HTTPS, I would advice performing a url rewrite in your database, which will replace each and every url of your domain from “http” to “https”.
But this is a fresh problem so there's a possibility that this solution will not work 100%, so I recommend to watch that thread. You can also disable this plugin until this problem is fixed by the author and maybe that will solve your problem for now. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "images, ssl"
} |
How do I retrieve a list of popular plugins using the WordPress.org Plugin API?
I'd like to retrieve a list of popular plugins from WordPress.org using their API.
I know I can do something like this to get a specific plugin:
<
And that I can get back a list of plugins using something like this:
<
But I don't know how to get the popular plugins. I'm guessing it is something like:
I'd like to do this without using WordPress' (the software) Plugin API. This should be something I could type into a browser and get back the results (like one can with the above).
Thanks! | I was wrong in the earlier version of the answer and 1.1 version of the API _does_ support this via GET request.
The basic request would be: [
And you can add more parameters by sticking with `request` passed as "array" (in GET interpretation of).
See the [poor] documentation in Codex and links from there for more detail.
For in–PHP way, independent of WP core I made a WPorg Client library which implements this, among other things. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "plugins, api, wp api, wordpress.org"
} |
why my wordpress dont have toolbar like, plugin, themes and other?
why my wordpress dont have toolbar like, plugin, themes and other ?
thet is screenprint of my wp. {
// Get every comment on this post
$args = array(
'post_id' => $post_ID
);
$comment_objects = get_comments( $args );
// Define an empty array to store the comments
$author_array = array();
// Run a loop through every comment object
foreach ( $comment_objects as $comment ) {
// Get the comment's author
$author_array[] = $comment->comment_author;
}
// Return the authors as an array
return $author_array;
}
So, `get_comment_authors(123);` will return every author that left a comment on the post that has an ID of 123. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "comments"
} |
Hide or remove the Remove button in WP_Customize_Image_Control
I'm using the `WP_Customize_Image_Control` function to allow users to upload an image. Once they've uploaded it, I don't want them to remove the image, only to change it. This is what I want (look ma, no remove button):
 WordPress inserts specific WP Code...
My question is (since I am curious) - is there a problem with simply just copying and pasting the image URL and inserting that into the text portion of a (for example) WordPress post?
Thanks | There is no actual problem of copying any link to the content. WordPress itself actually has an option for this. If you want to paste a URL, use this feature instead. You can add a media from URL in the `Add media` screen.
Click the `Add media` button in the visual editor, and then choose `Insert from URL` from the left panel. You can then add a caption, alt text and/or align your image.
But if you copy the link directly into the editor, you won't get stuff like captions. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "images"
} |
Can multiple sites under one folder structure share media directories?
I have a client that has 3 sites. Two of them are retail and one of them is wholesale. They all carry the same products, so the majority of the media files are the same on all 3 sites. Two of the sites are subfolders of the 'main' site.
To save drive space and effort on my part, is it possible to have a single media library and have the 3 sites share it? Could i do this by setting the media directory of 2 of the sites to a soft link to the 3rd media directory?
A multisite set up will not work for me due to the tools i'm using.
I'm assuming that the media serialized data would mess that up, but has anyone tried this before? | Yes you can use Linux symlinks for your "slave" sites `/uploads/` folders, and point those symlinks to your main site's `/uploads/` directory and WordPress doesn't know the difference :)
The folder structure of your server doesn't matter, this solution works with all kinds of complex directory trees as long as your have the ability to add symlinks:
<
You also should consider setting up a cron job to ensure the symlinks don't get overwritten. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "media library"
} |
Highlight another nav item
I am using WordPress to develop a picture gallery website. I have albums and galleries, with different permalinks...` and ` but only the albums appear in the main navigation.
The code for my navigation looks like:
<div id="nav">
<ul>
<?php wp_list_pages("title_li="); ?>
</ul>
</div>
Because I am using the `wp_list_pages()` function, the current page that you're on gets a `current_page_item` class added to the `li` tag.
The gallery page is not part of the main navigation, so when someone is viewing one of the gallery pages, nothing is highlighted in the main navigation.
I'd like to highlight the album page in the main navigation when someone is viewing a gallery page. Because each gallery is in album, it makes sense to highlight that page.
Can anyone point me in the right direction?
Thanks,
Josh | The `page_css_class` filter lets you modify the classes each menu item gets.
Here we check if we are currently viewing a singular `envira` post type and the menu item slug is `gallery`. In that case we add a class to the array of default classes passed to the function.
function wpd_page_css_class( $css_class, $page ){
if( is_singular( 'envira' ) && 'albums' == $page->post_name ){
$css_class[] = 'current_page_item';
}
return $css_class;
}
add_filter( 'page_css_class', 'wpd_page_css_class', 10, 2 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "menus, navigation, wp list pages"
} |
How can I link a file in admin with a button?
Let suppose I have made a file in my theme folder (with the name c.php) and I want it to link it with a custom button (that I have made in post/page) in admin using GET action. How can I achieve that | Finally, I make it, the way without losing the access to WordPress environment:
add_action( 'edit_form_after_title', 'custom_button' );
function custom_button() {
$button = sprintf('<a href="%1$s" class="button button-primary button-large">%2$s</a>', esc_url( add_query_arg( 'link' , true, get_the_permalink() ) ), 'Custom Button'
);
print_r($button);
}
**Update:**
**_Hint_** : Please make a function for validation the url for ssl and wrap get_the_permalink() inside it. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "permalinks, admin, buttons"
} |
How to do Conact form 7 name field validation?
I am using **contact-form-7** plugin, where i have created `name` field as Name.
The `name` field is accepting text and number too. But my requirement is that `name` field should not start from number so how i can do the name field only accept text not number ?
[text* your-name placeholder "Full Name"]
I search on Google and visited contact form 7 support too, but can not solve it. | According to the documentation you have to create a custom filter to support it - you can do it like this:
add_filter( 'wpcf7_validate_text*', 'custom_text_validation_filter', 20, 2 );
function custom_text_validation_filter( $result, $tag ) {
if ( 'your-name' == $tag->name ) {
// matches any utf words with the first not starting with a number
$re = '/^[^\p{N}][\p{L}]*/i';
if (!preg_match($re, $_POST['your-name'], $matches)) {
$result->invalidate($tag, "This is not a valid name!" );
}
}
return $result;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "plugins, validation, plugin contact form 7"
} |
Open the_author_link() in a new window
I need an extra pair of eyes on this. I have customized a block of code in a function of a commercial theme, which is the following code:
<div class="author-description">
<h5><span class="fn"><?php the_author_link(); ?></span></h5>
<p class="note"><?php the_author_meta( 'description', $id ); ?></p>
<?php csco_post_author_social_accounts( $id ); ?>
</div>
There's `the_author_link()` in it, which states either the name of the user, or the link to the website of the user, which can be filled in the admin users profile. The `the_author_link()` does not accept any parameters, according to the Codex.
I would like this function to open the link in a new window. Do I need to break the function down? | Yes, you have to get the url by user's meta:
<?php
if ( get_the_author_meta('url') ) {
// Author has website url
$author_url = get_the_author_meta('url');
} else {
// Author doesn't have website url, so get Author Posts Page
$author_url = get_author_posts_url( get_the_author_meta('ID') );
}
?>
<a href="<?php echo $author_url; ?>" target="_blank">Author's website</a> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "author, links"
} |
What is phpBB? Is it something like a plugin which I can use in Wordpress?
I did some research on phpBB. It says it's a forum plugin, but it is nowhere mentioned that this plugin can be used in Wordpress. Then I saw this forum where phpBB and Wordpress plugins are compared (still look like both are different).
I saw a couple of questions regarding phpBB in Wordpress Development StackExchange, but none of them answer my question.
So, if I buy this theme, then can I use it in Wordpress? If no, then which platform can be used to edit the theme? Will be code be PHP, or can I use HTML and CSS?
Sorry for too many questions. | > phpBB is a free flat-forum bulletin board software solution
>
> <
I am not sure where had you got “plugin” bit from, phpBB is most definitely _standalone software_ , which does not require or rely on WordPress.
If you see the mentions of the two together it typically refers to some form of integration, such as sharing login details for users between them.
Theme you link to is specifically _phpBB theme_ , you should check their documentation for expectations on editing it. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -2,
"tags": "plugins, themes"
} |
Why WordPress Core Functions Not Using function_exists()?
This might be a stupid question. But I thought to ask it here.
It is really bad changing core file and I know that there are **actions and filters** in WordPress. But there are some limitations.
So why WordPress Core Functions Not Using function_exists()? I mean something like below example in core files.
if(!function_exists('wp_insert_post')){
function wp_insert_post( $postarr, $wp_error = false ) {
//Core Code
}
}
Then give a way to run PHP file before core files. So any developer can modify the core files without changing core files. | _Some_ do, a number of core functions is specifically designated _pluggable_ and contained in `pluggable.php` for exactly this purpose.
It is also quite a messy approach and is often regretted it’s a thing at all.
The problems are loosely:
* the replacement works _exactly once_ ;
* letting extensions mess with core _definitions_ can lead to very volatile results.
The problem with letting developers modify core files is often not _how_ to allow this, but _how to make it unnecessary_. The latter is much more reasonable approach and basis for WP’s strong extensibility and success of its hooks API. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 0,
"tags": "core"
} |
Does Wordpress Import/Export tool actually exports media (images) as well?
I need to reinstall WP from scratch due to malware.
Can reliably use the built-in Import/Export tool (Tools > Import/Export)?
It appears it only gives me an XML file. What can I do to ensure all media is also available for import? | > In addition, you can import attachment by checking the "Download and import file attachments" option.
(source)
This means, if you use the official WordPress Importer plugin, it will read the media URL from the file, download that file and finally upload it to your new install.
When your old site is offline, eg. taken offline after malware infection, you won't be able to import any media files this way.
If you have backups, you can try to play that in (media related db tables + wp-content/uploads/ folder). But you'll need to take very close looks, as not to back up the previous infection as well. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "migration, installation, import, export, backup"
} |
How to add custom class to get_avatar()
I am using a custom walker class to customize my comments section. It uses the following code to get the comment author image from gravatar
<?php if ( 0 != $args['avatar_size'] ) echo get_avatar( $comment, $args['avatar_size'] ); ?>
The HTML output is as following
<img alt="" src="#" srcset="#" class="avatar avatar-60 photo" height="60" width="60">
I want to add a custom class to the `<img>` tag so the output will be like this
<img alt="" src="#" srcset="#" class="avatar avatar-60 photo myclass" height="60" width="60">
How do I do that ? | The `get_avatar()` function has many arguments, the last one is the interesting one, because you can pass additional classes, also described in the codex. So instead of
get_avatar( $comment, $args['avatar_size'] );
you could use
get_avatar( $comment, $args['avatar_size'], '', '', array('class' => 'myclass') ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development, comments, walker, gravatar"
} |
Category_in return empty
I have the following code to obtain products within a category
$product = new WC_Product($id);
$categories = $product->get_category_ids(); //return array(21)
$args = array();
$args["posts_per_page"] = 10;
$args["post_type"] = "product";
$args["post_status"] = "publish";
$args["category__in"] = $categories;
$myposts = get_posts($args);
And **get_posts** return empty when I know there are 5 products in this category | You can achieve that using the `tax_query`, see the example in the code below:
$args = array(
'posts_per_page' => 10,
'post_type' => 'product',
'post_status' => 'publish',
'tax_query' => array(
'taxonomy' => 'the_taxonomy_slug', //the slug of the taxonomy you want to get
'field' => 'term_id',
'terms' => $categories
)
);
See reference in the Codex | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "query, woocommerce offtopic, get posts"
} |
Function not receiving string from shortcode
I'm trying to write a function that will use a string (which will be a url once working) sent from a shortcode, but all it's sending back is the default value in the function.
My shortcode is
> [youtube-thumb-url videoUrl="test"]
My function is below:
add_shortcode('youtube-thumb-url', 'get_youtube_thumb_url_func');
function get_youtube_thumb_url_func($atts)
{
extract(shortcode_atts(array(
'videoUrl' => 'urlhere',
), $atts));
return $videoUrl;
}
Instead of returning "test", it's returning "urlhere". If 'urlhere' is left empty, it returns nothing. | It appears like you can not use upper case like that in a shortcode. Instead of `videoUrl`, use `video-url`:
function get_youtube_thumb_url_func( $atts ) {
$atts = shortcode_atts(
array(
'video-url' => 'urlHere',
), $atts, 'youtube-thumb-url' );
return $atts['video-url'];
}
add_shortcode( 'youtube-thumb-url', 'get_youtube_thumb_url_func' );
And your shortcode:
> [youtube-thumb-url video-url="test"]
This is the final function that I tested before posting. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions, shortcode"
} |
I want to increas my site image
I upload site image in my theme there is restriction so I want to change the style I inspect element and went to header to know the class name and id so I can modified pair my required but
It was like this
 . "/Functions_Folder/*.php") as $file){
require $file;
}
Its working fine with the *.php files located inside the parent folder --Functions_Folder.
Is there any function can call all the files **only** inside the --Functions_Folder including all the sub folders *.php files?
Thank you, | You need to use some recursion on the function:
function require_all_files($dir) {
foreach( glob( "$dir/*" ) as $path ){
if ( preg_match( '/\.php$/', $path ) ) {
require_once $path; // it's a PHP file so just require it
} elseif ( is_dir( $path ) ) {
require_all_files( $path ); // it's a subdir, so call the same function for this subdir
}
}
}
require_all_files( get_template_directory() . "/Functions_Folder" ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, filesystem"
} |
Parsing php string in jquery
I am sending php array using serialise but the response is different. Here is my attempt
$array = serialize($out);
var_dump(serialize($array));
//string(58) "s:50:"a:2:{s:9:"sidebar-1";i:5;s:12:"footer-insta";i:2;}";"
The way I am sending this value,
echo '<div data-ad = '.$array.' class="ash_loadmore"><span>LOAD MORE</span></div>';
As I am sending the serialised value using ajax, the value that ajax response give me,
string(54) "a:2:{s:9:\"sidebar-1\";i:5;s:12:\"footer-insta\";i:2;}"
I need the exact value as I have unserialise again to make it array. Why there is extra `\` and output is different. | Well it seems @JacobPeattie mentioned to use json, I just echoing that.
1. First json encode the variable `$array = json_encode($out);`
2. Then send this value `echo '<div data-ad = '.$array.' class="ash_loadmore"><span>LOAD MORE</span></div>';`
3. To get that `echo json_encode($_POST['ad'])`
I think that's it.BTW you don't have now that string problem as the output will be like this `{"footer-insta":2,"sidebar-1":3}` you see it is wrapped by `{}` | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "php, jquery, array, json"
} |
Remove link from product attributes in tab "additional information"
Since some updates of WooCommerce, Wordpress, Theme etc. on our product pages in the product-tab "additional information" some attributes are now linkable (to some automatic created pages). I cant find the setting how to disable it and even so no php solution for functions.php. I neither want that automatic pages then the links.
;
All plugins are shown and I can activate them. );` This is on the ACF field where I can select a specific user from a specific role.
The output of this is:
Array ( [ID] => 42 [user_firstname] => Sarah [user_lastname] => Piddington [nickname] => sarah_piddington [user_nicename] => sarah_piddington [display_name] => Sarah Piddington
The only part I need from this is the ID but im not sure how to access this on its own? Could somebody advise me if this even possible? I need it to use as a comparison. | You could just use:
echo get_field('consultant_name')['ID']; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "advanced custom fields, array"
} |
Media Library Won't Display Any Images
I've got a local install of WP and I've copied my live site's uploads dir to the proper spot in wp-content, but Media Library isn't showing a single image.
I've recursively set uploads and subsequent dirs to 755, that didn't fix it. I checked the upload_path in wp_options and it's blank like it is on the live server.
FYI, the import of posts I did came from a multi-site install where the live site is.
I'm at a loss as to where I can fix this missing link to the uploads folder. Posts are seeing the images in the uploads and rendering fine with the local dev url path in the images.
Thanks for any guidance!
 using Add From Server plugin as seen here:
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "uploads, media library"
} |
Variable not being passed into WordPress loop
In my WordPress custom post type loop only want to pull in from three posts 5171, 5167 and 5165.
If I do:
'post__in' => array(5171,5167,5165),
The loop outputs the values for those three correctly.
If I do:
'post__in' => array($my_share),
It only outputs the values for **5171**. However **$my_share** equals **5171,5167,5165**. If I do `echo $my_share` it also shows **5171,5167,5165**.
Is there any obvious reason why $my_share is only passing the first value into the post__in array or anyway around that issue? | If $my_share echoes as "5171,5167,5165" then it is a string not an array...
In other words `array($string)` does not equal `array(integer,integer,integer)` even if `$string` equals "integer,integer,integer" because array treats $string as a single value with further values separated by commas.
You could use `post__in => explode(",", $my_share),` to convert the string into an array while passing it... otherwise you could try just using `post__in => $my_share,` and it _might_ be converted into an array for you (but not sure without delving deep into the code to look.) | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "loop"
} |
How to display post excerpt beside post list inside Post of Dashboard
I need to display a little description of the posts on the post lists page, i.e inside Post page of admin dashboard. It is already displaying title, author, categories, tags, comment, date, and so on. but how can i fetch post excerpt to be displayed here beside title. | Please add follwing line of code in your theme's function.php to display a new column which will display excerpt in your posts.
function pkb_get_excerpt($post_ID) {
$content_post = get_post($post_ID);
$content = $content_post->post_content;
if ($content) {
return $content;
}
}
// ADD NEW COLUMN
function pkb_columns_head($defaults) {
$defaults['excerpt'] = 'excerpt';
return $defaults;
}
// SHOW THE EXCERPT
function pkb_columns_content($column_name, $post_ID) {
if ($column_name == 'excerpt') {
$post_content = pkb_get_excerpt($post_ID);
echo $str1= substr ($post_content,0,50);
}
}
add_filter('manage_posts_columns', 'pkb_columns_head');
add_action('manage_posts_custom_column', 'pkb_columns_content', 10, 2);
Please feel free to ask if you have any queries. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, excerpt, dashboard"
} |
Why does wordpress add Theme not list a specific theme anymore?
I used a theme on a wordpress site that I liked and now a year later I cannot find that theme for a second installation in any of the add themes tabs.
Does it get removed when not updated or downloaded? Or is it only when the theme developer removes it manually? | Official repositories will omit themes and plugins that hadn't been updated in two years from search and APIs. If you can find theme on repository site this is shown by following warning:
> This theme **hasn’t been updated in over 2 years**. It may no longer be maintained or supported and may have compatibility issues when used with more recent versions of WordPress.
If theme is really _gone_ and cannot be located on site then it was likely removed by author or repository team for some reason. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "themes"
} |
Permanent Custom Post Type
How do I add a custom post type to what I'm assuming is a table in WP's underlying database.
I.e. I don't want to have this loading on every page and I want to be able to use slug and post-type queries on it.
function cptui_register_my_cpts_app() {
$labels = array();
$args = array();
register_post_type( "app", $args );
}
add_action( 'init', 'cptui_register_my_cpts_app' );
More specifically, I want to be able to create a redirect from a custom post type (in this case 'app') to the login page if members are not already logged in.
function my_redirect() {
if( !is_user_logged_in() && is_singular('app') ) {
wp_redirect( 'login page' );
exit();
}
}
add_action('init', 'my_redirect'); | The built in post type definitions aren't stored in the database, they're registered on every request, just like custom types. There's no way around this.
If you just want to check the request and your logged in state as early as possible, you can use the `parse_request` action:
function wpd_parse_request( $request ) {
if( !is_user_logged_in() && isset( $request->query_vars['app'] ) ){
wp_redirect( wp_login_url() );
exit();
}
}
add_action( 'parse_request', 'wpd_parse_request' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, theme development, customization, post type"
} |
Loading child theme script after plugins scripts
Owl carousel js is getting loaded after my child theme scripts gets loaded, owl.carousel.min.js is located inside plugins directory which is inside wp-content folder. How can I make owl.carousel.min.js load before my custom script present inside child theme, following is the code I wrote in functions.php
add_action( 'wp_enqueue_scripts', 'custom_script' , 120);
function custom_script() {
wp_enqueue_script('jquery');
wp_enqueue_script( 'ultrabootstrap-bootstrap', get_template_directory_uri() . '/js/bootstrap.js', array(), '1.0.0', true );
wp_enqueue_script( 'ultrabootstrap-scripts', get_template_directory_uri() . '/js/script.js', array(), '1.0.0', true );
wp_enqueue_script(
'custom-script',
get_stylesheet_directory_uri() . '/custom-script.js',
array('jquery','ultrabootstrap-bootstrap','ultrabootstrap-scripts')
);
}; | The 3rd parameter of `wp_enqueue_script()`, called `$deps`, will help you to solve this. You just need to know the handle with which owl carousel was enqueued. Assuming it is `owlcarousel`, you'd change your code to this
wp_enqueue_script(
'custom-script',
get_stylesheet_directory_uri() . '/custom-script.js',
array('jquery','ultrabootstrap-bootstrap','ultrabootstrap-scripts','owlcarousel')
// added this new dependancy -----------------------------------------^
);
This way, WordPress will do the magic under the hood for you. If you don't know the handle, just check the source code of the plugin which enqueues owl carousel. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugins, child theme"
} |
Shortcode return function with link href inside PHP
I'm trying to write a shortcode in function.php with a link to share the current page in Twitter. However this link contains some PHP in the href and I can't figure it out how to make it work. Here is the code:
add_shortcode ( "indice", "indice_output" );
function indice_output( $atts, $content="null" ) {
extract( shortcode_atts( array(
'' => ''
), $atts ));
return '<div class="boxed max-width"><div class="indice-title"><span>' . $content . '</span><i class="fa fa-twitter" aria-hidden="true"></i></div></div>';
}
Thanks in advance for the help. | You can use ob_start and ob_get_clean to print out your shortcode.
function shortcode_html()
ob_start(); ?>
<div class="boxed max-width">
<div class="indice-title">
<span><?php echo $content; ?></span>
<i class="fa fa-twitter" aria-hidden="true"></i>
</div>
</div> <?php
return ob_get_clean();
}
add_shortcode( 'print_shortcode', 'shortcode_html' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "php, functions, links"
} |
Programatically adding custom filters to post list
 to only posts that have thumbnails?
I made a script that shows recent posts. But here's the problem, I want to show only posts that have thumbnails, and I want to show at least 10 posts if there are that many without thumbnails. So the filtering needs to happen before fetching 10 recent posts, because otherwise there's a possibility that none of them could have thumbnails and nothing will show.
Here's my code:
function add_before_my_siderbar() {
// get recent posts
$recent_posts = wp_get_recent_posts();
foreach( $recent_posts as $recent ) {
// Print recent posts
}
}
add_action( 'get_my_sb_widget', 'add_before_my_siderbar' ); | You can pass arguments to pass `meta_query` to your `wp_get_recent_posts()` function. `wp_get_recent_posts()` makes call for `get_posts()`, so you can make use of all the arguments `get_posts()` or `WP_Query` uses. As per your need.
$args= array(
'meta_query' => array(array('key' => '_thumbnail_id'))
);
$recent_posts = wp_get_recent_posts($args);
Along with other arguments you want to pass to your function.
Please check for proper syntax. Haven't tried the code. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "filters, hooks, post thumbnails, thumbnails, recent posts"
} |
Which file is the theme index page?
I'm new to wordpress, and I want to edit the **homepage** of a theme. I just could not find out which file should I be editing with. I've tried to remove _page.php_ , _index.php_ , _single.php_ under /wp-content/themes/mytheme, but my site is still working after I removed all these files, so which file is the theme actually using as the homepage?
I'm using wordpress 4.8, wooCommerce 3.1
I'm using **Rosa** theme, and the files listed under the theme root are these, index.php, page.php, single.php, sidebar.php, functions.php, footer.php, comments.php header.php | The homepage template depends on two things:
1. What the "Front page displays" setting has been set to.
2. Which files exist in the theme.
The WordPress Template Hierarchy shows how WordPress decides which theme file to use. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "homepage"
} |
How to remove function?
I'm trying to remove a function that is defined in my parent theme but can't get it to work. The function I want to remove prints previous/next post navigation.
Here's the function:
add_action( 'generate_after_entry_content', 'generate_footer_meta' );
function generate_footer_meta()
{
if ( 'post' == get_post_type() ) : ?>
<footer class="entry-meta">
<?php generate_entry_meta(); ?>
<?php if ( is_single() ) generate_content_nav( 'nav-below' ); ?>
</footer><!-- .entry-meta -->
<?php endif;
}
I'm using the `remove_action( );` function but I'm not sure which action hook to use.
Here's the code I'm using:
function remove_nav_links() {
remove_action( 'generate_after_entry_content', 'generate_footer_meta' );
}
add_action( 'wp_footer', 'remove_nav_links' );
I've tried a few different action hooks including `wp_footer` but none have worked. | Essentially you want to remove this _after_ it had been added, but _before_ that hook fires. Which is hard to tell in general without knowing _when_ does the parent theme executes this.
Also in often confusing way `functions.php` of child theme is loaded _before_ that of parent theme. Often makes timing of things counter–intuitive.
The very _general_ practice is that you wait until `init` hook to run any logic, other than strictly related to the load process. So my _guess_ would be on/around `init`, but really you should figure out when is it added and decide based on that. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "actions"
} |
How to add content to the end of a page with a hook?
I would like to add content to the end of this page (below the form), immediately before the footer. Can I do this with a custom function, via a hook? Adding the content to the WordPress editor does not insert it at the bottom of the page as desired.
I've tried two different custom functions, but they each placed the content in an undesired location (illustration):
\-- I tried using the `wp_footer()` hook, but that placed the content at the end of my footer.
\-- I tried appending content using `the_content()` hook, with the code below, but that did not place the content where I wanted.
function yourprefix_add_to_content( $content ) {
$content .= 'Your new content here';
return $content;
}
add_filter( 'the_content', 'yourprefix_add_to_content' );
I _can_ accomplish this by directly editing template, but I would rather not do that. | Unless that template that you don't want to edit has a `do_action()` function where you want to add the content, then no, you can't. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "hooks"
} |
Get category URL for current post
I am using this code to retrieve the category of the current post.
<?php $category = get_the_category();
$firstCategory = $category[0]->cat_name; echo $firstCategory;?>
How could I get the category URL without running another database query? | Pass the category id into `get_category_link()`:
<?php
$category = get_the_category();
$link = get_category_link( $category[0]->term_id );
?>
**Update** Outputting in template:
<?php
$category = get_the_category();
$first_category = $category[0];
echo sprintf( '<a href="%s">%s</a>', get_category_link( $first_category ), $first_category->name );
?> | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "functions, categories"
} |
Color different for the current category
I would like to change the color of the current category in this page :
 ); ?>
thank you :) | By default it will add `current-cat` class to the current category item.
If we need to change that, we can use:
> **'current_category'**
>
> (int|array) ID of category, or array of IDs of categories, that should get the `'current-cat'` class. Default 0.
as mentioned in the dev docs for `wp_list_categories()` arguments:
Then we can style it as needed via CSS.
**Example**
For your setup:
.ul-cat .current-cat a {
color: #aaa;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "categories"
} |
I updated my own theme's code and css
I have mt theme folder in my computer, where I did all the updates. Now I want to upload the new version of my theme with the changes I did. My question here: Do I just upload the theme folder via FTP and overwrite the existing one? Will this damage or change my posts or it will just update the theme design? I did this last night, but I'm afraid it changes everything... | This is a good use case for a local development environment. But, yes, if all you did was change files in the theme, then nothing that was saved to your database will be altered. If you are worried about things breaking, then I suggest getting a local copy of your WP install running and test things out there before pushing anything to your live site. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, theme options"
} |
display a div on ervery site but not frontpage?
i want to display a div on every single page, but not on the frontpage. For that i used the following code in the functions.php
if (! is_front_page()) :
'<div class="button-kontakt"> <a href="/kontakt"><p>ANFRAGE</p></a></div>';
endif;
But my code is not working? The div is not shown. Somebody could help me with this?
best regards
Tom | You need to tell the PHP to echo the div.
`if (! is_front_page()) : echo '<div class="button-kontakt"> <a href="/kontakt"><p>ANFRAGE</p></a></div>'; endif;`
Unless you just want it on the top of the page, you need to add that code to a template file, not the functions file. If it is something that appears at the bottom of every page except the homepage, putting it in footer.php may be applicable.
Also, have you set the page you don't want to see it on as the front page via the option in the Appearance->Customise menu? | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions"
} |
How to get different homepage layout, based on the URL and customizer
Not sure If my question is clear enough. I want to show different layout of the index.php, based on the URL and customizer settings. I see this format in some themes:
demo.website.com/theme/?home_layout=standard
For me it looks like it's a GET request, and based on this request different layout is loaded.
For example, I want to set layout to masonry in customizer and it should change the look of the homepage and the URL should be
demo.website.com/theme/?home_layout=masonry
If I switch to standard layout in customizer then I get this URL
demo.website.com/theme/?home_layout=standard
How to achieve this? | For those who wants to achieve the same, here is the answer: First we declare a variable with a simple condition to hold our GET request, if the value is not set than we define default value.
$layout = isset( $_GET['home_layout'] ) ? $_GET['home_layout'] : 'standard';
Then simply check the condition and load the template you want.
if ( $layout == 'grid' ) {
get_template_part( 'template-parts/standard-layout' );
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "homepage, home url"
} |
enqueued script with jquery dependency not getting jquery
Adding scripts for my theme and added jquery as a dependency. I see the jquery script tag in the header of the page but my script in the footer is getting a "$ is not a function" error.
function wpdocs_template_scripts() {
wp_enqueue_style( 'style', get_stylesheet_uri() );
wp_enqueue_script('modernizer', get_template_directory_uri() .'/js/vendor/modernizr-2.8.3.min.js', null, null, false);
wp_enqueue_script('bootstrap', get_template_directory_uri() .'/js/bootstrap.min.js', array('jquery'), null, true);
wp_enqueue_script('main', get_template_directory_uri() .'/js/main.js', array('jquery'), null, true);
}
add_action( 'wp_enqueue_scripts', 'wpdocs_template_scripts' ); | Put this in your `.js` file
(function($) {
// Your code inside here;
})(jQuery);
This is called an anonymous function, you're passing the jQuery object as a parameter to it.
**OR**
var $ = jQuery; // This at the top of the file
This is simple, you're just assigning the `jQuery` object to the `$` variable
References:
is-not-a-function-jquery-error
jquery-is-not-a-function-error | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "jquery, wp enqueue script"
} |
Podcast set up within a page, or, adding a /feed to a page
I have no idea really to start. Basically my media guy want's a /feed for one of my pages. My website is www.clccedarrapids.com and that has a working www.clccedarrapids.com. However, the "sermons" page does not have a feed. So www.clccedarrapids.com/sermons/feed is 404ed. Is there a way to way to easily add a /feed? I do know HTML and PHP and am not afraid of code, I just have never messed with RSS and don't know where to start. The end result we hope to achieve is to set up a streamlined podcast so that when we upload a sermon we also upload a podcast episode. If someone could just point me in the right direction it would be greatly appreciated, I don't even know what to Google! Thanks again! | Try this url since it seems `sermons` is a custom post type
<
Actually, scratch the above. I got a response on my end from: < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "rss, podcasting"
} |
Globally force SSL on all pages
Right now my domain `www.example.com` is setup to force HTTPS and it works. The site also correctly links everything to HTTPS. (there are no occurences of HTTP in the database anywhere).
But if you are visiting a subpage, you can change the url to HTTP again, for example ` and it will not enforce HTTPS.
I have this rule in my `.htaccess` in the root:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ [R,L]
Any ideas what the cause of this is? | To globally redirect all your pages to HTTPS add the following lines to your `.htaccess`:
# Globally force SSL.
RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ [L,R=301]
This should be placed directly after `RewriteEngine on` if you have no previous rewrites. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "htaccess, ssl, https"
} |
get_template_part in for loop
Due to the setup of my template (and layout), I need to be able to place 4 different posts in 4 different divs.
For example, my structure would be like this
<div>Post 1</div>
<div>
<div>Post 2</div>
<div>
<div>Post 3</div>
<div>Post 4</div>
</div>
</div>
But I'm having some trouble getting this to work, I use `get_posts` to get the 4 latest posts.
$posts = get_posts(array(
'post_type' => 'post',
'post_count' => 4
));
And then I try to display my post
<?php setup_postdata($posts[0]); ?>
<?php get_template_part( 'template-parts/post-thumbnail' ); ?>
<?php wp_reset_postdata(); ?>
In `template-parts/post-thumbnail.php` I'm trying to display the title and permalink, but it's always showing the title and link of the current page. Never of the actual post. | Your problem is that the variable passed to `setup_postdata()` _must_ be the global `$post` variable, like this:
// Reference global $post variable.
global $post;
// Get posts.
$posts = get_posts(array(
'post_type' => 'post',
'post_count' => 4
));
// Set global post variable to first post.
$post = $posts[0];
// Setup post data.
setup_postdata( $post );
// Output template part.
get_template_part( 'template-parts/post-thumbnail' );
// Reset post data.
wp_reset_postdata();
Now normal template functions, like `the_post_thumbnail()` inside the template part will reference the correct post. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 5,
"tags": "wp query, loop, get posts"
} |
restrict uploaded image size and fixed image display size
I quite new in wordpress , and currently studying it. I am trying to build a kind of blog for a project and i am stuck in some part. I've made a search on this website and it seems that nobody has ask this question or maybe i am not searching the right posts: I want images uploaded by whatever user,except admin, from media library to be displayed in the frontend to a specific size only for example 600x900 and additionally I want to restrict users that upload their photos through media library to some specific size, lets say if the files are lesser 600x900 it is rejected and whatever is above goes through.
Anyone can help please? Is there a plugin that can do this or some lines of codes which i can insert into functions.php?
Thanks | Add this code to your theme's functions.php file, and it will limit image dimentions
add_filter('wp_handle_upload_prefilter','tc_handle_upload_prefilter');
function tc_handle_upload_prefilter($file)
{
$img=getimagesize($file['tmp_name']);
$minimum = array('width' => '600', 'height' => '900');
$width= $img[0];
$height =$img[1];
if ($width < $minimum['width'] )
return array("error"=>"Image dimensions are too small. Minimum width is {$minimum['width']}px. Uploaded image width is $width px");
elseif ($height < $minimum['height'])
return array("error"=>"Image dimensions are too small. Minimum height is {$minimum['height']}px. Uploaded image height is $height px");
else
return $file;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions, uploads, images"
} |
How does gettext works for translating readme file of plugin?
I am doing translation of my plugin. I am using __ & _e in php files. But can't figure out how to do same for readme.txt file? Is it's content on Wordpress site's plugin page automatically get translated using Wordpress translation dictionary once plugin adds code for loading textdomain? | Translations for readmes on .org are done through < You could contribute translations for your own plugin if you wanted. Start by picking a locale/language you want to translate into, search for your plugin, and select the Readme Sub Project.
You don't need to do anything special to the readme itself. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "plugin development, translation, xgettext"
} |
Get smaller size of image, get_the_post_thumbnail
My theme is using this code in a shortcode to get the image of the post. However, this is the full size image and i am looking to get the small thumbnail instead. How could I do this?
$image_output = '<div class="x-recent-posts-img">' . get_the_post_thumbnail( get_the_ID(), 'entry', NULL ) . '</div>'; | Just change the code to:
$image_output = '<div class="x-recent-posts-img">' . get_the_post_thumbnail( get_the_ID(), 'thumbnail', NULL ) . '</div>';
See in the Codex:
Thumbnail Sizes
get_the_post_thumbnail | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "post thumbnails"
} |
If a post has two categories with different permissions, what will happen?
I have a category that(using a plugin) is member only. What happens if a post is given a category that is member only, and a category that is available to everyone? If it is still accessible to everyone, how can I prevent that? | I tested it, and by default it will show it to everyone even if one of the categories is member only. If you need a fix for that(like me), then use the following in `functions.php`:
function my_filter( $content ) {
$categories = array(
'news',
'opinions',
'sports',
'other',
);
if ( in_category( $categories ) ) {
if ( is_logged_in() ) {
return $content;
} else {
$content = '<p>Sorry, this post is only available to members</p>';
return $content;
}
} else {
return $content;
}
}
add_filter( 'the_content', 'my_filter' );
from my other question. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "categories"
} |
WooCommerce get Shipping Class of product from either the product id or the order after order is completed
I have been trying to figure out how to get the shipping class from the order after payment is complete. I have found this...
$shipping_class = $cart_item['data']->get_shipping_class();
but that retrieves the shipping class from an active cart, I need to get this after the order is processed, possibly from...
$order = new wc_get_order(id);
$items = $order->get_items();
I can then get the product and variation ids but for some reason I am not seeing how to get the shipping class from this.
any help on this would be greatly appreciated! | Palm to FACE!!!
using the product id...
~~$_product = get_product(id);~~
$_product = wc_get_product()
$shipclass = $_product->get_shipping_class();
this returns the products shipping class.
EDIT: as mentioned by Aniruddha get_product is depreciated answer has been updated. | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 3,
"tags": "plugin development, woocommerce offtopic"
} |
What is meant by Multisite in WordPress?
I am a newbie in WordPress not totally but 6 months. I am confused with **MULTISITE**. I want to know that what is it, **_correct me if I wrong =>_** is it a way to create a multi purpose site/theme easily means in default WordPress we can create a blog or a business site etc, but by using multisite functions that WordPress provide, I think it that we can create a multipurpose website easily again correct me if I wrong. Or is it used for something else if it is
1. then what is that,
2. what is the role of multisite functions,
3. what the can do (means what they can provide so that I can make my site/theme better),
4. are they useful for developers (means did I have to make my site/theme using these functions),
5. we can make secure site/theme,
6. the beginners need to also learn about multisite functions | Wordpress Multisite allows you to use one WordPress code installation to run multiple websites.
mywebsite1.com mywebsite2.com mywebsite3.com etc
All run from the same code, can share the same plugins, can share the same themes (but use different themes), share the same admin login (but different sites can be limited to different editors), keep all data in the same database (but stored in different, not-shared tables). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "multisite, multisite user management"
} |
Using nonce in menu item
I have a log out link in the main header menu, when you click on the link to log out, you are redirected to the page asking if you really want to log out. I know it's doing this because there is no nonce in the menu URL.
My question is: is it even possible to add a nonce in CMS appearance>menus in the edit menus screen? The url is something like: `example.com/wp-login.php?action=logout&redirect_to=
Just for giggles I tried adding `wp_create_nonce('logout')` to the end but of course it doesn't' work.
If this isn't possible is there another way to bypass the 'are you sure you want to log out' screen? | Just add a filter:
function change_menu($items){
foreach($items as $item){
if( $item->title == "Log Out"){
$item->url = $item->url . "&_wpnonce=" . wp_create_nonce( 'log-out' );
}
}
return $items;
}
add_filter('wp_nav_menu_objects', 'change_menu'); | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 5,
"tags": "menus, nonce"
} |
Remove all categories from URL
This is the original I need to modify:
These are the things I have done (which is what I wanted!)
But... I want to include a condition, for example I do not want theses URLs to be touched:
Here's my Awesome regex :
RewriteRule /?(.*)([0-9]+)-(.*)$ /$3 [R=301,L]
I probably have to say that **I NEED** `/(.*)/0000-post`, but if I add a slash within the regex it does not work anymore.
I used < btw. | Could help some Wordpress user who want to not get 404 when changing permalinks.
# You dont want your medias to be rewritten
RewriteCond %{REQUEST_URI} !^/(wp-content/uploads)/
RewriteRule /?(.*)(/)([0-9]+)-(.*)$ /$4 [R=301,L] | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "url rewriting, htaccess, regex"
} |
How to fix a missing image
Someone made a website for me using wordpress.org. They said that they used "Wordpress Framework".
Although I haven't changed anything, the logo of the website (which was an image near the top of the homepage is now missing. Not sure how it could disappear without me changing anything, but I am trying to rectify this myself. I am not familiar with wordpress and so am hoping I can find some assistance; at least an idea of where to begin.
When I look what the active theme is, it just says 'Yescorts" which is the name of the website (yescorts.co.uk). I'm guessing that the creator customised an existing theme and then changed the name.
I know I will probably get down-voted for being vague, but if I knew enough to be specific, I would be able to fix this already. I'm just looking for some suggestions of where I start looking to fix this. Or what more info I can provide to help you help me.
Thanks in advance of any advice received. | The code of your site shows that the HTML is referencing your developer's server for the logo. They must have cleaned up and deleted that server installation recently. You'll need to re-upload a logo to your own media library. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "images"
} |
Getting the teaser text without overriding global variables
I am trying to make a WordPress theme, following the Wordpress Coding Standards - WPCS. In functions.php, I have a function to get only the teaser (text above the read more-tag). The function works, however I get an error from Code Sniffer that `Overriding WordPress globals is prohibited`
Any suggestions on how to achieve this, while following the Coding Standards would be great!
My code:
global $more;
$more_saved = $more;
// Sets $more to not showing the content after the more tag.
$more = 0;
echo esc_html( get_the_content( '', false ) );
// Restores $more.
$more = $more_saved; | get_extended() saved me! The returned array has 'main' and 'extended' keys. Main has the text before the `<!--more-->`. The 'extended' key has the content after the `<!--more-->` comment.
$content = get_post_field( 'post_content', get_the_ID() );
$content_parts = get_extended( $content );
echo esc_html( strip_tags( $content_parts['main'] ) ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, theme development, themes, globals"
} |
Symlinked plugin directory doesn't appear in Admin
I have a simple test plugin - a folder called `tester` containing a file called `tester.php` that contains only this:
<?php
/*
Plugin Name: My tester
*/
?>
I have a copy of WordPress running locally on my Mac. When the plugin is in the plugins directory it appears in the Admin list of plugins.
When I move the plugin directory elsewhere and symlink to it, it doesn't show up.
I've done similar with a theme, and WordPress happily uses that. From what I've read this should now work with plugins too. Am I missing something?
(WordPress 4.8) | What have you done to add the symlink?
In using VVV I am able to symlink using your plugin tester code:
# ssh into vagrant
$ vagrant ssh
# create symlink
$ sudo ln -s /srv/www/wordpress-default/wp-content/testing-dir/tester /srv/www/wordpress-default/wp-content/plugins/tester | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 6,
"tags": "plugins, plugin development"
} |
How does translation (gettext) work for translating config file of plugin?
I am doing translation of my plugin. I am using `__` & `_e` in php files. But can't figure out how to do same for config file that contains constants added using define(name, value)? Does it automatically get translated using Wordpress translation dictionary once plugin adds code for loading text-domain? Also, Do I need to use add text domain compulsorily or will Wordpress's translator will translate it even then? | WordPress doesn't automatically translate anything, you need to use the `__` and `_e` functions, even in your config file, if you want it to be translateable.
`define( 'CONSTANT', __( 'some string', 'textdomain' ) );` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, plugin development, translation, xgettext"
} |
How do I edit the <title> tag without using the deprecated `wp_title()` function?
How do I edit the tag without using the deprecated `wp_title()` function? I need to add a microdata parameter - `itemprop="name"` -, as seen in the example below:
<head itemscope itemtype="
<title itemprop="name">Your WebSite Name</title>
<link rel="canonical" href=" itemprop="url">
The is injected using theme support.
**Note 1:** All the custom hooks provided by WordPress allow for title content manipulation only, not the tag itself.
**Note 2:** This is not a duplicate of Custom attribute for the title tag with wp_title() as the accepted answer does not function anymore. | It looks like _wp_render_title_tag() method is what outputs the tag, and the source code in 4.8 is available here: <
You can see:
echo '<title>' . wp_get_document_title() . '</title>' . "\n";
You could first remove the action from wp_head:
remove_action( 'wp_head', '_wp_render_title_tag', 1 );
Then add your own title render method:
add_action( 'wp_head', '_wp_render_title_tag_itemprop', 1 );
function _wp_render_title_tag_itemprop() {
if ( did_action( 'wp_head' ) || doing_action( 'wp_head' ) ) {
echo '<title itemprop="name">' . wp_get_document_title() . '</title>' . "\n";
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "title"
} |
Ensuring a plugin is loaded/run last?
How can you ensure a given plugin is run _last_ before the page finishes rendering?
Can it be ensured?
Specifically, I am writing a plugin that I want to post-process all content of a given post/page (after any formatting, extra links, ad injections, etc). The rest of the blog doesn't need to be processed - just posts & pages. | You'll want to hook into "the_content" filter at a very high priority. Example:
function my_alter_the_content( $content ) {
if ( in_array( get_post_type(), array( 'post', 'page' ) ) ) {
// Do stuff here for posts and pages
}
return $content;
}
add_action( 'the_content', 'my_alter_the_content', PHP_INT_MAX
);
Using the PHP_INT_MAX constant for the hook priority you can ensure it runs as last as possible (most plugins/themes will just use the default priority of 10).
The issue is when you say "after all ad injections...etc" that really depends how things are being added. Because if there are ads being added via javascript then of course the only way to override it would be via javascript. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "plugin development, order"
} |
Local installation is broken
Yesterday I asked here how can I upload the whole installation to a server and I changed "localhost" to "website.com" locally and after that I changed it back to "localhost" but now I try to see a post locally and it send me to xamp dashboard. How can I fix it? | Have you double checked your wp-config.php file to make sure it's pointing to the correct database?
Also if your site was previously locally hosted and now it's live also make sure that the siteurl and home URL's are correct in the database for the live site under the 'wp_options' table.
**Edit** : If you can access the admin try going to Settings > Permalinks and clicking the save button to refresh your .htaccess file incase things got messed up there. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "localhost, local installation"
} |
redirect word-press page with page values
I am trying to redirect my wordpress page . This code is working good.
<a href="'. get_permalink('dashboard') .'" class="wpum-profile-account-edit">'. __(' (Edit Account)', 'wpum') .'</a>
But I am trying to redirect with page value " dashboard/?dashboard=myprofile" .But this code is not working
<a href="'. get_permalink('dashboard/?dashboard=myprofile') .'" class="wpum-profile-account-edit">'. __(' (Edit Account)', 'wpum') .'</a> | Use this code and check`<a href="'. get_permalink('dashboard') .'?dashboard=myprofile" class="wpum-profile-account-edit">'. __(' (Edit Account)', 'wpum') .'</a>`. In get_permalink() function you can only pass the post ids or page titles to get the page url but you have added additional parameters with that so it was not getting the correct url. So I have edited the code to append the extra parameters after the function. | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 0,
"tags": "plugin development, url rewriting, urls, site url"
} |
locate_template function - File not getting included
$locate = locate_template( 'widgets/the-post-widget.php' );
I am using the above path and method to include a file in `functions.php`, but that is not happening.
The file doesn't seem to include. Am I doing a mistake? | `locate_template` just returns the filename of the template. If you want to load the template, set the second argument to `true`:
locate_template( 'widgets/the-post-widget.php', true ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "include, template include"
} |
How to change text widget title h2 to h1
I created text widget and wordpress created some default styles it uses h2 tag and class "widgettitle". How can i change tag to h1 and remove class from it.
This is my function.php file
function home_consultation_init() {
register_sidebar(array(
"name" => "Home Consulatation",
"id" => "home_consult",
"before_widget" => "",
"after_widget" => "",
"before-title" => "",
"after-title" => ""
));
} | The `before-title` and `after-title` arguments passed to `register_sidebar()` need to use underscores:
register_sidebar(array(
"name" => "Home Consulatation",
"id" => "home_consult",
"before_widget" => "",
"after_widget" => "",
"before_title" => "",
"after_title" => ""
));
If you use that the titles won't have any tags. You need to provide them to the `before_title` and `after_title` arguments, like so:
register_sidebar(array(
"name" => "Home Consulatation",
"id" => "home_consult",
"before_widget" => "",
"after_widget" => "",
"before_title" => "<h1>",
"after_title" => "</h1>"
));
Your problem was that you were using the incorrect keys (with `-` instead of `_`), so it was using the defaults. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "widgets, widget text"
} |
How to get URL of current page displayed?
I want to add custom PHP code to ensure that whenever a page on my site loads in my browser, the URL of that page is echoed to the screen. I can use `echo get_permalink()`, but that does not work on all pages. Some pages (e.g. my homepage) display several posts, and if I use `get_permalink()` on these pages, the URL of the displayed page is not returned (I believe it returns the URL of the last post in the loop). For these pages, how can I return the URL?
Can I attach `get_permalink()` to a particular hook that fires before the loop is executed? Or can I somehow break out of the loop, or reset it once it is complete?
Thanks. | `get_permalink()` is only really useful for single pages and posts, and only works inside the loop.
The simplest way I've seen is this:
global $wp;
echo home_url( $wp->request )
`$wp->request` includes the path part of the URL, eg. `/path/to/page` and `home_url()` outputs the URL in Settings > General, but you can append a path to it, so we're appending the request path to the home URL in this code.
Note that this probably won't work with Permalinks set to Plain, and will leave off query strings (the `?foo=bar` part of the URL).
To get the URL when permalinks are set to plain you can use `$wp->query_vars` instead, by passing it to `add_query_arg()`:
global $wp;
echo add_query_arg( $wp->query_vars, home_url() );
And you could combine these two methods to get the current URL, including the query string, regardless of permalink settings:
global $wp;
echo add_query_arg( $wp->query_vars, home_url( $wp->request ) ); | stackexchange-wordpress | {
"answer_score": 207,
"question_score": 122,
"tags": "php, loop, permalinks, urls"
} |
How to display category from recent posts?
I have a code for display recent posts:
`<?php $args = array( 'numberposts' => '5' ); $recent_posts = wp_get_recent_posts( $args ); foreach( $recent_posts as $recent ){ echo '<h2><a href="' . get_permalink($recent["ID"]) . '">' . $recent["post_title"].'</a> </h2> '; echo '<p>' . date_i18n('d F Y', strtotime($recent['post_date'])) .'</p> '; // what code here? } wp_reset_query(); ?>`
now I want to display category name and link also. What kind of code should I use in here? I try some but without effect...
Thx :) | You can use `get_the_category_list()` to output a comma-separated list of links to categories:
<?php
$args = array( 'numberposts' => '5' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
echo '<h2><a href="' . get_permalink($recent["ID"]) . '">' . $recent["post_title"].'</a> </h2> ';
echo '<p>' . date_i18n('d F Y', strtotime($recent['post_date'])) .'</p> ';
echo get_the_category_list( ', ', '', $recent["ID"] );
}
wp_reset_query();
?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "posts, categories"
} |
change position of element using hook
I am using Storefront (Woocommerce theme).
I created a child theme.
I want to move the secondary navigation below the main menu.
I added this to functions.php to the child theme but it doesn't work.
Any idea ?
Thanks
<?php
remove_action( 'storefront_header', 'storefront_secondary_navigation', 30 );
add_action( 'storefront_header', 'storefront_secondary_navigation', 52 );
?> | Instead of adding and removing the hooks like this. You should do the work on some action/hook. which gets fire before these hooks.
so you can call it in this way
add_action( 'init' , 'sf_change_header_position' , 10 );
function sf_change_header_position() {
remove_action( 'storefront_header', 'storefront_secondary_navigation', 30 );
add_action( 'storefront_header', 'storefront_secondary_navigation', 52 );
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": -1,
"tags": "hooks"
} |
I want to load a pre-built php page (and assocated scripts/styles/directories) as the front page. How do I go about this?
I've pre-built a front page for WordPress using PHP, JS, CSS and resources found in other files. The whole page setup is 23 files (1 .php, 1 .js, 2 .css, 2 .otf, 17 .svg/.png/.gif) and 2 folders.
Essentially I want to override the default front page with this new one that I've made. It needs to remain as files, so having it as a static page won't work. I want to avoid turning it into a theme at all costs, because it's really not necessary.
How shall I go about completing this? | As shown in the template hierarchy image from the documentation, you can name your `.php` file as `front-page.php`or `home.php`.
> By default, WordPress sets your site’s home page to display your latest blog posts. This page is called the blog posts index. You can also set your blog posts to display on a separate static page. The template file home.php is used to render the blog posts index, whether it is being used as the front page or on separate static page. If home.php does not exist, WordPress will use index.php.
>
> 1. home.php
> 2. index.php
>
>
> Note: If front-page.php exists, it will override the home.php template.
See the image below:
` ? | Yes, as `post_exists("great title")` runs the following SQL:
SELECT ID FROM $wpdb->posts WHERE 1=1 AND post_title = 'great title'
so there's no _post status_ or _post type_ restriction.
Check the docs on `post_exists()` for more info.
If you want to restrict by _post type_ , you can use:
$found_page = get_page_by_title( "great title", $output = OBJECT, $post_type = 'page' );
See the docs here. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "posts, conditional tags"
} |
Is there a plugin to have DMCA takedown notice form in Wordpress?
I was looking to do something like this in Wordpress:
<
But I can't find any plugin that makes that.
I hope you can help me with ideas.
Thanks in advance. | You may need to make your own form. One of the most popular contact form plugins is Contact Form 7. You can create a form with any number of fields/content/text, etc. A bit easier than creating your own form (which you could do with a template).
See < . | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, copyright"
} |
Delete a user from frontend
I'm developing a user management table, in which an user (I've already set restriction for for some specific roles) can create/edit or delete a user. How can I delete a user by clicking on delete link or button, I have stored the id in a variable. | If you know the user id, you could create a link similar to , where the value of the user is the user ID.
You can also hook into a function in the `users.php` file. It's a core file, so you don't want to change it. But you can use the functions therein to properly delete the user. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "users, login, user access, customization"
} |
What is the proper hook to use for recording a post view?
I'm creating a script for tracking post views in my future projects. I will use this code in my theme's `functions.php`.
What I'm asking is, how can I make sure a post view is recorded when a user actually hits the page?
I considered hooking into `init` or `wp`, but I'm not sure using the REST API and Ajax actions will also trigger a hit (which I want it to).
Is it possible? | Since it appears you want to track each kind of page view (which is what Google Analytics would do for you if you don't want to roll your own), then create a function that will use the current page-type, or even any type of page.
A function like (rough code)
function record_view($pagetype = 'post') { // function with default value
switch ($pagetype ) {
case "post":
//do something
break;
case "page":
// do something for a pge
break;
// add additional cases for whatever you are trackin
case default:
// do something if not any of the above types
break;
}
return;
}
See this page in the Codex for info about page types: < .
Then put a call for the function in the template of the various page types
record_view('post'); // this on the single post template
That might get you started, if I understand your question and comments correctly.
Good luck! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "hooks"
} |
How to disable a specific page for a specific user
For say, I have this page
>
I want to disable this page for the username `remo`.
How can I do this? | There is a global variable containing the current page in the admin area, called `$pagenow`. You can use this to detect where the user is now.
Now, in your case, you are on `admin.php` and there are 3 parameters set in the URL, `page`, `delete` and `id`. So:
if(
in_array( $pagenow, array('admin.php') ) &&
( $_GET['page'] == 'wpProQuiz' && $_GET['action'] == 'delete' && $_GET['id'] == '1' )
) {
// Now check the current user
$user = wp_get_current_user();
if ( $user->user_login == 'remo' ) {
wp_safe_redirect( admin_url() );
exit();
}
}
This will redirect the user back to their dashboard. Not that you don't need to check the password, since the username is unique. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "users, user roles, user access"
} |
How to use url formatter with integer
I have this below code to prevent users from deleting the quizzes.
if(
in_array( $pagenow, array('admin.php') ) &&
( $_GET['page'] == 'wpProQuiz' && $_GET['action'] == 'delete' && $_GET['id'] == '1' )
) {
// Now check the current user
$user = wp_get_current_user();
if ( $user->user_login == 'remo' ) {
wp_safe_redirect( admin_url() );
exit();
}
}
The code only for 1 quiz (see `$_GET['id'] == '1'`). But I have 40 quizzes. I learned that I could reuse this code without repeating 40 times using URL formatter.
Can someone help me out. | I found it, very simple logic. Don't specify any id number. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "users, urls, user access, id, content restriction"
} |
Clean up customize_changeset in DB
Is there something similar to
define( 'WP_POST_REVISIONS', 0 );
for customize_changeset type so they're not collected in DB. | No, there is not a way to disable `customize_changeset` posts from being created. These `customize_changeset` posts are created with the `auto-draft` status in the same way that a `post` gets created with the `auto-draft` status whenever you click on “Add New” in the admin. Note that because the `auto-draft` status is used, any such posts will get automatically deleted after 1 week. See `wp_delete_auto_drafts()`. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, database, theme customizer, revisions"
} |
Copy taxonomy terms from one post to another programmatically
Let's say i have a post with post id `"1"` and post with post id `"2"`.
And i have a custom taxonomy named `"my_taxonomy"`.
The post with post id "1" has: `"term1","term2","term3"` selected for the `"my_taxonomy"` terms.
And the post with post id `"2"` has: `"term3","term4","term5"` selected for the `"my_taxonomy"` terms.
I want to programmatically copy the terms from first post to second so the post with post id `"2"` will have: `"term1","term2","term3"` selected for the `"my_taxonomy"` terms now.
How can i do that the most "short coded way" ?
**A note:** both posts are a custom post type posts.
I tried:
wp_set_object_terms( '2', wp_get_object_terms( '1', 'my_taxonomy' ), 'my_taxonomy');
Doesn't seem to work. | This will work:
wp_set_object_terms(
'2',
wp_get_object_terms(
'1',
'my_taxonomy',
array("fields"=>"ids")
),
'my_taxonomy'
);
**Explanation:**
I added this: `,array("fields"=>"ids")` to the attempt i wrote in the question to make the `wp_get_object_terms` return array of ids alone (what the `wp_set_object_terms` want to get. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php, posts, custom taxonomy, taxonomy, terms"
} |
Display the latest posts, published in the last hour, with WP_Query
For a custom widget I want to retrieve the last posts published in the last hour.
All I can do actually is to display the posts of the day, with this query :
$queryArgs = array(
'category_name' => 'myCategory',
'posts_per_page'=> $number,
'date_query' => array(
array(
'year' => date( 'Y' ),
'month' => date( 'm' ),
'day' => date( 'd' )
),
),
);
$query = new WP_Query($queryArgs); | You can try the following to query for last hour posts:
'date_query' => [
[
'after' => '1 hour ago',
'inclusive' => true,
],
],
or
'date_query' => [
[
'after' => 'last hour',
'inclusive' => true,
],
],
or
'date_query' => [
[
'after' => '-1 hour',
'inclusive' => true,
],
],
Here we are playing with the `strtotime()` support in `date_query`. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "posts, wp query"
} |
My homemade plugin is trying to update to someone else's plugin
Wordpress is telling me that my self-built plugin has an update available, and this link leads me to someone else's repo.
After I first saw this message, I read a lot of questions on here asking similar questions, and have tried several things to try to get rid of this update available message, including:
* Ensuring both the folder name and filename are unique, even trying a random number at the end
* Changing the name of the plugin
* Changing the post type slug
None of these made a difference. The only think that seems to have worked so far is a really high version number (a horrible solution).
I thought perhaps Wordpress could be caching something somewhere? I don't have any caching plugins installed by the way.
Any ideas? | I was able to find out that wordpress does cache available updates in the wp_options table in an option named `_site_transient_update_plugins`.
By clearing this value I was able to get Wordpress to notice my changes. I used the following query:
`UPDATE wp_options SET option_value='' WHERE option_name='_site_transient_update_plugins';` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, updates, cache"
} |
How to manage a custom post type archive as a page?
Is there a way to manage a custom post type archive from the Page editing view?
I need to retain a certain url structure (so I need the formal wp archive), but also to be able to add images and content to the archive page from the admin. | The answer is: it's not possible. See comments above for workarounds. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, pages, urls, custom post type archives"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.