qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
203,815 |
<p>I try somehow to get array of pages names. I don't think it's possible in some default method from WP.</p>
<pre><code><?php $args = array(
'authors' => '',
'child_of' => 0,
'date_format' => get_option('date_format'),
'depth' => 0,
'echo' => 0,
'exclude' => '',
'include' => '',
'link_after' => '',
'link_before' => '',
'post_type' => 'page',
'post_status' => 'publish',
'show_date' => '',
'sort_column' => 'menu_order, post_title',
'sort_order' => '',
'title_li' => __('Pages'),
'walker' => new Walker_Page
)
;?>
$arr = wp_list_pages($args);
print_r($arr);
</code></pre>
<p>But this return LINK-s "< A >" tags ... Maybe in PHP I can in some way "transfrom" this links to string ? :)</p>
|
[
{
"answer_id": 203826,
"author": "coopersita",
"author_id": 21258,
"author_profile": "https://wordpress.stackexchange.com/users/21258",
"pm_score": 2,
"selected": false,
"text": "<p>You cad add it via <code>functions.php</code> with a hook, instead of inside the loop (you don't really want to add a loop to header.php):</p>\n\n<pre><code>function add_author_meta() {\n\n if (is_single()){\n global $post;\n $author = get_the_author_meta('user_nicename', $post->post_author);\n echo \"<meta name=\\\"author\\\" content=\\\"$author\\\">\";\n }\n}\nadd_action( 'wp_enqueue_scripts', 'add_author_meta' );\n</code></pre>\n"
},
{
"answer_id": 220507,
"author": "Harkály Gergő",
"author_id": 71655,
"author_profile": "https://wordpress.stackexchange.com/users/71655",
"pm_score": 0,
"selected": false,
"text": "<p>Add this into header.php</p>\n\n<pre><code><meta name=\"author\" content=\"<?php the_author_meta('user_nicename', $post->post_author); ?>\">\n</code></pre>\n"
},
{
"answer_id": 355595,
"author": "Rajnish Suvagiya",
"author_id": 128293,
"author_profile": "https://wordpress.stackexchange.com/users/128293",
"pm_score": 0,
"selected": false,
"text": "<p>You can add meta tags using <code>wp_head</code> hook action from <code>functions.php</code> of the Themes files or create a custom plugin.</p>\n\n<p>Here you can check example.</p>\n\n<pre><code>add_action('wp_head', 'fc_opengraph');\n\nfunction fc_opengraph() {\n\n\n if ( is_single() || is_page() ) {\n\n $post_id = get_queried_object_id(); // get current post id\n\n $author_name = 'set your author name';\n\n $site_name = get_bloginfo('name');\n\n $description = wp_trim_words( get_post_field('post_content', $post_id), 25 );\n\n $image = get_the_post_thumbnail_url($post_id);\n\n if( !empty( get_post_meta($post_id, 'og_image', true) ) ) $image = get_post_meta($post_id, 'og_image', true);\n\n $locale = get_locale();\n\n echo '<meta property=\"og:locale\" content=\"' . esc_attr($locale) . '\" />';\n echo '<meta property=\"og:type\" content=\"article\" />';\n echo '<meta property=\"author\" content=\"' . esc_attr($author_name) . '\" />';\n echo '<meta property=\"og:description\" content=\"' . esc_attr($description) . '\" />';\n echo '<meta property=\"og:url\" content=\"' . esc_url($url) . '\" />';\n echo '<meta property=\"og:site_name\" content=\"' . esc_attr($site_name) . '\" />';\n\n if($image) echo '<meta property=\"og:image\" content=\"' . esc_url($image) . '\" />';\n\n }\n\n}\n</code></pre>\n\n<p>Please check this url for the hook documentation: <a href=\"https://developer.wordpress.org/reference/hooks/wp_head/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/wp_head/</a></p>\n"
}
] |
2015/09/26
|
[
"https://wordpress.stackexchange.com/questions/203815",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/71139/"
] |
I try somehow to get array of pages names. I don't think it's possible in some default method from WP.
```
<?php $args = array(
'authors' => '',
'child_of' => 0,
'date_format' => get_option('date_format'),
'depth' => 0,
'echo' => 0,
'exclude' => '',
'include' => '',
'link_after' => '',
'link_before' => '',
'post_type' => 'page',
'post_status' => 'publish',
'show_date' => '',
'sort_column' => 'menu_order, post_title',
'sort_order' => '',
'title_li' => __('Pages'),
'walker' => new Walker_Page
)
;?>
$arr = wp_list_pages($args);
print_r($arr);
```
But this return LINK-s "< A >" tags ... Maybe in PHP I can in some way "transfrom" this links to string ? :)
|
You cad add it via `functions.php` with a hook, instead of inside the loop (you don't really want to add a loop to header.php):
```
function add_author_meta() {
if (is_single()){
global $post;
$author = get_the_author_meta('user_nicename', $post->post_author);
echo "<meta name=\"author\" content=\"$author\">";
}
}
add_action( 'wp_enqueue_scripts', 'add_author_meta' );
```
|
203,876 |
<p>I want to create a template where the first (latest) post is shown full width respectively without a sidebar. All the following posts should have been displayed normally, like <a href="http://www.kayture.com" rel="nofollow">here</a></p>
<pre><code>1st POST
2nd POST | SIDEBAR
3rd POST | SIDEBAR
4th POST | SIDEBAR
...
</code></pre>
<p>Can you tell me how to do this?</p>
|
[
{
"answer_id": 203890,
"author": "vol4ikman",
"author_id": 31075,
"author_profile": "https://wordpress.stackexchange.com/users/31075",
"pm_score": 0,
"selected": false,
"text": "<p>You have to create some counter, that will count all your posts in your query.</p>\n\n<p>Than, wrap the first post with full width div. For example:\n </p>\n\n\nTitle and content\n\n\n\n\nContent\n\n\n\n\n\n"
},
{
"answer_id": 204007,
"author": "nim",
"author_id": 70070,
"author_profile": "https://wordpress.stackexchange.com/users/70070",
"pm_score": 1,
"selected": false,
"text": "<p>You can also doe like below code snippet:</p>\n\n<pre><code>$flag=0;\n$args = array(\n'orderby' => 'title',\n'order' => 'DESC',); \n$query = new WP_Query( $args );\nwhile ( $query->have_posts() ) {\n{\n the_post();\n if($flag==0)\n {\n // you first post's title, content etc\n $flag=1;\n }\n else\n {\n //rest of your post's title, sidebar, etc\n }\n}\n</code></pre>\n"
}
] |
2015/09/27
|
[
"https://wordpress.stackexchange.com/questions/203876",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81057/"
] |
I want to create a template where the first (latest) post is shown full width respectively without a sidebar. All the following posts should have been displayed normally, like [here](http://www.kayture.com)
```
1st POST
2nd POST | SIDEBAR
3rd POST | SIDEBAR
4th POST | SIDEBAR
...
```
Can you tell me how to do this?
|
You can also doe like below code snippet:
```
$flag=0;
$args = array(
'orderby' => 'title',
'order' => 'DESC',);
$query = new WP_Query( $args );
while ( $query->have_posts() ) {
{
the_post();
if($flag==0)
{
// you first post's title, content etc
$flag=1;
}
else
{
//rest of your post's title, sidebar, etc
}
}
```
|
203,904 |
<p>I know how to remove items from the left nav bar (hook into <code>admin_menu</code> and do <code>global $menu; unset( $menu[ __( "Posts" ) ] );</code> for example). But it still shows a left nav bar (with nothing on it). I want the entire left nav bar gone.</p>
<p>I have tried this and it doesn't work:</p>
<pre><code>//This doesn't work (in any hook, or plugin constructor)
show_admin_bar(false);
//This also doesn't work
add_filter('show_admin_bar', '__return_false');
</code></pre>
<p>What is the hook/function to do this? </p>
|
[
{
"answer_id": 203890,
"author": "vol4ikman",
"author_id": 31075,
"author_profile": "https://wordpress.stackexchange.com/users/31075",
"pm_score": 0,
"selected": false,
"text": "<p>You have to create some counter, that will count all your posts in your query.</p>\n\n<p>Than, wrap the first post with full width div. For example:\n </p>\n\n\nTitle and content\n\n\n\n\nContent\n\n\n\n\n\n"
},
{
"answer_id": 204007,
"author": "nim",
"author_id": 70070,
"author_profile": "https://wordpress.stackexchange.com/users/70070",
"pm_score": 1,
"selected": false,
"text": "<p>You can also doe like below code snippet:</p>\n\n<pre><code>$flag=0;\n$args = array(\n'orderby' => 'title',\n'order' => 'DESC',); \n$query = new WP_Query( $args );\nwhile ( $query->have_posts() ) {\n{\n the_post();\n if($flag==0)\n {\n // you first post's title, content etc\n $flag=1;\n }\n else\n {\n //rest of your post's title, sidebar, etc\n }\n}\n</code></pre>\n"
}
] |
2015/09/28
|
[
"https://wordpress.stackexchange.com/questions/203904",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48989/"
] |
I know how to remove items from the left nav bar (hook into `admin_menu` and do `global $menu; unset( $menu[ __( "Posts" ) ] );` for example). But it still shows a left nav bar (with nothing on it). I want the entire left nav bar gone.
I have tried this and it doesn't work:
```
//This doesn't work (in any hook, or plugin constructor)
show_admin_bar(false);
//This also doesn't work
add_filter('show_admin_bar', '__return_false');
```
What is the hook/function to do this?
|
You can also doe like below code snippet:
```
$flag=0;
$args = array(
'orderby' => 'title',
'order' => 'DESC',);
$query = new WP_Query( $args );
while ( $query->have_posts() ) {
{
the_post();
if($flag==0)
{
// you first post's title, content etc
$flag=1;
}
else
{
//rest of your post's title, sidebar, etc
}
}
```
|
203,917 |
<p>Is there a section on the admin panel of my WordPress installation which just displays what role the current logged in user has?</p>
<p>For example, I know I have administrator permissions because I <strong>know</strong> that but I can't see it confirmed anywhere.</p>
<p>Also, if I set myself up as an Editor, how do I quickly check I am definitely logged in as an Editor? (apart from just "knowing").</p>
<p>It would be really nice just to know that in case you're doing 10 things at once and lose track.</p>
<p>Maybe it would be nice to display that after the "How are you.." in the top right.</p>
<p><strong>EDIT</strong></p>
<p>Before anyone jumps in and mentions the Users panel. Yes, I can see there is the Role column (as I am an admin), but someone who was just a Contributor wouldn't be able to see that, right?</p>
|
[
{
"answer_id": 203919,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 2,
"selected": false,
"text": "<p>As you suggested, here's how you can display the roles next to the username in the admin bar:</p>\n\n<pre><code>function wpse_203917_admin_bar_menu( $wp_admin_bar ) {\n if ( ! $node = $wp_admin_bar->get_node( 'my-account' ) )\n return;\n\n $roles = wp_get_current_user()->roles;\n\n $node->title .= sprintf( ' (%s)', implode( ', ', $roles ) );\n\n $wp_admin_bar->add_node( $node );\n}\n\nadd_action( 'admin_bar_menu', 'wpse_203917_admin_bar_menu' );\n</code></pre>\n"
},
{
"answer_id": 203921,
"author": "bueltge",
"author_id": 170,
"author_profile": "https://wordpress.stackexchange.com/users/170",
"pm_score": 2,
"selected": false,
"text": "<p>You check for the role for the current user and add the value to the admin bar, like the profile item.</p>\n\n<p>To get the role of the current user use the small function below:</p>\n\n<pre><code>/**\n * Returns the translated role of the current user. \n * No role, get false.\n *\n * @return string The translated name of the current role.\n **/\nfunction fb_get_current_user_role_fixed() {\n global $wp_roles;\n\n $current_user = wp_get_current_user();\n $roles = $current_user->roles;\n $role = array_shift( $roles );\n\n return isset( $wp_roles->role_names[ $role ] ) ? translate_user_role( $wp_roles->role_names[ $role ] ) : FALSE;\n}\n</code></pre>\n\n<p>Also a example to add the value from the function to the admin bar, in my example a new entry to the account item in the Admin Bar.</p>\n\n<pre><code>add_action( 'admin_bar_menu', 'fb_change_admin_bar_item' );\n/**\n * Add item to the admin bar, to the my-account item.\n *\n * @param Array $wp_admin_bar\n */\nfunction fb_change_admin_bar_item( $wp_admin_bar ) {\n\n $args = array(\n 'id' => 'user_role',\n 'title' => __( 'Role:' ) . ' ' . fb_get_current_user_role_fixed(),\n 'parent' => 'my-account' \n );\n $wp_admin_bar->add_node( $args );\n}\n</code></pre>\n\n<p>See the result as screenshot, much easier to understand the goal of the example.\n<a href=\"https://i.stack.imgur.com/ETBAw.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ETBAw.png\" alt=\"enter image description here\"></a></p>\n\n<p>As alternative the second example, that add the role name to the user name, on the default title in the admin bar.</p>\n\n<pre><code>add_action( 'admin_bar_menu', 'fb_change_admin_bar_item' );\nfunction fb_change_admin_bar_item( $wp_admin_bar ) {\n\n $node = $wp_admin_bar->get_node( 'my-account' );\n\n if ( ! $node ) {\n return $wp_admin_bar;\n }\n\n $node->title .= ' ' . fb_get_current_user_role_fixed();\n\n $wp_admin_bar->add_node( $node );\n}\n</code></pre>\n\n<p>Also here a screenshot of the result.</p>\n\n<p><a href=\"https://i.stack.imgur.com/1CWrS.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1CWrS.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 320220,
"author": "mondi",
"author_id": 124115,
"author_profile": "https://wordpress.stackexchange.com/users/124115",
"pm_score": 1,
"selected": false,
"text": "<p>I simply use:</p>\n\n<pre><code>global $current_user; echo array_shift($current_user->roles);\n</code></pre>\n\n<p>To display the current user role.</p>\n"
}
] |
2015/09/28
|
[
"https://wordpress.stackexchange.com/questions/203917",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81083/"
] |
Is there a section on the admin panel of my WordPress installation which just displays what role the current logged in user has?
For example, I know I have administrator permissions because I **know** that but I can't see it confirmed anywhere.
Also, if I set myself up as an Editor, how do I quickly check I am definitely logged in as an Editor? (apart from just "knowing").
It would be really nice just to know that in case you're doing 10 things at once and lose track.
Maybe it would be nice to display that after the "How are you.." in the top right.
**EDIT**
Before anyone jumps in and mentions the Users panel. Yes, I can see there is the Role column (as I am an admin), but someone who was just a Contributor wouldn't be able to see that, right?
|
As you suggested, here's how you can display the roles next to the username in the admin bar:
```
function wpse_203917_admin_bar_menu( $wp_admin_bar ) {
if ( ! $node = $wp_admin_bar->get_node( 'my-account' ) )
return;
$roles = wp_get_current_user()->roles;
$node->title .= sprintf( ' (%s)', implode( ', ', $roles ) );
$wp_admin_bar->add_node( $node );
}
add_action( 'admin_bar_menu', 'wpse_203917_admin_bar_menu' );
```
|
203,924 |
<p>I'm working on my first OOP (MVC) based plugin.</p>
<p>Everything works perfect, enqueue front/back-end styles, admin menu pages, shortcodes creation, etc...</p>
<p>I load my main plugin class using the <code>init</code> hook.</p>
<p>From the controller I instantiate the class <code>Custom_VC_Elements</code> (with constructor active).</p>
<pre><code>class Custom_VC_Elements {
public function __construct() {
// Armon Product link shortcode
add_shortcode( 'armon_product_link', array( $this, 'armon_product_link_shortcode' ) );
// Armon Product link VC element
add_action( 'vc_before_init', array( $this, 'armon_product_link_vc' ) );
}
// Add armon_product_link element to VC
public function armon_product_link_vc() {
vc_map(
array(
// All vc_map args here ...
)
);
}
} // Class
</code></pre>
<p>The <code>add_shortcode</code> is working without any problems... Somehow the <code>vc_before_init</code> hook is not.</p>
<p>I'm asking the question here and not on the Visual Composer forums, because <code>vc_before_init</code> hook works perfect from the main plugin file, so outside all plugin classes.</p>
<p>I tried the following:</p>
<ul>
<li>Use class name <code>$Custom_VC_Elements</code> instead off <code>$this</code>.</li>
<li>Create a class <code>Custom_VC_Elements_init</code> and create a instance of that class like so: <pre>add_action( 'vc_before_init', array( WPWDtools::load_class( "Custom_VC_Elements_init", "class-custom-vc-elements-init.php", 'add-ons' ), 'armon_product_link_vc' ) );</pre></li>
<li>First hook into <code>admin_init</code> and then into <code>vc_before_init</code>.</li>
<li>First hook into <code>plugins_loaded</code> and then into <code>vc_before_init</code>.</li>
</ul>
<p>I don't get any php error's, <code>wp_debug = true</code> ... So debugging this is not easy..</p>
<p>Like I said, this is my first OOP based plugin, so please try to explain your answer.</p>
<p>Many thanks!</p>
<p>Regards, Bjorn</p>
<p>[EDIT]</p>
<p>It now works when I (from the main plugin file) <code>require_once</code> a file with the <code>vc_before_init</code> hook. So, before my plugin <code>'init'</code> hook which instantiates my main plugin (abstract) class. Snippet main plugin file:</p>
<pre><code>// Testing
require_once WPWDTOOLS_ABSPATH . 'add-ons/custom-vc-elements-init.php';
// Load WPWDtools class, which holds common functions and variables.
require_once WPWDTOOLS_ABSPATH . 'classes/class-wpwdtools.php';
// Start plugin.
add_action( 'init', array( 'WPWDtools', 'run' ) );
</code></pre>
<p>I still don't understand this behaviour..? When I check inside my main plugin file if the <code>vc_before_init</code> hook is already fired it returns <code>true</code>...
But my current 'fix' (setting the hook outside any class) still works..? In short, it doesn't matter where or how I wrap <code>vc_before_init</code> in a class, it allways fails..</p>
|
[
{
"answer_id": 203940,
"author": "phatskat",
"author_id": 20143,
"author_profile": "https://wordpress.stackexchange.com/users/20143",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>vc_before_init hook works perfect from the main plugin file, so outside all plugin classes.</p>\n</blockquote>\n\n<p>You can try hooking it there then maybe. If you can instantiate the class in the main file as needed, and then hook into it, you should be fine:</p>\n\n<pre><code>$my_elements = new Custom_VC_Elements();\nadd_action( 'vc_before_init', array( $my_elements, 'armon_product_link_vc' ) );\n</code></pre>\n\n<p>Not sure if this works well with your classes, however. The other option would be to use a hook that happens later, as it sounds like <code>vc_before_init</code> may already have happened. To test this, you could do:</p>\n\n<pre><code><?php\n\n// Top of plugin file - NB that you should never use $GLOBALS\n// in production, but this is purely for debugging\n$GLOBALS['HAS_VC_BEFORE_INIT_RUN'] = false;\n\nadd_action( 'vc_before_init', 'test_my_vc_timing' );\n\nfunction test_my_vc_timing() {\n $GLOBALS['HAS_VC_BEFORE_INIT_RUN'] = true;\n}\n\n// In your class\nclass Custom_VC_Elements {\n public function __construct() {\n // Snip...\n // DEBUGGING!\n var_dump($GLOBALS['HAS_VC_BEFORE_INIT_RUN']);\n die;\n } // Snip...\n} // Class\n</code></pre>\n\n<p>If you can hook into <code>vc_before_init</code> in your classes constructor, then the <code>var_dump</code> should return <code>false</code>. If it's <code>true</code>, then the action has already run by the time your class is instantiated.</p>\n"
},
{
"answer_id": 204089,
"author": "Bjorn",
"author_id": 80876,
"author_profile": "https://wordpress.stackexchange.com/users/80876",
"pm_score": 2,
"selected": true,
"text": "<p>I found the solution...\nFirst I thought the problem had something to do with wrapping the hook inside a class.. But after some more testing (sometimes you need to take a step back), it appears the hook <code>vc_before_init</code> has already fired on the <code>init</code> hook with the (default) priority of 10...</p>\n\n<p>My current theme (Salient) has made a custom Visual Composer, that is provided in the theme package.. After checking the theme hooks with 'Prioritize Hooks' plugin. I found that the theme has the following:\n<code>add_action( 'init', 'add_nectar_to_vc', 5 );</code></p>\n\n<p>I now use <code>add_action( 'init', array( 'WPWDtools', 'run' ), 4 );</code> to start-up my plugin, and now everything works as expected.</p>\n\n<p>Without diving into my theme any further, I suspect that it forces the <code>vc_before_init</code> hook to fire early (on 'init' with priority:5).</p>\n\n<p>I want to thank @phatskat & @gmazzap for helping me. You guys where wright, telling me the hook probably already fired.</p>\n"
}
] |
2015/09/28
|
[
"https://wordpress.stackexchange.com/questions/203924",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80876/"
] |
I'm working on my first OOP (MVC) based plugin.
Everything works perfect, enqueue front/back-end styles, admin menu pages, shortcodes creation, etc...
I load my main plugin class using the `init` hook.
From the controller I instantiate the class `Custom_VC_Elements` (with constructor active).
```
class Custom_VC_Elements {
public function __construct() {
// Armon Product link shortcode
add_shortcode( 'armon_product_link', array( $this, 'armon_product_link_shortcode' ) );
// Armon Product link VC element
add_action( 'vc_before_init', array( $this, 'armon_product_link_vc' ) );
}
// Add armon_product_link element to VC
public function armon_product_link_vc() {
vc_map(
array(
// All vc_map args here ...
)
);
}
} // Class
```
The `add_shortcode` is working without any problems... Somehow the `vc_before_init` hook is not.
I'm asking the question here and not on the Visual Composer forums, because `vc_before_init` hook works perfect from the main plugin file, so outside all plugin classes.
I tried the following:
* Use class name `$Custom_VC_Elements` instead off `$this`.
* Create a class `Custom_VC_Elements_init` and create a instance of that class like so:
```
add_action( 'vc_before_init', array( WPWDtools::load_class( "Custom_VC_Elements_init", "class-custom-vc-elements-init.php", 'add-ons' ), 'armon_product_link_vc' ) );
```
* First hook into `admin_init` and then into `vc_before_init`.
* First hook into `plugins_loaded` and then into `vc_before_init`.
I don't get any php error's, `wp_debug = true` ... So debugging this is not easy..
Like I said, this is my first OOP based plugin, so please try to explain your answer.
Many thanks!
Regards, Bjorn
[EDIT]
It now works when I (from the main plugin file) `require_once` a file with the `vc_before_init` hook. So, before my plugin `'init'` hook which instantiates my main plugin (abstract) class. Snippet main plugin file:
```
// Testing
require_once WPWDTOOLS_ABSPATH . 'add-ons/custom-vc-elements-init.php';
// Load WPWDtools class, which holds common functions and variables.
require_once WPWDTOOLS_ABSPATH . 'classes/class-wpwdtools.php';
// Start plugin.
add_action( 'init', array( 'WPWDtools', 'run' ) );
```
I still don't understand this behaviour..? When I check inside my main plugin file if the `vc_before_init` hook is already fired it returns `true`...
But my current 'fix' (setting the hook outside any class) still works..? In short, it doesn't matter where or how I wrap `vc_before_init` in a class, it allways fails..
|
I found the solution...
First I thought the problem had something to do with wrapping the hook inside a class.. But after some more testing (sometimes you need to take a step back), it appears the hook `vc_before_init` has already fired on the `init` hook with the (default) priority of 10...
My current theme (Salient) has made a custom Visual Composer, that is provided in the theme package.. After checking the theme hooks with 'Prioritize Hooks' plugin. I found that the theme has the following:
`add_action( 'init', 'add_nectar_to_vc', 5 );`
I now use `add_action( 'init', array( 'WPWDtools', 'run' ), 4 );` to start-up my plugin, and now everything works as expected.
Without diving into my theme any further, I suspect that it forces the `vc_before_init` hook to fire early (on 'init' with priority:5).
I want to thank @phatskat & @gmazzap for helping me. You guys where wright, telling me the hook probably already fired.
|
203,937 |
<p>I am trying to add a Phone Number mandatory field to the Shipping Details page of the Woocommerce checkout but it should only be mandatory if an alternative shipping address is selected.</p>
<p>Woocommerce see this as a bespoke modification which is outside of their support remit and have suggested I post the question here.</p>
<p>I have made some progress after following the article <a href="http://docs.woothemes.com/document/tutorial-customising-checkout-fields-using-actions-and-filters/" rel="nofollow">http://docs.woothemes.com/document/tutorial-customising-checkout-fields-using-actions-and-filters/</a> which has got me almost there, but I am having some problems.</p>
<p>I only want the field to be mandatory if the customer is shipping to a different address, whereas it says that it needs to be completed even if alternative shipping details are not selected.</p>
<p>I've had to back out the changes as this is a live site, but I had updated functions.php with the following:</p>
<pre><code>//Add Tel Number to Shipping Address
// Hook in
add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );
// Our hooked in function - $fields is passed via the filter!
function custom_override_checkout_fields( $fields ) {
$fields['shipping']['shipping_phone'] = array(
'label' => __('Phone', 'woocommerce'),
'placeholder' => _x('Phone', 'placeholder', 'woocommerce'),
'required' => false,
'class' => array('form-row-wide'),
'clear' => true
);
return $fields;
}
/**
* Process the checkout
*/
add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');
function my_custom_checkout_field_process() {
// Check if set, if its not set add an error.
if ( ! $_POST['shipping_phone'] )
wc_add_notice( __( 'Please enter a phone number for the recipient.' ), 'error' );
}
</code></pre>
<p>This works, in that the field is displayed but I have two problems.</p>
<p>1) How can I get it to only require mandatory completion if ship to a different address is selected?</p>
<p>2) Even though the field is mandatory, how can I get a red asterisk to appear next to the Phone label like it does for the other fields?</p>
<p>If someone could help, I'd really appreciate it.</p>
<p>Thanks</p>
<p>Rob</p>
|
[
{
"answer_id": 204008,
"author": "Rob Wassell",
"author_id": 81096,
"author_profile": "https://wordpress.stackexchange.com/users/81096",
"pm_score": 3,
"selected": true,
"text": "<p>I went back through this myself and I have answered my own question.</p>\n\n<p>By following the Woocommerce documentation, I actually confused myself and the second mandatory check isn't applicable as we can use this primary function to set required from false to true. This automatically adds the red asterisk and makes the field mandatory without having to perform the additional check.</p>\n\n<p>Quite simply:</p>\n\n<pre><code>//Add Tel Number to Shipping Address \n// Hook in \nadd_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );\n\n// Our hooked in function - $fields is passed via the filter! \nfunction custom_override_checkout_fields( $fields ) { \n$fields['shipping']['shipping_phone'] = array( \n'label' => __('Phone', 'woocommerce'), \n'placeholder' => _x('Phone', 'placeholder', 'woocommerce'), \n'required' => true, \n'class' => array('form-row-wide'), \n'clear' => true \n);\n\nreturn $fields; \n}\n\n/** \n* Process the checkout \n*/ \nadd_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');\n</code></pre>\n\n<p>I hope this helps someone else.</p>\n\n<p>Regards,</p>\n\n<p>Rob</p>\n"
},
{
"answer_id": 295446,
"author": "divin kattipparambil",
"author_id": 137712,
"author_profile": "https://wordpress.stackexchange.com/users/137712",
"pm_score": 0,
"selected": false,
"text": "<pre><code>add_filter( 'woocommerce_checkout_fields', 'billing_fields_altration', 9999 );\n\nfunction billing_fields_altration( $woo_checkout_fields_array ) {\n\n\n // unset( $woo_checkout_fields_array['billing']['billing_first_name'] );\n unset( $woo_checkout_fields_array['billing']['billing_last_name'] );\n // unset( $woo_checkout_fields_array['billing']['billing_phone'] );\n // unset( $woo_checkout_fields_array['billing']['billing_email'] );\n // unset( $woo_checkout_fields_array['order']['order_comments'] );\n\n // and to remove the fields below\n unset( $woo_checkout_fields_array['billing']['billing_company'] );\n //unset( $woo_checkout_fields_array['billing']['billing_country'] );\n //unset( $woo_checkout_fields_array['billing']['billing_address_1'] );\n unset( $woo_checkout_fields_array['billing']['billing_address_2'] );//REMOVE FIELDS\n //unset( $woo_checkout_fields_array['billing']['billing_city'] );\n //unset( $woo_checkout_fields_array['billing']['billing_state'] );\n //unset( $woo_checkout_fields_array['billing']['billing_postcode'] );\n $woo_checkout_fields_array['billing']['billing_phone']['required'] = true;//ENABLE VALIDATION\n unset( $woo_checkout_fields_array['shipping']['shipping_last_name'] );\n //unset( $address_fields_array['postcode']['validate']);//DISABLE VALIDATION\n return $woo_checkout_fields_array;\n}\n</code></pre>\n"
}
] |
2015/09/28
|
[
"https://wordpress.stackexchange.com/questions/203937",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81096/"
] |
I am trying to add a Phone Number mandatory field to the Shipping Details page of the Woocommerce checkout but it should only be mandatory if an alternative shipping address is selected.
Woocommerce see this as a bespoke modification which is outside of their support remit and have suggested I post the question here.
I have made some progress after following the article <http://docs.woothemes.com/document/tutorial-customising-checkout-fields-using-actions-and-filters/> which has got me almost there, but I am having some problems.
I only want the field to be mandatory if the customer is shipping to a different address, whereas it says that it needs to be completed even if alternative shipping details are not selected.
I've had to back out the changes as this is a live site, but I had updated functions.php with the following:
```
//Add Tel Number to Shipping Address
// Hook in
add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );
// Our hooked in function - $fields is passed via the filter!
function custom_override_checkout_fields( $fields ) {
$fields['shipping']['shipping_phone'] = array(
'label' => __('Phone', 'woocommerce'),
'placeholder' => _x('Phone', 'placeholder', 'woocommerce'),
'required' => false,
'class' => array('form-row-wide'),
'clear' => true
);
return $fields;
}
/**
* Process the checkout
*/
add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');
function my_custom_checkout_field_process() {
// Check if set, if its not set add an error.
if ( ! $_POST['shipping_phone'] )
wc_add_notice( __( 'Please enter a phone number for the recipient.' ), 'error' );
}
```
This works, in that the field is displayed but I have two problems.
1) How can I get it to only require mandatory completion if ship to a different address is selected?
2) Even though the field is mandatory, how can I get a red asterisk to appear next to the Phone label like it does for the other fields?
If someone could help, I'd really appreciate it.
Thanks
Rob
|
I went back through this myself and I have answered my own question.
By following the Woocommerce documentation, I actually confused myself and the second mandatory check isn't applicable as we can use this primary function to set required from false to true. This automatically adds the red asterisk and makes the field mandatory without having to perform the additional check.
Quite simply:
```
//Add Tel Number to Shipping Address
// Hook in
add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );
// Our hooked in function - $fields is passed via the filter!
function custom_override_checkout_fields( $fields ) {
$fields['shipping']['shipping_phone'] = array(
'label' => __('Phone', 'woocommerce'),
'placeholder' => _x('Phone', 'placeholder', 'woocommerce'),
'required' => true,
'class' => array('form-row-wide'),
'clear' => true
);
return $fields;
}
/**
* Process the checkout
*/
add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');
```
I hope this helps someone else.
Regards,
Rob
|
203,951 |
<p>It seems that all web resources based on the subject of removing a custom post type slug ie</p>
<pre><code>yourdomain.com/CPT-SLUG/post-name
</code></pre>
<p>are now very outdated solutions often referencing pre WP version 3.5 installs. A common one is to:</p>
<pre><code>'rewrite' => array( 'slug' => false, 'with_front' => false ),
</code></pre>
<p>within your <code>register_post_type</code> function. This no longer works and is misleading. So I ask the community in Q4 2020...</p>
<p><strong>What are the modern and efficient ways to remove the Post Type Slug from a Custom Post Type post's URL from within the rewrite argument or anywhere else?</strong></p>
<p>UPDATE:
There seems to be several ways to force this to work with regex. Specifically the answer from Jan Beck should you be consistently willing to monitor content creation to ensure no conflicting page/post names are created.... However I'm convinced that this is a major weakness in WP core where it should be handled for us. Both as an option/hook when creating a CPT or an advanced set of options for permalinks. Please support the track ticket.</p>
<p>Footnote: Please support this trac ticket by watching/promoting it: <a href="https://core.trac.wordpress.org/ticket/34136#ticket" rel="noreferrer">https://core.trac.wordpress.org/ticket/34136#ticket</a></p>
|
[
{
"answer_id": 204166,
"author": "Jan Beck",
"author_id": 18760,
"author_profile": "https://wordpress.stackexchange.com/users/18760",
"pm_score": 4,
"selected": false,
"text": "<p>I tried to figure this out not long ago and the short answer from what I know is <strong>no</strong>. Not from within the rewrite argument at least.</p>\n\n<p>The long explanation becomes apparent if you look at the actual code of <code>register_post_type</code> in <a href=\"https://core.trac.wordpress.org/browser/tags/4.3/src/wp-includes/post.php#L1454\">wp-includes/post.php line 1454</a>:</p>\n\n<pre><code>add_permastruct( $post_type, \"{$args->rewrite['slug']}/%$post_type%\", $permastruct_args );\n</code></pre>\n\n<p>You can see it prefixes <code>$args->rewrite['slug']</code> to the <code>%$post_type%</code> rewrite tag. One could think \"let's just set the slug to <code>null</code> then\" until you look a few lines up:</p>\n\n<pre><code>if ( empty( $args->rewrite['slug'] ) )\n $args->rewrite['slug'] = $post_type;\n</code></pre>\n\n<p>You can see that the function <em>always</em> expects a slug value that is not empty and otherwise uses the post type.</p>\n"
},
{
"answer_id": 204210,
"author": "Nate Allen",
"author_id": 32698,
"author_profile": "https://wordpress.stackexchange.com/users/32698",
"pm_score": 8,
"selected": true,
"text": "<p>The following code will work, but you just have to keep in mind that conflicts can happen easily if the slug for your custom post type is the same as a page or post's slug...</p>\n\n<p>First, we will remove the slug from the permalink:</p>\n\n<pre><code>function na_remove_slug( $post_link, $post, $leavename ) {\n\n if ( 'events' != $post->post_type || 'publish' != $post->post_status ) {\n return $post_link;\n }\n\n $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );\n\n return $post_link;\n}\nadd_filter( 'post_type_link', 'na_remove_slug', 10, 3 );\n</code></pre>\n\n<p>Just removing the slug isn't enough. Right now, you'll get a 404 page because WordPress only expects posts and pages to behave this way. You'll also need to add the following:</p>\n\n<pre><code>function na_parse_request( $query ) {\n\n if ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {\n return;\n }\n\n if ( ! empty( $query->query['name'] ) ) {\n $query->set( 'post_type', array( 'post', 'events', 'page' ) );\n }\n}\nadd_action( 'pre_get_posts', 'na_parse_request' );\n</code></pre>\n\n<p>Just change \"events\" to your custom post type and you're good to go. You may need to refresh your permalinks.</p>\n"
},
{
"answer_id": 204389,
"author": "Jan Beck",
"author_id": 18760,
"author_profile": "https://wordpress.stackexchange.com/users/18760",
"pm_score": 3,
"selected": false,
"text": "<p>In response to <a href=\"https://wordpress.stackexchange.com/a/204166/18760\">my previous answer</a>:\nyou could of course set the <code>rewrite</code> parameter to <code>false</code> when registering a new post type and handle the rewrite rules yourself like so</p>\n\n<pre><code><?php\nfunction wpsx203951_custom_init() {\n\n $post_type = 'event';\n $args = (object) array(\n 'public' => true,\n 'label' => 'Events',\n 'rewrite' => false, // always set this to false\n 'has_archive' => true\n );\n register_post_type( $post_type, $args );\n\n // these are your actual rewrite arguments\n $args->rewrite = array(\n 'slug' => 'calendar'\n );\n\n // everything what follows is from the register_post_type function\n if ( is_admin() || '' != get_option( 'permalink_structure' ) ) {\n\n if ( ! is_array( $args->rewrite ) )\n $args->rewrite = array();\n if ( empty( $args->rewrite['slug'] ) )\n $args->rewrite['slug'] = $post_type;\n if ( ! isset( $args->rewrite['with_front'] ) )\n $args->rewrite['with_front'] = true;\n if ( ! isset( $args->rewrite['pages'] ) )\n $args->rewrite['pages'] = true;\n if ( ! isset( $args->rewrite['feeds'] ) || ! $args->has_archive )\n $args->rewrite['feeds'] = (bool) $args->has_archive;\n if ( ! isset( $args->rewrite['ep_mask'] ) ) {\n if ( isset( $args->permalink_epmask ) )\n $args->rewrite['ep_mask'] = $args->permalink_epmask;\n else\n $args->rewrite['ep_mask'] = EP_PERMALINK;\n }\n\n if ( $args->hierarchical )\n add_rewrite_tag( \"%$post_type%\", '(.+?)', $args->query_var ? \"{$args->query_var}=\" : \"post_type=$post_type&pagename=\" );\n else\n add_rewrite_tag( \"%$post_type%\", '([^/]+)', $args->query_var ? \"{$args->query_var}=\" : \"post_type=$post_type&name=\" );\n\n if ( $args->has_archive ) {\n $archive_slug = $args->has_archive === true ? $args->rewrite['slug'] : $args->has_archive;\n if ( $args->rewrite['with_front'] )\n $archive_slug = substr( $wp_rewrite->front, 1 ) . $archive_slug;\n else\n $archive_slug = $wp_rewrite->root . $archive_slug;\n\n add_rewrite_rule( \"{$archive_slug}/?$\", \"index.php?post_type=$post_type\", 'top' );\n if ( $args->rewrite['feeds'] && $wp_rewrite->feeds ) {\n $feeds = '(' . trim( implode( '|', $wp_rewrite->feeds ) ) . ')';\n add_rewrite_rule( \"{$archive_slug}/feed/$feeds/?$\", \"index.php?post_type=$post_type\" . '&feed=$matches[1]', 'top' );\n add_rewrite_rule( \"{$archive_slug}/$feeds/?$\", \"index.php?post_type=$post_type\" . '&feed=$matches[1]', 'top' );\n }\n if ( $args->rewrite['pages'] )\n add_rewrite_rule( \"{$archive_slug}/{$wp_rewrite->pagination_base}/([0-9]{1,})/?$\", \"index.php?post_type=$post_type\" . '&paged=$matches[1]', 'top' );\n }\n\n $permastruct_args = $args->rewrite;\n $permastruct_args['feed'] = $permastruct_args['feeds'];\n add_permastruct( $post_type, \"%$post_type%\", $permastruct_args );\n }\n}\nadd_action( 'init', 'wpsx203951_custom_init' );\n</code></pre>\n\n<p>You can see the <code>add_permastruct</code> call now doesn't include the slug anymore. \nI tested two scenarios:</p>\n\n<ol>\n<li>When I created a page with the slug \"calendar\" that page is overwritten by the post type archive which also uses the \"calendar\" slug. </li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/FTeqz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/FTeqz.png\" alt=\"enter image description here\"></a></p>\n\n<ol start=\"2\">\n<li>When I created a page with the slug \"my-event\" and an event (CPT) with the slug \"my-event\", the custom post type is displayed. </li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/I61Ft.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/I61Ft.png\" alt=\"enter image description here\"></a></p>\n\n<ol start=\"3\">\n<li>Any other pages do not work either. If you look at the picture above it becomes clear why: the custom post type rule will always match against a page slug. Because WordPress has no way of identifying if it's a page or a custom post type that does not exist, it will return 404. That's why you need a slug to identify either the page or CPT.\nA possible solution would be to intercept the error and look for a page that might exist <a href=\"https://wordpress.stackexchange.com/a/204210/18760\">similar to this answer</a>.</li>\n</ol>\n"
},
{
"answer_id": 257969,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": -1,
"selected": false,
"text": "<p>You dont need so much hard-code. Just use lightweight plugin:</p>\n\n<ul>\n<li><a href=\"https://wordpress.org/plugins/remove-base-slug-from-custom-post-type-url/\" rel=\"nofollow noreferrer\"><strong>Remove Base Slug From Custom Post</strong></a></li>\n</ul>\n\n<p>It has customizable options.</p>\n"
},
{
"answer_id": 258432,
"author": "Max Kondrachuk",
"author_id": 84937,
"author_profile": "https://wordpress.stackexchange.com/users/84937",
"pm_score": 2,
"selected": false,
"text": "<p>and we can make some changes to above-mentioned function:</p>\n\n<pre><code>function na_parse_request( $query ) {\n\nif ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {\n return;\n}\n\nif ( ! empty( $query->query['name'] ) ) {\n $query->set( 'post_type', array( 'post', 'events', 'page' ) );\n}\n}\n</code></pre>\n\n<p>to: </p>\n\n<pre><code>function na_parse_request( $query ) {\n\nif ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {\n return;\n}\n\nif ( ! empty( $query->query['name'] ) ) {\n\n global $wpdb;\n $pt = $wpdb->get_var(\n \"SELECT post_type FROM `{$wpdb->posts}` \" .\n \"WHERE post_name = '{$query->query['name']}'\"\n );\n $query->set( 'post_type', $pt );\n}\n}\n</code></pre>\n\n<p>in order to set right post_type value.</p>\n"
},
{
"answer_id": 263428,
"author": "Mayank Dudakiya",
"author_id": 117519,
"author_profile": "https://wordpress.stackexchange.com/users/117519",
"pm_score": 5,
"selected": false,
"text": "<p>Write following code into the taxonomy registration.</p>\n\n<pre><code>'rewrite' => [\n 'slug' => '/',\n 'with_front' => false\n]\n</code></pre>\n\n<p>Most important thing that you have to do after code changing</p>\n\n<p>After you’ve altered your custom post type taxonomy document, try to go to <strong>Settings > Permalinks</strong> and <strong>re-save your settings</strong>, else you will get 404 page not found.</p>\n"
},
{
"answer_id": 265707,
"author": "Malki Mohamed",
"author_id": 118944,
"author_profile": "https://wordpress.stackexchange.com/users/118944",
"pm_score": 1,
"selected": false,
"text": "<p>This worked for me:\n <code>'rewrite' => array('slug' => '/')</code></p>\n"
},
{
"answer_id": 268406,
"author": "Moe Loubani",
"author_id": 120639,
"author_profile": "https://wordpress.stackexchange.com/users/120639",
"pm_score": 2,
"selected": false,
"text": "<p>For anyone reading this that had trouble with child posts like I did I found the best way was to add your own rewrite rules.</p>\n<p>The main issue I was having was that WordPress treats the redirect from pages that are 2 levels (child posts) deep a little differently than it treats 3 levels deep (child of child posts).</p>\n<p>That means when I have /post-type/post-name/post-child/ I can use /post-name/post-child and it will redirect me to the one with post-type in front but if I have post-type/post-name/post-child/post-grandchild then I can't use post-name/post-child/post-grandchild.</p>\n<p>Taking a look into the rewrite rules it looks like it matches for things other than pagename at the first and second levels (I think the second level matches attachment) and then does something there to redirect you to the proper post. At three levels deep it doesn't work.</p>\n<p>First thing you need to do is to remove the post type link from children as well. This logic should happen here if you look at Nate Allen's answer above:</p>\n<pre><code>$post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );\n</code></pre>\n<p>Myself I used a mix of different conditionals to check if the post had children and whatnot in order to get to the right permalink. This part isn't too tricky and you'll find examples of people doing it elsewhere.</p>\n<p>The next step though is where things change from the given answer. Instead of adding things to the main query (which worked for custom posts and their children but not the further children) I added a rewrite that went to the bottom of the WordPress rules so that if pagename didn't check out and it was about to hit a 404 it would do one last check to see if a page within the custom post type had the same name otherwise it would throw out the 404.</p>\n<p>Here is the rewrite rule I used assuming 'event' is the name of your CPT</p>\n<pre><code>function rewrite_rules_for_removing_post_type_slug()\n{\n add_rewrite_rule(\n '(.?.+?)(?:/([0-9]+))?/?$',\n 'index.php?event=$matches[1]/$matches[2]&post_type=event',\n 'bottom'\n );\n}\n\nadd_action('init', 'rewrite_rules_for_removing_post_type_slug', 1, 1);\n</code></pre>\n<p>Hope this helps someone else, I couldn't find anything else that had to do with child of child posts and removing the slug from those.</p>\n"
},
{
"answer_id": 282040,
"author": "Matt Keys",
"author_id": 32799,
"author_profile": "https://wordpress.stackexchange.com/users/32799",
"pm_score": 5,
"selected": false,
"text": "<p>Looking through the answers here I think there is room for a better solution that combines some things I learned above and adds auto-detection and prevention of duplicate post slugs.</p>\n<p><em>NOTE: Make sure you change 'custom_post_type' for your own CPT name throughout my example below. There are many occurrences, and a 'find/replace' is an easy way to catch them all. All of this code can go in your functions.php or in a plugin.</em></p>\n<p><strong>Step 1:</strong> Disable rewrites on your custom post type by setting rewrites to 'false' when you register the post:</p>\n<pre><code>register_post_type( 'custom_post_type',\n array(\n 'rewrite' => false\n )\n);\n</code></pre>\n<p><strong>Step 2:</strong> Manually add our custom rewrites to the <em>bottom</em> of the WordPress rewrites for our custom_post_type</p>\n<pre><code>function custom_post_type_rewrites() {\n add_rewrite_rule( '[^/]+/attachment/([^/]+)/?$', 'index.php?attachment=$matches[1]', 'bottom');\n add_rewrite_rule( '[^/]+/attachment/([^/]+)/trackback/?$', 'index.php?attachment=$matches[1]&tb=1', 'bottom');\n add_rewrite_rule( '[^/]+/attachment/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$', 'index.php?attachment=$matches[1]&feed=$matches[2]', 'bottom');\n add_rewrite_rule( '[^/]+/attachment/([^/]+)/(feed|rdf|rss|rss2|atom)/?$', 'index.php?attachment=$matches[1]&feed=$matches[2]', 'bottom');\n add_rewrite_rule( '[^/]+/attachment/([^/]+)/comment-page-([0-9]{1,})/?$', 'index.php?attachment=$matches[1]&cpage=$matches[2]', 'bottom');\n add_rewrite_rule( '[^/]+/attachment/([^/]+)/embed/?$', 'index.php?attachment=$matches[1]&embed=true', 'bottom');\n add_rewrite_rule( '([^/]+)/embed/?$', 'index.php?custom_post_type=$matches[1]&embed=true', 'bottom');\n add_rewrite_rule( '([^/]+)/trackback/?$', 'index.php?custom_post_type=$matches[1]&tb=1', 'bottom');\n add_rewrite_rule( '([^/]+)/page/?([0-9]{1,})/?$', 'index.php?custom_post_type=$matches[1]&paged=$matches[2]', 'bottom');\n add_rewrite_rule( '([^/]+)/comment-page-([0-9]{1,})/?$', 'index.php?custom_post_type=$matches[1]&cpage=$matches[2]', 'bottom');\n add_rewrite_rule( '([^/]+)(?:/([0-9]+))?/?$', 'index.php?custom_post_type=$matches[1]', 'bottom');\n add_rewrite_rule( '[^/]+/([^/]+)/?$', 'index.php?attachment=$matches[1]', 'bottom');\n add_rewrite_rule( '[^/]+/([^/]+)/trackback/?$', 'index.php?attachment=$matches[1]&tb=1', 'bottom');\n add_rewrite_rule( '[^/]+/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$', 'index.php?attachment=$matches[1]&feed=$matches[2]', 'bottom');\n add_rewrite_rule( '[^/]+/([^/]+)/(feed|rdf|rss|rss2|atom)/?$', 'index.php?attachment=$matches[1]&feed=$matches[2]', 'bottom');\n add_rewrite_rule( '[^/]+/([^/]+)/comment-page-([0-9]{1,})/?$', 'index.php?attachment=$matches[1]&cpage=$matches[2]', 'bottom');\n add_rewrite_rule( '[^/]+/([^/]+)/embed/?$', 'index.php?attachment=$matches[1]&embed=true', 'bottom');\n}\nadd_action( 'init', 'custom_post_type_rewrites' );\n</code></pre>\n<p><em>NOTE: Depending on your needs, you may want to modify the above rewrites (disable trackbacks? feeds?, etc). These represent the 'default' types of rewrites that would have been generated if you didn't disable rewrites in step 1</em></p>\n<p><strong>Step 3:</strong> Make permalinks to your custom post type 'pretty' again</p>\n<pre><code>function custom_post_type_permalinks( $post_link, $post, $leavename ) {\n if ( isset( $post->post_type ) && 'custom_post_type' == $post->post_type ) {\n $post_link = home_url( $post->post_name );\n }\n\n return $post_link;\n}\nadd_filter( 'post_type_link', 'custom_post_type_permalinks', 10, 3 );\n</code></pre>\n<p><em>NOTE: You can stop here if you are not worried about your users creating a conflicting (duplicate) post in another post type that will create a situation where only one of them can load when the page is requested.</em></p>\n<p><strong>Step 4:</strong> Prevent duplicate post slugs</p>\n<pre><code>function prevent_slug_duplicates( $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug ) {\n $check_post_types = array(\n 'post',\n 'page',\n 'custom_post_type'\n );\n \n if ( ! in_array( $post_type, $check_post_types ) ) {\n return $slug;\n }\n\n if ( 'custom_post_type' == $post_type ) {\n // Saving a custom_post_type post, check for duplicates in POST or PAGE post types\n $post_match = get_page_by_path( $slug, 'OBJECT', 'post' );\n $page_match = get_page_by_path( $slug, 'OBJECT', 'page' );\n\n if ( $post_match || $page_match ) {\n $slug .= '-duplicate';\n }\n } else {\n // Saving a POST or PAGE, check for duplicates in custom_post_type post type\n $custom_post_type_match = get_page_by_path( $slug, 'OBJECT', 'custom_post_type' );\n\n if ( $custom_post_type_match ) {\n $slug .= '-duplicate';\n }\n }\n\n return $slug;\n}\nadd_filter( 'wp_unique_post_slug', 'prevent_slug_duplicates', 10, 6 );\n</code></pre>\n<p><em>NOTE: This will append the string '-duplicate' to the end of any duplicate slugs. This code cannot prevent duplicate slugs if they already exist prior to implementing this solution. Be sure to check for duplicates first.</em></p>\n<p>I would love to hear back from anyone else who gives this a go to see if it worked well for them as well.</p>\n"
},
{
"answer_id": 340928,
"author": "Friedrich Siever",
"author_id": 107825,
"author_profile": "https://wordpress.stackexchange.com/users/107825",
"pm_score": 1,
"selected": false,
"text": "<p>Had the same problems here and there seems to be no movement on wordpress site. In my particular situation where for single blogposts the structure /blog/%postname%/ was needed this solution </p>\n\n<p><a href=\"https://kellenmace.com/remove-custom-post-type-slug-from-permalinks/\" rel=\"nofollow noreferrer\">https://kellenmace.com/remove-custom-post-type-slug-from-permalinks/</a></p>\n\n<p>ended in a bunch of 404s</p>\n\n<p>But together with this wonderful approach, which is not using the backend permalink strukture for the blogpost it finally works like charme.\n<a href=\"https://www.bobz.co/add-blog-prefix-permalink-structure-blog-posts/\" rel=\"nofollow noreferrer\">https://www.bobz.co/add-blog-prefix-permalink-structure-blog-posts/</a></p>\n\n<p>Thanks a bunch.</p>\n"
},
{
"answer_id": 354738,
"author": "squarecandy",
"author_id": 41488,
"author_profile": "https://wordpress.stackexchange.com/users/41488",
"pm_score": 4,
"selected": false,
"text": "<h1>Plugin Roundup</h1>\n\n<p>It's almost 2020 and a lot of these answers don't work. Here's my own roundup of the current options:</p>\n\n<ul>\n<li><strong><a href=\"https://wordpress.stackexchange.com/a/282040/41488\">Matt Keys answer</a></strong> seems to be the only one on the right track if you want a custom code solution. None of the plugins I found can do everything listed here, especially the duplicate checking. This approach seems like a really good opportunity for a plugin if anyone wanted to take that on.</li>\n<li><strong><a href=\"https://wordpress.org/plugins/permalink-manager/\" rel=\"noreferrer\">Permalink Manager Lite</a></strong>\n\n<ul>\n<li> Best of the free plugins I tried.</li>\n<li> Gives full control over all Page/Post/CPT complete permalink structure and allows them to be the same. The GUI is by far the most feature-rich.</li>\n<li> Allows full override per-post as well and lets you see what the original/default would be and reset to the default if needed.</li>\n<li> Supports multi-site.</li>\n<li> Does <strong>not</strong> check for duplicates between post types, which is sad. If a page and a CPT have the same URL, the page loads and the CPT is inaccessible. No warnings or errors, you just have to do your own manual checking for duplicates.</li>\n<li> All taxonomy features are in the PRO version. The upgrade nags are pretty heavy.</li>\n</ul></li>\n<li><strong><a href=\"https://wordpress.org/plugins/custom-permalinks/\" rel=\"noreferrer\">Custom Permalinks</a></strong>\n\n<ul>\n<li> The free version does a lot. Taxonomy permalinks and premium support seem to be the only things withheld from the pro version. </li>\n<li> Allows you to change the <strong>full</strong> permalink for any individual page/post/CPT.</li>\n<li> Supports multi-site.</li>\n<li> Does <strong>not</strong> allow you to change the default structure so you your Custom Post Types will still be example.com/cpt-slug/post-title but you can change them individually.</li>\n<li> Does <strong>not</strong> check for duplicates between post types, which is sad.</li>\n</ul></li>\n<li><strong><a href=\"https://wordpress.org/plugins/custom-post-type-permalinks/\" rel=\"noreferrer\">Custom Post Type Permalinks</a></strong>\n\n<ul>\n<li> Allows non-developer users to change the things that are easy to change already with <code>register_post_type</code></li>\n<li> Does <strong>not</strong> allow you to change the CPT base slug - only the part that comes after that - so pretty much useless for developers and the issue in this question.</li>\n</ul></li>\n<li><strong><a href=\"https://wordpress.org/plugins/remove-base-slug-from-custom-post-type-url/\" rel=\"noreferrer\">remove base slug...</a></strong> - dead for several years now... do not use.</li>\n</ul>\n"
},
{
"answer_id": 379838,
"author": "Tiago",
"author_id": 73651,
"author_profile": "https://wordpress.stackexchange.com/users/73651",
"pm_score": 1,
"selected": false,
"text": "<p>For me worked now:</p>\n<pre><code>'rewrite' => array( \n'slug' => '/',\n'with_front' => false\n)\n</code></pre>\n<p>Insert inside register_post_type() function.</p>\n"
},
{
"answer_id": 388749,
"author": "arafatgazi",
"author_id": 205432,
"author_profile": "https://wordpress.stackexchange.com/users/205432",
"pm_score": 3,
"selected": false,
"text": "<h1>Background</h1>\n<p>Even after looking around everywhere, I couldn't find a proper solution for removing CPT slug from permalinks that actually works and is consistent with how WordPress actually parses requests. As it seems, everyone else looking for the same solution is in the same boat as me.</p>\n<p>As it turns out, this is actually a two-part solution.</p>\n<ol>\n<li>Remove CPT slug from permalinks</li>\n<li>Instruct WordPress on how to find posts from the new permalinks</li>\n</ol>\n<p>The first part is quite straightforward and many existing answers already have it right. This is what it looks like:</p>\n<pre><code>// remove cpt slug from permalinks\nfunction remove_cpt_slug( $post_link, $post, $leavename ) {\n\n if ( $post->post_type != 'custom_post_type' ) {\n return $post_link;\n } else {\n $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );\n return $post_link;\n }\n}\nadd_filter( 'post_type_link', 'remove_cpt_slug', 10, 3 );\n</code></pre>\n<p>Now, the second part is where things get ugly. After solving the first part, your CPT permalinks don't have CPT slugs anymore. But, now, the problem is WordPress doesn't know how to find your posts from those new permalinks because all it knows is CPT permalinks have CPT slugs. So, without a CPT slug in the permalink, it can't find your post. That's why when you make a request for your posts at this point, it throws a 404 not found error.</p>\n<p>So, all you need to do now is instruct WordPress on how to find your posts using the new permalinks. But this is the part where existing answers don't do very well. Let's take a look at a few of those answers for example:</p>\n<p>The below function works pretty well but it will only work if your permalink structure is set to Post name.</p>\n<pre><code>function parse_request_remove_cpt_slug( $query ) {\n\n if ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {\n return;\n }\n\n if ( ! empty( $query->query['name'] ) ) {\n global $wpdb;\n $cpt = $wpdb->get_var("SELECT post_type FROM $wpdb->posts WHERE post_name = '{$query->query['name']}'");\n\n // Add CPT to the list of post types WP will include when it queries based on the post name.\n $query->set( 'post_type', $cpt );\n }\n}\nadd_action( 'pre_get_posts', 'parse_request_remove_cpt_slug' );\n</code></pre>\n<p>The below function works well for your custom post type regardless of the permalink structure however it will throw an error on all other post types.</p>\n<pre><code>function rewrite_rule_remove_cpt_slug() {\n\n add_rewrite_rule(\n '(.?.+?)(?:/([0-9]+))?/?$',\n 'index.php?custom_post_type=$matches[1]/$matches[2]&post_type=custom_post_type',\n 'bottom'\n );\n}\nadd_action( 'init', 'rewrite_rule_remove_cpt_slug', 1, 1 );\n</code></pre>\n<p>There is another answer that is supposed to work as a standalone solution but ends up causing more issues than solutions like throwing errors in your CPT posts as well as on others. This one requires modifying the rewrite argument in your CPT registration as follows:</p>\n<pre><code>'rewrite' => array( 'slug' => '/', 'with_front' => false )\n</code></pre>\n<p>So far, all the existing answers I found are like the above ones. Either they work partially or don't work anymore. This is probably because WordPress doesn't give a streamlined way to remove CPT slug from custom post type permalinks and therefore these answers are either based on considering particular scenarios or based on a hacky way.</p>\n<h1>Answer</h1>\n<p>Here is what I have come up with while trying to create a solution that works on most if not all scenarios. This will properly remove CPT slug from CPT permalinks as well as instruct WordPress on finding CPT posts from those new permalinks. It doesn't rewrite rules in the database so you won't need to resave your permalink structure. Besides, this solution is consistent with how WordPress actually parses requests to find posts from permalinks which helps make it a more acceptable solution.</p>\n<p><strong>Make sure to replace <code>custom_post_type</code> with your own custom post type name. It appears once in every function so two occurrences in total.</strong></p>\n<pre><code>// remove cpt slug from permalinks\nfunction remove_cpt_slug( $post_link, $post, $leavename ) {\n\n if ( $post->post_type != 'custom_post_type' ) {\n return $post_link;\n } else {\n $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );\n return $post_link;\n }\n}\nadd_filter( 'post_type_link', 'remove_cpt_slug', 10, 3 );\n\n\n// instruct wordpress on how to find posts from the new permalinks\nfunction parse_request_remove_cpt_slug( $query_vars ) {\n\n // return if admin dashboard \n if ( is_admin() ) {\n return $query_vars;\n }\n\n // return if pretty permalink isn't enabled\n if ( ! get_option( 'permalink_structure' ) ) {\n return $query_vars;\n }\n\n $cpt = 'custom_post_type';\n\n // store post slug value to a variable\n if ( isset( $query_vars['pagename'] ) ) {\n $slug = $query_vars['pagename'];\n } elseif ( isset( $query_vars['name'] ) ) {\n $slug = $query_vars['name'];\n } else {\n global $wp;\n \n $path = $wp->request;\n\n // use url path as slug\n if ( $path && strpos( $path, '/' ) === false ) {\n $slug = $path;\n } else {\n $slug = false;\n }\n }\n\n if ( $slug ) {\n $post_match = get_page_by_path( $slug, 'OBJECT', $cpt );\n\n if ( ! is_admin() && $post_match ) {\n\n // remove any 404 not found error element from the query_vars array because a post match already exists in cpt\n if ( isset( $query_vars['error'] ) && $query_vars['error'] == 404 ) {\n unset( $query_vars['error'] );\n }\n\n // remove unnecessary elements from the original query_vars array\n unset( $query_vars['pagename'] );\n \n // add necessary elements in the the query_vars array\n $query_vars['post_type'] = $cpt;\n $query_vars['name'] = $slug;\n $query_vars[$cpt] = $slug; // this constructs the "cpt=>post_slug" element\n }\n }\n\n return $query_vars;\n}\nadd_filter( 'request', "parse_request_remove_cpt_slug" , 1, 1 );\n</code></pre>\n<p><strong>Considerations:</strong></p>\n<ol>\n<li><p>This solution intentionally leaves out <em>Plain</em> permalink structure from its scope as it isn't one of the pretty permalink structures. So, it will work with all permalink structures apart from the <em>Plain</em> one.</p>\n</li>\n<li><p>As WordPress doesn't automatically prevent creating duplicate slugs across different post types, you may find problems accessing posts having the same post slugs because of losing uniqueness in CPT permalinks after removing the CPT slugs. This code doesn't include any functionality to prevent that behavior so you may want to find a separate solution to address that.</p>\n</li>\n<li><p>In case there is a duplicate permalink, this code will prioritize your CPT over others and therefore display the post in your CPT when requested.</p>\n</li>\n</ol>\n"
},
{
"answer_id": 393394,
"author": "Lucas Bustamante",
"author_id": 27278,
"author_profile": "https://wordpress.stackexchange.com/users/27278",
"pm_score": 1,
"selected": false,
"text": "<p>This is what worked for me. Replace <code>podcast</code> with your CPT slug:</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action('init', function () {\n register_post_type(\n 'podcast',\n [\n 'rewrite' => false,\n ]\n );\n});\n\nadd_filter('post_type_link', function ($post_link, $post, $leavename) {\n if (isset($post->post_type) && $post->post_type === 'podcast') {\n $post_link = home_url($post->post_name);\n }\n\n return $post_link;\n}, 10, 3);\n\nadd_action('init', function () {\n add_rewrite_rule('(.+?)/?$', 'index.php?podcast=$matches[1]', 'bottom');\n});\n</code></pre>\n"
}
] |
2015/09/28
|
[
"https://wordpress.stackexchange.com/questions/203951",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/18726/"
] |
It seems that all web resources based on the subject of removing a custom post type slug ie
```
yourdomain.com/CPT-SLUG/post-name
```
are now very outdated solutions often referencing pre WP version 3.5 installs. A common one is to:
```
'rewrite' => array( 'slug' => false, 'with_front' => false ),
```
within your `register_post_type` function. This no longer works and is misleading. So I ask the community in Q4 2020...
**What are the modern and efficient ways to remove the Post Type Slug from a Custom Post Type post's URL from within the rewrite argument or anywhere else?**
UPDATE:
There seems to be several ways to force this to work with regex. Specifically the answer from Jan Beck should you be consistently willing to monitor content creation to ensure no conflicting page/post names are created.... However I'm convinced that this is a major weakness in WP core where it should be handled for us. Both as an option/hook when creating a CPT or an advanced set of options for permalinks. Please support the track ticket.
Footnote: Please support this trac ticket by watching/promoting it: <https://core.trac.wordpress.org/ticket/34136#ticket>
|
The following code will work, but you just have to keep in mind that conflicts can happen easily if the slug for your custom post type is the same as a page or post's slug...
First, we will remove the slug from the permalink:
```
function na_remove_slug( $post_link, $post, $leavename ) {
if ( 'events' != $post->post_type || 'publish' != $post->post_status ) {
return $post_link;
}
$post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
return $post_link;
}
add_filter( 'post_type_link', 'na_remove_slug', 10, 3 );
```
Just removing the slug isn't enough. Right now, you'll get a 404 page because WordPress only expects posts and pages to behave this way. You'll also need to add the following:
```
function na_parse_request( $query ) {
if ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {
return;
}
if ( ! empty( $query->query['name'] ) ) {
$query->set( 'post_type', array( 'post', 'events', 'page' ) );
}
}
add_action( 'pre_get_posts', 'na_parse_request' );
```
Just change "events" to your custom post type and you're good to go. You may need to refresh your permalinks.
|
203,977 |
<p>I am using a customized <code>mini-cart.php</code> file, in which there is this line of code:</p>
<pre><code>$product_name = apply_filters( 'woocommerce_cart_item_name', $_product->get_title(),
$cart_item, $cart_item_key );
</code></pre>
<p>I sell two types of products, "shorts" and "longshorts". I don't want to see these two words in my cart widget, because titles get too long and it's useless, so I want the results of <code>$product_name</code> to strip apart these words from the result.</p>
<p>To resume, actually I have this: </p>
<pre><code> - Short grey front pouch military
- Short blue fisherman
- Longshorts denim gray
- Longshorts denim black
</code></pre>
<p>And I would prefer:</p>
<pre><code> - grey front pouch military
- blue fisherman
- denim gray
- denim black
</code></pre>
|
[
{
"answer_id": 203982,
"author": "Caspar",
"author_id": 27191,
"author_profile": "https://wordpress.stackexchange.com/users/27191",
"pm_score": 1,
"selected": false,
"text": "<p>You need to add a function in your theme's <code>functions.php</code> file that will find and remove those two words \"shorts\" and \"longshorts\" from a php string. Then you can add that function as a filter to the <code>woocommerce_cart_item_name</code> event that is being applied in your <code>mini-cart.php</code> Try something like:</p>\n\n<pre><code>function wpse_remove_shorts_from_cart_title( $product_name ) {\n $product_name = str_ireplace( 'longshorts', '', $product_name ); // remove \"longshorts\";\n $product_name = str_ireplace( 'shorts', '', $product_name ); // remove \"shorts\"\n\n return $product_name;\n}\nadd_filter( 'woocommerce_cart_item_name', 'wpse_remove_shorts_from_cart_title' );\n</code></pre>\n\n<p>Note, I've used <code>str_ireplace()</code> to cover occurrences whether they're capitalized or not (which is common in titles).</p>\n"
},
{
"answer_id": 203997,
"author": "Xavier C.",
"author_id": 81047,
"author_profile": "https://wordpress.stackexchange.com/users/81047",
"pm_score": 0,
"selected": false,
"text": "<p>What i finally did was i took this line from mini-cart.php</p>\n\n<pre><code><?php echo str_ireplace( array( 'http:', 'https:' ), '', $thumbnail ) . $product_name . '&nbsp;'; ?>\n</code></pre>\n\n<p>and changed it to </p>\n\n<pre><code><?php echo str_ireplace( array( 'longshorts', 'short' ), '', $product_name ) . '&nbsp;'; ?>\n</code></pre>\n\n<p>I had already disabled thumbnails anyway.\nAnd it works!</p>\n"
}
] |
2015/09/28
|
[
"https://wordpress.stackexchange.com/questions/203977",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81047/"
] |
I am using a customized `mini-cart.php` file, in which there is this line of code:
```
$product_name = apply_filters( 'woocommerce_cart_item_name', $_product->get_title(),
$cart_item, $cart_item_key );
```
I sell two types of products, "shorts" and "longshorts". I don't want to see these two words in my cart widget, because titles get too long and it's useless, so I want the results of `$product_name` to strip apart these words from the result.
To resume, actually I have this:
```
- Short grey front pouch military
- Short blue fisherman
- Longshorts denim gray
- Longshorts denim black
```
And I would prefer:
```
- grey front pouch military
- blue fisherman
- denim gray
- denim black
```
|
You need to add a function in your theme's `functions.php` file that will find and remove those two words "shorts" and "longshorts" from a php string. Then you can add that function as a filter to the `woocommerce_cart_item_name` event that is being applied in your `mini-cart.php` Try something like:
```
function wpse_remove_shorts_from_cart_title( $product_name ) {
$product_name = str_ireplace( 'longshorts', '', $product_name ); // remove "longshorts";
$product_name = str_ireplace( 'shorts', '', $product_name ); // remove "shorts"
return $product_name;
}
add_filter( 'woocommerce_cart_item_name', 'wpse_remove_shorts_from_cart_title' );
```
Note, I've used `str_ireplace()` to cover occurrences whether they're capitalized or not (which is common in titles).
|
204,022 |
<p>I am working on a custom registration form. How can I assign a role of "participant" to the new user? I tried many methods but did not succeed; the role change is not reflected in the admin user's list. </p>
|
[
{
"answer_id": 237479,
"author": "Charles Xavier",
"author_id": 101716,
"author_profile": "https://wordpress.stackexchange.com/users/101716",
"pm_score": -1,
"selected": false,
"text": "<p>go to setting > general > New User Default Role change to participant</p>\n"
},
{
"answer_id": 299165,
"author": "Marcelo Henriques Cortez",
"author_id": 44437,
"author_profile": "https://wordpress.stackexchange.com/users/44437",
"pm_score": 0,
"selected": false,
"text": "<p>One way of doing it is, when you are submitting the registration form, define a value for the 'role' and then pass it with <code>wp_insert_user</code> <a href=\"https://codex.wordpress.org/Function_Reference/wp_insert_user\" rel=\"nofollow noreferrer\">Codex</a>.</p>\n\n<p>Like this:</p>\n\n<pre><code>$fields_user = get_fields_user(); //get the values from the form and put them in an array.\n$fields_user['role'] = 'participant'; //define a value for the key 'role'\n$user_id = wp_insert_user($fields_user); //get all the info and register it with the wp_insert_user\n</code></pre>\n\n<p>But that role has to be already created in the admin</p>\n"
}
] |
2015/09/29
|
[
"https://wordpress.stackexchange.com/questions/204022",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81139/"
] |
I am working on a custom registration form. How can I assign a role of "participant" to the new user? I tried many methods but did not succeed; the role change is not reflected in the admin user's list.
|
One way of doing it is, when you are submitting the registration form, define a value for the 'role' and then pass it with `wp_insert_user` [Codex](https://codex.wordpress.org/Function_Reference/wp_insert_user).
Like this:
```
$fields_user = get_fields_user(); //get the values from the form and put them in an array.
$fields_user['role'] = 'participant'; //define a value for the key 'role'
$user_id = wp_insert_user($fields_user); //get all the info and register it with the wp_insert_user
```
But that role has to be already created in the admin
|
204,038 |
<p>I am looking for a guide/guidance to create a proper custom wordpress repository for themes and plugins hosted on a website hosting account. I do not want to host it on github.com or anywhere else. I searched in google but without any success so far. Anyone could help?</p>
|
[
{
"answer_id": 237479,
"author": "Charles Xavier",
"author_id": 101716,
"author_profile": "https://wordpress.stackexchange.com/users/101716",
"pm_score": -1,
"selected": false,
"text": "<p>go to setting > general > New User Default Role change to participant</p>\n"
},
{
"answer_id": 299165,
"author": "Marcelo Henriques Cortez",
"author_id": 44437,
"author_profile": "https://wordpress.stackexchange.com/users/44437",
"pm_score": 0,
"selected": false,
"text": "<p>One way of doing it is, when you are submitting the registration form, define a value for the 'role' and then pass it with <code>wp_insert_user</code> <a href=\"https://codex.wordpress.org/Function_Reference/wp_insert_user\" rel=\"nofollow noreferrer\">Codex</a>.</p>\n\n<p>Like this:</p>\n\n<pre><code>$fields_user = get_fields_user(); //get the values from the form and put them in an array.\n$fields_user['role'] = 'participant'; //define a value for the key 'role'\n$user_id = wp_insert_user($fields_user); //get all the info and register it with the wp_insert_user\n</code></pre>\n\n<p>But that role has to be already created in the admin</p>\n"
}
] |
2015/09/29
|
[
"https://wordpress.stackexchange.com/questions/204038",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/15801/"
] |
I am looking for a guide/guidance to create a proper custom wordpress repository for themes and plugins hosted on a website hosting account. I do not want to host it on github.com or anywhere else. I searched in google but without any success so far. Anyone could help?
|
One way of doing it is, when you are submitting the registration form, define a value for the 'role' and then pass it with `wp_insert_user` [Codex](https://codex.wordpress.org/Function_Reference/wp_insert_user).
Like this:
```
$fields_user = get_fields_user(); //get the values from the form and put them in an array.
$fields_user['role'] = 'participant'; //define a value for the key 'role'
$user_id = wp_insert_user($fields_user); //get all the info and register it with the wp_insert_user
```
But that role has to be already created in the admin
|
204,062 |
<p>I currently have a site running on HTTPS with an SSL plugin activated</p>
<p>Website: <code>https://www.greenwichsentinel.com</code></p>
<p>SSL Plugin: Really Simple SSL</p>
<p>Wordpress Version: 4.0.7 (Multisite)</p>
<p>Everything seem configured correctly, however when trying to log into the site or view any dashboard panel i get caught in a redirect loop.</p>
<p>For example, trying to log in through <a href="https://www.greenwichsentinel.com/wp-admin" rel="nofollow">https://www.greenwichsentinel.com/wp-admin</a> causes the page to go to <code>https://www.greenwichsentinel.com/wp-login.php?redirect_to=http%3A%2F%2Fwww.greenwichsentinel.com%2Fwp-admin%2F&reauth=1</code> . The only link that seems to work is <a href="https://www.greenwichsentinel.com/wp-login.php" rel="nofollow">https://www.greenwichsentinel.com/wp-login.php</a> .</p>
<p>I have checked every setting and cannot see why this issue occurs. Any guidance on this issue is greatly appreciated.</p>
<p>Thank you</p>
<p><strong>Edit 1</strong> Without the plugin activated and with other plugins this is not an issue, it seems to be tied to this specific plugin</p>
|
[
{
"answer_id": 204099,
"author": "Mike D",
"author_id": 81182,
"author_profile": "https://wordpress.stackexchange.com/users/81182",
"pm_score": 0,
"selected": false,
"text": "<p>I used a redirect in <code>.htaccess</code> to a site recently and it seems to be working just fine.</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTPS} off\nRewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]\n</code></pre>\n"
},
{
"answer_id": 267754,
"author": "louie171",
"author_id": 94399,
"author_profile": "https://wordpress.stackexchange.com/users/94399",
"pm_score": 1,
"selected": false,
"text": "<p>you'd be better not using a plugin and editing the .htaccess file (in root of website) something like this at the top:</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTP_HOST} ^somesite.com [NC]\nRewriteRule ^(.*)$ https://www.somesite.com/$1 [L,R=301]\n</code></pre>\n\n<p>so your .htaccess file might look something like this:</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTP_HOST} ^somesite.com [NC]\nRewriteRule ^(.*)$ https://www.somesite.com/$1 [L,R=301]\n\n# BEGIN WordPress\n<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n</IfModule>\n\n# END WordPress\n</code></pre>\n\n<p>and remember to set WordPress Address (URL) and Site Address (URL) in Wordpress admin (settings -> general), so that they are on https not http</p>\n"
},
{
"answer_id": 311079,
"author": "De Coder",
"author_id": 144159,
"author_profile": "https://wordpress.stackexchange.com/users/144159",
"pm_score": 0,
"selected": false,
"text": "<p>Unless you're using the Pro edition of the plugin, which includes scans of content in your database, and maybe css and js files, you should put your redirect in the .htaccess file.</p>\n\n<p>Since you're running multi-site, I suggest this:</p>\n\n<pre><code> RewriteEngine On\n RewriteCond %{HTTPS} off\n RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]\n</code></pre>\n\n<p>This not only handles your multiple domain names, but ensures a proper 301 redirect to make Google, and other search engines happy, as well as user browsers.</p>\n\n<p>It is also short and sweet, and is done well before loading any PHP code, to help with your initial load speed.</p>\n\n<p>Also be sure you set the site and home path for each site, to use https. This is done as super admin, under My Sites > Network Admin > Sites</p>\n"
}
] |
2015/09/29
|
[
"https://wordpress.stackexchange.com/questions/204062",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78020/"
] |
I currently have a site running on HTTPS with an SSL plugin activated
Website: `https://www.greenwichsentinel.com`
SSL Plugin: Really Simple SSL
Wordpress Version: 4.0.7 (Multisite)
Everything seem configured correctly, however when trying to log into the site or view any dashboard panel i get caught in a redirect loop.
For example, trying to log in through <https://www.greenwichsentinel.com/wp-admin> causes the page to go to `https://www.greenwichsentinel.com/wp-login.php?redirect_to=http%3A%2F%2Fwww.greenwichsentinel.com%2Fwp-admin%2F&reauth=1` . The only link that seems to work is <https://www.greenwichsentinel.com/wp-login.php> .
I have checked every setting and cannot see why this issue occurs. Any guidance on this issue is greatly appreciated.
Thank you
**Edit 1** Without the plugin activated and with other plugins this is not an issue, it seems to be tied to this specific plugin
|
you'd be better not using a plugin and editing the .htaccess file (in root of website) something like this at the top:
```
RewriteEngine On
RewriteCond %{HTTP_HOST} ^somesite.com [NC]
RewriteRule ^(.*)$ https://www.somesite.com/$1 [L,R=301]
```
so your .htaccess file might look something like this:
```
RewriteEngine On
RewriteCond %{HTTP_HOST} ^somesite.com [NC]
RewriteRule ^(.*)$ https://www.somesite.com/$1 [L,R=301]
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
```
and remember to set WordPress Address (URL) and Site Address (URL) in Wordpress admin (settings -> general), so that they are on https not http
|
204,111 |
<p>I have a custom post type called <code>Event</code> which is registered like this:</p>
<pre><code>add_action('init', 'register_custom_post_types');
function register_custom_post_types() {
$event_capabilities = array(
'publish_posts' => 'publish_events',
'edit_posts' => 'edit_events',
'edit_others_posts' => 'edit_others_event',
'delete_posts' => 'delete_events',
'delete_published_posts' => 'delete_published_events',
'delete_others_posts' => 'delete_others_events',
'read_private_posts' => 'read_private_events',
'edit_post' => 'edit_event',
'delete_post' => 'delete_event',
'read_post' => 'read_event',
);
register_post_type('event',
array(
'labels' => array(
'name' => __( 'Event' )
),
'rewrite' => 'event',
'public' => true,
'has_archive' => true,
'show_ui' => true,
'menu_position' => 8,
'capability_type' => array('event', 'events'),
'capabilities' => $event_capabilities,
'supports' => array('title', 'thumbnail', 'page-attributes'),
'map_meta_cap' => true,
'hierarchical' => true,
)
);
}
</code></pre>
<p>I would like to be able to set an event as the parent of a ordinary page. In other words I would like all my events to show up in the <code>Parent</code> select element under the <code>Page Attributes</code>.</p>
<p>I have read many posts on how to set a CPT as the child of a page, but not the other way around.</p>
|
[
{
"answer_id": 204439,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 4,
"selected": true,
"text": "<p>The challenge we try to take on here is how to:</p>\n\n<ul>\n<li><p>not remove or replace the current <em>Page Attribute</em> meta box</p></li>\n<li><p>keep the hierarchical information in the drop-down.</p></li>\n</ul>\n\n<p>We assume we're on the single page edit screen, and want to add the <code>event</code> post type to the <code>page</code> <em>parent drop-down</em>.</p>\n\n<p>The drop-down is displayed using the <code>wp_dropdown_pages()</code> function, that calls the <code>get_pages()</code> function. It only supports a single post type. </p>\n\n<p>Here are two ways to do this:</p>\n\n<h2>Method #1 - Modify SQL</h2>\n\n<p><em>Here's an experimental way, since it deals with SQL modifications.</em></p>\n\n<p>Since there's no obvious way to filter the generated SQL query in <code>get_pages()</code>, we can use the general <code>query</code> filter to our needs.</p>\n\n<p>To make the dropdown more user friendly, when it contains titles from multiple post types, we use the <code>list_pages</code> filter, to prepend the post type info.</p>\n\n<p><strong>Example:</strong></p>\n\n<p>So instead of displaying the options like:</p>\n\n<pre><code>\"(no parent)\"\n\"About the Music Hall\"\n \"History\"\n \"Location\"\n\"Concerts\"\n \"Of Monsters and Men\"\n \"Vienna Philharmonic Orchestra\"\n\"Tickets\"\n</code></pre>\n\n<p>we get: </p>\n\n<pre><code>\"(no parent)\"\n\"page - About the Music Hall\"\n \"page - History\" \n \"page - Location\"\n\"event - Concerts\"\n \"event - Of Monsters and Men\"\n \"event - Vienna Philharmonic Orchestra\"\n\"page - Tickets\"\n</code></pre>\n\n<p><strong>Demo plugin:</strong></p>\n\n<p>Here's the code snippet that could be placed in a plugin for testing:</p>\n\n<pre><code>/**\n * Add the hierarchical 'event' post type, to the 'page' parent drop-down.\n *\n * @link http://wordpress.stackexchange.com/a/204439/26350\n */ \nis_admin() && add_filter( 'page_attributes_dropdown_pages_args', function( $dropdown_args, $post )\n{\n // Only do this for the 'page' post type on the single edit 'page' screen\n if( 'page' === get_current_screen()->id && 'page' === $post->post_type )\n {\n // Modify the options' titles\n add_filter( 'list_pages', 'wpse_add_post_type_info_in_options', 10, 2 );\n\n // Modify the get_pages() query\n add_filter( 'query', function( $sql )\n {\n // Only run this once\n if( ! did_action( 'wpse_change_cpt' ) )\n {\n do_action( 'wpse_change_cpt' );\n\n // Adjust the post type part of the query - add the 'event' post type\n $sql = str_replace( \n \"post_type = 'page' \", \n \"post_type IN ( 'event', 'page' ) \", \n $sql \n );\n }\n return $sql;\n } );\n }\n return $dropdown_args;\n}, 10, 2 );\n</code></pre>\n\n<p>where:</p>\n\n<pre><code>function wpse_add_post_type_info_in_options ( $title, $page )\n{\n return $page->post_type . ' - ' . $title;\n}\n</code></pre>\n\n<p>and a little bit of clean up:</p>\n\n<pre><code>add_filter( 'wp_dropdown_pages', function( $output )\n{\n if( did_action( 'wpse_change_cpt' ) )\n remove_filter( 'list_pages', 'wpse_add_post_type_info_in_options', 10, 2 );\n\n return $output;\n} );\n</code></pre>\n\n<h2>Method #2 - Only use <code>wp_dropdown_pages()</code></h2>\n\n<p>Here we let<code>wp_dropdown_pages()</code> run twice and then merge it into a single drop-down; once for the <code>page</code> post type and again for the <code>event</code> post type:</p>\n\n<pre><code>/**\n * Add the hierarchical 'event' post type, to the 'page' parent drop-down.\n *\n * @link http://wordpress.stackexchange.com/a/204439/26350\n */ \nis_admin() && add_filter( 'page_attributes_dropdown_pages_args', 'wpse_attributes', 99, 2 );\n\nfunction wpse_attributes( $dropdown_args, $post )\n{\n // Run this filter callback only once\n remove_filter( current_filter(), __FUNCTION__, 99 );\n\n // Only do this for the 'page' post type on the edit page screen\n if( 'page' === get_current_screen()->id && 'page' === $post->post_type )\n {\n // Modify the input arguments, for the 'event' drop-down\n $modified_args = $dropdown_args;\n $modified_args['post_type'] = 'page';\n $modified_args['show_option_no_change'] = __( '=== Select Events here below: ===' ); \n $modified_args['show_option_none'] = false;\n\n // Add the 'event' drop-down\n add_filter( 'wp_dropdown_pages', function( $output ) use ( $modified_args )\n {\n // Only run it once\n if( ! did_action( 'wpse_dropdown' ) )\n {\n do_action( 'wpse_dropdown' );\n\n // Create our second drop-down for events\n $output .= wp_dropdown_pages( $modified_args );\n\n // Adjust the output, so we only got a single drop-down\n $output = str_replace( \n [ \"<select name='parent_id' id='parent_id'>\", \"</select>\"],\n '', \n $output \n );\n $output = \"<select name='parent_id' id='parent_id'>\" . $output . \"</select>\";\n }\n return $output;\n } );\n }\n return $dropdown_args;\n}\n</code></pre>\n\n<p>Here the two hierarchical drop-downs are separated by the empty <em>=== Select Events here below: ===</em> option. </p>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>\"(no parent)\"\n\"About the Music Hall\"\n \"History\"\n \"Location\"\n\"Tickets\"\n\"=== Select Events here below: ===\"\n\"Concerts\"\n \"Of Monsters and Men\"\n \"Vienna Philharmonic Orchestra\"\n</code></pre>\n\n<h2>Adjusting the main query</h2>\n\n<p>Assume now that we create a page called <em>Of Monsters And Men - Info</em> with the <code>omam-info</code> slug and select the event <em>Of Monsters And Men</em> as the parent, with the <code>omam</code> slug.</p>\n\n<p>Then the path would be</p>\n\n<pre><code>example.tld/omam/omam-info\n</code></pre>\n\n<p>but this gives a 404 error. The reason is that the <code>get_page_path()</code> check inside the <code>\\WP_Query</code> class, for the main query, fails:</p>\n\n<pre><code>if ( '' != $qv['pagename'] ) {\n $this->queried_object = get_page_by_path($qv['pagename']);\n if ( !empty($this->queried_object) )\n $this->queried_object_id = (int) $this->queried_object->ID;\n else\n unset($this->queried_object);\n</code></pre>\n\n<p>This is because here <code>get_page_by_path()</code> only checks for the <code>page</code> and <code>attachment</code> post types, not the <code>event</code> post type. Unfortunately there's no explicit filter to change that.</p>\n\n<p>We could of course use the <code>query</code> filter, like we did above, but let's try another workaround.</p>\n\n<p>We can try to adjust the un-assigned properties <code>queried_object_id</code> and <code>queried_object_id</code> of the <code>\\WP_Query</code> object with:</p>\n\n<pre><code>/**\n * Support for page slugs with any kind event parent hierarchy\n *\n * @link http://wordpress.stackexchange.com/a/204439/26350\n */\nadd_action( 'pre_get_posts', function( \\WP_Query $q )\n{\n if( \n ! is_admin() // Front-end only\n && $q->is_main_query() // Target the main query\n && $q->get( 'pagename' ) // Check for pagename query variable\n && ! $q->get( 'post_type' ) // Target the 'page' post type\n && $page = get_page_by_path( $q->get( 'pagename' ), OBJECT, [ 'page', 'event', 'attachment' ] ) \n ) {\n if( is_a( $page, '\\WP_Post' ) )\n { \n $q->queried_object_id = $page->ID;\n $q->queried_object = $page;\n }\n }\n} );\n</code></pre>\n\n<p>This should also support any number of event parents, like the following hierarchy:</p>\n\n<pre><code>ecample.tld/event-grandparent/event-parent/event-child/page-slug\n</code></pre>\n\n<h2>Note</h2>\n\n<p>For the parent drop-downs in the <code>edit.php</code> screen, we might use the <code>quick_edit_dropdown_pages_args</code> filter, instead of the <code>page_attributes_dropdown_pages_args</code> filter we used above.</p>\n"
},
{
"answer_id": 204484,
"author": "Abhik",
"author_id": 26991,
"author_profile": "https://wordpress.stackexchange.com/users/26991",
"pm_score": 1,
"selected": false,
"text": "<p>Fisrt, you need to remove the core <strong>Page Attributes</strong> Meta Box, then add your own keeping everything intact except altering the parent post type. Here are my codes, tweaked to work with your <code>events</code> post type. Tried to make it copy/paste ready, however, if you encounter errors, please let me know. </p>\n\n<pre><code>/* Remove the core Page Attribute Metabox */\nfunction event_remove_pa_meta_boxes() {\n remove_meta_box( 'pageparentdiv', 'page', 'side' );\n}\nadd_action( 'do_meta_boxes', 'event_remove_pa_meta_boxes' );\n\n/* Set the Page Attribute Metabox again*/\nfunction events_pa_meta_box( $post ) {\n\n add_meta_box(\n 'event-select',\n __( 'Page Attributes', 'textdomain' ),\n 'events_selectors_box',\n 'page',\n 'side',\n 'core'\n );\n}\nadd_action( 'add_meta_boxes_page', 'events_pa_meta_box' );\n\n/* Recreate the meta box. */\nfunction events_selectors_box( $post ) {\n\n /* Set Events as Post Parent */\n $parents = get_posts(\n array(\n 'post_type' => 'event', \n 'orderby' => 'title', \n 'order' => 'ASC', \n 'numberposts' => -1 \n )\n );\n\n echo '<p><strong>Parent</strong></p><label class=\"screen-reader-text\" for=\"parent_id\">Parent</label>';\n if ( !empty( $parents ) ) {\n\n echo '<select id=\"parent_id\" name=\"parent_id\">';\n\n foreach ( $parents as $parent ) {\n printf( '<option value=\"%s\"%s>%s</option>', esc_attr( $parent->ID ), selected( $parent->ID, $post->post_parent, false ), esc_html( $parent->post_title ) );\n }\n\n echo '</select>';\n\n } else {\n\n echo '<p>Please <a href=\"' . admin_url( \"post-new.php?post_type=event\" ) . '\">create an event first</a>.</p>';\n\n }\n\n /* Page Templates */\n\n if ( 'page' == $post->post_type && 0 != count( get_page_templates( $post ) ) && get_option( 'page_for_posts' ) != $post->ID ) {\n\n $template = !empty($post->page_template) ? $post->page_template : false;\n\n echo '<p><strong>Template</strong></p><label class=\"screen-reader-text\" for=\"page_template\">Page Template</label>';\n\n echo '<select id=\"page_template\" name=\"page_template\">';\n\n $default_title = apply_filters( 'default_page_template_title', __( 'Default Template' ), 'meta-box' );\n\n echo '<option value=\"default\">' . esc_html( $default_title ) . '</option>' \n\n page_template_dropdown($template);\n\n echo '</select>';\n\n }\n\n /* Page Order */\n echo '<p><strong>' . _e('Order') .'</strong></p>';\n\n echo '<label class=\"screen-reader-text\" for=\"menu_order\">'. _e('Order') . '</label><input name=\"menu_order\" type=\"text\" size=\"4\" id=\"menu_order\" value=\"'. esc_attr($post->menu_order) .'\" />';\n\n /* Help Paragraph */\n if ( 'page' == $post->post_type && get_current_screen()->get_help_tabs() ) { ?>\n echo '<p>' . _e( 'Need help? Use the Help tab in the upper right of your screen.' ) . '</p>';\n }\n} \n</code></pre>\n\n<p><strong>EDIT:</strong>\nJust noticed that there's filter available to modify the default args in page attribute meta box: </p>\n\n<pre><code>$dropdown_args = array(\n 'post_type' => $post->post_type,\n 'exclude_tree' => $post->ID,\n 'selected' => $post->post_parent,\n 'name' => 'parent_id',\n 'show_option_none' => __('(no parent)'),\n 'sort_column' => 'menu_order, post_title',\n 'echo' => 0,\n);\n\n$dropdown_args = apply_filters( 'page_attributes_dropdown_pages_args', $dropdown_args, $post ); \n</code></pre>\n\n<p>So, there could be a super easy way to do what you want.</p>\n"
}
] |
2015/09/30
|
[
"https://wordpress.stackexchange.com/questions/204111",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/14870/"
] |
I have a custom post type called `Event` which is registered like this:
```
add_action('init', 'register_custom_post_types');
function register_custom_post_types() {
$event_capabilities = array(
'publish_posts' => 'publish_events',
'edit_posts' => 'edit_events',
'edit_others_posts' => 'edit_others_event',
'delete_posts' => 'delete_events',
'delete_published_posts' => 'delete_published_events',
'delete_others_posts' => 'delete_others_events',
'read_private_posts' => 'read_private_events',
'edit_post' => 'edit_event',
'delete_post' => 'delete_event',
'read_post' => 'read_event',
);
register_post_type('event',
array(
'labels' => array(
'name' => __( 'Event' )
),
'rewrite' => 'event',
'public' => true,
'has_archive' => true,
'show_ui' => true,
'menu_position' => 8,
'capability_type' => array('event', 'events'),
'capabilities' => $event_capabilities,
'supports' => array('title', 'thumbnail', 'page-attributes'),
'map_meta_cap' => true,
'hierarchical' => true,
)
);
}
```
I would like to be able to set an event as the parent of a ordinary page. In other words I would like all my events to show up in the `Parent` select element under the `Page Attributes`.
I have read many posts on how to set a CPT as the child of a page, but not the other way around.
|
The challenge we try to take on here is how to:
* not remove or replace the current *Page Attribute* meta box
* keep the hierarchical information in the drop-down.
We assume we're on the single page edit screen, and want to add the `event` post type to the `page` *parent drop-down*.
The drop-down is displayed using the `wp_dropdown_pages()` function, that calls the `get_pages()` function. It only supports a single post type.
Here are two ways to do this:
Method #1 - Modify SQL
----------------------
*Here's an experimental way, since it deals with SQL modifications.*
Since there's no obvious way to filter the generated SQL query in `get_pages()`, we can use the general `query` filter to our needs.
To make the dropdown more user friendly, when it contains titles from multiple post types, we use the `list_pages` filter, to prepend the post type info.
**Example:**
So instead of displaying the options like:
```
"(no parent)"
"About the Music Hall"
"History"
"Location"
"Concerts"
"Of Monsters and Men"
"Vienna Philharmonic Orchestra"
"Tickets"
```
we get:
```
"(no parent)"
"page - About the Music Hall"
"page - History"
"page - Location"
"event - Concerts"
"event - Of Monsters and Men"
"event - Vienna Philharmonic Orchestra"
"page - Tickets"
```
**Demo plugin:**
Here's the code snippet that could be placed in a plugin for testing:
```
/**
* Add the hierarchical 'event' post type, to the 'page' parent drop-down.
*
* @link http://wordpress.stackexchange.com/a/204439/26350
*/
is_admin() && add_filter( 'page_attributes_dropdown_pages_args', function( $dropdown_args, $post )
{
// Only do this for the 'page' post type on the single edit 'page' screen
if( 'page' === get_current_screen()->id && 'page' === $post->post_type )
{
// Modify the options' titles
add_filter( 'list_pages', 'wpse_add_post_type_info_in_options', 10, 2 );
// Modify the get_pages() query
add_filter( 'query', function( $sql )
{
// Only run this once
if( ! did_action( 'wpse_change_cpt' ) )
{
do_action( 'wpse_change_cpt' );
// Adjust the post type part of the query - add the 'event' post type
$sql = str_replace(
"post_type = 'page' ",
"post_type IN ( 'event', 'page' ) ",
$sql
);
}
return $sql;
} );
}
return $dropdown_args;
}, 10, 2 );
```
where:
```
function wpse_add_post_type_info_in_options ( $title, $page )
{
return $page->post_type . ' - ' . $title;
}
```
and a little bit of clean up:
```
add_filter( 'wp_dropdown_pages', function( $output )
{
if( did_action( 'wpse_change_cpt' ) )
remove_filter( 'list_pages', 'wpse_add_post_type_info_in_options', 10, 2 );
return $output;
} );
```
Method #2 - Only use `wp_dropdown_pages()`
------------------------------------------
Here we let`wp_dropdown_pages()` run twice and then merge it into a single drop-down; once for the `page` post type and again for the `event` post type:
```
/**
* Add the hierarchical 'event' post type, to the 'page' parent drop-down.
*
* @link http://wordpress.stackexchange.com/a/204439/26350
*/
is_admin() && add_filter( 'page_attributes_dropdown_pages_args', 'wpse_attributes', 99, 2 );
function wpse_attributes( $dropdown_args, $post )
{
// Run this filter callback only once
remove_filter( current_filter(), __FUNCTION__, 99 );
// Only do this for the 'page' post type on the edit page screen
if( 'page' === get_current_screen()->id && 'page' === $post->post_type )
{
// Modify the input arguments, for the 'event' drop-down
$modified_args = $dropdown_args;
$modified_args['post_type'] = 'page';
$modified_args['show_option_no_change'] = __( '=== Select Events here below: ===' );
$modified_args['show_option_none'] = false;
// Add the 'event' drop-down
add_filter( 'wp_dropdown_pages', function( $output ) use ( $modified_args )
{
// Only run it once
if( ! did_action( 'wpse_dropdown' ) )
{
do_action( 'wpse_dropdown' );
// Create our second drop-down for events
$output .= wp_dropdown_pages( $modified_args );
// Adjust the output, so we only got a single drop-down
$output = str_replace(
[ "<select name='parent_id' id='parent_id'>", "</select>"],
'',
$output
);
$output = "<select name='parent_id' id='parent_id'>" . $output . "</select>";
}
return $output;
} );
}
return $dropdown_args;
}
```
Here the two hierarchical drop-downs are separated by the empty *=== Select Events here below: ===* option.
**Example:**
```
"(no parent)"
"About the Music Hall"
"History"
"Location"
"Tickets"
"=== Select Events here below: ==="
"Concerts"
"Of Monsters and Men"
"Vienna Philharmonic Orchestra"
```
Adjusting the main query
------------------------
Assume now that we create a page called *Of Monsters And Men - Info* with the `omam-info` slug and select the event *Of Monsters And Men* as the parent, with the `omam` slug.
Then the path would be
```
example.tld/omam/omam-info
```
but this gives a 404 error. The reason is that the `get_page_path()` check inside the `\WP_Query` class, for the main query, fails:
```
if ( '' != $qv['pagename'] ) {
$this->queried_object = get_page_by_path($qv['pagename']);
if ( !empty($this->queried_object) )
$this->queried_object_id = (int) $this->queried_object->ID;
else
unset($this->queried_object);
```
This is because here `get_page_by_path()` only checks for the `page` and `attachment` post types, not the `event` post type. Unfortunately there's no explicit filter to change that.
We could of course use the `query` filter, like we did above, but let's try another workaround.
We can try to adjust the un-assigned properties `queried_object_id` and `queried_object_id` of the `\WP_Query` object with:
```
/**
* Support for page slugs with any kind event parent hierarchy
*
* @link http://wordpress.stackexchange.com/a/204439/26350
*/
add_action( 'pre_get_posts', function( \WP_Query $q )
{
if(
! is_admin() // Front-end only
&& $q->is_main_query() // Target the main query
&& $q->get( 'pagename' ) // Check for pagename query variable
&& ! $q->get( 'post_type' ) // Target the 'page' post type
&& $page = get_page_by_path( $q->get( 'pagename' ), OBJECT, [ 'page', 'event', 'attachment' ] )
) {
if( is_a( $page, '\WP_Post' ) )
{
$q->queried_object_id = $page->ID;
$q->queried_object = $page;
}
}
} );
```
This should also support any number of event parents, like the following hierarchy:
```
ecample.tld/event-grandparent/event-parent/event-child/page-slug
```
Note
----
For the parent drop-downs in the `edit.php` screen, we might use the `quick_edit_dropdown_pages_args` filter, instead of the `page_attributes_dropdown_pages_args` filter we used above.
|
204,114 |
<p>I have set up some CPTs and storing a meta key/val for each of them. When I get those posts, I need to order them by the meta value, but, <strong>the order of the meta values will be defined in an array by me</strong>. The <strong>default ordering for meta values is either alphabetical or numerical</strong>, which I do not want.</p>
<p>I'll explain it in an example:</p>
<pre><code>Post 1 =>
Meta key: Fruit
Meta value: Apple
Post 2 =>
Meta key: Fruit
Meta value: Melon
Post 3 =>
Meta key: Fruit
Meta value: Guava
Post 4 =>
Meta key: Fruit
Meta value: Banana
</code></pre>
<p>I get the order from an external source, and I want to get the posts in that order. Example: I get an order in an array: <code>['Apple', 'Banana', 'Guava', 'Melon']</code>. When I fetch the CPTs, I need to get them in this order. (Ignore the alphabetical ordering, I am just trying to give a general example).</p>
<p>How do I achieve it using a <code>meta_query</code> or any other solution?</p>
<p>If there is an existing thread, please redirect me to it. </p>
|
[
{
"answer_id": 204116,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 2,
"selected": false,
"text": "<p>If the value of the meta field is a single value (not serialized), this filter could work:</p>\n<pre><code>add_filter( 'posts_orderby', 'custom_posts_orderby' );\nfunction custom_posts_orderby( $orderby_statement ) {\n\n $custom_order = array( 'Apple', 'Banana', 'Guava', 'Melon' );\n\n $custom_order = "'" . implode ( "', '", $custom_order ) . "'";\n\n $orderby_statement = "FIELD( meta_value, " . $custom_order . " )";\n\n return $orderby_statement;\n\n}\n</code></pre>\n<p>Note that this will affect to all queries, so you need to define the conditions to apply filter or not.</p>\n<p>You can see more examples to build the <code>ORDER BY FIELD()</code> statemnet in <a href=\"http://www.electrictoolbox.com/mysql-order-specific-field-values/\" rel=\"nofollow noreferrer\">this post</a>.</p>\n"
},
{
"answer_id": 204118,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<p><em>My proposed solution is already posted by @cybmeta (+1), but I add it anyway, since it deals with it in a general way ;-)</em></p>\n\n<p>In the same way the <code>WP_Query</code> parameters:</p>\n\n<pre><code>'post__in' => [1,2,3],\n'orderby' => 'post__in'\n</code></pre>\n\n<p>give use the custom defined order:</p>\n\n<pre><code>ORDERBY FIELD( wp_posts.ID, 1, 2, 3 )\n</code></pre>\n\n<p>we can define our own meta ordering using:</p>\n\n<pre><code>'meta__in' => [ 'apple', 'orange', 'banana' ],\n'orderby' => 'meta__in'\n</code></pre>\n\n<p>to get the following SQL part:</p>\n\n<pre><code>ORDERBY FIELD( wp_postmeta.meta_value, 'apple', 'orange', 'banana' )\n</code></pre>\n\n<p>First we define our own version of the <code>wp_parse_id_list()</code> helper function.</p>\n\n<pre><code>/**\n* Note that this function is based on the core wp_parse_id_list() function.\n* Clean up an array, comma- or space-separated list of string keys.\n*\n* @uses sanitize_key()\n* @param array|string $list List of keys.\n* @return array Sanitized array of keys.\n*/\nfunction wpse_parse_meta_list( $list )\n{\n if ( ! is_array( $list ) )\n $list = preg_split('/[\\s,]+/', $list);\n\n return array_unique( array_map( 'sanitize_key', $list ) );\n} \n</code></pre>\n\n<h2>Demo plugin</h2>\n\n<p>Then we construct the following demo plugin, to add a support for <code>'meta__in'</code> ordering, in <code>WP_Query</code>:</p>\n\n<pre><code><?php\n/**\n * Plugin Name: Support for order by meta__in in WP_Query\n */\n\nadd_filter( 'posts_orderby', function ( $orderby, \\WP_Query $q )\n{\n if( $meta__in = $q->get( 'meta__in' ) )\n {\n if( is_array( $meta__in ) && ! empty( $meta__in ) )\n {\n global $wpdb; \n\n // Transform the meta__in array into a comma separated strings of keys\n // Example [ 'apple', 'banana' ] --> \"apple\", \"banana\"\n $list = '\"' . join( '\",\"', wpse_parse_meta_list( $meta__in ) ) . '\"'; \n\n // Override the orderby part with custom ordering:\n $orderby = \" FIELD( {$wpdb->postmeta}.meta_value, {$list} ) \";\n }\n }\n return $orderby;\n}, 10, 2 );\n\n/**\n * Note that this function is based on the core wp_parse_id_list() function.\n * Clean up an array, comma- or space-separated list of string keys.\n *\n * @uses sanitize_key()\n * @param array|string $list List of keys.\n * @return array Sanitized array of keys.\n */\nfunction wpse_parse_meta_list( $list )\n{\n if ( ! is_array( $list ) )\n $list = preg_split('/[\\s,]+/', $list);\n\n return array_unique( array_map( 'sanitize_key', $list ) );\n} \n</code></pre>\n\n<p>where we've added the helper function into the plugin.</p>\n\n<h2>Notes</h2>\n\n<p>We only use the <code>'meta__in'</code> parameter for ordering and not for extra <code>WHERE</code> restrictions, like we have with the <code>'post__in'</code> parameter. But that might be an interesting extension ;-)</p>\n\n<p>Also note that <code>get_posts()</code>, that's just a <code>WP_Query</code> wrapper, has the following parameter set up by default:</p>\n\n<pre><code>'suppress_filters' => true \n</code></pre>\n\n<p>i.e. it doesn't accept the <code>posts_*</code> filters by default.</p>\n\n<p>So if you can't use <code>WP_Query</code> or <code>get_posts()</code> with the <code>suppress_filters => false</code>, then you would need an alternative approach, e.g. suggested by @PieterGoosen.</p>\n"
},
{
"answer_id": 204119,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 0,
"selected": false,
"text": "<p>As I stated, IMHO, with your best option for what you need is going to be <code>usort()</code> to sort the returned array of posts</p>\n\n<p>Here is an untested theory</p>\n\n<pre><code>$sortorder = ['Apple', 'Banana', 'Guava', 'Melon'];\n$args = [\n 'meta_query' => [\n [\n 'key' => 'Fruit',\n 'value' => $sortorder\n ]\n ],\n];\n$q = new WP_Query( $args );\n\n@usort( $q->posts, function( $a, $b ) use ( $sortorder ) {\n // Get the meta values from the two posts to be compared\n $array_a = get_post_meta( $a->ID, 'Fruit', true );\n $array_b = get_post_meta( $b->ID, 'Fruit', true );\n\n // Reverse our $sortorder, key/value becomes value/key\n $flipped_order = array_flip( $sortorder );\n\n // Let start our sorting\n // If our meta values are the same order by date\n if ( $flipped_order[$array_a] != $flipped_order[$array_b] ) {\n return $flipped_order[$array_a] - $flipped_order[$array_b] // Swop around to reverse ordering\n } else {\n return $a->post_date < $b->post_date; // Change to > if you need oldest posts first\n }\n});\n\n// Run your loop normally\n</code></pre>\n\n<h2>EDIT</h2>\n\n<p>I have not brought in any safety to my code. You would want to make sure that <code>$sortorder</code> is a valid array, then you need to sanitize and validate the values before you use them to avoid malicious code.</p>\n\n<p>You can do this for the main query aswell, the only thing is then that you would want to wrap the <code>usort()</code> function in the <code>the_posts</code> filter and then use <code>$posts</code> in place of <code>$q->posts</code></p>\n"
},
{
"answer_id": 409445,
"author": "mozboz",
"author_id": 176814,
"author_profile": "https://wordpress.stackexchange.com/users/176814",
"pm_score": 0,
"selected": false,
"text": "<p>Building on the answer of @cybmeta here's another snippet of code that shows example of how you might sensibly decide when to this filter should activate. This assumes that you've specified an order by the meta_key on the query object somewhere, e.g. by hooking <code>parse_query</code>.</p>\n<pre><code>function custom_orderby_orders($orderby, $query) {\n\n if ($query->query['post_type'] == 'some_post_type' &&\n $query->query_vars['meta_key'] == 'meta_key_you_want_to_order') {\n \n $neworder = ['foo', 'bar', 'baz'];\n\n $ordersql = "'" . implode("', '", $neworder) . "'";\n\n return "FIELD(meta_value, " . $ordersql . ")";\n\n } else { \n\n return $orderby;\n\n }\n}\n\nadd_filter('posts_orderby', 'custom_orderby_orders', 10,2);\n</code></pre>\n"
}
] |
2015/09/30
|
[
"https://wordpress.stackexchange.com/questions/204114",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/4740/"
] |
I have set up some CPTs and storing a meta key/val for each of them. When I get those posts, I need to order them by the meta value, but, **the order of the meta values will be defined in an array by me**. The **default ordering for meta values is either alphabetical or numerical**, which I do not want.
I'll explain it in an example:
```
Post 1 =>
Meta key: Fruit
Meta value: Apple
Post 2 =>
Meta key: Fruit
Meta value: Melon
Post 3 =>
Meta key: Fruit
Meta value: Guava
Post 4 =>
Meta key: Fruit
Meta value: Banana
```
I get the order from an external source, and I want to get the posts in that order. Example: I get an order in an array: `['Apple', 'Banana', 'Guava', 'Melon']`. When I fetch the CPTs, I need to get them in this order. (Ignore the alphabetical ordering, I am just trying to give a general example).
How do I achieve it using a `meta_query` or any other solution?
If there is an existing thread, please redirect me to it.
|
If the value of the meta field is a single value (not serialized), this filter could work:
```
add_filter( 'posts_orderby', 'custom_posts_orderby' );
function custom_posts_orderby( $orderby_statement ) {
$custom_order = array( 'Apple', 'Banana', 'Guava', 'Melon' );
$custom_order = "'" . implode ( "', '", $custom_order ) . "'";
$orderby_statement = "FIELD( meta_value, " . $custom_order . " )";
return $orderby_statement;
}
```
Note that this will affect to all queries, so you need to define the conditions to apply filter or not.
You can see more examples to build the `ORDER BY FIELD()` statemnet in [this post](http://www.electrictoolbox.com/mysql-order-specific-field-values/).
|
204,250 |
<p>My posts contain a meta-field that holds an external id.
I'm trying to create a function with a loop that goes through all posts and puts all the meta-keys in an array and returns this array. </p>
<p>This is what i came up with, but it seems i'm missing something. Does anyone have a clue?</p>
<pre><code>function gather_ids ()
{
$args = array(
'post_type' => 'post',
);
$posts = new WP_Query( $args );
// The Loop
if ( $posts->have_posts() ) {
while ( $posts->have_posts() ) {
$temp[] = get_post_meta($post_id, 'json_id');
}
return $temp;
} else {
// no posts found
echo "no posts found to delete";
}
/* Restore original Post Data */
wp_reset_postdata();
}
</code></pre>
|
[
{
"answer_id": 204260,
"author": "Mitul",
"author_id": 74728,
"author_profile": "https://wordpress.stackexchange.com/users/74728",
"pm_score": 0,
"selected": false,
"text": "<p>Please pass the 3rd argument true.</p>\n\n<p>like</p>\n\n<pre><code>get_post_meta($post_id, 'json_id', true);\n</code></pre>\n"
},
{
"answer_id": 204347,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>You don't set the <code>$post_id</code> to anything. You probably need to call <code>the_post()</code> at the loop and use the <code>$post</code> global to access the id.</p>\n"
},
{
"answer_id": 204353,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>Your function is unreliable and totally overboard and really really expensive. Furthermore, as already stated by @MarkKaplun, you are not calling <code>the_post()</code> which causes the <code>$post</code> global not to be updated to the current post being looped through, so the value from <code>get_post_meta()</code> will always have the same value.</p>\n\n<p>Although <code>$post_id</code> might work, it is one of those crappy variables set globally that is actually used to get the comments. It is better to use <code>get_the_ID()</code> or even <code>$post->ID</code> as you are inside the loop. For extra info, read <a href=\"https://wordpress.stackexchange.com/a/112400/31545\">this post</a></p>\n\n<p>To solve your issue, I would just create a function with a custom SQL query to fetch all unique values from a specific meta key. Here is a function I have used on another answer</p>\n\n<pre><code>/** \n * Description: Getting all the values associated with a specific custom post meta key, across all posts\n * Author: Chinmoy Paul\n * Author URL: http://pwdtechnology.com\n *\n * @param string $key Post Meta Key.\n *\n * @param string $type Post Type. Default is post. You can pass custom post type here.\n *\n * @param string $status Post Status like Publish, draft, future etc. default is publish\n *\n * @return array\n */\nfunction get_unique_post_meta_values( $key = '', $type = 'post', $status = 'publish' ) \n{\n global $wpdb;\n if( empty( $key ) )\n return;\n $res = $wpdb->get_col( \n $wpdb->prepare( \n \"SELECT DISTINCT pm.meta_value \n FROM {$wpdb->postmeta} pm\n LEFT JOIN {$wpdb->posts} p \n ON p.ID = pm.post_id\n WHERE pm.meta_key = '%s'\n AND p.post_status = '%s'\n AND p.post_type = '%s'\", \n $key, \n $status, \n $type \n ) \n );\n return $res;\n}\n</code></pre>\n\n<p>You can then just use it as follow to get an array of unique meta value</p>\n\n<pre><code>$unique_values = get_unique_post_meta_values( 'json_id' );\n?><pre><?php var_dump( $unique_values ); ?></pre><?php \n</code></pre>\n\n<p>You can also build in some cache/transient system into the function to optimize it even more</p>\n"
}
] |
2015/10/01
|
[
"https://wordpress.stackexchange.com/questions/204250",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81263/"
] |
My posts contain a meta-field that holds an external id.
I'm trying to create a function with a loop that goes through all posts and puts all the meta-keys in an array and returns this array.
This is what i came up with, but it seems i'm missing something. Does anyone have a clue?
```
function gather_ids ()
{
$args = array(
'post_type' => 'post',
);
$posts = new WP_Query( $args );
// The Loop
if ( $posts->have_posts() ) {
while ( $posts->have_posts() ) {
$temp[] = get_post_meta($post_id, 'json_id');
}
return $temp;
} else {
// no posts found
echo "no posts found to delete";
}
/* Restore original Post Data */
wp_reset_postdata();
}
```
|
Your function is unreliable and totally overboard and really really expensive. Furthermore, as already stated by @MarkKaplun, you are not calling `the_post()` which causes the `$post` global not to be updated to the current post being looped through, so the value from `get_post_meta()` will always have the same value.
Although `$post_id` might work, it is one of those crappy variables set globally that is actually used to get the comments. It is better to use `get_the_ID()` or even `$post->ID` as you are inside the loop. For extra info, read [this post](https://wordpress.stackexchange.com/a/112400/31545)
To solve your issue, I would just create a function with a custom SQL query to fetch all unique values from a specific meta key. Here is a function I have used on another answer
```
/**
* Description: Getting all the values associated with a specific custom post meta key, across all posts
* Author: Chinmoy Paul
* Author URL: http://pwdtechnology.com
*
* @param string $key Post Meta Key.
*
* @param string $type Post Type. Default is post. You can pass custom post type here.
*
* @param string $status Post Status like Publish, draft, future etc. default is publish
*
* @return array
*/
function get_unique_post_meta_values( $key = '', $type = 'post', $status = 'publish' )
{
global $wpdb;
if( empty( $key ) )
return;
$res = $wpdb->get_col(
$wpdb->prepare(
"SELECT DISTINCT pm.meta_value
FROM {$wpdb->postmeta} pm
LEFT JOIN {$wpdb->posts} p
ON p.ID = pm.post_id
WHERE pm.meta_key = '%s'
AND p.post_status = '%s'
AND p.post_type = '%s'",
$key,
$status,
$type
)
);
return $res;
}
```
You can then just use it as follow to get an array of unique meta value
```
$unique_values = get_unique_post_meta_values( 'json_id' );
?><pre><?php var_dump( $unique_values ); ?></pre><?php
```
You can also build in some cache/transient system into the function to optimize it even more
|
204,253 |
<p>Obviously WordPress knows where the plugins that are installed are located. </p>
<p>Compared to other CMS software, the specifications for the location of a WordPress plugin are very loose. If I'm not mistaken, a plugin file is not required to be in the standard plugin folder, and it can be in a subfolder of the plugin folder, or a subfolder in a subfolder. There may even be multiple plugins in the same folder, or another plugin in a folder of an already existing plugin.</p>
<p>The path must, at some point during the installation, be "registered" stored by WordPress. Where exactly does WordPress document this information, and is it easily accessible for the administrator?</p>
|
[
{
"answer_id": 204260,
"author": "Mitul",
"author_id": 74728,
"author_profile": "https://wordpress.stackexchange.com/users/74728",
"pm_score": 0,
"selected": false,
"text": "<p>Please pass the 3rd argument true.</p>\n\n<p>like</p>\n\n<pre><code>get_post_meta($post_id, 'json_id', true);\n</code></pre>\n"
},
{
"answer_id": 204347,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>You don't set the <code>$post_id</code> to anything. You probably need to call <code>the_post()</code> at the loop and use the <code>$post</code> global to access the id.</p>\n"
},
{
"answer_id": 204353,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>Your function is unreliable and totally overboard and really really expensive. Furthermore, as already stated by @MarkKaplun, you are not calling <code>the_post()</code> which causes the <code>$post</code> global not to be updated to the current post being looped through, so the value from <code>get_post_meta()</code> will always have the same value.</p>\n\n<p>Although <code>$post_id</code> might work, it is one of those crappy variables set globally that is actually used to get the comments. It is better to use <code>get_the_ID()</code> or even <code>$post->ID</code> as you are inside the loop. For extra info, read <a href=\"https://wordpress.stackexchange.com/a/112400/31545\">this post</a></p>\n\n<p>To solve your issue, I would just create a function with a custom SQL query to fetch all unique values from a specific meta key. Here is a function I have used on another answer</p>\n\n<pre><code>/** \n * Description: Getting all the values associated with a specific custom post meta key, across all posts\n * Author: Chinmoy Paul\n * Author URL: http://pwdtechnology.com\n *\n * @param string $key Post Meta Key.\n *\n * @param string $type Post Type. Default is post. You can pass custom post type here.\n *\n * @param string $status Post Status like Publish, draft, future etc. default is publish\n *\n * @return array\n */\nfunction get_unique_post_meta_values( $key = '', $type = 'post', $status = 'publish' ) \n{\n global $wpdb;\n if( empty( $key ) )\n return;\n $res = $wpdb->get_col( \n $wpdb->prepare( \n \"SELECT DISTINCT pm.meta_value \n FROM {$wpdb->postmeta} pm\n LEFT JOIN {$wpdb->posts} p \n ON p.ID = pm.post_id\n WHERE pm.meta_key = '%s'\n AND p.post_status = '%s'\n AND p.post_type = '%s'\", \n $key, \n $status, \n $type \n ) \n );\n return $res;\n}\n</code></pre>\n\n<p>You can then just use it as follow to get an array of unique meta value</p>\n\n<pre><code>$unique_values = get_unique_post_meta_values( 'json_id' );\n?><pre><?php var_dump( $unique_values ); ?></pre><?php \n</code></pre>\n\n<p>You can also build in some cache/transient system into the function to optimize it even more</p>\n"
}
] |
2015/10/01
|
[
"https://wordpress.stackexchange.com/questions/204253",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80462/"
] |
Obviously WordPress knows where the plugins that are installed are located.
Compared to other CMS software, the specifications for the location of a WordPress plugin are very loose. If I'm not mistaken, a plugin file is not required to be in the standard plugin folder, and it can be in a subfolder of the plugin folder, or a subfolder in a subfolder. There may even be multiple plugins in the same folder, or another plugin in a folder of an already existing plugin.
The path must, at some point during the installation, be "registered" stored by WordPress. Where exactly does WordPress document this information, and is it easily accessible for the administrator?
|
Your function is unreliable and totally overboard and really really expensive. Furthermore, as already stated by @MarkKaplun, you are not calling `the_post()` which causes the `$post` global not to be updated to the current post being looped through, so the value from `get_post_meta()` will always have the same value.
Although `$post_id` might work, it is one of those crappy variables set globally that is actually used to get the comments. It is better to use `get_the_ID()` or even `$post->ID` as you are inside the loop. For extra info, read [this post](https://wordpress.stackexchange.com/a/112400/31545)
To solve your issue, I would just create a function with a custom SQL query to fetch all unique values from a specific meta key. Here is a function I have used on another answer
```
/**
* Description: Getting all the values associated with a specific custom post meta key, across all posts
* Author: Chinmoy Paul
* Author URL: http://pwdtechnology.com
*
* @param string $key Post Meta Key.
*
* @param string $type Post Type. Default is post. You can pass custom post type here.
*
* @param string $status Post Status like Publish, draft, future etc. default is publish
*
* @return array
*/
function get_unique_post_meta_values( $key = '', $type = 'post', $status = 'publish' )
{
global $wpdb;
if( empty( $key ) )
return;
$res = $wpdb->get_col(
$wpdb->prepare(
"SELECT DISTINCT pm.meta_value
FROM {$wpdb->postmeta} pm
LEFT JOIN {$wpdb->posts} p
ON p.ID = pm.post_id
WHERE pm.meta_key = '%s'
AND p.post_status = '%s'
AND p.post_type = '%s'",
$key,
$status,
$type
)
);
return $res;
}
```
You can then just use it as follow to get an array of unique meta value
```
$unique_values = get_unique_post_meta_values( 'json_id' );
?><pre><?php var_dump( $unique_values ); ?></pre><?php
```
You can also build in some cache/transient system into the function to optimize it even more
|
204,263 |
<p>i make a wordpress theme i make a grid structure show below
i have this grid structure </p>
<p><a href="https://i.stack.imgur.com/QOiNk.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QOiNk.jpg" alt="Grid Structure"></a></p>
<p>it contain two rows and every row has three column
i want to show my wordpress random posts in this grid </p>
<p>this is my code</p>
<pre><code> <div class="row">
<div class="col-xs-12">
<div class="rst-mediagrid">
<div class="div">
<?php $args = array(
'posts_per_page' => 6,
'offset' => 0,
'category' => '2',
'category_name' => '',
'orderby' => 'date',
'include' => '',
'exclude' => '',
'meta_key' => '',
'meta_value' => '',
'post_type' => 'post',
'post_mime_type' => '',
'post_parent' => '',
'author' => '',
'post_status' => 'publish',
'suppress_filters' => true
);
global $post;
$post = get_post($args);
$next_post = get_adjacent_post( true, '', false, 'taxonomy_slug' );
?>
<div class="rst-col rst-col-50">
<div class="rst-postpic">
<?php echo get_the_post_thumbnail($post->ID); //latest post thumbnail ?>
</div>
</div>
<?php //endif; ?>
<div class="rst-col rst-col-25">
<div class="rst-postpic rst-postvideo">
<?php echo get_the_post_thumbnail($next_post->ID); ?>
</div>
</div>
<div class="rst-col rst-col-25">
<div class="rst-postpic">
<?php echo get_the_post_thumbnail($next_post->ID); ?>
</div>
</div>
<div class="clear"></div>
</div>
<div class="div">
<div class="rst-col rst-col-25">
<div class="rst-postpic">
<?php echo get_the_post_thumbnail($next_post->ID); ?>
</div>
</div>
<div class="rst-col rst-col-25">
<div class="rst-postpic rst-postvideo">
<?php echo get_the_post_thumbnail($next_post->ID); ?>
</div>
</div>
<div class="rst-col rst-col-50">
<div class="rst-postpic">
<?php echo get_the_post_thumbnail($next_post->ID); ?>
</div>
</div>
<div class="clear"></div>
</div>
</div>
</div>
</div>
</code></pre>
<hr>
<p>the above code repeat the same image i want to show thumbnails in a perfact order like first row has three columns and first column has latest image second column has image of previous post and third column has image of previous of previous mean 3rd post from latest post and second row also has same things if you have better suggestion kindly tell me</p>
|
[
{
"answer_id": 204379,
"author": "Hafiz Usman aftab",
"author_id": 79858,
"author_profile": "https://wordpress.stackexchange.com/users/79858",
"pm_score": 0,
"selected": false,
"text": "<p>at last i found a solution of my question if some one else have same issue then use this </p>\n\n<pre><code><?php \n\nglobal $post;\n\n$loop = new WP_Query( array( 'posts_per_page' => 9,'orderby'=>rand) );\n$posts = array();\n\nwhile ( $loop->have_posts() ) : \n\n $items = array();\n\n $items['link']=wp_get_attachment_url( get_post_thumbnail_id( $post->ID ));\n $items['Image'] = get_the_post_thumbnail($loop->the_post());\n $items['LinkPost']=get_permalink($post->ID); \n $items['Title']=get_the_title($post->ID);\n $items['PostTime']=get_the_time('M d,Y', $post->ID);\n\n array_push($posts, $items);\n\nendwhile;\n\nfor($i = 1; $i< count($posts); $i++){\n ?>\n\n <?php\n\n if($i==1){\n ?>\n <div class=\"div\">\n <div class=\"rst-col rst-col-50\">\n <div class=\"rst-postpic\">\n <a href=\"<?php echo $posts[$i]['LinkPost']; ?>\">\n <img src=\"<?php echo $posts[$i+1]['link']; ?>\" alt=\"\" style=\"height: 385px;width: 770px\"/>\n </a>\n </div>\n <div class=\"rst-postinfo\">\n <a href=\"#\"><span>Sport</span></a>\n <h6><a href=\"<?php echo $posts[$i]['LinkPost']; ?>\"><?php echo $posts[$i]['Title']; ?></a></h6>\n <time><i class=\"fa fa-clock-o\"></i><?php echo $posts[$i]['PostTime']; ?></time>\n </div>\n </div>\n <?php //endif; ?>\n\n <div class=\"rst-col rst-col-25\">\n <div class=\"rst-postpic rst-postvideo\">\n <a href=\"<?php echo $posts[$i+1]['LinkPost']; ?>\">\n <img src=\"<?php echo $posts[$i+2]['link']; ?>\" alt=\"\" style=\"height: 385px;width: 770px\"/>\n </a>\n </div>\n <div class=\"rst-postinfo\">\n <a href=\"#\"><span>Sport</span></a>\n <h6><a href=\"<?php echo $posts[$i+1]['LinkPost']; ?>\"><?php echo $posts[$i+1]['Title']; ?></a></h6>\n <time><i class=\"fa fa-clock-o\"></i><?php echo $posts[$i+1]['PostTime']; ?></time>\n </div>\n </div>\n\n <div class=\"rst-col rst-col-25\">\n <div class=\"rst-postpic\">\n <a href=\"<?php echo $posts[$i+2]['LinkPost']; ?>\">\n <img src=\"<?php echo $posts[$i+3]['link']; ?>\" alt=\"\" style=\"height: 385px;width: 770px\"/>\n </a>\n </div>\n <div class=\"rst-postinfo\">\n <a href=\"#\"><span>Sport</span></a>\n <h6><a href=\"<?php echo $posts[$i+2]['LinkPost']; ?>\"><?php echo $posts[$i+2]['Title']; ?></a></h6>\n <time><i class=\"fa fa-clock-o\"></i><?php echo $posts[$i+2]['PostTime']; ?></time>\n </div>\n </div>\n\n <div class=\"clear\"></div>\n\n </div><!-- end first row-->\n <?php } //end if ?>\n\n <?php\n if ($i == 2 ) {\n ?>\n\n <div class=\"div\">\n <div class=\"rst-col rst-col-25\">\n <div class=\"rst-postpic\">\n <a href=\"<?php echo $posts[$i]['LinkPost']; ?>\">\n <img src=\"<?php echo $posts[$i+1]['link']; ?>\" alt=\"\" style=\"height: 385px;width: 770px\"/>\n </a>\n </div>\n <div class=\"rst-postinfo\">\n <a href=\"#\"><span>Sport</span></a>\n <h6><a href=\"<?php echo $posts[$i]['LinkPost']; ?>\"><?php echo $posts[$i]['Title']; ?></a></h6>\n <time><i class=\"fa fa-clock-o\"></i><?php echo $posts[$i]['PostTime']; ?></time>\n </div>\n </div>\n\n <div class=\"rst-col rst-col-25\">\n <div class=\"rst-postpic rst-postvideo\">\n <a href=\"<?php echo $posts[$i+1]['LinkPost']; ?>\">\n <img src=\"<?php echo $posts[$i+2]['link']; ?>\" alt=\"\" style=\"height: 385px;width: 770px\"/>\n </a>\n </div>\n <div class=\"rst-postinfo\">\n <a href=\"#\"><span>Sport</span></a>\n <h6><a href=\"<?php echo $posts[$i+1]['LinkPost']; ?>\"><?php echo $posts[$i+1]['Title']; ?></a></h6>\n <time><i class=\"fa fa-clock-o\"></i><?php echo $posts[$i+1]['PostTime']; ?></time>\n </div>\n </div>\n\n <div class=\"rst-col rst-col-50\">\n <div class=\"rst-postpic\">\n <a href=\"<?php echo $posts[$i+2]['LinkPost']; ?>\">\n <img src=\"<?php echo $posts[$i+3]['link']; ?>\" alt=\"\" style=\"height: 385px;width: 770px\"/>\n </a>\n </div>\n <div class=\"rst-postinfo\">\n <a href=\"#\"><span>Sport</span></a>\n <h6><a href=\"<?php echo $posts[$i+2]['LinkPost']; ?>\"><?php echo $posts[$i+2]['Title']; ?></a></h6>\n <time><i class=\"fa fa-clock-o\"></i><?php echo $posts[$i+2]['PostTime']; ?></time>\n </div>\n </div>\n\n <div class=\"clear\"></div>\n\n </div><!--end second row-->\n <?php\n\n }//end if\n\n}//end for loop ?>\n</code></pre>\n\n<p>if some have better suggestion kindly post you answer here and also any logical issue in my code then also tell me</p>\n"
},
{
"answer_id": 204404,
"author": "Webloper",
"author_id": 29035,
"author_profile": "https://wordpress.stackexchange.com/users/29035",
"pm_score": 3,
"selected": true,
"text": "<p>Here is the template layout and code for your original question. I am using <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_recent_posts\" rel=\"nofollow\">wp_get_recent_posts</a> as it gives me recent posts from the category as you wanted, if not change orderby to rand for random posts, as wp_get_recent_posts return posts by default in array form you can also have a choice to shuffle them. </p>\n\n<p>I checked your answer its not consistent and too much replication of codes as your first post uses <code>rst-postpic</code> and than <code>rst-postinfo</code> and so on, instead of this use post type or some meta field to determine the type of post and according to that print information about post.</p>\n\n<p>Hope it helps and gives you an idea to proceed further.</p>\n\n<p>Happy coding!</p>\n\n<pre><code><?php\n $args = array(\n 'numberposts' => 6,\n 'category' => 0,\n 'post_status' => 'publish',\n 'orderby' => 'post_date',\n );\n $recent_post = wp_get_recent_posts( $args );\n\n //shuffle( $recent_post ); // Just for randomness\n?>\n<div class=\"row\">\n <div class=\"col-xs-12\">\n <div class=\"rst-mediagrid\">\n <?php\n foreach ($recent_post as $key => $value) {\n $class_col_50 = $key == 0 || $key == count( $recent_post ) - 1 ? ' rst-col-50' : ' rst-col-25';\n $class_col_video = $key % 3 == 1 ? ' rst-postvideo' : '';\n\n if ( $key % 3 === 0 )\n echo '<div class=\"div\">';\n\n echo \"<div class='rst-col$class'>\";\n echo \"<div class='rst-postpic$class_col_video'>\";\n echo $value['ID'], ' ';\n echo '</div>';\n echo '</div>';\n\n if ( $key % 3 === 2 )\n echo '<div class=\"clear\"></div></div>';\n }\n ?>\n </div>\n </div>\n</div>\n</code></pre>\n"
}
] |
2015/10/01
|
[
"https://wordpress.stackexchange.com/questions/204263",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/79858/"
] |
i make a wordpress theme i make a grid structure show below
i have this grid structure
[](https://i.stack.imgur.com/QOiNk.jpg)
it contain two rows and every row has three column
i want to show my wordpress random posts in this grid
this is my code
```
<div class="row">
<div class="col-xs-12">
<div class="rst-mediagrid">
<div class="div">
<?php $args = array(
'posts_per_page' => 6,
'offset' => 0,
'category' => '2',
'category_name' => '',
'orderby' => 'date',
'include' => '',
'exclude' => '',
'meta_key' => '',
'meta_value' => '',
'post_type' => 'post',
'post_mime_type' => '',
'post_parent' => '',
'author' => '',
'post_status' => 'publish',
'suppress_filters' => true
);
global $post;
$post = get_post($args);
$next_post = get_adjacent_post( true, '', false, 'taxonomy_slug' );
?>
<div class="rst-col rst-col-50">
<div class="rst-postpic">
<?php echo get_the_post_thumbnail($post->ID); //latest post thumbnail ?>
</div>
</div>
<?php //endif; ?>
<div class="rst-col rst-col-25">
<div class="rst-postpic rst-postvideo">
<?php echo get_the_post_thumbnail($next_post->ID); ?>
</div>
</div>
<div class="rst-col rst-col-25">
<div class="rst-postpic">
<?php echo get_the_post_thumbnail($next_post->ID); ?>
</div>
</div>
<div class="clear"></div>
</div>
<div class="div">
<div class="rst-col rst-col-25">
<div class="rst-postpic">
<?php echo get_the_post_thumbnail($next_post->ID); ?>
</div>
</div>
<div class="rst-col rst-col-25">
<div class="rst-postpic rst-postvideo">
<?php echo get_the_post_thumbnail($next_post->ID); ?>
</div>
</div>
<div class="rst-col rst-col-50">
<div class="rst-postpic">
<?php echo get_the_post_thumbnail($next_post->ID); ?>
</div>
</div>
<div class="clear"></div>
</div>
</div>
</div>
</div>
```
---
the above code repeat the same image i want to show thumbnails in a perfact order like first row has three columns and first column has latest image second column has image of previous post and third column has image of previous of previous mean 3rd post from latest post and second row also has same things if you have better suggestion kindly tell me
|
Here is the template layout and code for your original question. I am using [wp\_get\_recent\_posts](https://codex.wordpress.org/Function_Reference/wp_get_recent_posts) as it gives me recent posts from the category as you wanted, if not change orderby to rand for random posts, as wp\_get\_recent\_posts return posts by default in array form you can also have a choice to shuffle them.
I checked your answer its not consistent and too much replication of codes as your first post uses `rst-postpic` and than `rst-postinfo` and so on, instead of this use post type or some meta field to determine the type of post and according to that print information about post.
Hope it helps and gives you an idea to proceed further.
Happy coding!
```
<?php
$args = array(
'numberposts' => 6,
'category' => 0,
'post_status' => 'publish',
'orderby' => 'post_date',
);
$recent_post = wp_get_recent_posts( $args );
//shuffle( $recent_post ); // Just for randomness
?>
<div class="row">
<div class="col-xs-12">
<div class="rst-mediagrid">
<?php
foreach ($recent_post as $key => $value) {
$class_col_50 = $key == 0 || $key == count( $recent_post ) - 1 ? ' rst-col-50' : ' rst-col-25';
$class_col_video = $key % 3 == 1 ? ' rst-postvideo' : '';
if ( $key % 3 === 0 )
echo '<div class="div">';
echo "<div class='rst-col$class'>";
echo "<div class='rst-postpic$class_col_video'>";
echo $value['ID'], ' ';
echo '</div>';
echo '</div>';
if ( $key % 3 === 2 )
echo '<div class="clear"></div></div>';
}
?>
</div>
</div>
</div>
```
|
204,265 |
<p>I'm exhaustively searching for a method to provide <strong>Next and Previous Post Links</strong> in a different way from which it usually appears in <strong>Single Post</strong>.</p>
<p><strong>By DEFAULT it:</strong></p>
<ul>
<li><p>Is chronological ordered</p></li>
<li><p>Links to posts from all blog categories</p></li>
</ul>
<p><strong>But I NEED it:</strong></p>
<ul>
<li><p>ALPHABETICALLY ordered</p></li>
<li><p>Linking to posts on SAME CATEGORY only</p></li>
</ul>
<p>I'm not a developer but I think if I could merge the two codes below the problem would be solved.</p>
<p><strong>CODE 1</strong> - Turn Next/Prev links alphabetcally, but not from same category (<a href="https://wordpress.stackexchange.com/questions/166932/how-to-get-next-and-previous-post-links-alphabetically-by-title-across-post-ty">source</a>)</p>
<pre><code>function filter_next_post_sort($sort) {
$sort = "ORDER BY p.post_title ASC LIMIT 1";
return $sort;
}
function filter_next_post_where($where) {
global $post, $wpdb;
return $wpdb->prepare("WHERE p.post_title > '%s' AND p.post_type = '". get_post_type($post)."' AND p.post_status = 'publish'",$post->post_title);
}
function filter_previous_post_sort($sort) {
$sort = "ORDER BY p.post_title DESC LIMIT 1";
return $sort;
}
function filter_previous_post_where($where) {
global $post, $wpdb;
return $wpdb->prepare("WHERE p.post_title < '%s' AND p.post_type = '". get_post_type($post)."' AND p.post_status = 'publish'",$post->post_title);
}
add_filter('get_next_post_sort', 'filter_next_post_sort');
add_filter('get_next_post_where', 'filter_next_post_where');
add_filter('get_previous_post_sort', 'filter_previous_post_sort');
add_filter('get_previous_post_where', 'filter_previous_post_where');
</code></pre>
<p><strong>CODE 2</strong> - Turn Next/Prev links from same category, but not alphabetically (<a href="http://presscustomizr.com/snippet/restrict-post-navigation-category/" rel="nofollow noreferrer">source</a>)</p>
<pre><code>add_filter( 'get_next_post_join', 'navigate_in_same_taxonomy_join', 20);
add_filter( 'get_previous_post_join', 'navigate_in_same_taxonomy_join', 20 );
function navigate_in_same_taxonomy_join() {
global $wpdb;
return " INNER JOIN $wpdb->term_relationships AS tr ON p.ID = tr.object_id INNER JOIN $wpdb->term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id";
}
add_filter( 'get_next_post_where' , 'navigate_in_same_taxonomy_where' );
add_filter( 'get_previous_post_where' , 'navigate_in_same_taxonomy_where' );
function navigate_in_same_taxonomy_where( $original ) {
global $wpdb, $post;
$where = '';
$taxonomy = 'category';
$op = ('get_previous_post_where' == current_filter()) ? '<' : '>';
$where = $wpdb->prepare( "AND tt.taxonomy = %s", $taxonomy );
if ( ! is_object_in_taxonomy( $post->post_type, $taxonomy ) )
return $original ;
$term_array = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) );
$term_array = array_map( 'intval', $term_array );
if ( ! $term_array || is_wp_error( $term_array ) )
return $original ;
$where = " AND tt.term_id IN (" . implode( ',', $term_array ) . ")";
return $wpdb->prepare( "WHERE p.post_date $op %s AND p.post_type = %s AND p.post_status = 'publish' $where", $post->post_date, $post->post_type );
}
</code></pre>
<p><strong>THANK YOU FOR HELP ME!</strong></p>
|
[
{
"answer_id": 204270,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 4,
"selected": true,
"text": "<p>To get next/prev posts, usually all you need is to se to <code>true</code> the parameter that indicates that next/prev post should be in the same taxonomy term in the get next/prev post functions, you don't need to deal with any filter.</p>\n\n<p>For example:</p>\n\n<p>To get next and prev post objects:</p>\n\n<pre><code>// First parameter for these functions indicates\n// if next/prev post should be in the same taxonomy term\n// More in https://codex.wordpress.org/Function_Reference/get_next_post\n// And https://codex.wordpress.org/Function_Reference/get_previous_post\n$prev_post = get_previous_post(true);\n$next_post = get_next_post(true);\n</code></pre>\n\n<p>To print prev/next post links:</p>\n\n<pre><code>// Third parameter for these functions indicates\n// if next/prev post should be in the same taxonomy term\n// More in https://codex.wordpress.org/Template_Tags/next_post_link\n// And https://codex.wordpress.org/Template_Tags/previous_post_link\nprevious_post_link( '&laquo; %link', '%title', true );\nnext_post_link( '%link &raquo;', '%title', true );\n</code></pre>\n\n<p>The problem is that, when you filter the where statement to change the order, you change the same taxonomy part, so you need to rebuilt it.</p>\n\n<p>This code should work (I've not tested it):</p>\n\n<pre><code>add_filter('get_next_post_sort', 'filter_next_and_prev_post_sort');\nadd_filter('get_previous_post_sort', 'filter_next_and_prev_post_sort');\nfunction filter_next_and_prev_post_sort($sort) {\n $op = ('get_previous_post_sort' == current_filter()) ? 'DESC' : 'ASC';\n $sort = \"ORDER BY p.post_title \".$op .\" LIMIT 1\";\n return $sort;\n\n}\n\nadd_filter( 'get_next_post_join', 'navigate_in_same_taxonomy_join', 20);\nadd_filter( 'get_previous_post_join', 'navigate_in_same_taxonomy_join', 20 );\nfunction navigate_in_same_taxonomy_join() {\n global $wpdb;\n return \" INNER JOIN $wpdb->term_relationships AS tr ON p.ID = tr.object_id INNER JOIN $wpdb->term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id\";\n}\n\nadd_filter( 'get_next_post_where' , 'filter_next_and_prev_post_where' );\nadd_filter( 'get_previous_post_where' , 'filter_next_and_prev_post_where' );\nfunction filter_next_and_prev_post_where( $original ) {\n global $wpdb, $post;\n $where = '';\n $taxonomy = 'category';\n $op = ('get_previous_post_where' == current_filter()) ? '<' : '>';\n\n if ( ! is_object_in_taxonomy( $post->post_type, $taxonomy ) ) {\n return $original ;\n }\n\n $term_array = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) );\n\n $term_array = array_map( 'intval', $term_array );\n\n if ( ! $term_array || is_wp_error( $term_array ) ) {\n return $original;\n }\n $where = \" AND tt.term_id IN (\" . implode( ',', $term_array ) . \")\";\n return $wpdb->prepare( \"WHERE p.post_title $op %s AND p.post_type = %s AND p.post_status = 'publish' $where\", $post->post_title, $post->post_type );\n}\n</code></pre>\n"
},
{
"answer_id": 368287,
"author": "piskedi",
"author_id": 71151,
"author_profile": "https://wordpress.stackexchange.com/users/71151",
"pm_score": 0,
"selected": false,
"text": "<p>Adapted for custom post type category worked flawlessly.</p>\n\n<p>My question is to run this filter only on certain pages. how can i add one.</p>\n\n<p>add if (! is_singular ('portfolio')) </p>\n\n<pre><code>add_filter( 'get_next_post_join', 'results_navigate_in_same_taxonomy_join', 20);\nadd_filter( 'get_previous_post_join', 'results_navigate_in_same_taxonomy_join', 20 );\nfunction results_navigate_in_same_taxonomy_join() {\nglobal $wpdb;\nreturn \"INNER JOIN $wpdb->term_relationships AS tr ON p.ID = tr.object_id INNER JOIN $wpdb->term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id\";\n}\n\nadd_filter( 'get_next_post_where' , 'results_navigate_in_same_taxonomy_where' );\nadd_filter( 'get_previous_post_where' , 'results_navigate_in_same_taxonomy_where' );\nfunction results_navigate_in_same_taxonomy_where( $original ) {\n global $wpdb, $post;\n $where = '';\n $taxonomy = 'portfolio_category';\n $op = ('get_previous_post_where' == current_filter()) ? '<' : '>';\n $where = $wpdb->prepare( \"AND tt.taxonomy = %s\", $taxonomy );\n if ( ! is_object_in_taxonomy( $post->post_type, $taxonomy ) )\n return $original ;\n\n $term_array = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) );\n $term_array = array_map( 'intval', $term_array );\n\n if ( ! $term_array || is_wp_error( $term_array ) )\n return $original ;\n\n $where = \" AND tt.term_id IN (\" . implode( ',', $term_array ) . \")\";\n return $wpdb->prepare( \"WHERE p.post_date $op %s AND p.post_type = %s AND p.post_status = 'publish' $where\", $post->post_date, $post->post_type );\n}\n</code></pre>\n"
}
] |
2015/10/01
|
[
"https://wordpress.stackexchange.com/questions/204265",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81268/"
] |
I'm exhaustively searching for a method to provide **Next and Previous Post Links** in a different way from which it usually appears in **Single Post**.
**By DEFAULT it:**
* Is chronological ordered
* Links to posts from all blog categories
**But I NEED it:**
* ALPHABETICALLY ordered
* Linking to posts on SAME CATEGORY only
I'm not a developer but I think if I could merge the two codes below the problem would be solved.
**CODE 1** - Turn Next/Prev links alphabetcally, but not from same category ([source](https://wordpress.stackexchange.com/questions/166932/how-to-get-next-and-previous-post-links-alphabetically-by-title-across-post-ty))
```
function filter_next_post_sort($sort) {
$sort = "ORDER BY p.post_title ASC LIMIT 1";
return $sort;
}
function filter_next_post_where($where) {
global $post, $wpdb;
return $wpdb->prepare("WHERE p.post_title > '%s' AND p.post_type = '". get_post_type($post)."' AND p.post_status = 'publish'",$post->post_title);
}
function filter_previous_post_sort($sort) {
$sort = "ORDER BY p.post_title DESC LIMIT 1";
return $sort;
}
function filter_previous_post_where($where) {
global $post, $wpdb;
return $wpdb->prepare("WHERE p.post_title < '%s' AND p.post_type = '". get_post_type($post)."' AND p.post_status = 'publish'",$post->post_title);
}
add_filter('get_next_post_sort', 'filter_next_post_sort');
add_filter('get_next_post_where', 'filter_next_post_where');
add_filter('get_previous_post_sort', 'filter_previous_post_sort');
add_filter('get_previous_post_where', 'filter_previous_post_where');
```
**CODE 2** - Turn Next/Prev links from same category, but not alphabetically ([source](http://presscustomizr.com/snippet/restrict-post-navigation-category/))
```
add_filter( 'get_next_post_join', 'navigate_in_same_taxonomy_join', 20);
add_filter( 'get_previous_post_join', 'navigate_in_same_taxonomy_join', 20 );
function navigate_in_same_taxonomy_join() {
global $wpdb;
return " INNER JOIN $wpdb->term_relationships AS tr ON p.ID = tr.object_id INNER JOIN $wpdb->term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id";
}
add_filter( 'get_next_post_where' , 'navigate_in_same_taxonomy_where' );
add_filter( 'get_previous_post_where' , 'navigate_in_same_taxonomy_where' );
function navigate_in_same_taxonomy_where( $original ) {
global $wpdb, $post;
$where = '';
$taxonomy = 'category';
$op = ('get_previous_post_where' == current_filter()) ? '<' : '>';
$where = $wpdb->prepare( "AND tt.taxonomy = %s", $taxonomy );
if ( ! is_object_in_taxonomy( $post->post_type, $taxonomy ) )
return $original ;
$term_array = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) );
$term_array = array_map( 'intval', $term_array );
if ( ! $term_array || is_wp_error( $term_array ) )
return $original ;
$where = " AND tt.term_id IN (" . implode( ',', $term_array ) . ")";
return $wpdb->prepare( "WHERE p.post_date $op %s AND p.post_type = %s AND p.post_status = 'publish' $where", $post->post_date, $post->post_type );
}
```
**THANK YOU FOR HELP ME!**
|
To get next/prev posts, usually all you need is to se to `true` the parameter that indicates that next/prev post should be in the same taxonomy term in the get next/prev post functions, you don't need to deal with any filter.
For example:
To get next and prev post objects:
```
// First parameter for these functions indicates
// if next/prev post should be in the same taxonomy term
// More in https://codex.wordpress.org/Function_Reference/get_next_post
// And https://codex.wordpress.org/Function_Reference/get_previous_post
$prev_post = get_previous_post(true);
$next_post = get_next_post(true);
```
To print prev/next post links:
```
// Third parameter for these functions indicates
// if next/prev post should be in the same taxonomy term
// More in https://codex.wordpress.org/Template_Tags/next_post_link
// And https://codex.wordpress.org/Template_Tags/previous_post_link
previous_post_link( '« %link', '%title', true );
next_post_link( '%link »', '%title', true );
```
The problem is that, when you filter the where statement to change the order, you change the same taxonomy part, so you need to rebuilt it.
This code should work (I've not tested it):
```
add_filter('get_next_post_sort', 'filter_next_and_prev_post_sort');
add_filter('get_previous_post_sort', 'filter_next_and_prev_post_sort');
function filter_next_and_prev_post_sort($sort) {
$op = ('get_previous_post_sort' == current_filter()) ? 'DESC' : 'ASC';
$sort = "ORDER BY p.post_title ".$op ." LIMIT 1";
return $sort;
}
add_filter( 'get_next_post_join', 'navigate_in_same_taxonomy_join', 20);
add_filter( 'get_previous_post_join', 'navigate_in_same_taxonomy_join', 20 );
function navigate_in_same_taxonomy_join() {
global $wpdb;
return " INNER JOIN $wpdb->term_relationships AS tr ON p.ID = tr.object_id INNER JOIN $wpdb->term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id";
}
add_filter( 'get_next_post_where' , 'filter_next_and_prev_post_where' );
add_filter( 'get_previous_post_where' , 'filter_next_and_prev_post_where' );
function filter_next_and_prev_post_where( $original ) {
global $wpdb, $post;
$where = '';
$taxonomy = 'category';
$op = ('get_previous_post_where' == current_filter()) ? '<' : '>';
if ( ! is_object_in_taxonomy( $post->post_type, $taxonomy ) ) {
return $original ;
}
$term_array = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) );
$term_array = array_map( 'intval', $term_array );
if ( ! $term_array || is_wp_error( $term_array ) ) {
return $original;
}
$where = " AND tt.term_id IN (" . implode( ',', $term_array ) . ")";
return $wpdb->prepare( "WHERE p.post_title $op %s AND p.post_type = %s AND p.post_status = 'publish' $where", $post->post_title, $post->post_type );
}
```
|
204,281 |
<p>I have created a custom post type called <code>Event</code> and I have enabled support for featured images in my <code>functions.php</code> file, but still my custom user role can not see the featured image meta box on the edit page for an event. If a user logges in as administrator the <code>Featured Image</code> meta box is displayed without any errors.</p>
<p>Here is my code to register the CPT:</p>
<pre><code>add_action('init', 'event_post_init');
function event_post_init() {
// array of all capabilities for our CPT
$capabilities = array(
'publish_posts' => 'publish_events',
'edit_posts' => 'edit_events',
'edit_others_posts' => 'edit_others_events',
'delete_posts' => 'delete_events',
'delete_published_posts' => 'delete_published_events',
'delete_others_posts' => 'delete_others_events',
'read_private_posts' => 'read_private_events',
'edit_post' => 'edit_event',
'delete_post' => 'delete_event',
'read_post' => 'read_event',
);
// register the CPT
register_post_type( 'event',
array(
'labels' => array(
'name' => __('Event')
),
'public' => true,
'has_archive' => true,
'show_ui' => true,
'menu_position' => 8,
'capability_type' => array('event', 'events'),
'capabilities' => $capabilities,
'supports' => array('title', 'thumbnail', 'page-attributes'),
'map_meta_cap' => true,
'hierarchical' => true,
)
);
}
</code></pre>
<p>and here is how I setup my custom user role:</p>
<pre><code>function create_event_admin_role(){
add_role('event_admin', 'Event Administrator', array(
'publish_events' => false,
'edit_events' => true,
'edit_others_events' => false,
'delete_events' => false,
'delete_others_events' => false,
'read_private_events' => true,
'edit_published_events' => true,
'read' => true,
'assign_terms' => true,
'edit_terms' => true,
'manage_terms' => true,
'read_private_pages' => true
)
);
}
</code></pre>
<p>The strange thing is that if I look at the markup for the edit page I can see the <code>#postimagediv</code> element but for some reason it is hidden. Here is the markup in the page:</p>
<pre><code><div class="postbox hide-if-js" id="postimagediv" style="">
<div title="Click to toggle" class="handlediv"><br></div>
<h3 class="hndle ui-sortable-handle"><span>Featured Image</span></h3>
<div class="inside">
<p class="hide-if-no-js">
<a class="thickbox" id="set-post-thumbnail" href="http://example.com/wp-admin/media-upload.php?post_id=662&amp;type=image&amp;TB_iframe=1&amp;width=753&amp;height=294" title="Set featured image">Set featured image</a>
</p>
</div>
</div>
</code></pre>
<p>and the css that actually hides the meta box:</p>
<pre><code>#postimagediv {
display: hidden !important;
}
</code></pre>
<p>Notice that I <strong>have</strong> enabled <code>Featured Image</code> under <code>Screen Options</code>.</p>
<p>Perhaps I also should point out that I have tried giving the above role the <code>upload_files</code> privilege using the following code:</p>
<pre><code>function extend_event_admin_role() {
$role = get_role('event_admin');
$role->add_cap('upload_files');
}
</code></pre>
<p>Another thing to point out is that if I <strong>do</strong> add the <code>upload_files</code> permission, then <code>Featured Image</code> is visible under <code>Screen Options</code> and also other meta boxes which has support for media has a <code>Add Media</code> button, which if I set <code>upload_files</code> to <code>false</code> disappears.</p>
<p><a href="https://i.stack.imgur.com/2xRNI.png" rel="noreferrer"><img src="https://i.stack.imgur.com/2xRNI.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/hzdZq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/hzdZq.png" alt="enter image description here"></a></p>
<p>If I change the code in <code>wp-admin/edit-form-advanced.php</code> which add the featured image metabox then I can tell that it's really calling <code>add_metabox()</code>:</p>
<pre><code>if ( $thumbnail_support && current_user_can( 'upload_files' ) ):
add_meta_box('postimagediv', __('Featured Image'), 'post_thumbnail_meta_box', null, 'side', 'low');
print 'Support for Featured Image';
exit;
endif;
</code></pre>
|
[
{
"answer_id": 204538,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<p>Users that are only assigned to your <code>event_admin</code> role, don't have the <code>upload_files</code> capability, needed to display the <em>featured image</em> meta box.</p>\n\n<p>Here's the relevant code from the core:</p>\n\n<pre><code>if ( $thumbnail_support && current_user_can( 'upload_files' ) ) // <-- Notice this check\n add_meta_box( \n 'postimagediv', \n esc_html( $post_type_object->labels->featured_image ), \n 'post_thumbnail_meta_box', \n null, \n 'side', \n 'low'\n );\n</code></pre>\n\n<p>Note that if you later try to add the option:</p>\n\n<pre><code>'upload_files' => true\n</code></pre>\n\n<p>to your <code>add_role()</code> setup, it might not update, since it's cached in the <code>wp_user_roles</code> option.</p>\n\n<p>You therefore need to update the database to adjust it:</p>\n\n<ul>\n<li>use <a href=\"https://codex.wordpress.org/Function_Reference/remove_role\" rel=\"nofollow\"><code>remove_role()</code></a> and then <code>add_role()</code> again, </li>\n<li>use the <a href=\"https://codex.wordpress.org/Function_Reference/add_cap\" rel=\"nofollow\"><code>add_cap()</code></a> method of the <code>\\WP_Role</code> class.</li>\n</ul>\n\n<p>It might also be possible to use filters like <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/user_has_cap\" rel=\"nofollow\"><code>user_has_cap</code></a> to adjust this dynamically.</p>\n"
},
{
"answer_id": 204547,
"author": "Webloper",
"author_id": 29035,
"author_profile": "https://wordpress.stackexchange.com/users/29035",
"pm_score": 1,
"selected": false,
"text": "<p>As per my understanding you need a custom-post type <code>Event</code> + <code>featured_image</code> + <code>Custom Role</code>, what I don't understand is capability_type event and events unless and until you are customizing to much, whats the reason here for such customization?</p>\n\n<p>What I did here is cloned editor role to <code>event_amdin</code> with all its capabilities and make capability_type to page as you are using page-attributes in your question.</p>\n\n<p>Test: Created two users <em>test</em> as <em>contributor</em> and <em>cyclone</em> as <em>Event Administrator</em> and its working fine. Please provide more information about your need so I update this answer. Thanks!</p>\n\n<p><strong>Edit 1</strong> : Updated code, check edit 1 start/end section into <code>cloneUserRole</code> function. </p>\n\n<p>Happy Coding!!</p>\n\n<pre><code>function cloneUserRole()\n{\n global $wp_roles;\n\n if (!isset($wp_roles))\n $wp_roles = new WP_Roles();\n\n $editor = $wp_roles->get_role('editor');\n // Adding a new role with all editor caps.\n $wp_roles->add_role('event_admin', 'Event Administrator', $editor->capabilities);\n\n // edit 1 start : updated to add cap to new user role\n $event_admin = $wp_roles->get_role('event_admin');\n\n $event_admin->add_cap( 'read_event' );\n $event_admin->add_cap( 'delete_event' );\n $event_admin->add_cap( 'edit_event' );\n $event_admin->add_cap( 'read_private_events' );\n $event_admin->add_cap( 'delete_others_events' ); // don't add\n $event_admin->add_cap( 'delete_published_events' );\n $event_admin->add_cap( 'delete_events' ); // don't add\n $event_admin->add_cap( 'edit_others_events' ); // don't add\n $event_admin->add_cap( 'edit_events' );\n $event_admin->add_cap( 'publish_events' ); // don't add\n // edit 1 ends : \n\n //echo '<pre>', print_r( $wp_roles, 1), '</pre>';\n //die;\n}\nadd_action('init', 'cloneUserRole');\n\n\nfunction stack_event_init() {\n $labels = array(\n 'name' => _x( 'Events', 'post type general name', 'stack' ),\n 'singular_name' => _x( 'Event', 'post type singular name', 'stack' ),\n 'menu_name' => _x( 'Events', 'admin menu', 'stack' ),\n 'name_admin_bar' => _x( 'Event', 'add new on admin bar', 'stack' ),\n 'add_new' => _x( 'Add New', 'event', 'stack' ),\n 'add_new_item' => __( 'Add New Event', 'stack' ),\n 'new_item' => __( 'New Event', 'stack' ),\n 'edit_item' => __( 'Edit Event', 'stack' ),\n 'view_item' => __( 'View Event', 'stack' ),\n 'all_items' => __( 'All Events', 'stack' ),\n 'search_items' => __( 'Search Events', 'stack' ),\n 'parent_item_colon' => __( 'Parent Events:', 'stack' ),\n 'not_found' => __( 'No events found.', 'stack' ),\n 'not_found_in_trash' => __( 'No events found in Trash.', 'stack' )\n );\n\n $args = array(\n 'labels' => $labels,\n 'description' => __( 'Description.', 'stack' ),\n 'public' => true,\n 'publicly_queryable' => true,\n 'show_ui' => true,\n 'show_in_nav_menus' => true,\n 'show_in_menu' => true,\n 'show_in_admin_bar' => true,\n 'query_var' => true,\n 'rewrite' => array( 'slug' => 'event' ),\n 'capability_type' => 'page',\n 'has_archive' => true,\n 'hierarchical' => true,\n 'menu_position' => null,\n 'supports' => array( 'title', 'thumbnail', 'page-attributes' )\n );\n\n register_post_type( 'event', $args );\n}\nadd_action('init', 'stack_event_init');\n\nfunction my_rewrite_flush() {\n stack_event_init();\n flush_rewrite_rules();\n}\nadd_action( 'after_switch_theme', 'my_rewrite_flush' );\n</code></pre>\n\n<ol>\n<li><a href=\"https://codex.wordpress.org/Roles_and_Capabilities\" rel=\"nofollow\">Roles and Capabilities</a></li>\n<li><a href=\"https://codex.wordpress.org/Function_Reference/register_post_type\" rel=\"nofollow\">Register post type</a></li>\n<li><a href=\"https://codex.wordpress.org/Function_Reference/register_post_type#Flushing_Rewrite_on_Activation\" rel=\"nofollow\">Flush Rewrite Rules</a></li>\n</ol>\n"
},
{
"answer_id": 204601,
"author": "Cyclonecode",
"author_id": 14870,
"author_profile": "https://wordpress.stackexchange.com/users/14870",
"pm_score": 2,
"selected": true,
"text": "<p>I finally tracked the problem down to an activated plugin called <a href=\"https://sv.wordpress.org/plugins/revisionary/\" rel=\"nofollow\"><code>Revisionary</code></a>. The function that is responsible for hiding the <code>postimagediv</code> element is <code>act_hide_admin_divs</code> located in <code>revisionary/admin/admin_rvy.php</code>. What the function does is to hide metaboxes with content that doesn't support revisions. </p>\n\n<p>In order to show the featured image for my specific role I used the <code>rvy_hidden_meta_boxes</code> filter:</p>\n\n<pre><code>add_filter('rvy_hidden_meta_boxes', 'revisor_show_featured_image_box');\n\nfunction revisor_show_featured_image_box($unrevisable_css_ids) {\n $key = array_search('postimagediv', $unrevisable_css_ids, true);\n unset($unrevisable_css_ids[$key]);\n\n return $unrevisable_css_ids;\n}\n</code></pre>\n"
}
] |
2015/10/01
|
[
"https://wordpress.stackexchange.com/questions/204281",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/14870/"
] |
I have created a custom post type called `Event` and I have enabled support for featured images in my `functions.php` file, but still my custom user role can not see the featured image meta box on the edit page for an event. If a user logges in as administrator the `Featured Image` meta box is displayed without any errors.
Here is my code to register the CPT:
```
add_action('init', 'event_post_init');
function event_post_init() {
// array of all capabilities for our CPT
$capabilities = array(
'publish_posts' => 'publish_events',
'edit_posts' => 'edit_events',
'edit_others_posts' => 'edit_others_events',
'delete_posts' => 'delete_events',
'delete_published_posts' => 'delete_published_events',
'delete_others_posts' => 'delete_others_events',
'read_private_posts' => 'read_private_events',
'edit_post' => 'edit_event',
'delete_post' => 'delete_event',
'read_post' => 'read_event',
);
// register the CPT
register_post_type( 'event',
array(
'labels' => array(
'name' => __('Event')
),
'public' => true,
'has_archive' => true,
'show_ui' => true,
'menu_position' => 8,
'capability_type' => array('event', 'events'),
'capabilities' => $capabilities,
'supports' => array('title', 'thumbnail', 'page-attributes'),
'map_meta_cap' => true,
'hierarchical' => true,
)
);
}
```
and here is how I setup my custom user role:
```
function create_event_admin_role(){
add_role('event_admin', 'Event Administrator', array(
'publish_events' => false,
'edit_events' => true,
'edit_others_events' => false,
'delete_events' => false,
'delete_others_events' => false,
'read_private_events' => true,
'edit_published_events' => true,
'read' => true,
'assign_terms' => true,
'edit_terms' => true,
'manage_terms' => true,
'read_private_pages' => true
)
);
}
```
The strange thing is that if I look at the markup for the edit page I can see the `#postimagediv` element but for some reason it is hidden. Here is the markup in the page:
```
<div class="postbox hide-if-js" id="postimagediv" style="">
<div title="Click to toggle" class="handlediv"><br></div>
<h3 class="hndle ui-sortable-handle"><span>Featured Image</span></h3>
<div class="inside">
<p class="hide-if-no-js">
<a class="thickbox" id="set-post-thumbnail" href="http://example.com/wp-admin/media-upload.php?post_id=662&type=image&TB_iframe=1&width=753&height=294" title="Set featured image">Set featured image</a>
</p>
</div>
</div>
```
and the css that actually hides the meta box:
```
#postimagediv {
display: hidden !important;
}
```
Notice that I **have** enabled `Featured Image` under `Screen Options`.
Perhaps I also should point out that I have tried giving the above role the `upload_files` privilege using the following code:
```
function extend_event_admin_role() {
$role = get_role('event_admin');
$role->add_cap('upload_files');
}
```
Another thing to point out is that if I **do** add the `upload_files` permission, then `Featured Image` is visible under `Screen Options` and also other meta boxes which has support for media has a `Add Media` button, which if I set `upload_files` to `false` disappears.
[](https://i.stack.imgur.com/2xRNI.png)
[](https://i.stack.imgur.com/hzdZq.png)
If I change the code in `wp-admin/edit-form-advanced.php` which add the featured image metabox then I can tell that it's really calling `add_metabox()`:
```
if ( $thumbnail_support && current_user_can( 'upload_files' ) ):
add_meta_box('postimagediv', __('Featured Image'), 'post_thumbnail_meta_box', null, 'side', 'low');
print 'Support for Featured Image';
exit;
endif;
```
|
I finally tracked the problem down to an activated plugin called [`Revisionary`](https://sv.wordpress.org/plugins/revisionary/). The function that is responsible for hiding the `postimagediv` element is `act_hide_admin_divs` located in `revisionary/admin/admin_rvy.php`. What the function does is to hide metaboxes with content that doesn't support revisions.
In order to show the featured image for my specific role I used the `rvy_hidden_meta_boxes` filter:
```
add_filter('rvy_hidden_meta_boxes', 'revisor_show_featured_image_box');
function revisor_show_featured_image_box($unrevisable_css_ids) {
$key = array_search('postimagediv', $unrevisable_css_ids, true);
unset($unrevisable_css_ids[$key]);
return $unrevisable_css_ids;
}
```
|
204,295 |
<p>How can I get the Title of a Home Page to appear?</p>
<p>I am using the Quark "out-of-the-box" <strong>Front Page Template</strong>.</p>
<p>Home Page "view source":</p>
<pre><code><article id="post-1" class="post-1 page type-page status-publish hentry">
<div class="entry-content">
</code></pre>
<p>Inner Page "view source":</p>
<pre><code><article id="post-2" class="post-2 page type-page status-publish hentry">
<header class="entry-header">
<h1 class="entry-title">Inner Page</h1>
</header>
<div class="entry-content">
</code></pre>
|
[
{
"answer_id": 204304,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>To return the name of your page, simply:</p>\n\n<pre><code><header class=\"entry-header\">\n <h1 class=\"entry-title\"><?php echo get_the_title( $ID ); ?></h1>\n</header>\n</code></pre>\n\n<p>Ref: <a href=\"https://codex.wordpress.org/Function_Reference/get_the_title\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/get_the_title</a></p>\n"
},
{
"answer_id": 301293,
"author": "d79",
"author_id": 69071,
"author_profile": "https://wordpress.stackexchange.com/users/69071",
"pm_score": 1,
"selected": false,
"text": "<pre><code>$id_frontpage = get_option('page_on_front');\necho get_the_title( $id_frontpage );\n</code></pre>\n\n<p>If you need the ID of the page that displays posts use <code>get_option('page_for_posts')</code>.</p>\n"
}
] |
2015/10/01
|
[
"https://wordpress.stackexchange.com/questions/204295",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/62808/"
] |
How can I get the Title of a Home Page to appear?
I am using the Quark "out-of-the-box" **Front Page Template**.
Home Page "view source":
```
<article id="post-1" class="post-1 page type-page status-publish hentry">
<div class="entry-content">
```
Inner Page "view source":
```
<article id="post-2" class="post-2 page type-page status-publish hentry">
<header class="entry-header">
<h1 class="entry-title">Inner Page</h1>
</header>
<div class="entry-content">
```
|
```
$id_frontpage = get_option('page_on_front');
echo get_the_title( $id_frontpage );
```
If you need the ID of the page that displays posts use `get_option('page_for_posts')`.
|
204,306 |
<p>I need to change the product position of an addon called "misura anello" in the products (i use product add-ons plugin), i want to place it above the price, like the attributes...</p>
<p>i post to attach to images...</p>
<p><a href="https://i.stack.imgur.com/0QGmu.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0QGmu.jpg" alt="using product addons"></a></p>
<p><a href="https://i.stack.imgur.com/VB0Lo.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VB0Lo.jpg" alt="using attributes"></a></p>
|
[
{
"answer_id": 219100,
"author": "Awert",
"author_id": 89601,
"author_profile": "https://wordpress.stackexchange.com/users/89601",
"pm_score": 0,
"selected": false,
"text": "<p>Search for class-product-addon-display.php in plugin folder.\nYou need function __construct().</p>\n\n<p>For me it worked like this:</p>\n\n<pre><code>// Addon display\nadd_action( 'woocommerce_after_add_to_cart_button', array( $this, 'display' ), 10 );\nadd_action( 'woocommerce_before_add_to_cart_button', array( $this, 'totals' ), 20 );\n</code></pre>\n"
},
{
"answer_id": 287528,
"author": "Laurence Caton",
"author_id": 132510,
"author_profile": "https://wordpress.stackexchange.com/users/132510",
"pm_score": 1,
"selected": false,
"text": "<p>For anyone wanting to do this outside of the plugin, to future proof this from updates, you can use the global var in place of the $this</p>\n\n<pre><code>add_action( 'woocommerce_after_add_to_cart_button', array( $GLOBALS['Product_Addon_Display'], 'display' ), 10 );\nadd_action( 'woocommerce_before_add_to_cart_button', array( $GLOBALS['Product_Addon_Display'], 'totals' ), 20 );\n</code></pre>\n"
}
] |
2015/10/01
|
[
"https://wordpress.stackexchange.com/questions/204306",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77095/"
] |
I need to change the product position of an addon called "misura anello" in the products (i use product add-ons plugin), i want to place it above the price, like the attributes...
i post to attach to images...
[](https://i.stack.imgur.com/0QGmu.jpg)
[](https://i.stack.imgur.com/VB0Lo.jpg)
|
For anyone wanting to do this outside of the plugin, to future proof this from updates, you can use the global var in place of the $this
```
add_action( 'woocommerce_after_add_to_cart_button', array( $GLOBALS['Product_Addon_Display'], 'display' ), 10 );
add_action( 'woocommerce_before_add_to_cart_button', array( $GLOBALS['Product_Addon_Display'], 'totals' ), 20 );
```
|
204,310 |
<p>All 404 implementations seem to revolve around showing related content. I think we can do one better by automatically searching for the missing post... How can this be done?</p>
|
[
{
"answer_id": 204311,
"author": "rothschild86",
"author_id": 81286,
"author_profile": "https://wordpress.stackexchange.com/users/81286",
"pm_score": 3,
"selected": true,
"text": "<p>This can be done in two easy steps.</p>\n\n<ol>\n<li><p>Upgrade your site search with a plug in, such as Relevanssi (optional).</p></li>\n<li><p>Add the following code in functions.php or via Code Snippets (thx to @Howdy_McGee and Russell Jamieson for ideas!)</p></li>\n</ol>\n\n\n\n<pre><code>function wpse_204310() {\n\n global $wp_query;\n\n if( is_404()\n && !is_robots() \n && !is_feed() \n && !is_trackback()\n ) {\n $uri = $_SERVER['REQUEST_URI'];\n $clean = str_replace( \"/\", \"%20\", $uri );\n $clean2 = str_replace( \"-\", \"%20\", $clean ); \n wp_redirect( home_url( \"/?s={$clean2}\" ) );\n exit();\n }\n}\n\nadd_action( 'template_redirect', 'wpse_204310' );\n</code></pre>\n\n<p>That's it. This code will parse the url for the blog title, and pass it along to your search page. All transparent to the user. This assumes a simple permalink structure, such as domain.com/post-title</p>\n"
},
{
"answer_id": 204315,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 1,
"selected": false,
"text": "<p>You could grab the pagename they're looking for on 404 and use <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/template_redirect\" rel=\"nofollow\"><code>template_redirect</code></a> to put that pagename into the default search:</p>\n\n<pre><code>function wpse_204310() {\n global $wp_query;\n\n if( is_404() ) {\n $slug = $wp_query->get( 'pagename' );\n wp_redirect( home_url( \"/?s={$slug}\" ) );\n exit();\n }\n}\nadd_action( 'template_redirect', 'wpse_204310' );\n</code></pre>\n\n<p>The default WordPress search isn't the best and I'm not sure how the above snippet will interact with plugins that attempt to improve the default search but that's one possible solution.</p>\n"
}
] |
2015/10/01
|
[
"https://wordpress.stackexchange.com/questions/204310",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81286/"
] |
All 404 implementations seem to revolve around showing related content. I think we can do one better by automatically searching for the missing post... How can this be done?
|
This can be done in two easy steps.
1. Upgrade your site search with a plug in, such as Relevanssi (optional).
2. Add the following code in functions.php or via Code Snippets (thx to @Howdy\_McGee and Russell Jamieson for ideas!)
```
function wpse_204310() {
global $wp_query;
if( is_404()
&& !is_robots()
&& !is_feed()
&& !is_trackback()
) {
$uri = $_SERVER['REQUEST_URI'];
$clean = str_replace( "/", "%20", $uri );
$clean2 = str_replace( "-", "%20", $clean );
wp_redirect( home_url( "/?s={$clean2}" ) );
exit();
}
}
add_action( 'template_redirect', 'wpse_204310' );
```
That's it. This code will parse the url for the blog title, and pass it along to your search page. All transparent to the user. This assumes a simple permalink structure, such as domain.com/post-title
|
204,313 |
<p>i have 2 categories that have book in adult, So i need when any user open this category to show him pop up message like :-</p>
<blockquote>
<p>The content you are about to view are of a mature matter. Please be advised that the content may not be suitable for those under the age of 18</p>
</blockquote>
<p>And when click yes,, we can show this category,But when select No ,, we need to return him to home page,</p>
<p>This two categories are for the WooCommerce plugin.</p>
<p>How can I do that?</p>
|
[
{
"answer_id": 204319,
"author": "tushonline",
"author_id": 15946,
"author_profile": "https://wordpress.stackexchange.com/users/15946",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Option 1)</strong> You'll need to use conditional tags to determine which category page is being shown. It's mentioned on the <a href=\"http://docs.woothemes.com/document/conditional-tags/\" rel=\"nofollow\">Woocommerce Docs</a>. </p>\n\n<pre><code> if ( is_product_category( array( 'abc', 'xyz' ) ) ) {\n //do this;\n } \n</code></pre>\n\n<p><strong>Option 2)</strong> And just in case, if you decide to render specific elements for those categories pages, you can do so by creating templates only for those categories at <code>theme/woocommerce/templates</code> & filenames would be <em>taxonomy-product_cat-abc.php</em> & <em>taxonomy-product_cat-xyz.php</em></p>\n"
},
{
"answer_id": 204321,
"author": "Daniel Muñoz Parsapoormoghadam",
"author_id": 81262,
"author_profile": "https://wordpress.stackexchange.com/users/81262",
"pm_score": 1,
"selected": false,
"text": "<p><strong>1)</strong> Open your <code>templates/content-product_cat.php</code> file.</p>\n\n<p><br>\n<strong>2)</strong> Locate the following piece of code:</p>\n\n<pre><code><li <?php wc_product_cat_class(); ?>>\n<?php do_action( 'woocommerce_before_subcategory', $category ); ?>\n\n<a href=\"<?php echo get_term_link( $category->slug, 'product_cat' ); ?>\">\n</code></pre>\n\n<p><br>\n<strong>3)</strong> Replace the line</p>\n\n<pre><code><a href=\"<?php echo get_term_link( $category->slug, 'product_cat' ); ?>\">\n</code></pre>\n\n<p>for the following piece of code:</p>\n\n<pre><code><?php if ($category->name == \"adults1\" || $category->name == \"adults2\") { ?>\n\n <a onclick=\"return confirm('The content you are about to view are of a mature matter. Please be advised that the content may not be suitable for those under the age of 18')\" href=\"<?php echo get_term_link( $category->slug, 'product_cat' ); ?>\">\n\n<?php } else { ?>\n\n <a href=\"<?php echo get_term_link( $category->slug, 'product_cat' ); ?>\"> \n\n<?php } ?>\n</code></pre>\n\n<p><br>\n<strong>4)</strong> Replace <code>\"adults1\"</code> and <code>\"adults2\"</code> for the names of the two categories you want to control.</p>\n\n<p>Hope it solves your issue.</p>\n"
},
{
"answer_id": 270314,
"author": "Sid",
"author_id": 110516,
"author_profile": "https://wordpress.stackexchange.com/users/110516",
"pm_score": -1,
"selected": false,
"text": "<p>You could simply add a Javascript Popup on them. In the page where your category name and links are generated add the code:</p>\n\n<pre><code>if ($term->name === 'adult1' || $term->name === 'adult2') {\n <a href=\"http://www.google.com/\" onclick=\"window.alert('Google Link');\">Google</a>\n}\nelse {\n<a href=\"http://www.google.com\">Google</a>\n}\n</code></pre>\n\n<p>The basic idea is to look if the category name is \"adult1\" or \"adult2\". If Yes then add a Javascript <code>onclick('');</code> function to your link.</p>\n\n<p>Hope this helps.</p>\n"
}
] |
2015/10/01
|
[
"https://wordpress.stackexchange.com/questions/204313",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81259/"
] |
i have 2 categories that have book in adult, So i need when any user open this category to show him pop up message like :-
>
> The content you are about to view are of a mature matter. Please be advised that the content may not be suitable for those under the age of 18
>
>
>
And when click yes,, we can show this category,But when select No ,, we need to return him to home page,
This two categories are for the WooCommerce plugin.
How can I do that?
|
**1)** Open your `templates/content-product_cat.php` file.
**2)** Locate the following piece of code:
```
<li <?php wc_product_cat_class(); ?>>
<?php do_action( 'woocommerce_before_subcategory', $category ); ?>
<a href="<?php echo get_term_link( $category->slug, 'product_cat' ); ?>">
```
**3)** Replace the line
```
<a href="<?php echo get_term_link( $category->slug, 'product_cat' ); ?>">
```
for the following piece of code:
```
<?php if ($category->name == "adults1" || $category->name == "adults2") { ?>
<a onclick="return confirm('The content you are about to view are of a mature matter. Please be advised that the content may not be suitable for those under the age of 18')" href="<?php echo get_term_link( $category->slug, 'product_cat' ); ?>">
<?php } else { ?>
<a href="<?php echo get_term_link( $category->slug, 'product_cat' ); ?>">
<?php } ?>
```
**4)** Replace `"adults1"` and `"adults2"` for the names of the two categories you want to control.
Hope it solves your issue.
|
204,368 |
<p>I want to use $wpdb to get user's firstname. I know how to do it with php and mysql query, but I want to use $wpdb.</p>
<p>The problem is that I don't know how to use it. I tried to create simple
query to display user fist_name by user_id and than echo it. This is what I ended up with:</p>
<pre><code>$mywpdb1 = $wpdb->get_var(
$wpdb->prepare(
"SELECT first_name
FROM $wpdb->usermeta
WHERE user_id = 2",
$user->first_name
)
);
echo $mywpdb1;
</code></pre>
|
[
{
"answer_id": 204369,
"author": "Paul",
"author_id": 49716,
"author_profile": "https://wordpress.stackexchange.com/users/49716",
"pm_score": 2,
"selected": false,
"text": "<p>You should'nt really be using wp query here, use <a href=\"https://codex.wordpress.org/Function_Reference/get_user_meta\" rel=\"nofollow\">get_user_meta();</a></p>\n\n<p>Example:</p>\n\n<pre><code>$first_name = get_user_meta(2, 'first_name', true);\n</code></pre>\n"
},
{
"answer_id": 204380,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to make a direct database query for <code>first_name</code> meta field the correct way is:</p>\n\n<pre><code>global $wpdb;\n\n$user_id = 2;\n$meta_key = \"first_name\";\n\n$first_name = $wpdb->get_var( \n $wpdb->prepare( \n \"SELECT meta_value \n FROM $wpdb->usermeta \n WHERE user_id = %d \n AND meta_key = %s\",\n $user_id,\n $meta_key\n ) \n);\n\necho $first_name;\n</code></pre>\n\n<p>But I think it is better to use the <code>WP_User</code> object, which contains the <code>first_name</code> meta field as a public property:</p>\n\n<pre><code>// Get the user with ID = 2\n$user = new WP_User( 2 );\n\n// Grab de the first_name\n$first_name = $user->first_name;\n</code></pre>\n\n<p>You can use <code>get_user_meta()</code> function also, as suggested by @PaulH:</p>\n\n<pre><code>$first_name = get_user_meta(2, 'first_name', true);\n</code></pre>\n\n<p>But I thhink <code>WP_User</code> object is better than <code>get_user_meta()</code> for this specific case for these main reasons:</p>\n\n<ol>\n<li>Usually, when working with users you have to load the user object anyway. For example, in the description of question the user object is already loaded, so <strong>there is no need for anything else</strong>, just use <code>$user->first_name</code>.</li>\n<li>I don't think there is a huge perfomance difference between both methods but looking how <code>get_user_meta()</code> works (<a href=\"https://developer.wordpress.org/reference/functions/update_meta_cache/\" rel=\"nofollow\">at the end it uses this function</a>), it loads all user meta fields, even if you only want one field. That may have a worst perfomance than loading a <code>WP_User</code> object in some situations.</li>\n</ol>\n"
}
] |
2015/10/02
|
[
"https://wordpress.stackexchange.com/questions/204368",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78089/"
] |
I want to use $wpdb to get user's firstname. I know how to do it with php and mysql query, but I want to use $wpdb.
The problem is that I don't know how to use it. I tried to create simple
query to display user fist\_name by user\_id and than echo it. This is what I ended up with:
```
$mywpdb1 = $wpdb->get_var(
$wpdb->prepare(
"SELECT first_name
FROM $wpdb->usermeta
WHERE user_id = 2",
$user->first_name
)
);
echo $mywpdb1;
```
|
You should'nt really be using wp query here, use [get\_user\_meta();](https://codex.wordpress.org/Function_Reference/get_user_meta)
Example:
```
$first_name = get_user_meta(2, 'first_name', true);
```
|
204,405 |
<p>As administrator, if I make a new user, I can choose to email my new users a link which they click to go to wp-login.php where they are invited to set their password for the first time. (Wordpress used to email out a password, but I can see why they changed that!)</p>
<p>Users arrive at wp-login which records the username in a hidden field, and shows a suggested password which they can customise. </p>
<p>Some of my more easily boggled users are confused by this. They find the generated password incomprehensible, and do not understand that they can click on the suggested password in the box and change it to something they can remember. I would like to add some help text and maybe automatically select the suggested password too at this point. </p>
<p>I am not sure which hooks will allow me to do stuff that <strong>only</strong> appears to users setting their password, and not to anyone else who is logging in. </p>
<p>How can I do that? </p>
|
[
{
"answer_id": 204429,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>You can add an extra help message box, on the <em>reset password</em> screen:</p>\n\n<p><a href=\"https://i.stack.imgur.com/D2ZAj.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/D2ZAj.jpg\" alt=\"help text\"></a></p>\n\n<p>with the following:</p>\n\n<pre><code> /**\n * Display an extra help message box on the 'reset password' screen\n * \n * @link http://wordpress.stackexchange.com/a/204429/26350\n */\n add_action( 'validate_password_reset', function( $errors )\n {\n add_action( 'login_message', function( $message )\n {\n // Modify this help message box to your needs:\n $mybox = sprintf( \n '<br/><p class=\"message reset-pass\">%s</p>',\n __( 'Some help text here!' )\n );\n\n return $message . $mybox; \n } );\n } );\n</code></pre>\n\n<p>Here we add the extra message box by using the <code>login_message</code> filter. It should only show up on the <em>reset password</em> screen, because we hook it into the <code>validate_password_reset</code> action.</p>\n"
},
{
"answer_id": 287460,
"author": "squarecandy",
"author_id": 41488,
"author_profile": "https://wordpress.stackexchange.com/users/41488",
"pm_score": 0,
"selected": false,
"text": "<p>I ended up using this. \nIt's definitely a hack... if someone else knows how better to modify what's happening in <a href=\"https://github.com/WordPress/WordPress/blob/4.9-branch/wp-admin/js/user-profile.js\" rel=\"nofollow noreferrer\" title=\"wp-admin/js/user-profile.js\">wp-admin/js/user-profile.js</a> without hacking core, please let me know. I don't want to deregister the entire script because I like all of the password strength checking, etc that's in there.</p>\n\n<pre><code>// add some js to the login page\nfunction squarecandy_login_stylesheet() {\n wp_enqueue_script( 'custom-login-js', get_stylesheet_directory_uri() . '/js/login.js' );\n}\nadd_action( 'login_enqueue_scripts', 'squarecandy_login_stylesheet' );\n</code></pre>\n\n<p>login.js</p>\n\n<pre><code>jQuery(document).ready(function($){\n // wait half a second so WP can fill the suggestion first\n setTimeout( function(){\n // Switch to the non-visible entry mode\n $('.wp-hide-pw').click();\n // clear the password fields, put the cursor in the field\n $('#pass1, #pass1-text').val('').focus();\n }, 500 );\n});\n</code></pre>\n"
}
] |
2015/10/02
|
[
"https://wordpress.stackexchange.com/questions/204405",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37897/"
] |
As administrator, if I make a new user, I can choose to email my new users a link which they click to go to wp-login.php where they are invited to set their password for the first time. (Wordpress used to email out a password, but I can see why they changed that!)
Users arrive at wp-login which records the username in a hidden field, and shows a suggested password which they can customise.
Some of my more easily boggled users are confused by this. They find the generated password incomprehensible, and do not understand that they can click on the suggested password in the box and change it to something they can remember. I would like to add some help text and maybe automatically select the suggested password too at this point.
I am not sure which hooks will allow me to do stuff that **only** appears to users setting their password, and not to anyone else who is logging in.
How can I do that?
|
You can add an extra help message box, on the *reset password* screen:
[](https://i.stack.imgur.com/D2ZAj.jpg)
with the following:
```
/**
* Display an extra help message box on the 'reset password' screen
*
* @link http://wordpress.stackexchange.com/a/204429/26350
*/
add_action( 'validate_password_reset', function( $errors )
{
add_action( 'login_message', function( $message )
{
// Modify this help message box to your needs:
$mybox = sprintf(
'<br/><p class="message reset-pass">%s</p>',
__( 'Some help text here!' )
);
return $message . $mybox;
} );
} );
```
Here we add the extra message box by using the `login_message` filter. It should only show up on the *reset password* screen, because we hook it into the `validate_password_reset` action.
|
204,408 |
<p>I've created an image field using Image URL via the ACF plugin. This field appears across my pages. This field enables admin to change the background image for a selected class.</p>
<p>Here's the code I have inserted between the <code><head></head></code> tags: </p>
<pre><code><?php
while ( have_posts() ) : the_post();
$background = get_field('background'); ?>
<style>
.site-header {
background: url(<?php echo $background; ?>) no-repeat center;
background-size: cover;
}
</style>
<?php endwhile; // end of the loop.
?>
</code></pre>
<p>The url appears blank via the source. What am I doing wrong? I understand that ACF doesn't work outside of the loop which is why I've added a loop to the <code><head></code>.</p>
<p>Here's the ACF export: </p>
<pre><code>if( function_exists('acf_add_local_field_group') ):
acf_add_local_field_group(array (
'key' => 'group_560e6c0620487',
'title' => 'Header Background',
'fields' => array (
array (
'key' => 'field_560e6c0ed9ca8',
'label' => 'Background Image',
'name' => 'background',
'type' => 'image',
'instructions' => '',
'required' => 0,
'conditional_logic' => 0,
'wrapper' => array (
'width' => '',
'class' => '',
'id' => '',
),
'return_format' => 'url',
'preview_size' => 'thumbnail',
'library' => 'all',
'min_width' => '',
'min_height' => '',
'min_size' => '',
'max_width' => '',
'max_height' => '',
'max_size' => '',
'mime_types' => '',
),
),
'location' => array (
array (
array (
'param' => 'page_type',
'operator' => '==',
'value' => 'top_level',
),
),
),
'menu_order' => 0,
'position' => 'normal',
'style' => 'default',
'label_placement' => 'top',
'instruction_placement' => 'label',
'hide_on_screen' => '',
'active' => 1,
'description' => '',
));
endif;
</code></pre>
|
[
{
"answer_id": 204409,
"author": "Stijn De Lathouwer",
"author_id": 45458,
"author_profile": "https://wordpress.stackexchange.com/users/45458",
"pm_score": 0,
"selected": false,
"text": "<p>What is ACF returning? An object? Or a URL? With an object, you have to get the correct URL/size out of the object.</p>\n\n<p><a href=\"http://www.advancedcustomfields.com/resources/image/\" rel=\"nofollow\">http://www.advancedcustomfields.com/resources/image/</a></p>\n\n<p>--</p>\n\n<p>Sorry, got a bit carried away increasing my SO-involvement :)\nUsing the post ID is indeed necessary, depending on where you use get_field</p>\n"
},
{
"answer_id": 204419,
"author": "dswebsme",
"author_id": 62906,
"author_profile": "https://wordpress.stackexchange.com/users/62906",
"pm_score": 1,
"selected": false,
"text": "<p>You don't have to add a loop in the header to get the desired result. This should work outside the loop according to the documentation:</p>\n\n<pre><code><?php\n// using $post from the global scope (not within loop) - your setup may vary\n$background = get_field('background', $post->ID);\n?>\n\n<style>\n .site-header {\n background: url(<?php echo $background; ?>) no-repeat center;\n background-size: cover;\n }\n</style>\n</code></pre>\n\n<p>The code example you provided is using the proper ACF calls. This example just removes the loop to help clean things up a bit.</p>\n\n<p>If you still see a blank URL in that space double check to ensure the field name is correctly named \"background\" to rule out the possibility of typos. Also be sure to clear any caching plugins or local cache that may be sticking (CSS likes to stick around).</p>\n\n<p>If this is still giving you trouble perhaps you could export the field via ACF Export and paste that into your original question so I can assist further.</p>\n"
},
{
"answer_id": 204421,
"author": "vol4ikman",
"author_id": 31075,
"author_profile": "https://wordpress.stackexchange.com/users/31075",
"pm_score": 1,
"selected": false,
"text": "<p>You don't have to use get_field function inside the wp loop. If you use get_field before wp_head(), so you need to define post id. Your code must be something like this:</p>\n\n<pre><code>$bg = get_field('fieldname', $post->ID):\n</code></pre>\n"
},
{
"answer_id": 204426,
"author": "jsonUK",
"author_id": 81337,
"author_profile": "https://wordpress.stackexchange.com/users/81337",
"pm_score": 3,
"selected": true,
"text": "<p>In the <code>header.php</code> template, you cannot access the <code>$post</code> variable.</p>\n\n<p>So you will have to map it using <code>$wp_query</code>, as mentioned on ACF forum <a href=\"http://support.advancedcustomfields.com/forums/topic/selection-option-used-in-header/\" rel=\"nofollow\">here</a>.</p>\n\n<p>Try this:</p>\n\n<pre><code><?php \nglobal $wp_query; \n$post = $wp_query->post;\n$background = get_field('background', $post->ID); \n?>\n\n<style>\n .site-header {\n background: url(<?php echo $background; ?>) no-repeat center;\n background-size: cover;\n }\n</style>\n</code></pre>\n"
}
] |
2015/10/02
|
[
"https://wordpress.stackexchange.com/questions/204408",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37548/"
] |
I've created an image field using Image URL via the ACF plugin. This field appears across my pages. This field enables admin to change the background image for a selected class.
Here's the code I have inserted between the `<head></head>` tags:
```
<?php
while ( have_posts() ) : the_post();
$background = get_field('background'); ?>
<style>
.site-header {
background: url(<?php echo $background; ?>) no-repeat center;
background-size: cover;
}
</style>
<?php endwhile; // end of the loop.
?>
```
The url appears blank via the source. What am I doing wrong? I understand that ACF doesn't work outside of the loop which is why I've added a loop to the `<head>`.
Here's the ACF export:
```
if( function_exists('acf_add_local_field_group') ):
acf_add_local_field_group(array (
'key' => 'group_560e6c0620487',
'title' => 'Header Background',
'fields' => array (
array (
'key' => 'field_560e6c0ed9ca8',
'label' => 'Background Image',
'name' => 'background',
'type' => 'image',
'instructions' => '',
'required' => 0,
'conditional_logic' => 0,
'wrapper' => array (
'width' => '',
'class' => '',
'id' => '',
),
'return_format' => 'url',
'preview_size' => 'thumbnail',
'library' => 'all',
'min_width' => '',
'min_height' => '',
'min_size' => '',
'max_width' => '',
'max_height' => '',
'max_size' => '',
'mime_types' => '',
),
),
'location' => array (
array (
array (
'param' => 'page_type',
'operator' => '==',
'value' => 'top_level',
),
),
),
'menu_order' => 0,
'position' => 'normal',
'style' => 'default',
'label_placement' => 'top',
'instruction_placement' => 'label',
'hide_on_screen' => '',
'active' => 1,
'description' => '',
));
endif;
```
|
In the `header.php` template, you cannot access the `$post` variable.
So you will have to map it using `$wp_query`, as mentioned on ACF forum [here](http://support.advancedcustomfields.com/forums/topic/selection-option-used-in-header/).
Try this:
```
<?php
global $wp_query;
$post = $wp_query->post;
$background = get_field('background', $post->ID);
?>
<style>
.site-header {
background: url(<?php echo $background; ?>) no-repeat center;
background-size: cover;
}
</style>
```
|
204,427 |
<p>Is There Any Way to get the template Name By full URL
for example</p>
<p>If the full url is</p>
<pre><code>www.example.com/hello-world
</code></pre>
<p>I need a function that return the template name (<code>page.php</code>)</p>
<p>I know that WordPress matches every url with regular expression to determine the query and decide which template to include.</p>
<p>That's exactly what I need, a built in or (custom made) function that takes the URL
and returns back the corresponding template</p>
|
[
{
"answer_id": 204431,
"author": "Joel",
"author_id": 65652,
"author_profile": "https://wordpress.stackexchange.com/users/65652",
"pm_score": 1,
"selected": false,
"text": "<p>You should be able to use <a href=\"https://codex.wordpress.org/Function_Reference/get_page_template_slug\" rel=\"nofollow\"><code>get_page_template_slug()</code></a></p>\n\n<p>And since that function requires an id instead of a URL, use <a href=\"https://codex.wordpress.org/Function_Reference/url_to_postid\" rel=\"nofollow\"><code>url_to_postid()</code></a> to find the ID first</p>\n"
},
{
"answer_id": 204464,
"author": "nkuldip",
"author_id": 44954,
"author_profile": "https://wordpress.stackexchange.com/users/44954",
"pm_score": 0,
"selected": false,
"text": "<p>Use the following code in header.php to know the current template:</p>\n\n<pre><code><body id=\"<?php echo get_option('current_page_template'); ?>\">\n</code></pre>\n\n<p>I'd be happy if this helps.</p>\n"
},
{
"answer_id": 204472,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 2,
"selected": false,
"text": "<p>You can make use of the global <code>$template</code> which holds the complete path of the current template being use to display a page. From there you can manipulate the value to get the name of the template</p>\n\n<p>As example, the value of <code>$template</code> looks like this: (<em>This is on my localhost on my PC</em>)</p>\n\n<pre><code>E:\\xammp\\htdocs\\wordpress/wp-content/themes/pietergoosen2014/page-test.php\n</code></pre>\n\n<p>To only return the <code>page-test.php</code> part, I use the following function which uses the PHP functions <code>substr</code> and <code>strrpos</code> which finds the last <code>/</code> character in URL and then returns everything after that:</p>\n\n<pre><code>function get_current_template() {\n global $template;\n return substr( $template, strrpos( $template, '/' ) + 1 );\n}\n</code></pre>\n\n<p>You can then use it anywhere in your template like </p>\n\n<pre><code>echo get_current_template();\n</code></pre>\n\n<p>I usually just print the template name in my site's header on my localhost like</p>\n\n<pre><code>add_action( 'wp_head', function () \n{\n global $template;\n print substr( $template, strrpos( $template, '/' ) + 1 );\n});\n</code></pre>\n\n<p>or </p>\n\n<pre><code>add_action( 'wp_head', function () \n{\n global $template;\n print $template;\n});\n</code></pre>\n"
}
] |
2015/10/02
|
[
"https://wordpress.stackexchange.com/questions/204427",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/7984/"
] |
Is There Any Way to get the template Name By full URL
for example
If the full url is
```
www.example.com/hello-world
```
I need a function that return the template name (`page.php`)
I know that WordPress matches every url with regular expression to determine the query and decide which template to include.
That's exactly what I need, a built in or (custom made) function that takes the URL
and returns back the corresponding template
|
You can make use of the global `$template` which holds the complete path of the current template being use to display a page. From there you can manipulate the value to get the name of the template
As example, the value of `$template` looks like this: (*This is on my localhost on my PC*)
```
E:\xammp\htdocs\wordpress/wp-content/themes/pietergoosen2014/page-test.php
```
To only return the `page-test.php` part, I use the following function which uses the PHP functions `substr` and `strrpos` which finds the last `/` character in URL and then returns everything after that:
```
function get_current_template() {
global $template;
return substr( $template, strrpos( $template, '/' ) + 1 );
}
```
You can then use it anywhere in your template like
```
echo get_current_template();
```
I usually just print the template name in my site's header on my localhost like
```
add_action( 'wp_head', function ()
{
global $template;
print substr( $template, strrpos( $template, '/' ) + 1 );
});
```
or
```
add_action( 'wp_head', function ()
{
global $template;
print $template;
});
```
|
204,438 |
<p>I am using this code in <code>functions.php</code> to so it will show on the front of my site and show the read more, but the read more is not showing, your help would be appreciated.</p>
<pre><code> function new_excerpt_more( $more ) {
return ' <a href="'. get_permalink( get_the_ID() ) . ' '
. __('<br/><br/> Read More') . '</a>';
}
add_filter( 'excerpt_more', 'new_excerpt_more');
</code></pre>
<p>Here is my site demo link: <a href="http://visionedc.com/2015/news" rel="nofollow">http://visionedc.com/2015/news</a></p>
|
[
{
"answer_id": 204441,
"author": "shanebp",
"author_id": 16575,
"author_profile": "https://wordpress.stackexchange.com/users/16575",
"pm_score": 1,
"selected": false,
"text": "<p>The <code>excerpt_more</code> filter only handles the linked text - not the link itself. </p>\n\n<p>Try:</p>\n\n<pre><code>function new_excerpt_more( $more ) {\n return '<br/><br/>Read More';\n}\nadd_filter( 'excerpt_more', 'new_excerpt_more');\n</code></pre>\n"
},
{
"answer_id": 245221,
"author": "hmanni",
"author_id": 106392,
"author_profile": "https://wordpress.stackexchange.com/users/106392",
"pm_score": 0,
"selected": false,
"text": "<p>I advises you to use this simple function in your functions.php</p>\n\n<pre><code>function read_more_modif(){\n $readmore = \"make your custom text her\" ;\n return '<div class=\"lireSuite\"><a href=\"' . get_permalink() . '\">\"'.$readmore.'</a></div>'; \n } \n\nadd_filter( 'the_content_more_link', ' read_more_modif' );\n</code></pre>\n"
},
{
"answer_id": 380705,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Add this in functions.php:</p>\n<pre><code>function develop_custom_excerpt_more($more) {\n global $post;\n // edit here if you like\n return '... <a class="excerpt-read-more" href="'. get_permalink( $post->ID ) . '" title="'. __( 'Read ', 'domain_name' ) . esc_attr( get_the_title( $post->ID ) ).'">'. __( 'Show more &raquo;', 'domain_name' ) .'</a>';\n }\n add_filter( 'excerpt_more', 'develop_custom_excerpt_more' );\n</code></pre>\n"
}
] |
2015/10/02
|
[
"https://wordpress.stackexchange.com/questions/204438",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68271/"
] |
I am using this code in `functions.php` to so it will show on the front of my site and show the read more, but the read more is not showing, your help would be appreciated.
```
function new_excerpt_more( $more ) {
return ' <a href="'. get_permalink( get_the_ID() ) . ' '
. __('<br/><br/> Read More') . '</a>';
}
add_filter( 'excerpt_more', 'new_excerpt_more');
```
Here is my site demo link: <http://visionedc.com/2015/news>
|
The `excerpt_more` filter only handles the linked text - not the link itself.
Try:
```
function new_excerpt_more( $more ) {
return '<br/><br/>Read More';
}
add_filter( 'excerpt_more', 'new_excerpt_more');
```
|
204,446 |
<p>I want to create a new sidebar widget area in the header of my child theme. What would be the best way to do this?</p>
<p>Here is the code for one of the sidebars in the parent theme:</p>
<pre><code><?php
add_action( 'widgets_init', 'ci_widgets_init' );
if ( ! function_exists( 'ci_widgets_init' ) ) :
function ci_widgets_init() {
register_sidebar( array(
'name' => __( 'Blog Sidebar', 'ci_theme'),
'id' => 'blog-sidebar',
'description' => __( 'The list of widgets assigned here will appear in your blog posts.', 'ci_theme'),
'before_widget' => '<aside id="%1$s" class="widget %2$s group">',
'after_widget' => '</aside>',
'before_title' => '<h3 class="widget-title"><span>',
'after_title' => '</span></h3>',
) );
}
</code></pre>
<p>Can I just change the <code>name</code>, <code>id</code> and <code>description</code>, and put it in my child theme's <code>functions.php</code> file?</p>
|
[
{
"answer_id": 204469,
"author": "dswebsme",
"author_id": 62906,
"author_profile": "https://wordpress.stackexchange.com/users/62906",
"pm_score": 1,
"selected": false,
"text": "<p>Short answer is yes, adding the widget directly in the child theme functions.php file is perfectly acceptable.</p>\n\n<p>Some parent themes provide recommendations on how best to add new functionality within child themes (helpers, classes, specific design patterns, etc.) so the ideal approach may vary from one theme to the next.</p>\n\n<p>I'm happy to elaborate if you can provide any additional information about your setup.</p>\n"
},
{
"answer_id": 204517,
"author": "jrcollins",
"author_id": 68414,
"author_profile": "https://wordpress.stackexchange.com/users/68414",
"pm_score": 2,
"selected": false,
"text": "<p>Well, this is what worked for me. In my <code>functions.php</code> file I put the following code:</p>\n\n<pre><code>function header_widgets_init() {\n\nregister_sidebar( array(\n\n 'name' => 'Header Sidebar',\n\n 'id' => 'header_sidebar',\n\n 'before_widget' => '<aside class=\"widget %2$s\">',\n\n 'after_widget' => '</aside>',\n\n 'before_title' => '<h2 class=\"widget-title\">',\n\n 'after_title' => '</h2>',\n\n) );\n\n}\n\nadd_action( 'widgets_init', 'header_widgets_init' );\n</code></pre>\n\n<p>...and in my <code>header.php</code> file I used: </p>\n\n<pre><code><?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('header_sidebar') ) : endif; ?>\n</code></pre>\n"
}
] |
2015/10/02
|
[
"https://wordpress.stackexchange.com/questions/204446",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68414/"
] |
I want to create a new sidebar widget area in the header of my child theme. What would be the best way to do this?
Here is the code for one of the sidebars in the parent theme:
```
<?php
add_action( 'widgets_init', 'ci_widgets_init' );
if ( ! function_exists( 'ci_widgets_init' ) ) :
function ci_widgets_init() {
register_sidebar( array(
'name' => __( 'Blog Sidebar', 'ci_theme'),
'id' => 'blog-sidebar',
'description' => __( 'The list of widgets assigned here will appear in your blog posts.', 'ci_theme'),
'before_widget' => '<aside id="%1$s" class="widget %2$s group">',
'after_widget' => '</aside>',
'before_title' => '<h3 class="widget-title"><span>',
'after_title' => '</span></h3>',
) );
}
```
Can I just change the `name`, `id` and `description`, and put it in my child theme's `functions.php` file?
|
Well, this is what worked for me. In my `functions.php` file I put the following code:
```
function header_widgets_init() {
register_sidebar( array(
'name' => 'Header Sidebar',
'id' => 'header_sidebar',
'before_widget' => '<aside class="widget %2$s">',
'after_widget' => '</aside>',
'before_title' => '<h2 class="widget-title">',
'after_title' => '</h2>',
) );
}
add_action( 'widgets_init', 'header_widgets_init' );
```
...and in my `header.php` file I used:
```
<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('header_sidebar') ) : endif; ?>
```
|
204,447 |
<p><em>Side note: I've been designing in wordpress for only a few months, and don't know where else or how else to ask this, so my language may seem somewhat inaccurate.</em></p>
<p>I'm using the Jupiter theme within Wordpress to create my site, which is essentially a textbook. One of the chapters has content I've created with the "tabs' element on the Visual Composer front-end editor. However, the content needs to be formatted so that for each of 5 tabs, within each tab there are nested tabs. </p>
<p>Apparently this function isn't allowed in Visual Composer(dragging the tabs element within another tabs element), so I created class names for each tab and used javascript to append the tabs to be within the corresponding tab. If anyone could assist and tell me why I can't seem to move the other classes to the new tabs, I would really appreciate it. I also tried putting the tabs within an accordion, and that fails as well.</p>
<p><strong>This method works for the first occurrence of a nested tab, but for the others, the same javascript fails to work.</strong> </p>
<p>The page I need assistance on: <a href="http://www.foresightcompany.com/guide/chapter-10/" rel="nofollow">Chapter 10</a></p>
<p>The javascript:</p>
<pre><code>//These next few lines relate to the Chapter 10 page
$('.tabonecontent').appendTo($(".tabone").parents(".mk-tabs-pane"));
$('.tabtwocontent').appendTo($(".tabtwo").parents(".mk-tabs-pane"));
$('.tabthreecontent').appendTo($(".tabthree").parents(".mk-tabs-pane"));
$('.tabfourcontent').appendTo($(".tabfour").parents(".mk-tabs-pane"));
$('.tabfivecontent').appendTo($(".tabfive").parents(".mk-tabs-pane"));
</code></pre>
|
[
{
"answer_id": 204465,
"author": "dswebsme",
"author_id": 62906,
"author_profile": "https://wordpress.stackexchange.com/users/62906",
"pm_score": 1,
"selected": true,
"text": "<p>A couple of things before I get into the code:</p>\n\n<p>1) It would probably be a cleaner solution to solve this in the theme via extended functionality (PHP modifications) as you gain more experience with WordPress.</p>\n\n<p>2) If you are able to use numbers (1,2,3) instead of words (one,two,three) you can clean up the javascript solution even further.</p>\n\n<p>On with the code!</p>\n\n<p>See the fiddle for a working example: <a href=\"https://jsfiddle.net/2nzcnhwL/\" rel=\"nofollow\">https://jsfiddle.net/2nzcnhwL/</a></p>\n\n<pre><code>// run after load to be safe\n$(document).ready(function () {\n // map our numbers to words\n var subTabGroups = ['one','two','three','four','five'];\n // loop through all of the panes\n $('.mk-tabs-pane').each(function (i) {\n // append each group of subtabs to the corresponding pane\n $(this).append($('.tab' + subTabGroups[i] + 'content'));\n });\n});\n</code></pre>\n"
},
{
"answer_id": 204646,
"author": "user3427486",
"author_id": 81344,
"author_profile": "https://wordpress.stackexchange.com/users/81344",
"pm_score": 1,
"selected": false,
"text": "<p>I managed to fix my issue, by creating a loop of the tabs being appended. Thanks for the help! I'll look into how I can also solve this problem in PHP as well.</p>\n\n<pre><code>//These next few lines relate to the Chapter 10 page\nvar tabs = [\"one\", \"two\", \"three\", \"four\", \"five\"];\nfor(var i = 0; i<tabs.length; i++){\n tabNum = tabs[i];\n $('.tab'+tabNum+'description').appendTo($(\".tab\"+tabNum).parents(\".mk-tabs-pane\"));\n $('.tab'+tabNum+'content').appendTo($(\".tab\"+tabNum).parents(\".mk-tabs-pane\")); \n}\n</code></pre>\n"
}
] |
2015/10/02
|
[
"https://wordpress.stackexchange.com/questions/204447",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81344/"
] |
*Side note: I've been designing in wordpress for only a few months, and don't know where else or how else to ask this, so my language may seem somewhat inaccurate.*
I'm using the Jupiter theme within Wordpress to create my site, which is essentially a textbook. One of the chapters has content I've created with the "tabs' element on the Visual Composer front-end editor. However, the content needs to be formatted so that for each of 5 tabs, within each tab there are nested tabs.
Apparently this function isn't allowed in Visual Composer(dragging the tabs element within another tabs element), so I created class names for each tab and used javascript to append the tabs to be within the corresponding tab. If anyone could assist and tell me why I can't seem to move the other classes to the new tabs, I would really appreciate it. I also tried putting the tabs within an accordion, and that fails as well.
**This method works for the first occurrence of a nested tab, but for the others, the same javascript fails to work.**
The page I need assistance on: [Chapter 10](http://www.foresightcompany.com/guide/chapter-10/)
The javascript:
```
//These next few lines relate to the Chapter 10 page
$('.tabonecontent').appendTo($(".tabone").parents(".mk-tabs-pane"));
$('.tabtwocontent').appendTo($(".tabtwo").parents(".mk-tabs-pane"));
$('.tabthreecontent').appendTo($(".tabthree").parents(".mk-tabs-pane"));
$('.tabfourcontent').appendTo($(".tabfour").parents(".mk-tabs-pane"));
$('.tabfivecontent').appendTo($(".tabfive").parents(".mk-tabs-pane"));
```
|
A couple of things before I get into the code:
1) It would probably be a cleaner solution to solve this in the theme via extended functionality (PHP modifications) as you gain more experience with WordPress.
2) If you are able to use numbers (1,2,3) instead of words (one,two,three) you can clean up the javascript solution even further.
On with the code!
See the fiddle for a working example: <https://jsfiddle.net/2nzcnhwL/>
```
// run after load to be safe
$(document).ready(function () {
// map our numbers to words
var subTabGroups = ['one','two','three','four','five'];
// loop through all of the panes
$('.mk-tabs-pane').each(function (i) {
// append each group of subtabs to the corresponding pane
$(this).append($('.tab' + subTabGroups[i] + 'content'));
});
});
```
|
204,454 |
<p>I'm building an application for a client that is accessed via an <em>email address</em> and a <em>project number</em> - a custom field.</p>
<p>I created a really simple form from scratch (i.e. not using <code>wp_login_form</code>), and I validate the posted values with <code>WP_QUERY</code>.</p>
<p>My problem is that when the form values are incorrect, or blank, the user is being automatically redirected to the wp-login.php page.</p>
<p>How can I override this behavior and keep the user on the custom log-in page template?</p>
<pre><code> <form action="<?php the_permalink(); ?>" method="post">
<label for="form_email">Email Address:</label>
<input id="form_email" type="text" name="email" value="" />
</label>
<label for="form_project">Project Number:</label>
<input id="form_project" type="text" name="project" value="" />
</label>
<input type="submit" name="submit" value="Submit" />
</form>
</code></pre>
|
[
{
"answer_id": 204457,
"author": "dswebsme",
"author_id": 62906,
"author_profile": "https://wordpress.stackexchange.com/users/62906",
"pm_score": 1,
"selected": false,
"text": "<p>This has been covered quite thoroughly here:</p>\n\n<p><a href=\"https://wordpress.stackexchange.com/a/105224/62906\">https://wordpress.stackexchange.com/a/105224/62906</a></p>\n\n<p>I've linked directly to the most informative and complete answer of the group (IMO).</p>\n"
},
{
"answer_id": 204463,
"author": "nkuldip",
"author_id": 44954,
"author_profile": "https://wordpress.stackexchange.com/users/44954",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to customize it through coding then this tutorial is surely gonna help you. You can easily replace default WordPress login page with your own custom login page. </p>\n\n<p><a href=\"http://www.inkthemes.com/how-to-redirecting-wordpress-default-login-into-a-custom-login-page/\" rel=\"nofollow\">http://www.inkthemes.com/how-to-redirecting-wordpress-default-login-into-a-custom-login-page/</a></p>\n"
}
] |
2015/10/03
|
[
"https://wordpress.stackexchange.com/questions/204454",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/59093/"
] |
I'm building an application for a client that is accessed via an *email address* and a *project number* - a custom field.
I created a really simple form from scratch (i.e. not using `wp_login_form`), and I validate the posted values with `WP_QUERY`.
My problem is that when the form values are incorrect, or blank, the user is being automatically redirected to the wp-login.php page.
How can I override this behavior and keep the user on the custom log-in page template?
```
<form action="<?php the_permalink(); ?>" method="post">
<label for="form_email">Email Address:</label>
<input id="form_email" type="text" name="email" value="" />
</label>
<label for="form_project">Project Number:</label>
<input id="form_project" type="text" name="project" value="" />
</label>
<input type="submit" name="submit" value="Submit" />
</form>
```
|
This has been covered quite thoroughly here:
<https://wordpress.stackexchange.com/a/105224/62906>
I've linked directly to the most informative and complete answer of the group (IMO).
|
204,485 |
<p>The security settings of a website we have was done according to Wordpress Recommendations and we did not have any single hacking attempts for months. Especially that wp-login.php and wp-admin are only limited by IP Address as follows:</p>
<pre><code><Files wp-login.php>
order deny,allow
allow from a.b.c.d
deny from all
</Files>
</code></pre>
<p>Today, we had hacking attempts through Tor network according Wordfence security. Luckily, all the IP addresses were blocked and the website is safe. But how can they login if they don't have access to wp-login.php? I have tested it via url and got a forbidden error:</p>
<blockquote>
<pre><code>Forbidden
You don't have permission to access /wp-login.php on this server.
</code></pre>
</blockquote>
<p>What makes it even weirder for me, is that wordfence says that those IP addresses did not access any single page while trying to login. They don't even appear in the "All Hits" section, just in the "Logins and Logouts" section.</p>
<p>Any help is appreciated.</p>
|
[
{
"answer_id": 204486,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>WordPress is also an XML-RPC server. So I guess these bots tried to gain access through the XML-RPC protocol via the <code>xmlrpc.php</code> file in your WordPress root directory.</p>\n\n<p>It's possible to login and most likely your security plugin is picking up failed login attempts when <code>wp_authenticate()</code> is called and the <code>wp_login_failed</code> hook is activated.</p>\n\n<p>Here's the relevant part:</p>\n\n<pre><code>/**\n * Filter whether XML-RPC is enabled.\n *\n * This is the proper filter for turning off XML-RPC.\n *\n * @since 3.5.0\n *\n * @param bool $enabled Whether XML-RPC is enabled. Default true.\n */\n $enabled = apply_filters( 'xmlrpc_enabled', $enabled );\n\n if ( ! $enabled ) {\n $this->error = new IXR_Error( \n 405, \n sprintf( __( 'XML-RPC services are disabled on this site.' ) ) \n );\n return false;\n }\n\n $user = wp_authenticate($username, $password);\n</code></pre>\n\n<p>so you can see that using:</p>\n\n<pre><code>add_filter( 'xmlrpc_enabled', '__return_false' );\n</code></pre>\n\n<p>will throw an <code>IXR_Error</code> error instead of trying to authenticate the user.</p>\n\n<p>Some choose to block access to the <code>xmlrpc.php</code> file.</p>\n"
},
{
"answer_id": 204487,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>In addition to the obvious login via XML-RPC, it is just not smart to think that there are admin,login and front-end url with a clear cut separation between them. If you use one of the ajaxified login plugin then login attempts can come from anywhere without passing via the login.php file. The only real way to protect against brute force attacks is to have a strong password.</p>\n\n<p>Security plugins will obviously notify you on any perceived security event to make you think they are doing something worthy, but like with fighting spam, you should not be worried about being attacked but about having a good defense. Once and attacker passed your defense even one time, the game is probably over and it is too late to react.</p>\n\n<p>As for blocking IP ranges - it can be useful if all the computers in the range are under your control, otherwise it is not very effective. Lets say you have limit the IP to the US, do you know how many open proxies, tor node, hacked servers and hacked desktops are there in the US? and some of them at some point will be used against you. If your password is 123456 you will be easily hacked even with IP limiting. And then of course someone can get your authoritative cookies when you admin over a public WiFi and doesn't even need to go to wp-login.php to \"login\".</p>\n"
}
] |
2015/10/03
|
[
"https://wordpress.stackexchange.com/questions/204485",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81361/"
] |
The security settings of a website we have was done according to Wordpress Recommendations and we did not have any single hacking attempts for months. Especially that wp-login.php and wp-admin are only limited by IP Address as follows:
```
<Files wp-login.php>
order deny,allow
allow from a.b.c.d
deny from all
</Files>
```
Today, we had hacking attempts through Tor network according Wordfence security. Luckily, all the IP addresses were blocked and the website is safe. But how can they login if they don't have access to wp-login.php? I have tested it via url and got a forbidden error:
>
>
> ```
> Forbidden
>
> You don't have permission to access /wp-login.php on this server.
>
> ```
>
>
What makes it even weirder for me, is that wordfence says that those IP addresses did not access any single page while trying to login. They don't even appear in the "All Hits" section, just in the "Logins and Logouts" section.
Any help is appreciated.
|
WordPress is also an XML-RPC server. So I guess these bots tried to gain access through the XML-RPC protocol via the `xmlrpc.php` file in your WordPress root directory.
It's possible to login and most likely your security plugin is picking up failed login attempts when `wp_authenticate()` is called and the `wp_login_failed` hook is activated.
Here's the relevant part:
```
/**
* Filter whether XML-RPC is enabled.
*
* This is the proper filter for turning off XML-RPC.
*
* @since 3.5.0
*
* @param bool $enabled Whether XML-RPC is enabled. Default true.
*/
$enabled = apply_filters( 'xmlrpc_enabled', $enabled );
if ( ! $enabled ) {
$this->error = new IXR_Error(
405,
sprintf( __( 'XML-RPC services are disabled on this site.' ) )
);
return false;
}
$user = wp_authenticate($username, $password);
```
so you can see that using:
```
add_filter( 'xmlrpc_enabled', '__return_false' );
```
will throw an `IXR_Error` error instead of trying to authenticate the user.
Some choose to block access to the `xmlrpc.php` file.
|
204,488 |
<p>In the admin panel, if I go to "Users -> Your Profile" I don't have the inputs to set the password. I can only generate it, but I want to set it by hand. Is that some kind of bug, or was this intentionally removed from wordpress.</p>
<p><a href="https://i.stack.imgur.com/tvxe9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tvxe9.png" alt="enter image description here"></a></p>
<p>If I check html with firebug I can see that inputs are actually there, but they are hidden.</p>
<p>EDIT:</p>
<p>In some old wordpress installation that has not been updated I can still see inputs for password change. See this screenshot:</p>
<p><a href="https://i.stack.imgur.com/wPZ1x.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wPZ1x.png" alt="enter image description here"></a></p>
|
[
{
"answer_id": 204486,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>WordPress is also an XML-RPC server. So I guess these bots tried to gain access through the XML-RPC protocol via the <code>xmlrpc.php</code> file in your WordPress root directory.</p>\n\n<p>It's possible to login and most likely your security plugin is picking up failed login attempts when <code>wp_authenticate()</code> is called and the <code>wp_login_failed</code> hook is activated.</p>\n\n<p>Here's the relevant part:</p>\n\n<pre><code>/**\n * Filter whether XML-RPC is enabled.\n *\n * This is the proper filter for turning off XML-RPC.\n *\n * @since 3.5.0\n *\n * @param bool $enabled Whether XML-RPC is enabled. Default true.\n */\n $enabled = apply_filters( 'xmlrpc_enabled', $enabled );\n\n if ( ! $enabled ) {\n $this->error = new IXR_Error( \n 405, \n sprintf( __( 'XML-RPC services are disabled on this site.' ) ) \n );\n return false;\n }\n\n $user = wp_authenticate($username, $password);\n</code></pre>\n\n<p>so you can see that using:</p>\n\n<pre><code>add_filter( 'xmlrpc_enabled', '__return_false' );\n</code></pre>\n\n<p>will throw an <code>IXR_Error</code> error instead of trying to authenticate the user.</p>\n\n<p>Some choose to block access to the <code>xmlrpc.php</code> file.</p>\n"
},
{
"answer_id": 204487,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>In addition to the obvious login via XML-RPC, it is just not smart to think that there are admin,login and front-end url with a clear cut separation between them. If you use one of the ajaxified login plugin then login attempts can come from anywhere without passing via the login.php file. The only real way to protect against brute force attacks is to have a strong password.</p>\n\n<p>Security plugins will obviously notify you on any perceived security event to make you think they are doing something worthy, but like with fighting spam, you should not be worried about being attacked but about having a good defense. Once and attacker passed your defense even one time, the game is probably over and it is too late to react.</p>\n\n<p>As for blocking IP ranges - it can be useful if all the computers in the range are under your control, otherwise it is not very effective. Lets say you have limit the IP to the US, do you know how many open proxies, tor node, hacked servers and hacked desktops are there in the US? and some of them at some point will be used against you. If your password is 123456 you will be easily hacked even with IP limiting. And then of course someone can get your authoritative cookies when you admin over a public WiFi and doesn't even need to go to wp-login.php to \"login\".</p>\n"
}
] |
2015/10/03
|
[
"https://wordpress.stackexchange.com/questions/204488",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/47802/"
] |
In the admin panel, if I go to "Users -> Your Profile" I don't have the inputs to set the password. I can only generate it, but I want to set it by hand. Is that some kind of bug, or was this intentionally removed from wordpress.
[](https://i.stack.imgur.com/tvxe9.png)
If I check html with firebug I can see that inputs are actually there, but they are hidden.
EDIT:
In some old wordpress installation that has not been updated I can still see inputs for password change. See this screenshot:
[](https://i.stack.imgur.com/wPZ1x.png)
|
WordPress is also an XML-RPC server. So I guess these bots tried to gain access through the XML-RPC protocol via the `xmlrpc.php` file in your WordPress root directory.
It's possible to login and most likely your security plugin is picking up failed login attempts when `wp_authenticate()` is called and the `wp_login_failed` hook is activated.
Here's the relevant part:
```
/**
* Filter whether XML-RPC is enabled.
*
* This is the proper filter for turning off XML-RPC.
*
* @since 3.5.0
*
* @param bool $enabled Whether XML-RPC is enabled. Default true.
*/
$enabled = apply_filters( 'xmlrpc_enabled', $enabled );
if ( ! $enabled ) {
$this->error = new IXR_Error(
405,
sprintf( __( 'XML-RPC services are disabled on this site.' ) )
);
return false;
}
$user = wp_authenticate($username, $password);
```
so you can see that using:
```
add_filter( 'xmlrpc_enabled', '__return_false' );
```
will throw an `IXR_Error` error instead of trying to authenticate the user.
Some choose to block access to the `xmlrpc.php` file.
|
204,502 |
<p>I change a user via SQL in wordpress:</p>
<pre><code>SET @old_user='old_user';
SET @new_user='new_user';
UPDATE wp_users SET user_login = replace(user_login, @old_user, @new_user);
UPDATE wp_users SET user_nicename = replace(user_nicename, @old_user, @new_user);
UPDATE wp_usermeta SET meta_value = replace(meta_value, @old_user, @new_user);
</code></pre>
<p>However, while posting a new one, the author is still the old one, for instace, </p>
<blockquote>
<p>Posted on October 3, 2015 by <strong>old_user</strong>. </p>
</blockquote>
<p>I must ignore something, please guide me.</p>
|
[
{
"answer_id": 204503,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 3,
"selected": true,
"text": "<p>You probably haven't changed the display name, which is probably what is being displayed. \"nicename\" is used for the author's posts page url and not for display.</p>\n\n<pre><code>UPDATE wp_users SET display_name = replace(display_name, @old_user, @new_user);\n</code></pre>\n"
},
{
"answer_id": 205133,
"author": "Hemant Shah",
"author_id": 81736,
"author_profile": "https://wordpress.stackexchange.com/users/81736",
"pm_score": -1,
"selected": false,
"text": "<p>best is to update it via your Phpmyadmin.. easy select your database and then select users table amd just rename what you need.. </p>\n"
}
] |
2015/10/03
|
[
"https://wordpress.stackexchange.com/questions/204502",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70476/"
] |
I change a user via SQL in wordpress:
```
SET @old_user='old_user';
SET @new_user='new_user';
UPDATE wp_users SET user_login = replace(user_login, @old_user, @new_user);
UPDATE wp_users SET user_nicename = replace(user_nicename, @old_user, @new_user);
UPDATE wp_usermeta SET meta_value = replace(meta_value, @old_user, @new_user);
```
However, while posting a new one, the author is still the old one, for instace,
>
> Posted on October 3, 2015 by **old\_user**.
>
>
>
I must ignore something, please guide me.
|
You probably haven't changed the display name, which is probably what is being displayed. "nicename" is used for the author's posts page url and not for display.
```
UPDATE wp_users SET display_name = replace(display_name, @old_user, @new_user);
```
|
204,504 |
<p>My code is as follows:</p>
<pre><code>$custom_args = array(
'orderby' => 'name',
'order' => 'ASC',
'depth' => 1,
'number' => 4,
);
wp_list_categories($custom_args);
</code></pre>
<p>I'd like to create a list of categories and to show only the parent category, I use <code>'depth' => 1,</code> but because I also want to control the number of categories, I added <code>'number' => 4</code> hoping that would be enough however it only shows one parent category. </p>
<p>If I remove <code>depth</code> it shows the 4 categories but the links are also children categories.</p>
<p>Any idea on how to solve this issue I'm having?
Many thanks in advance.</p>
|
[
{
"answer_id": 204505,
"author": "kiarashi",
"author_id": 68619,
"author_profile": "https://wordpress.stackexchange.com/users/68619",
"pm_score": 0,
"selected": false,
"text": "<p>Structure is as follows:</p>\n\n<pre><code><ul class=\"main-menu\"> \n <li><a href=\"\">CMS Themes</a>\n <ul class=\"children\">\n <li><a href=\"\">Moodle</a></li>\n </ul>\n </li>\n <li><a href=\"\">Empty Cat</a></li>\n <li><a href=\"\">HTML</a>\n <ul class=\"children\">\n <li><a href=\"\">Creative</a></li>\n </ul>\n </li>\n <li><a href=\"\">Photography</a></li>\n <li><a href=\"\">Wordpress</a>\n <ul class=\"children\">\n <li><a href=\"\">Blog / Magazine</a></li>\n <li><a href=\"\">Corporate</a></li>\n <li><a href=\"\">Creative</a></li>\n <li><a href=\"\">eCommerce</a></li>\n </li>\n </ul>\n </li>\n</ul>\n</code></pre>\n"
},
{
"answer_id": 403606,
"author": "Arli",
"author_id": 220156,
"author_profile": "https://wordpress.stackexchange.com/users/220156",
"pm_score": 1,
"selected": false,
"text": "<p>You should add <code>'child_of' => 0,</code></p>\n<p>That way you will display only Main categories aka children of 0.</p>\n<pre><code>$custom_args = array(\n 'orderby' => 'name',\n 'order' => 'ASC', \n 'child_of' => 0, \n 'depth' => 1,\n 'number' => 4, \n);\nwp_list_categories($custom_args);\n</code></pre>\n<p>If you want to get WooCommerce categories try this:</p>\n<pre><code>function getCustomProductCats () {\n $orderby = 'name';\n $order = 'asc';\n $hide_empty = false ;\n $cat_args = array(\n 'orderby' => $orderby,\n 'order' => $order,\n 'child_of' => 0,\n 'number' => 4,\n 'hide_empty' => $hide_empty,\n );\n \n $product_categories = get_terms( 'product_cat', $cat_args );\n \n if( !empty($product_categories) ){\n echo '<ul>';\n foreach ($product_categories as $key => $category) {\n echo '<li>';\n echo '<a href="'.get_term_link($category).'" >';\n echo $category->name;\n echo '</a>';\n echo '</li>';\n }\n echo '</ul>';\n }\n}\ngetCustomProductCats();\n</code></pre>\n<p>source for WC solution <a href=\"https://phptechnologytutorials.wordpress.com/2018/03/10/get-list-of-all-product-categories-in-woocommerce/\" rel=\"nofollow noreferrer\">https://phptechnologytutorials.wordpress.com/2018/03/10/get-list-of-all-product-categories-in-woocommerce/</a></p>\n"
}
] |
2015/10/03
|
[
"https://wordpress.stackexchange.com/questions/204504",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68619/"
] |
My code is as follows:
```
$custom_args = array(
'orderby' => 'name',
'order' => 'ASC',
'depth' => 1,
'number' => 4,
);
wp_list_categories($custom_args);
```
I'd like to create a list of categories and to show only the parent category, I use `'depth' => 1,` but because I also want to control the number of categories, I added `'number' => 4` hoping that would be enough however it only shows one parent category.
If I remove `depth` it shows the 4 categories but the links are also children categories.
Any idea on how to solve this issue I'm having?
Many thanks in advance.
|
You should add `'child_of' => 0,`
That way you will display only Main categories aka children of 0.
```
$custom_args = array(
'orderby' => 'name',
'order' => 'ASC',
'child_of' => 0,
'depth' => 1,
'number' => 4,
);
wp_list_categories($custom_args);
```
If you want to get WooCommerce categories try this:
```
function getCustomProductCats () {
$orderby = 'name';
$order = 'asc';
$hide_empty = false ;
$cat_args = array(
'orderby' => $orderby,
'order' => $order,
'child_of' => 0,
'number' => 4,
'hide_empty' => $hide_empty,
);
$product_categories = get_terms( 'product_cat', $cat_args );
if( !empty($product_categories) ){
echo '<ul>';
foreach ($product_categories as $key => $category) {
echo '<li>';
echo '<a href="'.get_term_link($category).'" >';
echo $category->name;
echo '</a>';
echo '</li>';
}
echo '</ul>';
}
}
getCustomProductCats();
```
source for WC solution <https://phptechnologytutorials.wordpress.com/2018/03/10/get-list-of-all-product-categories-in-woocommerce/>
|
204,536 |
<p>I am an Admin of wordpress website and I have created one user with Editor role, I have installed one plugin Pretty Link(<a href="https://wordpress.org/plugins/pretty-link/" rel="nofollow">https://wordpress.org/plugins/pretty-link/</a>) this plugin shows its menu on Admin page but not on Editors page. </p>
<p>I want to display this menu option on Editor page also, so how to do this? I am using following code for my other menus:</p>
<pre><code>if ( ! function_exists( 'toplevel_admin_menu_pages' ) ) {
function toplevel_admin_menu_pages(){
if ( !current_user_can('administrator') ) { // If the user is not the administrator remove and add new menus
remove_menu_page( 'edit.php' ); // Posts
remove_menu_page( 'edit.php?post_type=page' ); // Pages
remove_menu_page( 'upload.php' ); // Media
remove_menu_page( 'tools.php' ); // Contact From 7
add_menu_page( 'Home', 'Home', 'edit_posts', 'post.php?post=8&action=edit', '', 'dashicons-admin-home', 25 );
add_menu_page( 'Life Insurance', 'Life Insurance', 'edit_posts', 'post.php?post=31&action=edit', '', 'dashicons-id-alt', 26 );
add_menu_page( 'Income Protection', 'Income Protection', 'edit_posts', 'post.php?post=40&action=edit', '', 'dashicons-lock', 27 );
add_menu_page( 'Superannuation', 'Superannuation', 'edit_posts', 'post.php?post=43&action=edit', '', 'dashicons-search', 28 );
// add_menu_page( 'Home Loan', 'Home Loan', 'edit_posts', 'post.php?post=47&action=edit', '', 'dashicons-building', 29 );
add_menu_page( 'About us', 'About Us', 'edit_posts', 'post.php?post=50&action=edit', '', 'dashicons-universal-access-alt', 30 );
add_menu_page( 'Contact us', 'Contact Us', 'edit_posts', 'post.php?post=55&action=edit', '', 'dashicons-email-alt', 31 );
add_menu_page( 'Settings', 'Settings', 'edit_posts', 'post.php?post=16&action=edit', '', 'dashicons-admin-generic', 32 );
add_menu_page( 'Pretty Links', 'Pretty Links', 'edit_posts', 'post.php?post=16&action=edit', '', 'dashicons-admin-generic', 32 );
}
}
add_action( 'admin_menu', 'toplevel_admin_menu_pages' );
}
</code></pre>
|
[
{
"answer_id": 204562,
"author": "dswebsme",
"author_id": 62906,
"author_profile": "https://wordpress.stackexchange.com/users/62906",
"pm_score": 0,
"selected": false,
"text": "<p>The free version of this plugin does not appear to support dynamic role assignment. Only users with an access level of 8+ are permitted to manage Pretty Links.</p>\n\n<p>You'll find this coded throughout the plugin:</p>\n\n<pre><code>$current_user->user_level >= 8\n</code></pre>\n\n<p>If you modify the plugin and change the 8 to a 7 your editors should immediately gain access to the plugin. Based on what I'm seeing in the source code there are just under 20 locations where this may need to be changed but the most important one is in prli-main.php (near line 159).</p>\n\n<p>Additionally, you may be able to reach out to the developer and ask them to improve the role assignment capabilities of the plugin but that might be something that requires an upgrade to the PRO version. The developer would be able to advise you best.</p>\n"
},
{
"answer_id": 207098,
"author": "Bryan Willis",
"author_id": 38123,
"author_profile": "https://wordpress.stackexchange.com/users/38123",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Check these links below.</strong> This is where the permissions are being set for your pretty link plugin admin menu:</p>\n\n<p><strong><a href=\"https://github.com/wp-plugins/pretty-link/blob/master/prli-main.php#L16\" rel=\"nofollow\">pretty-link/prli-main.php -> line 16</a> -</strong> <strong>it's set to <code>administrator</code> you want <code>edit_posts</code></strong> </p>\n\n<p><strong><a href=\"https://github.com/wp-plugins/pretty-link/blob/master/prli-main.php#L159\" rel=\"nofollow\">pretty-link/prli-main.php -> line 160</a> -</strong> <strong>it's set to <code>$current_user->user_level >= 8</code> you want <code>$current_user->user_level >= 7</code></strong></p>\n\n<hr>\n\n<p><br>\n<strong><em>What are your options?</em></strong> </p>\n\n<p><br>\n<strong>OPTION 1 - Change the code</strong> </p>\n\n<ol>\n<li>Go to this exact link (example should be your site name) and change <code>administrator</code> to <code>edit_posts</code>:</li>\n</ol>\n\n<p><a href=\"http://example.com/wp-admin/plugin-editor.php?file=pretty-link/prli-main.php&a=te&scrollto=265\" rel=\"nofollow\">http://example.com/wp-admin/plugin-editor.php?file=pretty-link/prli-main.php&a=te&scrollto=265</a></p>\n\n<ol start=\"2\">\n<li>Go to this exact link and change <code>if($current_user->user_level >= 8)</code> to <code>if($current_user->user_level >= 7)</code></li>\n</ol>\n\n<p><a href=\"http://example.com/wp-admin/plugin-editor.php?file=pretty-link/prli-main.php&a=te&scrollto=2933\" rel=\"nofollow\">http://example.com/wp-admin/plugin-editor.php?file=pretty-link/prli-main.php&a=te&scrollto=2933</a></p>\n\n<ol start=\"3\">\n<li>Save the changes. </li>\n</ol>\n\n<p><br>\n<strong>OPTION 2 - Override the code</strong></p>\n\n<ol>\n<li><p>Add this below to your <code>functions.php</code> to add the admin menus. If you want the dashboard widget as well and they don't have access just do the following for the <code>prli_add_dashboard_widgets</code> function as well.</p>\n\n<pre><code>remove_action('admin_menu', 'prli_menu');\nadd_action('admin_menu', 'prli_menu_new', 99999);\n\nfunction prli_menu_new()\n{\n global $prli_options, $prlipro_options;\n\n $role = 'edit_posts';\n if(isset($prlipro_options->min_role))\n $role = $prlipro_options->min_role;\n\n $prli_menu_hook = add_menu_page( __('Pretty Link | Manage Pretty Links', 'pretty-link'), __('Pretty Link', 'pretty-link'), $role, 'pretty-link', 'PrliLinksController::route', PRLI_IMAGES_URL.'/pretty-link-small.png' );\n $prli_add_links_menu_hook = add_submenu_page( 'pretty-link', __('Pretty Link | Add New Link', 'pretty-link'), __('Add New Link', 'pretty-link'), $role, 'add-new-pretty-link', 'PrliLinksController::new_link' );\n add_submenu_page('pretty-link', 'Pretty Link | Groups', 'Groups', $role, PRLI_PATH.'/prli-groups.php');\n\n if( isset($prli_options->extended_tracking) and $prli_options->extended_tracking != \"count\" )\n add_submenu_page('pretty-link', 'Pretty Link | Hits', 'Hits', $role, PRLI_PATH.'/prli-clicks.php');\n\n add_submenu_page('pretty-link', 'Pretty Link | Tools', 'Tools', $role, PRLI_PATH.'/prli-tools.php');\n add_submenu_page('pretty-link', 'Pretty Link | Options', 'Options', $role, PRLI_PATH.'/prli-options.php');\n\n add_action('admin_head-pretty-link/prli-clicks.php', 'prli_reports_admin_header');\n add_action('admin_print_scripts-' . $prli_menu_hook, 'PrliLinksController::load_scripts');\n add_action('admin_print_scripts-' . $prli_add_links_menu_hook, 'PrliLinksController::load_scripts');\n add_action('admin_head-pretty-link/prli-groups.php', 'prli_groups_admin_header');\n add_action('admin_head-pretty-link/prli-options.php', 'prli_options_admin_header');\n\n add_action('admin_print_styles-' . $prli_menu_hook, 'PrliLinksController::load_styles');\n add_action('admin_print_styles-' . $prli_add_links_menu_hook, 'PrliLinksController::load_styles');\n\n add_action('admin_head-' . $prli_menu_hook, 'PrliLinksController::load_dynamic_scripts', 100);\n}\n</code></pre></li>\n</ol>\n\n<p><br>\n<strong>Option 3:</strong> <strong>You can also add these on an individual basis if you don't need to give them access to everything. For example:</strong></p>\n\n<pre><code>add_action( 'admin_menu', 'pretty_links_override_action_edit_posts_role', 99999 );\n\nfunction pretty_links_override_action_edit_posts_role() {\n $role = 'edit_posts';\n // remove them first\n remove_menu_page( 'pretty-link');\n remove_submenu_page('pretty-link', 'add-new-pretty-link');\n\n add_menu_page( __('Pretty Link | Manage Pretty Links', 'pretty-link'), __('Pretty Link', 'pretty-link'), $role, 'pretty-link', 'PrliLinksController::route', PRLI_IMAGES_URL.'/pretty-link-small.png' ); \n add_submenu_page( 'pretty-link', __('Pretty Link | Add New Link', 'pretty-link'), __('Add New Link', 'pretty-link'), $role, 'add-new-pretty-link', 'PrliLinksController::new_link' );\n\n}\n</code></pre>\n\n<p><br>\n<strong>Option 4: A plugin</strong> </p>\n\n<p>Try installing <a href=\"https://wordpress.org/plugins/admin-menu-editor/\" rel=\"nofollow\">admin menu editor</a> or <a href=\"https://wordpress.org/plugins/wp-admin-ui-customize/\" rel=\"nofollow\">admin ui customize</a></p>\n\n<p><br>\n<strong>Option 5: Premium</strong> </p>\n\n<p>Pay for the premium version which has support for this</p>\n\n<p><br>\n<strong>Option 6: Hack premium options</strong> </p>\n\n<p>Hardcode <code>$prlipro_options</code>. While this makes the most sense to me, it's probably not appropriate to add here, since I'd be screwing the plugin author.</p>\n"
}
] |
2015/10/04
|
[
"https://wordpress.stackexchange.com/questions/204536",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78442/"
] |
I am an Admin of wordpress website and I have created one user with Editor role, I have installed one plugin Pretty Link(<https://wordpress.org/plugins/pretty-link/>) this plugin shows its menu on Admin page but not on Editors page.
I want to display this menu option on Editor page also, so how to do this? I am using following code for my other menus:
```
if ( ! function_exists( 'toplevel_admin_menu_pages' ) ) {
function toplevel_admin_menu_pages(){
if ( !current_user_can('administrator') ) { // If the user is not the administrator remove and add new menus
remove_menu_page( 'edit.php' ); // Posts
remove_menu_page( 'edit.php?post_type=page' ); // Pages
remove_menu_page( 'upload.php' ); // Media
remove_menu_page( 'tools.php' ); // Contact From 7
add_menu_page( 'Home', 'Home', 'edit_posts', 'post.php?post=8&action=edit', '', 'dashicons-admin-home', 25 );
add_menu_page( 'Life Insurance', 'Life Insurance', 'edit_posts', 'post.php?post=31&action=edit', '', 'dashicons-id-alt', 26 );
add_menu_page( 'Income Protection', 'Income Protection', 'edit_posts', 'post.php?post=40&action=edit', '', 'dashicons-lock', 27 );
add_menu_page( 'Superannuation', 'Superannuation', 'edit_posts', 'post.php?post=43&action=edit', '', 'dashicons-search', 28 );
// add_menu_page( 'Home Loan', 'Home Loan', 'edit_posts', 'post.php?post=47&action=edit', '', 'dashicons-building', 29 );
add_menu_page( 'About us', 'About Us', 'edit_posts', 'post.php?post=50&action=edit', '', 'dashicons-universal-access-alt', 30 );
add_menu_page( 'Contact us', 'Contact Us', 'edit_posts', 'post.php?post=55&action=edit', '', 'dashicons-email-alt', 31 );
add_menu_page( 'Settings', 'Settings', 'edit_posts', 'post.php?post=16&action=edit', '', 'dashicons-admin-generic', 32 );
add_menu_page( 'Pretty Links', 'Pretty Links', 'edit_posts', 'post.php?post=16&action=edit', '', 'dashicons-admin-generic', 32 );
}
}
add_action( 'admin_menu', 'toplevel_admin_menu_pages' );
}
```
|
**Check these links below.** This is where the permissions are being set for your pretty link plugin admin menu:
**[pretty-link/prli-main.php -> line 16](https://github.com/wp-plugins/pretty-link/blob/master/prli-main.php#L16) -** **it's set to `administrator` you want `edit_posts`**
**[pretty-link/prli-main.php -> line 160](https://github.com/wp-plugins/pretty-link/blob/master/prli-main.php#L159) -** **it's set to `$current_user->user_level >= 8` you want `$current_user->user_level >= 7`**
---
***What are your options?***
**OPTION 1 - Change the code**
1. Go to this exact link (example should be your site name) and change `administrator` to `edit_posts`:
<http://example.com/wp-admin/plugin-editor.php?file=pretty-link/prli-main.php&a=te&scrollto=265>
2. Go to this exact link and change `if($current_user->user_level >= 8)` to `if($current_user->user_level >= 7)`
<http://example.com/wp-admin/plugin-editor.php?file=pretty-link/prli-main.php&a=te&scrollto=2933>
3. Save the changes.
**OPTION 2 - Override the code**
1. Add this below to your `functions.php` to add the admin menus. If you want the dashboard widget as well and they don't have access just do the following for the `prli_add_dashboard_widgets` function as well.
```
remove_action('admin_menu', 'prli_menu');
add_action('admin_menu', 'prli_menu_new', 99999);
function prli_menu_new()
{
global $prli_options, $prlipro_options;
$role = 'edit_posts';
if(isset($prlipro_options->min_role))
$role = $prlipro_options->min_role;
$prli_menu_hook = add_menu_page( __('Pretty Link | Manage Pretty Links', 'pretty-link'), __('Pretty Link', 'pretty-link'), $role, 'pretty-link', 'PrliLinksController::route', PRLI_IMAGES_URL.'/pretty-link-small.png' );
$prli_add_links_menu_hook = add_submenu_page( 'pretty-link', __('Pretty Link | Add New Link', 'pretty-link'), __('Add New Link', 'pretty-link'), $role, 'add-new-pretty-link', 'PrliLinksController::new_link' );
add_submenu_page('pretty-link', 'Pretty Link | Groups', 'Groups', $role, PRLI_PATH.'/prli-groups.php');
if( isset($prli_options->extended_tracking) and $prli_options->extended_tracking != "count" )
add_submenu_page('pretty-link', 'Pretty Link | Hits', 'Hits', $role, PRLI_PATH.'/prli-clicks.php');
add_submenu_page('pretty-link', 'Pretty Link | Tools', 'Tools', $role, PRLI_PATH.'/prli-tools.php');
add_submenu_page('pretty-link', 'Pretty Link | Options', 'Options', $role, PRLI_PATH.'/prli-options.php');
add_action('admin_head-pretty-link/prli-clicks.php', 'prli_reports_admin_header');
add_action('admin_print_scripts-' . $prli_menu_hook, 'PrliLinksController::load_scripts');
add_action('admin_print_scripts-' . $prli_add_links_menu_hook, 'PrliLinksController::load_scripts');
add_action('admin_head-pretty-link/prli-groups.php', 'prli_groups_admin_header');
add_action('admin_head-pretty-link/prli-options.php', 'prli_options_admin_header');
add_action('admin_print_styles-' . $prli_menu_hook, 'PrliLinksController::load_styles');
add_action('admin_print_styles-' . $prli_add_links_menu_hook, 'PrliLinksController::load_styles');
add_action('admin_head-' . $prli_menu_hook, 'PrliLinksController::load_dynamic_scripts', 100);
}
```
**Option 3:** **You can also add these on an individual basis if you don't need to give them access to everything. For example:**
```
add_action( 'admin_menu', 'pretty_links_override_action_edit_posts_role', 99999 );
function pretty_links_override_action_edit_posts_role() {
$role = 'edit_posts';
// remove them first
remove_menu_page( 'pretty-link');
remove_submenu_page('pretty-link', 'add-new-pretty-link');
add_menu_page( __('Pretty Link | Manage Pretty Links', 'pretty-link'), __('Pretty Link', 'pretty-link'), $role, 'pretty-link', 'PrliLinksController::route', PRLI_IMAGES_URL.'/pretty-link-small.png' );
add_submenu_page( 'pretty-link', __('Pretty Link | Add New Link', 'pretty-link'), __('Add New Link', 'pretty-link'), $role, 'add-new-pretty-link', 'PrliLinksController::new_link' );
}
```
**Option 4: A plugin**
Try installing [admin menu editor](https://wordpress.org/plugins/admin-menu-editor/) or [admin ui customize](https://wordpress.org/plugins/wp-admin-ui-customize/)
**Option 5: Premium**
Pay for the premium version which has support for this
**Option 6: Hack premium options**
Hardcode `$prlipro_options`. While this makes the most sense to me, it's probably not appropriate to add here, since I'd be screwing the plugin author.
|
204,564 |
<p>It seems a lot of plugin developers take the time to add filter/action hooks to let users tweak their products’ functionality. Which is great, but what they often don’t do is provide a list of hooks and how many arguments they take. </p>
<p>Has anyone found the best automated way to point at a plugin (or theme) directory and see a list of all available hooks?</p>
<p>I’ve seem some plugins that scan for hooks, but as far as I can tell, they show you which ones are actually being called to render a given page. Which I get can be handy. But sometimes if I know I’m interacting with a particular plugin, I want to know every place it might let me hook an action or filter. </p>
<p>So what I’m really looking for is something that, given a plugin root directory will create a list where each item includes:</p>
<ul>
<li>tag</li>
<li>type (action or filter)</li>
<li>number of arguments </li>
<li>where it’s called (via <code>do_action()</code> or <code>apply_filter()</code>) in the source</li>
</ul>
<p>A script would be great since this could presumably nicely HTMLify the whole thing and show it to me right in the admin UI for every plugin. But even a command-line script that outputs a useful static file would be great.</p>
|
[
{
"answer_id": 204822,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": false,
"text": "<p>There is no script or plugin that I know of to do what you want. As you have stated, there are scripts (<em>even global variables</em>) which you can use to print filters and actions currently being used.</p>\n\n<p>As for dormant filters and actions, I have written two very basic functions (<em>with some help here and there</em>) which finds all <code>apply_filters</code> and <code>do_action</code> instances in a file and then prints it out</p>\n\n<h2>BASICS</h2>\n\n<ul>\n<li><p>We will use the <code>RecursiveDirectoryIterator</code>,<code>RecursiveIteratorIterator</code> and <code>RegexIterator</code> PHP classes to get all the PHP files within a directory. As example, on my localhost, I have used <code>E:\\xammp\\htdocs\\wordpress\\wp-includes</code></p></li>\n<li><p>We will then loop through the files, and search and return (<em><code>preg_match_all</code></em>) all instances of <code>apply_filters</code> and <code>do_action</code>. I have set it up to match nested instances of parenthesis and also to match possible whitespaces between <code>apply_filters</code>/<code>do_action</code> and the first parenthesis</p></li>\n</ul>\n\n<p>We will simple then create an array with all filters and actions and then loop through the array and output the file name and filters and actions. We will skip files without filters/actions</p>\n\n<h2>IMPORTANT NOTES</h2>\n\n<ul>\n<li><p>This functions are very expensive. Run them only on a local test installation. </p></li>\n<li><p>Modify the functions as needed. You can decide to write the output to a file, create a special backend page for that, the options are unlimited</p></li>\n</ul>\n\n<h2>OPTION 1</h2>\n\n<p>The first options function is very simple, we will return the contents of a file as a string using <code>file_get_contents</code>, search for the <code>apply_filters</code>/<code>do_action</code> instances and simply output the filename and filter/action names</p>\n\n<p>I have commented the code for easy following</p>\n\n<pre><code>function get_all_filters_and_actions( $path = '' )\n{\n //Check if we have a path, if not, return false\n if ( !$path ) \n return false;\n\n // Validate and sanitize path\n $path = filter_var( $path, FILTER_SANITIZE_URL );\n /**\n * If valiadtion fails, return false\n *\n * You can add an error message of something here to tell\n * the user that the URL validation failed\n */\n if ( !$path ) \n return false;\n\n // Get each php file from the directory or URL \n $dir = new RecursiveDirectoryIterator( $path );\n $flat = new RecursiveIteratorIterator( $dir );\n $files = new RegexIterator( $flat, '/\\.php$/i' );\n\n if ( $files ) {\n\n $output = '';\n foreach($files as $name=>$file) {\n /**\n * Match and return all instances of apply_filters(**) or do_action(**)\n * The regex will match the following\n * - Any depth of nesting of parentheses, so apply_filters( 'filter_name', parameter( 1,2 ) ) will be matched\n * - Whitespaces that might exist between apply_filters or do_action and the first parentheses\n */\n // Use file_get_contents to get contents of the php file\n $get_file_content = file_get_contents( $file );\n // Use htmlspecialchars() to avoid HTML in filters from rendering in page\n $save_content = htmlspecialchars( $get_file_content );\n preg_match_all( '/(apply_filters|do_action)\\s*(\\([^()]*(?:(?-1)[^()]*)*+\\))/', $save_content, $matches );\n\n // Build an array to hold the file name as key and apply_filters/do_action values as value\n if ( $matches[0] )\n $array[$name] = $matches[0];\n }\n foreach ( $array as $file_name=>$value ) {\n\n $output .= '<ul>';\n $output .= '<strong>File Path: ' . $file_name .'</strong></br>';\n $output .= 'The following filters and/or actions are available';\n foreach ( $value as $k=>$v ) {\n $output .= '<li>' . $v . '</li>';\n }\n $output .= '</ul>';\n }\n return $output;\n }\n\n return false;\n}\n</code></pre>\n\n<p>You can use at follow on a template, frontend or backend</p>\n\n<pre><code>echo get_all_filters_and_actions( 'E:\\xammp\\htdocs\\wordpress\\wp-includes' );\n</code></pre>\n\n<p>This will print</p>\n\n<p><a href=\"https://i.stack.imgur.com/BmZVh.png\" rel=\"nofollow noreferrer\"><a href=\"https://i.stack.imgur.com/BmZVh.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BmZVh.png\" alt=\"enter image description here\"></a></a></p>\n\n<h2>OPTION 2</h2>\n\n<p>This option is a bit more expensive to run. This function returns the line number where the filter/action can be found.</p>\n\n<p>Here we use <code>file</code> to explode the file into an array, then we search and return the filter/action and the line number</p>\n\n<pre><code>function get_all_filters_and_actions2( $path = '' )\n{\n //Check if we have a path, if not, return false\n if ( !$path ) \n return false;\n\n // Validate and sanitize path\n $path = filter_var( $path, FILTER_SANITIZE_URL );\n /**\n * If valiadtion fails, return false\n *\n * You can add an error message of something here to tell\n * the user that the URL validation failed\n */\n if ( !$path ) \n return false;\n\n // Get each php file from the directory or URL \n $dir = new RecursiveDirectoryIterator( $path );\n $flat = new RecursiveIteratorIterator( $dir );\n $files = new RegexIterator( $flat, '/\\.php$/i' );\n\n if ( $files ) {\n\n $output = '';\n $array = [];\n foreach($files as $name=>$file) {\n /**\n * Match and return all instances of apply_filters(**) or do_action(**)\n * The regex will match the following\n * - Any depth of nesting of parentheses, so apply_filters( 'filter_name', parameter( 1,2 ) ) will be matched\n * - Whitespaces that might exist between apply_filters or do_action and the first parentheses\n */\n // Use file_get_contents to get contents of the php file\n $get_file_contents = file( $file );\n foreach ( $get_file_contents as $key=>$get_file_content ) {\n preg_match_all( '/(apply_filters|do_action)\\s*(\\([^()]*(?:(?-1)[^()]*)*+\\))/', $get_file_content, $matches );\n\n if ( $matches[0] )\n $array[$name][$key+1] = $matches[0];\n }\n }\n\n if ( $array ) {\n foreach ( $array as $file_name=>$values ) {\n $output .= '<ul>';\n $output .= '<strong>File Path: ' . $file_name .'</strong></br>';\n $output .= 'The following filters and/or actions are available';\n\n foreach ( $values as $line_number=>$string ) {\n $whitespaces = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';\n $output .= '<li>Line reference ' . $line_number . $whitespaces . $string[0] . '</li>';\n }\n $output .= '</ul>';\n }\n }\n return $output;\n\n }\n\n return false;\n}\n</code></pre>\n\n<p>You can use at follow on a template, frontend or backend</p>\n\n<pre><code>echo get_all_filters_and_actions2( 'E:\\xammp\\htdocs\\wordpress\\wp-includes' );\n</code></pre>\n\n<p>This will print</p>\n\n<p><a href=\"https://i.stack.imgur.com/GsppZ.png\" rel=\"nofollow noreferrer\"><a href=\"https://i.stack.imgur.com/GsppZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/GsppZ.png\" alt=\"enter image description here\"></a></a></p>\n\n<h2>EDIT</h2>\n\n<p>This is basically as much as I can do without the scripts timing out or running out of memory. With the code in option 2, it is as easy as going to the said file and said line in the source code and then get all the valid parameter values of the filter/action, also, importantly, get the function and further context in which the filter/action is used</p>\n"
},
{
"answer_id": 204834,
"author": "Jan Beck",
"author_id": 18760,
"author_profile": "https://wordpress.stackexchange.com/users/18760",
"pm_score": 3,
"selected": false,
"text": "<p>Sounds like <a href=\"https://github.com/WordPress/phpdoc-parser\">WP Parser</a> does what you are looking for.\nIt is used to generate the official <a href=\"https://developer.wordpress.org/reference/\">developer reference</a>. It lists parameters, @since tags and references to the source. It works with all WordPress plugins and can be accessed via command line:</p>\n\n<pre><code>wp parser create /path/to/source/code --user=<id|login>\n</code></pre>\n"
},
{
"answer_id": 204838,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<h2>The Fast and the Furious</h2>\n\n<p>The good ol' <code>*nix</code> command-line is always handy: </p>\n\n<pre><code># grep --line-number \\\n --exclude-dir=/path/to/some/directory \\\n --include=*.php \\ \n --recursive \\\n \"add_filter\\|do_action\\|apply_filters\" \\\n /path/to/wp-content/plugins/some-plugin \\ \n | less\n</code></pre>\n\n<p>Many more options via <code>#man grep</code>. </p>\n\n<p>Then we can even create a simple bash script <code>wp-search.sh</code>:</p>\n\n<pre><code>#!/bash/bin\ngrep --line-number \\\n --exclude-dir=/path/to/some/directory \\\n --include=*.$1 \\\n --recursive $2 $3\n</code></pre>\n\n<p>and run it with.</p>\n\n<pre><code> # bash wp-search.sh php \"add_filter\\|do_action\\|apply_filters\" /path/to/some-plugin\n</code></pre>\n\n<h2>Pretty output</h2>\n\n<p>We can use <code>--color</code> attribute to colorize the output of <code>grep</code>, but note that it will not work with <code>less</code>.</p>\n\n<p>Another option would be to generate an HTML table for the search results.</p>\n\n<p>Here's an <code>awk</code> example I constructed that outputs the search results as an HTML table, into the <code>results.html</code> file: </p>\n\n<pre><code> | sed 's/:/: /2' \\\n | awk ' \\\n BEGIN { \\\n print \"<table><tr><th>Results</th><th>Location</th></tr>\" \\\n } \\\n { \\\n $1=$1; location=$1; $1=\"\"; print \"<tr><td>\" $0 \"</td><td>\" location \"</td><tr>\" \\\n } \\\n END { \\\n print \"</table>\" \\\n }' \\\n > results.html\n</code></pre>\n\n<p>where I used <a href=\"https://unix.stackexchange.com/a/117047/31912\">this trick</a> to remove all leading white space and <a href=\"https://stackoverflow.com/a/2961994/2078474\">this one</a> to print all fields but the first one. </p>\n\n<p>I use <code>sed</code> here just to add extra space after the second colon (<code>:</code>), just in case there's no space there.</p>\n\n<h2>Script</h2>\n\n<p>We could add this to our <code>wp-search.sh</code> script:</p>\n\n<pre><code>#!/bash/bin\ngrep --with-filename \\\n --line-number \\\n --exclude-dir=/path/to/some/directory \\\n --include=*.$1 \\\n --recursive $2 $3 \\\n| sed 's/:/: /2' \\\n| awk ' BEGIN { \\\n print \"<table><tr><th>Results</th><th>Location</th></tr>\" \\\n } \\\n { \\\n $1=$1; location=$1; $1=\"\"; print \"<tr><td>\" $0 \"</td><td>\" location \"</td><tr>\" \\\n } \\\n END { \\\n print \"</table>\" \\\n }' \\\n> /path/to/results.html\n</code></pre>\n\n<p>where you have to adjust the <code>/path/to/some/directory</code> and <code>/path/to/results.html</code> to your needs.</p>\n\n<h2>Example - Searching a plugin</h2>\n\n<p>If we try this on the <code>wordpress-importer</code> plugin with:</p>\n\n<pre><code>bash wp-search.sh php \"add_filter\\|do_action\" /path/to/wp-content/plugins/wordpress-importer/\n</code></pre>\n\n<p>then the <code>results.html</code> file will display as:</p>\n\n<p><a href=\"https://i.stack.imgur.com/lXZhp.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lXZhp.jpg\" alt=\"results\"></a></p>\n\n<h2>Example - Searching the core</h2>\n\n<p>I time tested it for the core:</p>\n\n<pre><code>time bash wp-search.sh php \"add_filter\\|do_action\" /path/to/wordpress/core/\n\nreal 0m0.083s\nuser 0m0.067s\nsys 0m0.017s\n</code></pre>\n\n<p>and it's fast!</p>\n\n<h2>Notes</h2>\n\n<p>To get extra context we might use the <code>-C NUMBER</code> of grep.</p>\n\n<p>We could modify the HTML output in various ways, but hopefully you can adjust this further to your needs.</p>\n"
}
] |
2015/10/04
|
[
"https://wordpress.stackexchange.com/questions/204564",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80980/"
] |
It seems a lot of plugin developers take the time to add filter/action hooks to let users tweak their products’ functionality. Which is great, but what they often don’t do is provide a list of hooks and how many arguments they take.
Has anyone found the best automated way to point at a plugin (or theme) directory and see a list of all available hooks?
I’ve seem some plugins that scan for hooks, but as far as I can tell, they show you which ones are actually being called to render a given page. Which I get can be handy. But sometimes if I know I’m interacting with a particular plugin, I want to know every place it might let me hook an action or filter.
So what I’m really looking for is something that, given a plugin root directory will create a list where each item includes:
* tag
* type (action or filter)
* number of arguments
* where it’s called (via `do_action()` or `apply_filter()`) in the source
A script would be great since this could presumably nicely HTMLify the whole thing and show it to me right in the admin UI for every plugin. But even a command-line script that outputs a useful static file would be great.
|
There is no script or plugin that I know of to do what you want. As you have stated, there are scripts (*even global variables*) which you can use to print filters and actions currently being used.
As for dormant filters and actions, I have written two very basic functions (*with some help here and there*) which finds all `apply_filters` and `do_action` instances in a file and then prints it out
BASICS
------
* We will use the `RecursiveDirectoryIterator`,`RecursiveIteratorIterator` and `RegexIterator` PHP classes to get all the PHP files within a directory. As example, on my localhost, I have used `E:\xammp\htdocs\wordpress\wp-includes`
* We will then loop through the files, and search and return (*`preg_match_all`*) all instances of `apply_filters` and `do_action`. I have set it up to match nested instances of parenthesis and also to match possible whitespaces between `apply_filters`/`do_action` and the first parenthesis
We will simple then create an array with all filters and actions and then loop through the array and output the file name and filters and actions. We will skip files without filters/actions
IMPORTANT NOTES
---------------
* This functions are very expensive. Run them only on a local test installation.
* Modify the functions as needed. You can decide to write the output to a file, create a special backend page for that, the options are unlimited
OPTION 1
--------
The first options function is very simple, we will return the contents of a file as a string using `file_get_contents`, search for the `apply_filters`/`do_action` instances and simply output the filename and filter/action names
I have commented the code for easy following
```
function get_all_filters_and_actions( $path = '' )
{
//Check if we have a path, if not, return false
if ( !$path )
return false;
// Validate and sanitize path
$path = filter_var( $path, FILTER_SANITIZE_URL );
/**
* If valiadtion fails, return false
*
* You can add an error message of something here to tell
* the user that the URL validation failed
*/
if ( !$path )
return false;
// Get each php file from the directory or URL
$dir = new RecursiveDirectoryIterator( $path );
$flat = new RecursiveIteratorIterator( $dir );
$files = new RegexIterator( $flat, '/\.php$/i' );
if ( $files ) {
$output = '';
foreach($files as $name=>$file) {
/**
* Match and return all instances of apply_filters(**) or do_action(**)
* The regex will match the following
* - Any depth of nesting of parentheses, so apply_filters( 'filter_name', parameter( 1,2 ) ) will be matched
* - Whitespaces that might exist between apply_filters or do_action and the first parentheses
*/
// Use file_get_contents to get contents of the php file
$get_file_content = file_get_contents( $file );
// Use htmlspecialchars() to avoid HTML in filters from rendering in page
$save_content = htmlspecialchars( $get_file_content );
preg_match_all( '/(apply_filters|do_action)\s*(\([^()]*(?:(?-1)[^()]*)*+\))/', $save_content, $matches );
// Build an array to hold the file name as key and apply_filters/do_action values as value
if ( $matches[0] )
$array[$name] = $matches[0];
}
foreach ( $array as $file_name=>$value ) {
$output .= '<ul>';
$output .= '<strong>File Path: ' . $file_name .'</strong></br>';
$output .= 'The following filters and/or actions are available';
foreach ( $value as $k=>$v ) {
$output .= '<li>' . $v . '</li>';
}
$output .= '</ul>';
}
return $output;
}
return false;
}
```
You can use at follow on a template, frontend or backend
```
echo get_all_filters_and_actions( 'E:\xammp\htdocs\wordpress\wp-includes' );
```
This will print
[[](https://i.stack.imgur.com/BmZVh.png)](https://i.stack.imgur.com/BmZVh.png)
OPTION 2
--------
This option is a bit more expensive to run. This function returns the line number where the filter/action can be found.
Here we use `file` to explode the file into an array, then we search and return the filter/action and the line number
```
function get_all_filters_and_actions2( $path = '' )
{
//Check if we have a path, if not, return false
if ( !$path )
return false;
// Validate and sanitize path
$path = filter_var( $path, FILTER_SANITIZE_URL );
/**
* If valiadtion fails, return false
*
* You can add an error message of something here to tell
* the user that the URL validation failed
*/
if ( !$path )
return false;
// Get each php file from the directory or URL
$dir = new RecursiveDirectoryIterator( $path );
$flat = new RecursiveIteratorIterator( $dir );
$files = new RegexIterator( $flat, '/\.php$/i' );
if ( $files ) {
$output = '';
$array = [];
foreach($files as $name=>$file) {
/**
* Match and return all instances of apply_filters(**) or do_action(**)
* The regex will match the following
* - Any depth of nesting of parentheses, so apply_filters( 'filter_name', parameter( 1,2 ) ) will be matched
* - Whitespaces that might exist between apply_filters or do_action and the first parentheses
*/
// Use file_get_contents to get contents of the php file
$get_file_contents = file( $file );
foreach ( $get_file_contents as $key=>$get_file_content ) {
preg_match_all( '/(apply_filters|do_action)\s*(\([^()]*(?:(?-1)[^()]*)*+\))/', $get_file_content, $matches );
if ( $matches[0] )
$array[$name][$key+1] = $matches[0];
}
}
if ( $array ) {
foreach ( $array as $file_name=>$values ) {
$output .= '<ul>';
$output .= '<strong>File Path: ' . $file_name .'</strong></br>';
$output .= 'The following filters and/or actions are available';
foreach ( $values as $line_number=>$string ) {
$whitespaces = ' ';
$output .= '<li>Line reference ' . $line_number . $whitespaces . $string[0] . '</li>';
}
$output .= '</ul>';
}
}
return $output;
}
return false;
}
```
You can use at follow on a template, frontend or backend
```
echo get_all_filters_and_actions2( 'E:\xammp\htdocs\wordpress\wp-includes' );
```
This will print
[[](https://i.stack.imgur.com/GsppZ.png)](https://i.stack.imgur.com/GsppZ.png)
EDIT
----
This is basically as much as I can do without the scripts timing out or running out of memory. With the code in option 2, it is as easy as going to the said file and said line in the source code and then get all the valid parameter values of the filter/action, also, importantly, get the function and further context in which the filter/action is used
|
204,615 |
<p>on my newssite i have the first post in a full-width column, after that all older post are in three columns per row. But now i want that wordpress put after every three columns a and to keeps the elements into rows.
I tried to adjust the following solutions:
<a href="https://stackoverflow.com/questions/29922657/adding-a-row-div-after-every-four-post-in-wordpress">Solution 1</a>
<a href="https://stackoverflow.com/questions/21496052/wrap-every-2-wordpress-posts-inside-bootstrap-row-class">Solution 2</a>
<a href="https://wordpress.org/support/topic/the-multiple-loop-how-to-for-3-rows-each-row-3-posts" rel="nofollow noreferrer">Solution 3</a></p>
<p>But nothing of that will work.</p>
<p>Here is my code to get my posts:</p>
<pre><code> <div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<div class=" entry-content">
<?php if (have_posts()) : ?>
<?php $post = $posts[0]; $c=0;?>
<?php while (have_posts()) : the_post(); ?>
<?php $c++;
if( !$paged && $c == 1) :?>
<?php get_template_part( 'template-parts/content', 'aktuelles-first' ); ?>
<div class="accordion">
<div class="row">
<?php else :?>
<?php get_template_part( 'template-parts/content', 'aktuelles' ); ?>
<?php endif;?>
<?php endwhile; ?>
<?php endif; ?>
</div></div>
</main><!-- #main -->
</div><!-- #primary -->
</code></pre>
<p>Is there any solution without changing my way to get the posts?</p>
|
[
{
"answer_id": 204617,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>If HHVM has bugs with core PHP functionality then it is not ready to be used for production sites.</p>\n"
},
{
"answer_id": 204641,
"author": "phatskat",
"author_id": 20143,
"author_profile": "https://wordpress.stackexchange.com/users/20143",
"pm_score": 0,
"selected": false,
"text": "<p>In <code>pomo/po.php</code>:</p>\n\n<pre><code># pomo/po.php\n# 168: $res = implode(\"\\n\", array_map(create_function('$x', \"return $php_with.\\$x;\"), $lines));\n# 256: $is_final = create_function('$context', 'return $context == \"msgstr\" || $context == \"msgstr_plural\";');\n# 349: if (array() == array_filter($entry->translations, create_function('$t', 'return $t || \"0\" === $t;'))) {\n\n $res = implode( \"\\n\", array_map( function( $x ) {\n return $php_with.\\$x;\n }, $lines ) );\n\n $is_final = function( $context ) {\n return $context == \"msgstr\" || $context == \"msgstr_plural\";\n }\n\n if (array() == array_filter($entry->translations, function($t) { return $t || \"0\" === $t; } ) ) {\n</code></pre>\n\n<p>However, in <code>pomo/translations.php</code>, the line is </p>\n\n<pre><code>pomo/translations.php\n208: return create_function('$n', $func_body);\n</code></pre>\n\n<p>Since $func_body is a variable, we have to take a closer look at the code:</p>\n\n<pre><code>function make_plural_form_function($nplurals, $expression) {\n $expression = str_replace('n', '$n', $expression);\n $func_body = \"\n \\$index = (int)($expression);\n return (\\$index < $nplurals)? \\$index : $nplurals - 1;\";\n return create_function('$n', $func_body);\n}\n</code></pre>\n\n<p>We can try to use PHP's <code>use</code> keyword (haven't tested this, no promises it works):</p>\n\n<pre><code>function make_plural_form_function($nplurals, $expression) {\n $expression = str_replace('n', '$n', $expression);\n return function( $n ) use ( $expression, $nplurals ) {\n $index = (int)($expression);\n return ($index < $nplurals) ? $index : $nplurals - 1;\n } \n}\n</code></pre>\n\n<p>Having said all of this, unless you absolutely <strong>must</strong> use HHVM, don't. This is a large issue, and even fixing these calls once means that you'll have to do it over and over each time you reinstall or upgrade WordPress.</p>\n\n<p><strong>EDIT: BIG WARNING HERE. WHAT I AM SUGGESTING IS A MODIFICATION TO WORDPRESS CORE. THIS SHOULD NEVER BE AN OPTION, ESPECIALLY IN A PRODUCTION ENVIRONMENT, UNLESS YOU ARE WILLING TO TAKE ON THE LONG-TERM MAINTENANCE OF A HACK TO THE CORE. DO NOT DO THIS</strong></p>\n"
}
] |
2015/10/05
|
[
"https://wordpress.stackexchange.com/questions/204615",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75019/"
] |
on my newssite i have the first post in a full-width column, after that all older post are in three columns per row. But now i want that wordpress put after every three columns a and to keeps the elements into rows.
I tried to adjust the following solutions:
[Solution 1](https://stackoverflow.com/questions/29922657/adding-a-row-div-after-every-four-post-in-wordpress)
[Solution 2](https://stackoverflow.com/questions/21496052/wrap-every-2-wordpress-posts-inside-bootstrap-row-class)
[Solution 3](https://wordpress.org/support/topic/the-multiple-loop-how-to-for-3-rows-each-row-3-posts)
But nothing of that will work.
Here is my code to get my posts:
```
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<div class=" entry-content">
<?php if (have_posts()) : ?>
<?php $post = $posts[0]; $c=0;?>
<?php while (have_posts()) : the_post(); ?>
<?php $c++;
if( !$paged && $c == 1) :?>
<?php get_template_part( 'template-parts/content', 'aktuelles-first' ); ?>
<div class="accordion">
<div class="row">
<?php else :?>
<?php get_template_part( 'template-parts/content', 'aktuelles' ); ?>
<?php endif;?>
<?php endwhile; ?>
<?php endif; ?>
</div></div>
</main><!-- #main -->
</div><!-- #primary -->
```
Is there any solution without changing my way to get the posts?
|
If HHVM has bugs with core PHP functionality then it is not ready to be used for production sites.
|
204,626 |
<p>I am using this code, but nothing is being shown on the front page. It seems the shortcode is registered correctly though. </p>
<pre><code>function choose_ashtopbar() {
?><img src="/images/flag_globe2.png" class="ttupmg" /><div class="dmzeus"><ul><li class="f-selection">London<ul><li>New York</li><li>Paris</li><li>Milan</li></ul></li></ul></div><?php
}
function register_ashcodes(){
add_shortcode('ashtopbar', 'choose_ashtopbar');
}
add_action( 'init', 'register_ashcodes');
</code></pre>
|
[
{
"answer_id": 204629,
"author": "dswebsme",
"author_id": 62906,
"author_profile": "https://wordpress.stackexchange.com/users/62906",
"pm_score": 1,
"selected": false,
"text": "<p>Your code works as expected. Two things you need to check:</p>\n\n<p>1) In order for shortcodes to render as expected you need to use the_content() within the loop OR wrap your content in apply_filters() as shown here:</p>\n\n<pre><code>echo apply_filters('the_content', $my_content);\n</code></pre>\n\n<p>The apply_filters() helper tells WordPress to parse the content before it's rendered, resolving things like shortcodes, line breaks, etc. Within the loop, the_content() handles the call to apply_filters() automatically.</p>\n\n<p>2) Be sure you clear any server side or local cache that may be in place while debugging to ensure you can see your changes as you make them.</p>\n"
},
{
"answer_id": 204632,
"author": "phatskat",
"author_id": 20143,
"author_profile": "https://wordpress.stackexchange.com/users/20143",
"pm_score": 3,
"selected": true,
"text": "<p><s>As <code>birgire</code> mentioned in the comments, \"you're missing the <code>return</code> part\" to which you replied \"how do I add that without escaping the HTML code?\"</s></p>\n\n<p><strong>EDIT</strong>: Just a clarification. Your code should have worked, as pointed out by dswebsme. I just tested with and without a return, and both work (although returning would be preferred). The next question would be: are you putting your shortcode tag properly in to your content? e.g. <code>[ashtopbar/]</code> ? and it's not misspelled, right?</p>\n\n<p>Leaving the section about heredoc anyway:</p>\n\n<p>In PHP, you have a number of ways to get complex data (including HTML) in to a string variable. In your case, I would use <a href=\"http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc\" rel=\"nofollow\">PHP's heredoc syntax</a>, as you can put virtually anything inside of it and not have to escape the syntax:</p>\n\n<pre><code><?php\n\nfunction choose_ashtopbar() {\n $html = <<<HTML\n<img src=\"/images/flag_globe2.png\" class=\"ttupmg\" />\n<div class=\"dmzeus\">\n <ul>\n <li class=\"f-selection\">London\n <ul>\n <li>New York</li>\n <li>Paris</li>\n <li>Milan</li>\n </ul>\n </li>\n </ul>\n</div>\nHTML;\n\n return $html;\n}\n\nfunction register_ashcodes(){\n add_shortcode('ashtopbar', 'choose_ashtopbar');\n}\n\n# I'm guessing init has already run by this point\n# add_action( 'init', 'register_ashcodes');\n# Use a different hook or just register your code\nregister_ashcodes();\n</code></pre>\n\n<p>Essentially, your original code was just echoing the HTML when <code>add_shortcode</code> ran the <code>choose_ashtopbar</code> function, which is probably not what you wanted. </p>\n"
},
{
"answer_id": 204633,
"author": "Robert hue",
"author_id": 22461,
"author_profile": "https://wordpress.stackexchange.com/users/22461",
"pm_score": 2,
"selected": false,
"text": "<p>Why are you using all that. Can't you simply define shortcode with <a href=\"https://codex.wordpress.org/Function_Reference/add_shortcode\" rel=\"nofollow\"><code>add_shortcode</code></a>?\nHere is the function.</p>\n\n<p>Also yes, you are missing the <code>return</code> in your function. Finished code here.</p>\n\n<pre><code>function choose_ashtopbar( $atts, $content ) {\n return '<img src=\"/images/flag_globe2.png\" class=\"ttupmg\" /><div class=\"dmzeus\"><ul><li class=\"f-selection\">London<ul><li>New York</li><li>Paris</li><li>Milan</li></ul></li></ul></div>';\n}\nadd_shortcode( 'ashtopbar', 'choose_ashtopbar' );\n</code></pre>\n"
}
] |
2015/10/05
|
[
"https://wordpress.stackexchange.com/questions/204626",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40727/"
] |
I am using this code, but nothing is being shown on the front page. It seems the shortcode is registered correctly though.
```
function choose_ashtopbar() {
?><img src="/images/flag_globe2.png" class="ttupmg" /><div class="dmzeus"><ul><li class="f-selection">London<ul><li>New York</li><li>Paris</li><li>Milan</li></ul></li></ul></div><?php
}
function register_ashcodes(){
add_shortcode('ashtopbar', 'choose_ashtopbar');
}
add_action( 'init', 'register_ashcodes');
```
|
~~As `birgire` mentioned in the comments, "you're missing the `return` part" to which you replied "how do I add that without escaping the HTML code?"~~
**EDIT**: Just a clarification. Your code should have worked, as pointed out by dswebsme. I just tested with and without a return, and both work (although returning would be preferred). The next question would be: are you putting your shortcode tag properly in to your content? e.g. `[ashtopbar/]` ? and it's not misspelled, right?
Leaving the section about heredoc anyway:
In PHP, you have a number of ways to get complex data (including HTML) in to a string variable. In your case, I would use [PHP's heredoc syntax](http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc), as you can put virtually anything inside of it and not have to escape the syntax:
```
<?php
function choose_ashtopbar() {
$html = <<<HTML
<img src="/images/flag_globe2.png" class="ttupmg" />
<div class="dmzeus">
<ul>
<li class="f-selection">London
<ul>
<li>New York</li>
<li>Paris</li>
<li>Milan</li>
</ul>
</li>
</ul>
</div>
HTML;
return $html;
}
function register_ashcodes(){
add_shortcode('ashtopbar', 'choose_ashtopbar');
}
# I'm guessing init has already run by this point
# add_action( 'init', 'register_ashcodes');
# Use a different hook or just register your code
register_ashcodes();
```
Essentially, your original code was just echoing the HTML when `add_shortcode` ran the `choose_ashtopbar` function, which is probably not what you wanted.
|
204,627 |
<p>I'm setting up a plugin that requires passing of a variable from a stand alone jQuery file to options.php. I have (I think) set up the scripts to be used in my plugin file like so:</p>
<pre><code>function ndw_js_init(){
wp_enqueue_script('jquery');
wp_register_script( 'ndw_js', plugin_dir_url( __FILE__ ) . '/ndw_js.js', array( 'jquery' ), '', true );
wp_enqueue_script( 'ndw_js', plugin_dir_url( __FILE__ ) . '/ndw_js.js', array(), '1.0.0', true);
$scriptdata = array('admin_ajax' => admin_url( 'admin-ajax.php' ));
wp_localize_script( 'ndw_js', 'toremove', $scriptdata);
}
add_action('admin_init', 'ndw_js_init');
</code></pre>
<p>Where I am coming unstuck is in the jQuery file. The variable is passed onclick. So far I have this which works fine (tested using an alert()):</p>
<pre><code>$('tr td .widget-remove a').click(function(){
var toremove = $(this).attr('rel');
var url = 'options.php'; // EDIT: Actualy, is this right? Or should the data be passed to the name of my plugin main page I wonder
// Out of ideas
});
</code></pre>
<p>So what I need is help to use the correct AJAX syntax to pass the value of var 'toremove' to 'options.php' and then do something in 'options.php' using the value of 'toremove'.</p>
<p>Hope that makes sense!</p>
<p><strong>EDIT No.1:</strong></p>
<p>OK, so after playing with different settings provided by all of you I have a (semi) functional script:</p>
<pre><code>function ndw_js_init(){
wp_register_script( 'ndw_js', plugin_dir_url( __FILE__ ) . '/ndw_js.js', array( 'jquery' ), '', true );
wp_enqueue_script( 'ndw_js' ); // not working without this
wp_localize_script( 'ndw_js', 'toremove', array('ajaxurl' => admin_url( 'admin-ajax.php' )));
}
add_action('admin_init', 'ndw_js_init');
</code></pre>
<p>Without these settings as they are <strong>nothing</strong> works. In my external js file I now have:</p>
<pre><code>$('tr td .widget-remove a').click(function(){
var toremove = $(this).attr('rel');
$.ajax({
type: 'POST',
dataType: 'json',
url: ajaxurl,
data: {
nonce : toremove.nonce,
toremove : toremove
},
complete: function( data ){
alert(toremove + " ding!");
}
});
});
</code></pre>
<p>This works - but only the jQuery code. In the Admin area on my plugin settings page the alert fires on click with the correct id no and the word 'ding!'.</p>
<p>Back to my plugin settings page and I add this (thanks @MMK):</p>
<pre><code>function ndw_ajax_function(){
$toremove = $_POST['toremove'];
echo "To remove: " . $toremove;
}
add_action('wp_ajax_my_ajax_action', 'ndw_ajax_function' );
</code></pre>
<p>This does <strong>not</strong> work, I view the generated source and the echoed line does not appear. However, I am not sure in that last add action what <code>wp_ajax_my_ajax_action</code> refers to.</p>
|
[
{
"answer_id": 204629,
"author": "dswebsme",
"author_id": 62906,
"author_profile": "https://wordpress.stackexchange.com/users/62906",
"pm_score": 1,
"selected": false,
"text": "<p>Your code works as expected. Two things you need to check:</p>\n\n<p>1) In order for shortcodes to render as expected you need to use the_content() within the loop OR wrap your content in apply_filters() as shown here:</p>\n\n<pre><code>echo apply_filters('the_content', $my_content);\n</code></pre>\n\n<p>The apply_filters() helper tells WordPress to parse the content before it's rendered, resolving things like shortcodes, line breaks, etc. Within the loop, the_content() handles the call to apply_filters() automatically.</p>\n\n<p>2) Be sure you clear any server side or local cache that may be in place while debugging to ensure you can see your changes as you make them.</p>\n"
},
{
"answer_id": 204632,
"author": "phatskat",
"author_id": 20143,
"author_profile": "https://wordpress.stackexchange.com/users/20143",
"pm_score": 3,
"selected": true,
"text": "<p><s>As <code>birgire</code> mentioned in the comments, \"you're missing the <code>return</code> part\" to which you replied \"how do I add that without escaping the HTML code?\"</s></p>\n\n<p><strong>EDIT</strong>: Just a clarification. Your code should have worked, as pointed out by dswebsme. I just tested with and without a return, and both work (although returning would be preferred). The next question would be: are you putting your shortcode tag properly in to your content? e.g. <code>[ashtopbar/]</code> ? and it's not misspelled, right?</p>\n\n<p>Leaving the section about heredoc anyway:</p>\n\n<p>In PHP, you have a number of ways to get complex data (including HTML) in to a string variable. In your case, I would use <a href=\"http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc\" rel=\"nofollow\">PHP's heredoc syntax</a>, as you can put virtually anything inside of it and not have to escape the syntax:</p>\n\n<pre><code><?php\n\nfunction choose_ashtopbar() {\n $html = <<<HTML\n<img src=\"/images/flag_globe2.png\" class=\"ttupmg\" />\n<div class=\"dmzeus\">\n <ul>\n <li class=\"f-selection\">London\n <ul>\n <li>New York</li>\n <li>Paris</li>\n <li>Milan</li>\n </ul>\n </li>\n </ul>\n</div>\nHTML;\n\n return $html;\n}\n\nfunction register_ashcodes(){\n add_shortcode('ashtopbar', 'choose_ashtopbar');\n}\n\n# I'm guessing init has already run by this point\n# add_action( 'init', 'register_ashcodes');\n# Use a different hook or just register your code\nregister_ashcodes();\n</code></pre>\n\n<p>Essentially, your original code was just echoing the HTML when <code>add_shortcode</code> ran the <code>choose_ashtopbar</code> function, which is probably not what you wanted. </p>\n"
},
{
"answer_id": 204633,
"author": "Robert hue",
"author_id": 22461,
"author_profile": "https://wordpress.stackexchange.com/users/22461",
"pm_score": 2,
"selected": false,
"text": "<p>Why are you using all that. Can't you simply define shortcode with <a href=\"https://codex.wordpress.org/Function_Reference/add_shortcode\" rel=\"nofollow\"><code>add_shortcode</code></a>?\nHere is the function.</p>\n\n<p>Also yes, you are missing the <code>return</code> in your function. Finished code here.</p>\n\n<pre><code>function choose_ashtopbar( $atts, $content ) {\n return '<img src=\"/images/flag_globe2.png\" class=\"ttupmg\" /><div class=\"dmzeus\"><ul><li class=\"f-selection\">London<ul><li>New York</li><li>Paris</li><li>Milan</li></ul></li></ul></div>';\n}\nadd_shortcode( 'ashtopbar', 'choose_ashtopbar' );\n</code></pre>\n"
}
] |
2015/10/05
|
[
"https://wordpress.stackexchange.com/questions/204627",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/35299/"
] |
I'm setting up a plugin that requires passing of a variable from a stand alone jQuery file to options.php. I have (I think) set up the scripts to be used in my plugin file like so:
```
function ndw_js_init(){
wp_enqueue_script('jquery');
wp_register_script( 'ndw_js', plugin_dir_url( __FILE__ ) . '/ndw_js.js', array( 'jquery' ), '', true );
wp_enqueue_script( 'ndw_js', plugin_dir_url( __FILE__ ) . '/ndw_js.js', array(), '1.0.0', true);
$scriptdata = array('admin_ajax' => admin_url( 'admin-ajax.php' ));
wp_localize_script( 'ndw_js', 'toremove', $scriptdata);
}
add_action('admin_init', 'ndw_js_init');
```
Where I am coming unstuck is in the jQuery file. The variable is passed onclick. So far I have this which works fine (tested using an alert()):
```
$('tr td .widget-remove a').click(function(){
var toremove = $(this).attr('rel');
var url = 'options.php'; // EDIT: Actualy, is this right? Or should the data be passed to the name of my plugin main page I wonder
// Out of ideas
});
```
So what I need is help to use the correct AJAX syntax to pass the value of var 'toremove' to 'options.php' and then do something in 'options.php' using the value of 'toremove'.
Hope that makes sense!
**EDIT No.1:**
OK, so after playing with different settings provided by all of you I have a (semi) functional script:
```
function ndw_js_init(){
wp_register_script( 'ndw_js', plugin_dir_url( __FILE__ ) . '/ndw_js.js', array( 'jquery' ), '', true );
wp_enqueue_script( 'ndw_js' ); // not working without this
wp_localize_script( 'ndw_js', 'toremove', array('ajaxurl' => admin_url( 'admin-ajax.php' )));
}
add_action('admin_init', 'ndw_js_init');
```
Without these settings as they are **nothing** works. In my external js file I now have:
```
$('tr td .widget-remove a').click(function(){
var toremove = $(this).attr('rel');
$.ajax({
type: 'POST',
dataType: 'json',
url: ajaxurl,
data: {
nonce : toremove.nonce,
toremove : toremove
},
complete: function( data ){
alert(toremove + " ding!");
}
});
});
```
This works - but only the jQuery code. In the Admin area on my plugin settings page the alert fires on click with the correct id no and the word 'ding!'.
Back to my plugin settings page and I add this (thanks @MMK):
```
function ndw_ajax_function(){
$toremove = $_POST['toremove'];
echo "To remove: " . $toremove;
}
add_action('wp_ajax_my_ajax_action', 'ndw_ajax_function' );
```
This does **not** work, I view the generated source and the echoed line does not appear. However, I am not sure in that last add action what `wp_ajax_my_ajax_action` refers to.
|
~~As `birgire` mentioned in the comments, "you're missing the `return` part" to which you replied "how do I add that without escaping the HTML code?"~~
**EDIT**: Just a clarification. Your code should have worked, as pointed out by dswebsme. I just tested with and without a return, and both work (although returning would be preferred). The next question would be: are you putting your shortcode tag properly in to your content? e.g. `[ashtopbar/]` ? and it's not misspelled, right?
Leaving the section about heredoc anyway:
In PHP, you have a number of ways to get complex data (including HTML) in to a string variable. In your case, I would use [PHP's heredoc syntax](http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc), as you can put virtually anything inside of it and not have to escape the syntax:
```
<?php
function choose_ashtopbar() {
$html = <<<HTML
<img src="/images/flag_globe2.png" class="ttupmg" />
<div class="dmzeus">
<ul>
<li class="f-selection">London
<ul>
<li>New York</li>
<li>Paris</li>
<li>Milan</li>
</ul>
</li>
</ul>
</div>
HTML;
return $html;
}
function register_ashcodes(){
add_shortcode('ashtopbar', 'choose_ashtopbar');
}
# I'm guessing init has already run by this point
# add_action( 'init', 'register_ashcodes');
# Use a different hook or just register your code
register_ashcodes();
```
Essentially, your original code was just echoing the HTML when `add_shortcode` ran the `choose_ashtopbar` function, which is probably not what you wanted.
|
204,657 |
<p>Today I got a client that wanted custom template for each page and section within.
I proposed Laravel custom sh3t, but he wanted WordPress, as it seems more easy to main( <em>not from my experience</em> ).</p>
<p>.. So far so good. I'm a little confused there. </p>
<p>So I decided that my parent entity would be page, so I can apply different template to each page. Then I have a section within this page, which should be not hardcored. User should have the ability to choose section layout ( <em>template</em> ), and remove or reorder sections within the current page. And
Finally I have posts as they are the smallest entity in the website. Posts would be rendered as columns like in bootstrap ( <em>col-md-2, col-lg-6</em> ), etc..</p>
<p>I decided to create a custom post type to use it as a section, but then I read that post types cannot have template, only pages can have ones. This compromised my plan so far and spend 5 hours in researching a solution( <em>no exit</em> ). So I need another strategy for doing this.
I need templates for two entities. </p>
<p>Can someone suggest a solution to this problem? ( <em>I will buy you a beer!</em> )</p>
<p><strong>EDIT:</strong></p>
<p>To create my own <em>custom post type</em>, I use plugin in wordpress called <em>'Custom Post Type UI'</em>, of course there's another way, by pasting a short code snippet into your <em>functions.php</em> file, but I'm not covering this here.</p>
|
[
{
"answer_id": 204661,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": false,
"text": "<p>Custom post types can have selectable templates, you'll just have to implement them yourself. The way WordPress does it internally with the page post type is by saving a template slug into post meta data, then checking if a value exists there when the template is loaded on the front end according to <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow\">the hierarchy</a>.</p>\n\n<p>The basic process would be to <a href=\"https://codex.wordpress.org/Function_Reference/add_meta_box\" rel=\"nofollow\">add a meta box</a> to your custom post type to let users select a template (maybe using <a href=\"https://codex.wordpress.org/Function_Reference/get_page_templates\" rel=\"nofollow\"><code>get_page_templates</code></a> to build a list).</p>\n\n<p>The second step is to <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/#filter-hierarchy\" rel=\"nofollow\">add a filter to <code>single_template</code></a> to load the selected template when that object is viewed on the front end.</p>\n\n<p>If you look inside the core files <code>wp-includes/template.php</code> and <code>wp-includes/post-template.php</code>, you can see the code WordPress uses (and where the filter is applied) and adapt it to your needs. <code>get_queried_object</code> will give you the object's <code>post_type</code> within the filter, as well as the ID to enable you to fetch the post's meta data.</p>\n\n<p>EDIT -</p>\n\n<p>Here is an example filter for the <code>post</code> post type that loads whatever is in the meta key <code>my_template</code> (like <code>whatever.php</code>). You can test it by creating a new post and entering a filename under that key using the native Custom Fields meta box. You can modify this for your custom type (change <code>'post'</code>), and whatever scheme you're using to store and name files.</p>\n\n<pre><code>function wpd_post_type_template( $template ){\n $object = get_queried_object();\n if( ! empty( $object->post_type )\n && 'post' == $object->post_type\n && $slug = get_post_meta( $object->ID, 'my_template', true ) ){\n if( $custom_template = locate_template( $slug, false ) ){\n $template = $custom_template;\n }\n }\n return $template;\n}\nadd_filter( 'single_template', 'wpd_post_type_template' ) ;\n</code></pre>\n"
},
{
"answer_id": 204671,
"author": "dswebsme",
"author_id": 62906,
"author_profile": "https://wordpress.stackexchange.com/users/62906",
"pm_score": 4,
"selected": true,
"text": "<p>Typically I wouldn't follow such a strong answer like the one @Milo provided with a post like this. Since I already had this code written for another project I thought I'd share.</p>\n\n<p>The code below does everything @Milo summarized in his answer and I've ported this across projects before with great success.</p>\n\n<p>Here's the cheat sheet for what's going on:</p>\n\n<p>1) Hook into the 'add_meta_boxes' action to render a new custom meta box on the edit screen (except on the native 'page' post type).</p>\n\n<p>2) Hook into the 'admin_menu' action to remove the existing 'Page Attributes' meta box (except on the native 'page' post type).</p>\n\n<p>3) Build out the custom meta box to replace the functionality of the native 'Page Attributes' meta box. This includes fields for defining the PARENT, TEMPLATE and ORDER of any custom post type you've initialized.</p>\n\n<p>4) Hook into the 'save_post' action to save your template selection in the post meta.</p>\n\n<p>5) Hook into the 'single_template' filter to load your custom template instead of the default WordPress template.</p>\n\n<p>Here's is the fully functional copy/paste for you:</p>\n\n<pre><code>/** Custom Post Type Template Selector **/\nfunction cpt_add_meta_boxes() {\n $post_types = get_post_types();\n foreach( $post_types as $ptype ) {\n if ( $ptype !== 'page') {\n add_meta_box( 'cpt-selector', 'Attributes', 'cpt_meta_box', $ptype, 'side', 'core' );\n }\n }\n}\nadd_action( 'add_meta_boxes', 'cpt_add_meta_boxes' );\n\nfunction cpt_remove_meta_boxes() {\n $post_types = get_post_types();\n foreach( $post_types as $ptype ) {\n if ( $ptype !== 'page') {\n remove_meta_box( 'pageparentdiv', $ptype, 'normal' );\n }\n }\n}\nadd_action( 'admin_menu' , 'cpt_remove_meta_boxes' );\n\nfunction cpt_meta_box( $post ) {\n $post_meta = get_post_meta( $post->ID );\n $templates = wp_get_theme()->get_page_templates();\n\n $post_type_object = get_post_type_object($post->post_type);\n if ( $post_type_object->hierarchical ) {\n $dropdown_args = array(\n 'post_type' => $post->post_type,\n 'exclude_tree' => $post->ID,\n 'selected' => $post->post_parent,\n 'name' => 'parent_id',\n 'show_option_none' => __('(no parent)'),\n 'sort_column' => 'menu_order, post_title',\n 'echo' => 0,\n );\n\n $dropdown_args = apply_filters( 'page_attributes_dropdown_pages_args', $dropdown_args, $post );\n $pages = wp_dropdown_pages( $dropdown_args );\n\n if ( $pages ) { \n echo \"<p><strong>Parent</strong></p>\";\n echo \"<label class=\\\"screen-reader-text\\\" for=\\\"parent_id\\\">Parent</label>\";\n echo $pages;\n }\n }\n\n // Template Selector\n echo \"<p><strong>Template</strong></p>\";\n echo \"<select id=\\\"cpt-selector\\\" name=\\\"_wp_page_template\\\"><option value=\\\"default\\\">Default Template</option>\";\n foreach ( $templates as $template_filename => $template_name ) {\n if ( $post->post_type == strstr( $template_filename, '-', true) ) {\n if ( isset($post_meta['_wp_page_template'][0]) && ($post_meta['_wp_page_template'][0] == $template_filename) ) {\n echo \"<option value=\\\"$template_filename\\\" selected=\\\"selected\\\">$template_name</option>\";\n } else {\n echo \"<option value=\\\"$template_filename\\\">$template_name</option>\";\n }\n }\n }\n echo \"</select>\";\n\n // Page order\n echo \"<p><strong>Order</strong></p>\";\n echo \"<p><label class=\\\"screen-reader-text\\\" for=\\\"menu_order\\\">Order</label><input name=\\\"menu_order\\\" type=\\\"text\\\" size=\\\"4\\\" id=\\\"menu_order\\\" value=\\\"\". esc_attr($post->menu_order) . \"\\\" /></p>\";\n}\n\nfunction save_cpt_template_meta_data( $post_id ) {\n\n if ( isset( $_REQUEST['_wp_page_template'] ) ) {\n update_post_meta( $post_id, '_wp_page_template', $_REQUEST['_wp_page_template'] );\n }\n}\nadd_action( 'save_post' , 'save_cpt_template_meta_data' );\n\nfunction custom_single_template($template) {\n global $post;\n\n $post_meta = ( $post ) ? get_post_meta( $post->ID ) : null;\n if ( isset($post_meta['_wp_page_template'][0]) && ( $post_meta['_wp_page_template'][0] != 'default' ) ) {\n $template = get_template_directory() . '/' . $post_meta['_wp_page_template'][0];\n }\n\n return $template;\n}\nadd_filter( 'single_template', 'custom_single_template' );\n/** END Custom Post Type Template Selector **/\n</code></pre>\n\n<p>The only assumption I've made here is that your templates follow a naming convention best practice of:</p>\n\n<pre><code>posttype-templatename.php\n</code></pre>\n\n<p>As an example you could define some custom templates for an \"Event\" custom post type using the following naming convention within your theme:</p>\n\n<pre><code>event-standard.php\nevent-allday.php\nevent-recurring.php\n</code></pre>\n\n<p>This code is smart enough to only allow \"event\" templates to be applied to the Event post type. In other words, a template called \"section-video.php\" template would never be visible to the Event post type. That template would instead appear as an option on the \"Section\" post type.</p>\n\n<p>To remove this feature you simply need to remove the conditional logic from the code above:</p>\n\n<pre><code>if ( $post->post_type == strstr( $template_filename, '-', true) ) { }\n</code></pre>\n"
},
{
"answer_id": 252381,
"author": "Landing on Jupiter",
"author_id": 74534,
"author_profile": "https://wordpress.stackexchange.com/users/74534",
"pm_score": 4,
"selected": false,
"text": "<p>As of WordPress 4.7, support for multiple templates has been given to Custom Post Types.</p>\n\n<p>In order to make a template available for your Custom Post Type, you add this header to meta portion of the template file:</p>\n\n<pre><code>Template Post Type: post, foo, bar \n</code></pre>\n\n<p>For example, we'll assume your Custom Post Type is labelled \"my_events\", and you'd like to make a template called \"Fullwidth\" available for both Pages and your Custom Post Type.</p>\n\n<p><strong>This:</strong></p>\n\n<pre><code>/**\n * Template Name: Fullwidth\n * \n * Template Description...\n **/\n</code></pre>\n\n<p><strong>Becomes This:</strong></p>\n\n<pre><code>/**\n * Template Name: Fullwidth\n * Template Post Type: page, my_events\n * \n * Template Description...\n **/\n</code></pre>\n\n<p><strong>More Info:</strong> <a href=\"https://make.wordpress.org/core/2016/11/03/post-type-templates-in-4-7/\" rel=\"noreferrer\">Post Type Templates in 4.7</a> from WordPress Core</p>\n"
},
{
"answer_id": 368014,
"author": "SUM1",
"author_id": 188655,
"author_profile": "https://wordpress.stackexchange.com/users/188655",
"pm_score": 2,
"selected": false,
"text": "<p>I know this is an old question, but I wanted to add my answer as to what helped me apply templates to custom post types.</p>\n\n<p>I made my custom post type manually (with my own plugin) rather than using the <a href=\"https://en-gb.wordpress.org/plugins/custom-post-type-ui/\" rel=\"nofollow noreferrer\">Custom Post Type UI</a> plugin.</p>\n\n<p>The code of the plugin looks like this:</p>\n\n<pre><code><?php\n/**\n * Plugin Name: [Your post type plugin]\n */\n\ndefined('ABSPATH') or die(''); // Prevents access to the file through its URL in the browser\n\nfunction yourPostTypeFunction() {\n register_post_type('your-post-type', array(\n 'labels'=>array(\n 'name'=>__('Post type pages'),\n 'singular_name'=>__('Post type page')\n ),\n 'description'=>'Your description',\n 'public'=>true,\n 'hierarchical'=>true, // Allows parent–child relationships\n 'show_in_rest'=>true,\n 'supports'=>array( // Features the post type should support\n 'title',\n 'editor',\n 'thumbnail',\n 'revisions',\n 'page-attributes' /* Necessary to show the metabox for setting parent–child\nrelationships if you are not using the 'Template Post Type' header field method */\n ),\n 'has_archive'=>true,\n )\n );\n}\nadd_action('init', 'yourPostTypeFunction');\n\nfunction CPTFlushPermalinks() {\n yourPostTypeFunction();\n flush_rewrite_rules();\n}\nregister_activation_hook(__FILE__, 'CPTFlushPermalinks');\n\n?>\n</code></pre>\n\n<p>See <a href=\"https://developer.wordpress.org/reference/functions/register_post_type/\" rel=\"nofollow noreferrer\">here</a> for details about all the options for <code>register_post_type()</code> (and why there's a <code>flush_rewrite_rules()</code> at the end). Many are set as defaults that you don't need to add.</p>\n\n<p>The important thing for me was that <code>'hierarchical'</code> was set to <code>true</code> and <code>'supports'</code> included <code>'page-attributes'</code>.</p>\n\n<p>After this, I created my template file. The code looks something like this:</p>\n\n<pre><code><?php\n/*\n * Template Name: [Your template]\n */\n\n// ... page content (mostly copied from page.php)\n\n?>\n\n</code></pre>\n\n<p>Notice how I omitted the post-WordPress-4.7 \"<a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/#creating-page-templates-for-specific-post-types\" rel=\"nofollow noreferrer\">Template Post Type</a>\" field? That's because this field is for allowing the visibility of a template in the 'Page Attributes' metabox to specific post types. The post types listed will be able to choose the template in their Page Attributes metabox. (If you do this, you won't need <code>'page-attributes'</code> support in your post type – the metabox will be created automatically.) Without it, only posts of the 'page' type can choose different templates in their 'Page Attributes' metabox.</p>\n\n<p>This is not what I wanted, as I wanted my template to be immediately applied to all pages with the post type. This is achieved by naming the template \"single-[post type name].php\".</p>\n\n<p>There are other naming schemes you can use for other purposes, listed <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/#single-post\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>This will work for single pages of the post type. I don't know about subsections, like the original question asked; there, you would probably need conditional statements in your other templates, such as \"<code>if ('your-post-type' === get_post_type()) { ...</code>\".</p>\n\n<p>You can freely rename the custom template through its \"Template Name\" field without affecting any pages. If you want to rename the file, you can do so, but you must then go into your database, search for the filename and rename the instances to the new name.</p>\n\n<p>Also, the <a href=\"https://en-gb.wordpress.org/plugins/post-type-switcher/\" rel=\"nofollow noreferrer\">Post Type Switcher</a> plugin is helpful for switching posts between post types, including in bulk. It worked seamlessly for me with no bugs.</p>\n\n<p><a href=\"https://wordpress.stackexchange.com/a/204671/188655\">dswebsme's</a> answer was an appropriate answer from before WordPress allowed non-'pages' to choose custom templates in the 'Page Attributes' box.</p>\n"
}
] |
2015/10/05
|
[
"https://wordpress.stackexchange.com/questions/204657",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81454/"
] |
Today I got a client that wanted custom template for each page and section within.
I proposed Laravel custom sh3t, but he wanted WordPress, as it seems more easy to main( *not from my experience* ).
.. So far so good. I'm a little confused there.
So I decided that my parent entity would be page, so I can apply different template to each page. Then I have a section within this page, which should be not hardcored. User should have the ability to choose section layout ( *template* ), and remove or reorder sections within the current page. And
Finally I have posts as they are the smallest entity in the website. Posts would be rendered as columns like in bootstrap ( *col-md-2, col-lg-6* ), etc..
I decided to create a custom post type to use it as a section, but then I read that post types cannot have template, only pages can have ones. This compromised my plan so far and spend 5 hours in researching a solution( *no exit* ). So I need another strategy for doing this.
I need templates for two entities.
Can someone suggest a solution to this problem? ( *I will buy you a beer!* )
**EDIT:**
To create my own *custom post type*, I use plugin in wordpress called *'Custom Post Type UI'*, of course there's another way, by pasting a short code snippet into your *functions.php* file, but I'm not covering this here.
|
Typically I wouldn't follow such a strong answer like the one @Milo provided with a post like this. Since I already had this code written for another project I thought I'd share.
The code below does everything @Milo summarized in his answer and I've ported this across projects before with great success.
Here's the cheat sheet for what's going on:
1) Hook into the 'add\_meta\_boxes' action to render a new custom meta box on the edit screen (except on the native 'page' post type).
2) Hook into the 'admin\_menu' action to remove the existing 'Page Attributes' meta box (except on the native 'page' post type).
3) Build out the custom meta box to replace the functionality of the native 'Page Attributes' meta box. This includes fields for defining the PARENT, TEMPLATE and ORDER of any custom post type you've initialized.
4) Hook into the 'save\_post' action to save your template selection in the post meta.
5) Hook into the 'single\_template' filter to load your custom template instead of the default WordPress template.
Here's is the fully functional copy/paste for you:
```
/** Custom Post Type Template Selector **/
function cpt_add_meta_boxes() {
$post_types = get_post_types();
foreach( $post_types as $ptype ) {
if ( $ptype !== 'page') {
add_meta_box( 'cpt-selector', 'Attributes', 'cpt_meta_box', $ptype, 'side', 'core' );
}
}
}
add_action( 'add_meta_boxes', 'cpt_add_meta_boxes' );
function cpt_remove_meta_boxes() {
$post_types = get_post_types();
foreach( $post_types as $ptype ) {
if ( $ptype !== 'page') {
remove_meta_box( 'pageparentdiv', $ptype, 'normal' );
}
}
}
add_action( 'admin_menu' , 'cpt_remove_meta_boxes' );
function cpt_meta_box( $post ) {
$post_meta = get_post_meta( $post->ID );
$templates = wp_get_theme()->get_page_templates();
$post_type_object = get_post_type_object($post->post_type);
if ( $post_type_object->hierarchical ) {
$dropdown_args = array(
'post_type' => $post->post_type,
'exclude_tree' => $post->ID,
'selected' => $post->post_parent,
'name' => 'parent_id',
'show_option_none' => __('(no parent)'),
'sort_column' => 'menu_order, post_title',
'echo' => 0,
);
$dropdown_args = apply_filters( 'page_attributes_dropdown_pages_args', $dropdown_args, $post );
$pages = wp_dropdown_pages( $dropdown_args );
if ( $pages ) {
echo "<p><strong>Parent</strong></p>";
echo "<label class=\"screen-reader-text\" for=\"parent_id\">Parent</label>";
echo $pages;
}
}
// Template Selector
echo "<p><strong>Template</strong></p>";
echo "<select id=\"cpt-selector\" name=\"_wp_page_template\"><option value=\"default\">Default Template</option>";
foreach ( $templates as $template_filename => $template_name ) {
if ( $post->post_type == strstr( $template_filename, '-', true) ) {
if ( isset($post_meta['_wp_page_template'][0]) && ($post_meta['_wp_page_template'][0] == $template_filename) ) {
echo "<option value=\"$template_filename\" selected=\"selected\">$template_name</option>";
} else {
echo "<option value=\"$template_filename\">$template_name</option>";
}
}
}
echo "</select>";
// Page order
echo "<p><strong>Order</strong></p>";
echo "<p><label class=\"screen-reader-text\" for=\"menu_order\">Order</label><input name=\"menu_order\" type=\"text\" size=\"4\" id=\"menu_order\" value=\"". esc_attr($post->menu_order) . "\" /></p>";
}
function save_cpt_template_meta_data( $post_id ) {
if ( isset( $_REQUEST['_wp_page_template'] ) ) {
update_post_meta( $post_id, '_wp_page_template', $_REQUEST['_wp_page_template'] );
}
}
add_action( 'save_post' , 'save_cpt_template_meta_data' );
function custom_single_template($template) {
global $post;
$post_meta = ( $post ) ? get_post_meta( $post->ID ) : null;
if ( isset($post_meta['_wp_page_template'][0]) && ( $post_meta['_wp_page_template'][0] != 'default' ) ) {
$template = get_template_directory() . '/' . $post_meta['_wp_page_template'][0];
}
return $template;
}
add_filter( 'single_template', 'custom_single_template' );
/** END Custom Post Type Template Selector **/
```
The only assumption I've made here is that your templates follow a naming convention best practice of:
```
posttype-templatename.php
```
As an example you could define some custom templates for an "Event" custom post type using the following naming convention within your theme:
```
event-standard.php
event-allday.php
event-recurring.php
```
This code is smart enough to only allow "event" templates to be applied to the Event post type. In other words, a template called "section-video.php" template would never be visible to the Event post type. That template would instead appear as an option on the "Section" post type.
To remove this feature you simply need to remove the conditional logic from the code above:
```
if ( $post->post_type == strstr( $template_filename, '-', true) ) { }
```
|
204,678 |
<p>I would like some very simple and limited Geo targeting functionality.</p>
<p>I want to display a different footer depending on whether the visitor is from US or not. Ideally the code should be something like this:</p>
<pre><code><?php if ( visitor is from usa ): ?>
<?php get_footer('us'); ?>
<?php else: ?>
<?php get_footer('other-countries'); ?>
<?php endif; ?>
</code></pre>
<p>I would prefer the solution to be as simple and light as possible.</p>
|
[
{
"answer_id": 204684,
"author": "Aric Watson",
"author_id": 81449,
"author_profile": "https://wordpress.stackexchange.com/users/81449",
"pm_score": 1,
"selected": false,
"text": "<p>I used this service a long time ago and it was <em>relatively</em> painless to set up:\n<a href=\"https://github.com/maxmind/geoip-api-php\" rel=\"nofollow\">https://github.com/maxmind/geoip-api-php</a></p>\n\n<p>Once you set it up, you can pull the visitor's country code or name based off their IP address.</p>\n"
},
{
"answer_id": 204694,
"author": "GµårÐïåñ",
"author_id": 37180,
"author_profile": "https://wordpress.stackexchange.com/users/37180",
"pm_score": 3,
"selected": true,
"text": "<p>I personally really like the GEO service provided by <a href=\"http://ip-api.com/docs/api:serialized_php\" rel=\"nofollow noreferrer\">ip-api.com</a></p>\n\n<p>It is very simple to use and a sample PHP code to grab the <code>countryCode</code> would give you what you need very simply. You can do MUCH more and you can read the full doc on it but for your specific needs listed, here is a sample code:</p>\n\n<pre><code>$ip = $_SERVER['REMOTE_ADDR'];\n$query = @unserialize(file_get_contents('http://ip-api.com/php/' . $ip));\n$geo = $query['countryCode'];\n</code></pre>\n\n<p>The rest is a simple if <code>$geo == 'US'</code> do whatever else do something else. That's pretty much it and its very simple to implement and you don't have to install anything. The MaxMind library is good but it can be heavy and difficult to manage for some.</p>\n\n<p>Good luck.</p>\n\n<hr>\n\n<h2>Update 1 [php] (3/5/18)</h2>\n\n<p>In response to your email, switching to <code>JSON</code> instead is not much different than how it is now. The only line that changes is this:</p>\n\n<pre><code>$query = json_decode(file_get_contents('http://ip-api.com/json/' . $ip), true);\n</code></pre>\n\n<p>and if you want to use a callback function, simply this:</p>\n\n<pre><code>$query = json_decode(file_get_contents('http://ip-api.com/json/' . $ip . '?callback=<function>'), true);\n</code></pre>\n\n<p>I recommend you use the <code>true</code> parameter on <code>json_decode</code> to get an array so it is easier to manipulate.</p>\n\n<h2>Update 2 [jquery] (3/5/18)</h2>\n\n<p>I just realized that in your email you mentioned jQuery and while I personally would opt for the above PHP method, here is an example of how to use jQuery to achieve the same thing.</p>\n\n<pre><code>var ip = ...;\nvar query = $.getJSON(\n \"http://ip-api.com/json/\"+ ip,\n function (json) {\n var whatever = json.whatever;\n // where whatever is something that is returned\n // such as status aka json.status\n // look at what is returned to see what you need\n });\n</code></pre>\n\n<p>... means the ip, however you are going to obtain it\nno callback should really be necessary as you can just do whatever you want inside the function above and that's it.</p>\n"
},
{
"answer_id": 295905,
"author": "Ravi Patel",
"author_id": 35477,
"author_profile": "https://wordpress.stackexchange.com/users/35477",
"pm_score": 1,
"selected": false,
"text": "<p>I personally really like the GEO service provided by <a href=\"https://ipinfo.io/developers\" rel=\"nofollow noreferrer\">ipinfo.io developer</a></p>\n\n<pre><code>$data = file_get_contents(\"http://ipinfo.io\");\n$loc_info = json_decode($data);\n$country = $loc_info->country; //get country code\n\n//check visitor country code here.\n\nif ( $country == 'US'):\n get_footer('us'); ?>\nelse:\n get_footer('other-countries')\nendif; \n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/bWNdb.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/bWNdb.png\" alt=\"enter image description here\"></a></p>\n"
}
] |
2015/10/05
|
[
"https://wordpress.stackexchange.com/questions/204678",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80031/"
] |
I would like some very simple and limited Geo targeting functionality.
I want to display a different footer depending on whether the visitor is from US or not. Ideally the code should be something like this:
```
<?php if ( visitor is from usa ): ?>
<?php get_footer('us'); ?>
<?php else: ?>
<?php get_footer('other-countries'); ?>
<?php endif; ?>
```
I would prefer the solution to be as simple and light as possible.
|
I personally really like the GEO service provided by [ip-api.com](http://ip-api.com/docs/api:serialized_php)
It is very simple to use and a sample PHP code to grab the `countryCode` would give you what you need very simply. You can do MUCH more and you can read the full doc on it but for your specific needs listed, here is a sample code:
```
$ip = $_SERVER['REMOTE_ADDR'];
$query = @unserialize(file_get_contents('http://ip-api.com/php/' . $ip));
$geo = $query['countryCode'];
```
The rest is a simple if `$geo == 'US'` do whatever else do something else. That's pretty much it and its very simple to implement and you don't have to install anything. The MaxMind library is good but it can be heavy and difficult to manage for some.
Good luck.
---
Update 1 [php] (3/5/18)
-----------------------
In response to your email, switching to `JSON` instead is not much different than how it is now. The only line that changes is this:
```
$query = json_decode(file_get_contents('http://ip-api.com/json/' . $ip), true);
```
and if you want to use a callback function, simply this:
```
$query = json_decode(file_get_contents('http://ip-api.com/json/' . $ip . '?callback=<function>'), true);
```
I recommend you use the `true` parameter on `json_decode` to get an array so it is easier to manipulate.
Update 2 [jquery] (3/5/18)
--------------------------
I just realized that in your email you mentioned jQuery and while I personally would opt for the above PHP method, here is an example of how to use jQuery to achieve the same thing.
```
var ip = ...;
var query = $.getJSON(
"http://ip-api.com/json/"+ ip,
function (json) {
var whatever = json.whatever;
// where whatever is something that is returned
// such as status aka json.status
// look at what is returned to see what you need
});
```
... means the ip, however you are going to obtain it
no callback should really be necessary as you can just do whatever you want inside the function above and that's it.
|
204,688 |
<p>I'm using my own taxonomy for blog posts and would like to remove Categories and Tags from the Dashboard. I've removed them from the Admin Menu and the meta boxes on the Edit Posts page from this question here: <a href="https://wordpress.stackexchange.com/questions/110782/remove-categories-tags-from-admin-menu">Remove Categories / Tags From Admin Menu</a></p>
<p>But now I'm trying to remove it from the All Posts page in the Dashboard where it shows a list of all the posts in a table and across the top are Title, Author, Categories, Tags, Date, etc. I can't seem to find how to do this.</p>
|
[
{
"answer_id": 204705,
"author": "fatwombat",
"author_id": 81482,
"author_profile": "https://wordpress.stackexchange.com/users/81482",
"pm_score": 1,
"selected": false,
"text": "<p>That actually requires you to rewrite the table itself.</p>\n\n<p>The following link can help you with this:\n<a href=\"https://wordpress.stackexchange.com/a/19182/81482\">https://wordpress.stackexchange.com/a/19182/81482</a></p>\n"
},
{
"answer_id": 204706,
"author": "denis.stoyanov",
"author_id": 76287,
"author_profile": "https://wordpress.stackexchange.com/users/76287",
"pm_score": 3,
"selected": true,
"text": "<p>Just like @fatwombat suggested you need to rewrite the table. If you can't modify the @Milo solution, here is a snippet that will remove the columns:</p>\n\n<pre><code>function my_manage_columns( $columns ) {\n unset($columns['categories'], $columns['tags']);\n return $columns;\n}\n\nfunction my_column_init() {\n add_filter( 'manage_posts_columns' , 'my_manage_columns' );\n}\n\nadd_action( 'admin_init' , 'my_column_init' );\n</code></pre>\n"
}
] |
2015/10/05
|
[
"https://wordpress.stackexchange.com/questions/204688",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/38890/"
] |
I'm using my own taxonomy for blog posts and would like to remove Categories and Tags from the Dashboard. I've removed them from the Admin Menu and the meta boxes on the Edit Posts page from this question here: [Remove Categories / Tags From Admin Menu](https://wordpress.stackexchange.com/questions/110782/remove-categories-tags-from-admin-menu)
But now I'm trying to remove it from the All Posts page in the Dashboard where it shows a list of all the posts in a table and across the top are Title, Author, Categories, Tags, Date, etc. I can't seem to find how to do this.
|
Just like @fatwombat suggested you need to rewrite the table. If you can't modify the @Milo solution, here is a snippet that will remove the columns:
```
function my_manage_columns( $columns ) {
unset($columns['categories'], $columns['tags']);
return $columns;
}
function my_column_init() {
add_filter( 'manage_posts_columns' , 'my_manage_columns' );
}
add_action( 'admin_init' , 'my_column_init' );
```
|
204,693 |
<p>I want to force users to accept the terms and conditions of the site when they log in for the first time. I found a couple plugins that would show the terms, but they don't prevent you from ignoring the form and moving on to other site pages. Is there a way to prevent the user from going anywhere until they have accepted the terms?</p>
|
[
{
"answer_id": 204705,
"author": "fatwombat",
"author_id": 81482,
"author_profile": "https://wordpress.stackexchange.com/users/81482",
"pm_score": 1,
"selected": false,
"text": "<p>That actually requires you to rewrite the table itself.</p>\n\n<p>The following link can help you with this:\n<a href=\"https://wordpress.stackexchange.com/a/19182/81482\">https://wordpress.stackexchange.com/a/19182/81482</a></p>\n"
},
{
"answer_id": 204706,
"author": "denis.stoyanov",
"author_id": 76287,
"author_profile": "https://wordpress.stackexchange.com/users/76287",
"pm_score": 3,
"selected": true,
"text": "<p>Just like @fatwombat suggested you need to rewrite the table. If you can't modify the @Milo solution, here is a snippet that will remove the columns:</p>\n\n<pre><code>function my_manage_columns( $columns ) {\n unset($columns['categories'], $columns['tags']);\n return $columns;\n}\n\nfunction my_column_init() {\n add_filter( 'manage_posts_columns' , 'my_manage_columns' );\n}\n\nadd_action( 'admin_init' , 'my_column_init' );\n</code></pre>\n"
}
] |
2015/10/05
|
[
"https://wordpress.stackexchange.com/questions/204693",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/69989/"
] |
I want to force users to accept the terms and conditions of the site when they log in for the first time. I found a couple plugins that would show the terms, but they don't prevent you from ignoring the form and moving on to other site pages. Is there a way to prevent the user from going anywhere until they have accepted the terms?
|
Just like @fatwombat suggested you need to rewrite the table. If you can't modify the @Milo solution, here is a snippet that will remove the columns:
```
function my_manage_columns( $columns ) {
unset($columns['categories'], $columns['tags']);
return $columns;
}
function my_column_init() {
add_filter( 'manage_posts_columns' , 'my_manage_columns' );
}
add_action( 'admin_init' , 'my_column_init' );
```
|
204,697 |
<p>I've set up some code to download zip files that exist in a folder above the web root. The download will be triggered from a user account page within WordPress. They don't need to be bank-level secure, but I'd like to prevent direct file access from outside the site and make them accessible only for users with the correct permission levels, and only from the appropriate user's account page. The site is entirely https.</p>
<p>The folder where the zip files reside is protected via htaccess.</p>
<p>Each user that's assigned to a specific user role will see a download link on their "Account" page:</p>
<pre><code>if(current_user_can('download_these_files')){
$SESSION['check'] = 'HVUKfb0IG1HIzHxJj5fZ';
?>
<form class="user-file-download-form" action="/download.php" method="POST">
<input type="submit" name="submit" value="Download File">
</form>
<?php
}
</code></pre>
<p>This form submits to download.php, which sits in the web root and includes some code that I've pieced together with help from Google.</p>
<pre><code>session_start();
if( isset( $_POST['submit'] ) ){
$check = $_SESSION['check'];
if( $check === 'HVUKfb0IG1HIzHxJj5fZ' ){
$file = /path/to/file/above/root.zip;
header('Content-Description: File Transfer');
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename=' . basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile( $file );
exit;
}else{
header( 'Location: https://example.com/404page/' );
}else{
header( 'Location: https://example.com/404page/' );
}
</code></pre>
<p>This works perfectly. But I can't help but wonder if I should be doing something differently. I was hoping to get input on whether or not this implementation is production-ready, or if I'm missing something important as this is the first time I'm attempting something like this.</p>
<p>Thank you.</p>
|
[
{
"answer_id": 204716,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": -1,
"selected": false,
"text": "<p>Instead of using a form just use a link like ..../download.php?file=abc.zip. Check the user credentials at downoad.php and you save both the need for the session and form handling.</p>\n"
},
{
"answer_id": 285018,
"author": "jaswrks",
"author_id": 81760,
"author_profile": "https://wordpress.stackexchange.com/users/81760",
"pm_score": 2,
"selected": false,
"text": "<p>What you have there is production ready. However, there is room for some minor improvements, so I will point those out for you. Also see my notes below regarding X-Sendfile and X-Accel-Redirect.</p>\n\n<hr>\n\n<p>Replace these lines:</p>\n\n<pre><code>ob_clean();\nflush();\n</code></pre>\n\n<p>with the following:</p>\n\n<pre><code>while (@ob_end_clean());\n</code></pre>\n\n<p><em>The point is, if there is something already in the output buffer, you don't want to flush it out, you only want to clean it. If you flush it, you'll be prefixing your downloadable file contents with the output buffer contents, which would only serve to corrupt the downloadable file. See: <a href=\"http://php.net/manual/en/function.ob-end-clean.php_\" rel=\"nofollow noreferrer\">http://php.net/manual/en/function.ob-end-clean.php</em></a></p>\n\n<hr>\n\n<p>After this line:</p>\n\n<pre><code>$file = /path/to/file/above/root.zip;\n</code></pre>\n\n<p>Add the following to ensure GZIP compression at the server-level is turned off. This might not make a difference at your current web host, but move the site elsewhere and without these lines you could see the script break badly.</p>\n\n<pre><code>@ini_set('zlib.output_compression', 0);\nif(function_exists('apache_setenv')) @apache_setenv('no-gzip', '1');\nheader('Content-Encoding: none');\n</code></pre>\n\n<hr>\n\n<p><strong>Caution:</strong> Be wary of using this PHP-driven file download technique on larger files (e.g., over 20MB in size). Why? Two reasons:</p>\n\n<ul>\n<li><p>PHP has an internal memory limit. If <code>readfile()</code> exceeds that limit when reading the file into memory and serving it out to a visitor, your script will fail.</p></li>\n<li><p>In addition, PHP scripts also have a time limit. If a visitor on a very slow connection takes a long time to download a larger file, the script will timeout and the user will experience a failed download attempt, or receive a partial/corrupted file.</p></li>\n</ul>\n\n<hr>\n\n<p><strong>Caution:</strong> Also be aware that PHP-driven file downloads using the <code>readfile()</code> technique do not support resumable byte ranges. So pausing the download, or the download being interrupted in some way, doesn't leave the user with an option to resume. They will need to start the download all over again. It is possible to support Range requests (resume) in PHP, but that is <a href=\"https://stackoverflow.com/questions/157318/resumable-downloads-when-using-php-to-send-the-file\">tedious</a>.</p>\n\n<hr>\n\n<p>In the long-term, my suggestion is that you start looking at a much more effective way of serving protected files, referred to as <a href=\"https://coderwall.com/p/8lpngg/x-sendfile-in-apache2\" rel=\"nofollow noreferrer\">X-Sendfile</a> in Apache, and <a href=\"https://www.nginx.com/resources/wiki/start/topics/examples/x-accel/\" rel=\"nofollow noreferrer\">X-Accel-Redirect</a> in Nginx.</p>\n\n<p>X-Sendfile and X-Accel-Redirect both work on the same underlying concept. Instead of asking a scripting language like PHP to pull a file into memory, simply tell the web server to do an internal redirect and serve the contents of an otherwise protected file. In short, you can do away with much of the above, and reduce the solution down to just <code>header('X-Accel-Redirect: ...')</code>.</p>\n"
}
] |
2015/10/06
|
[
"https://wordpress.stackexchange.com/questions/204697",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/54702/"
] |
I've set up some code to download zip files that exist in a folder above the web root. The download will be triggered from a user account page within WordPress. They don't need to be bank-level secure, but I'd like to prevent direct file access from outside the site and make them accessible only for users with the correct permission levels, and only from the appropriate user's account page. The site is entirely https.
The folder where the zip files reside is protected via htaccess.
Each user that's assigned to a specific user role will see a download link on their "Account" page:
```
if(current_user_can('download_these_files')){
$SESSION['check'] = 'HVUKfb0IG1HIzHxJj5fZ';
?>
<form class="user-file-download-form" action="/download.php" method="POST">
<input type="submit" name="submit" value="Download File">
</form>
<?php
}
```
This form submits to download.php, which sits in the web root and includes some code that I've pieced together with help from Google.
```
session_start();
if( isset( $_POST['submit'] ) ){
$check = $_SESSION['check'];
if( $check === 'HVUKfb0IG1HIzHxJj5fZ' ){
$file = /path/to/file/above/root.zip;
header('Content-Description: File Transfer');
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename=' . basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile( $file );
exit;
}else{
header( 'Location: https://example.com/404page/' );
}else{
header( 'Location: https://example.com/404page/' );
}
```
This works perfectly. But I can't help but wonder if I should be doing something differently. I was hoping to get input on whether or not this implementation is production-ready, or if I'm missing something important as this is the first time I'm attempting something like this.
Thank you.
|
What you have there is production ready. However, there is room for some minor improvements, so I will point those out for you. Also see my notes below regarding X-Sendfile and X-Accel-Redirect.
---
Replace these lines:
```
ob_clean();
flush();
```
with the following:
```
while (@ob_end_clean());
```
*The point is, if there is something already in the output buffer, you don't want to flush it out, you only want to clean it. If you flush it, you'll be prefixing your downloadable file contents with the output buffer contents, which would only serve to corrupt the downloadable file. See: [http://php.net/manual/en/function.ob-end-clean.php](http://php.net/manual/en/function.ob-end-clean.php_)*
---
After this line:
```
$file = /path/to/file/above/root.zip;
```
Add the following to ensure GZIP compression at the server-level is turned off. This might not make a difference at your current web host, but move the site elsewhere and without these lines you could see the script break badly.
```
@ini_set('zlib.output_compression', 0);
if(function_exists('apache_setenv')) @apache_setenv('no-gzip', '1');
header('Content-Encoding: none');
```
---
**Caution:** Be wary of using this PHP-driven file download technique on larger files (e.g., over 20MB in size). Why? Two reasons:
* PHP has an internal memory limit. If `readfile()` exceeds that limit when reading the file into memory and serving it out to a visitor, your script will fail.
* In addition, PHP scripts also have a time limit. If a visitor on a very slow connection takes a long time to download a larger file, the script will timeout and the user will experience a failed download attempt, or receive a partial/corrupted file.
---
**Caution:** Also be aware that PHP-driven file downloads using the `readfile()` technique do not support resumable byte ranges. So pausing the download, or the download being interrupted in some way, doesn't leave the user with an option to resume. They will need to start the download all over again. It is possible to support Range requests (resume) in PHP, but that is [tedious](https://stackoverflow.com/questions/157318/resumable-downloads-when-using-php-to-send-the-file).
---
In the long-term, my suggestion is that you start looking at a much more effective way of serving protected files, referred to as [X-Sendfile](https://coderwall.com/p/8lpngg/x-sendfile-in-apache2) in Apache, and [X-Accel-Redirect](https://www.nginx.com/resources/wiki/start/topics/examples/x-accel/) in Nginx.
X-Sendfile and X-Accel-Redirect both work on the same underlying concept. Instead of asking a scripting language like PHP to pull a file into memory, simply tell the web server to do an internal redirect and serve the contents of an otherwise protected file. In short, you can do away with much of the above, and reduce the solution down to just `header('X-Accel-Redirect: ...')`.
|
204,699 |
<p>I'm trying to add a top level menu to the left sidebar of the WordPress admin panel.</p>
<p>Here's the code I currently have:</p>
<pre><code>add_action( 'admin_menu', 'linked_url' );
function linked_url() {
add_menu_page( 'linked_url', 'Menu Title', 'read', 'my_slug', '', 'dashicons-text', 1 );
}
add_action( 'admin_menu' , 'linkedurl_function' );
function linkedurl_function() {
global $menu;
$menu[1][2] = "https://www.example.com";
}
</code></pre>
<p>This code DOES work and links the menu to an external page (<code>https://www.example.com</code>).</p>
<p>I learned how to do this from here: <a href="http://www.techedg.com/2014/09/06/5575/a-simple-way-to-add-an-external-link-to-the-wordpress-admin-menu/" rel="nofollow">http://www.techedg.com/2014/09/06/5575/a-simple-way-to-add-an-external-link-to-the-wordpress-admin-menu/</a></p>
<p>However, I can't figure out how to make the external link open in a new tab. I'd prefer than a new tab/window is opened so people don't lose what they already have open in their admin area.</p>
<p>Is there something I need to change or add? Or is it just not possible?</p>
|
[
{
"answer_id": 204708,
"author": "Robert hue",
"author_id": 22461,
"author_profile": "https://wordpress.stackexchange.com/users/22461",
"pm_score": 2,
"selected": false,
"text": "<p>You can do that with jQuery. We can open this link in new tab/window by adding <code>target=\"_blank\"</code> attribute dynamically on link which has URL <code>https://www.example.com</code>. Here is the example function for that.</p>\n\n<pre><code>function wpse_my_custom_script() {\n ?>\n <script type=\"text/javascript\">\n jQuery(document).ready( function($) {\n $( \"ul#adminmenu a[href$='https://www.example.com']\" ).attr( 'target', '_blank' );\n });\n </script>\n <?php\n}\nadd_action( 'admin_head', 'wpse_my_custom_script' );\n</code></pre>\n\n<p>Don't forget to change URL in above code or this will not work.</p>\n\n<p><strong>Tested & working!</strong></p>\n"
},
{
"answer_id": 204711,
"author": "Prasad Nevase",
"author_id": 62283,
"author_profile": "https://wordpress.stackexchange.com/users/62283",
"pm_score": 0,
"selected": false,
"text": "<p>While there is no parameter available in <code>add_menu_page</code> to open external link in new tab, you can achieve that using a jQuery. Please refer below code:</p>\n\n<pre><code>\njQuery( document ).ready(function() {\n jQuery('a').each(function() {\n var a = new RegExp('/' + window.location.host + '/');\n if(!a.test(this.href)) {\n jQuery(this).click(function(event) {\n event.preventDefault();\n event.stopPropagation();\n window.open(this.href, '_blank');\n });\n }\n });\n});</code></pre>\n\n<p>Create a file named admin-ext-url.js and put above code in that file. Then, in your theme's functions.php file put following code:</p>\n\n<pre><code>\nadd_action( 'admin_enqueue_scripts', 'admin_handle_ext_urls' );\nfunction admin_handle_ext_urls(){\n wp_enqueue_script( 'ext_urls_handler', get_stylesheet_directory_uri() . '/admin-ext-url.js' );\n}\n</code></pre>\n\n<p>Above code will enqueue the admin-ext-url.js file only on the admin side. This should solve your problem. Also, this will work for all external links on the admin side.</p>\n"
},
{
"answer_id": 372777,
"author": "fabian",
"author_id": 192947,
"author_profile": "https://wordpress.stackexchange.com/users/192947",
"pm_score": 1,
"selected": false,
"text": "<p>In your meta array when adding a menu item just add a "target" attribute like so:</p>\n<pre><code>$admin_bar->add_menu( array(\n 'id' => 'download-plugin',\n 'title' => 'Download Plugin',\n 'href' => '#',\n 'meta' => array(\n 'title' => __('Download Plugin'), \n 'target' => '_blank', \n ),\n\n));\n</code></pre>\n<p>By this, your newly added admin menu item will open in new tab.</p>\n"
}
] |
2015/10/06
|
[
"https://wordpress.stackexchange.com/questions/204699",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81477/"
] |
I'm trying to add a top level menu to the left sidebar of the WordPress admin panel.
Here's the code I currently have:
```
add_action( 'admin_menu', 'linked_url' );
function linked_url() {
add_menu_page( 'linked_url', 'Menu Title', 'read', 'my_slug', '', 'dashicons-text', 1 );
}
add_action( 'admin_menu' , 'linkedurl_function' );
function linkedurl_function() {
global $menu;
$menu[1][2] = "https://www.example.com";
}
```
This code DOES work and links the menu to an external page (`https://www.example.com`).
I learned how to do this from here: <http://www.techedg.com/2014/09/06/5575/a-simple-way-to-add-an-external-link-to-the-wordpress-admin-menu/>
However, I can't figure out how to make the external link open in a new tab. I'd prefer than a new tab/window is opened so people don't lose what they already have open in their admin area.
Is there something I need to change or add? Or is it just not possible?
|
You can do that with jQuery. We can open this link in new tab/window by adding `target="_blank"` attribute dynamically on link which has URL `https://www.example.com`. Here is the example function for that.
```
function wpse_my_custom_script() {
?>
<script type="text/javascript">
jQuery(document).ready( function($) {
$( "ul#adminmenu a[href$='https://www.example.com']" ).attr( 'target', '_blank' );
});
</script>
<?php
}
add_action( 'admin_head', 'wpse_my_custom_script' );
```
Don't forget to change URL in above code or this will not work.
**Tested & working!**
|
204,712 |
<p>I am struggling with SMS sending in WordPress without plugin, I have a, API, but that API is not working.
Example:</p>
<pre><code>function mysite_woocommerce_order_status_processing( $order_id ) {
$mobile="123456";
$url="****/api.php?username=******&password=1234&source=UPDATE&dmobile=".$mobile."&message='.$msg.' ";
$response = wp_remote_get( $url );
//print_r($response);
}
add_action( 'woocommerce_order_status_processing','mysite_woocommerce_order_status_processing' );
</code></pre>
<p>I am struggling with above hook, I can send Email through that hook, but not SMS. It would be great if any WordPress developer help me out !</p>
<p>Getting SyntaxError: </p>
<blockquote>
<p>JSON.parse: unexpected character at line 1 column 1 of the JSON data</p>
</blockquote>
|
[
{
"answer_id": 204713,
"author": "Robert hue",
"author_id": 22461,
"author_profile": "https://wordpress.stackexchange.com/users/22461",
"pm_score": 1,
"selected": false,
"text": "<p>I think this is the error. The last variable <code>$msg</code> is incorrectly inserted. Here is the corrected code.</p>\n\n<pre><code>function mysite_woocommerce_order_status_processing( $order_id ) {\n\n $mobile=\"123456\";\n\n $url=\"****/api.php?username=******&password=1234&source=UPDATE&dmobile=\".$mobile.\"&message='\".$msg.\"'\";\n\n $response = wp_remote_get( $url );\n\n //print_r($response);\n\n}\n\nadd_action( 'woocommerce_order_status_processing','mysite_woocommerce_order_status_processing' );\n</code></pre>\n"
},
{
"answer_id": 214996,
"author": "dam",
"author_id": 87094,
"author_profile": "https://wordpress.stackexchange.com/users/87094",
"pm_score": -1,
"selected": false,
"text": "<pre><code>function mysite_woocommerce_order_status_processing( $order_id ) {\n\n $mobile=\"123456\";\n\n $url=\"****/api.php?username=******&password=1234&source=UPDATE&dmobile=\".$mobile.\"&message='.$msg.' \";\n\n $response = file_get_contents( $url );\n\n //print_r($response);\n\n }\n\n add_action( 'woocommerce_order_status_processing','mysite_woocommerce_order_status_processing' );\n</code></pre>\n\n<p>use <code>file_get_contents( $url )</code> instead of <code>wp_remote_get($url)</code> it will work fine</p>\n"
}
] |
2015/10/06
|
[
"https://wordpress.stackexchange.com/questions/204712",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73468/"
] |
I am struggling with SMS sending in WordPress without plugin, I have a, API, but that API is not working.
Example:
```
function mysite_woocommerce_order_status_processing( $order_id ) {
$mobile="123456";
$url="****/api.php?username=******&password=1234&source=UPDATE&dmobile=".$mobile."&message='.$msg.' ";
$response = wp_remote_get( $url );
//print_r($response);
}
add_action( 'woocommerce_order_status_processing','mysite_woocommerce_order_status_processing' );
```
I am struggling with above hook, I can send Email through that hook, but not SMS. It would be great if any WordPress developer help me out !
Getting SyntaxError:
>
> JSON.parse: unexpected character at line 1 column 1 of the JSON data
>
>
>
|
I think this is the error. The last variable `$msg` is incorrectly inserted. Here is the corrected code.
```
function mysite_woocommerce_order_status_processing( $order_id ) {
$mobile="123456";
$url="****/api.php?username=******&password=1234&source=UPDATE&dmobile=".$mobile."&message='".$msg."'";
$response = wp_remote_get( $url );
//print_r($response);
}
add_action( 'woocommerce_order_status_processing','mysite_woocommerce_order_status_processing' );
```
|
204,722 |
<p>I want to redirect the url if it contains the string like <code>/blog/abcd.../</code> to blog listing page i.e. <code>/blog page</code>. I used a to code in htaccess file. </p>
<p><code>Redirect 301 /blog/abcd http://www.example.com/blog</code></p>
<p>But the browser says <code>Too many redirect</code> error. I think Wordpress also do a redirection for blog single post that is <code>/blog/abcd</code> to <code>/abcd</code>. Can we force htaccess to do redirect if url contains <code>/blog/</code> to blog listing page.</p>
|
[
{
"answer_id": 204713,
"author": "Robert hue",
"author_id": 22461,
"author_profile": "https://wordpress.stackexchange.com/users/22461",
"pm_score": 1,
"selected": false,
"text": "<p>I think this is the error. The last variable <code>$msg</code> is incorrectly inserted. Here is the corrected code.</p>\n\n<pre><code>function mysite_woocommerce_order_status_processing( $order_id ) {\n\n $mobile=\"123456\";\n\n $url=\"****/api.php?username=******&password=1234&source=UPDATE&dmobile=\".$mobile.\"&message='\".$msg.\"'\";\n\n $response = wp_remote_get( $url );\n\n //print_r($response);\n\n}\n\nadd_action( 'woocommerce_order_status_processing','mysite_woocommerce_order_status_processing' );\n</code></pre>\n"
},
{
"answer_id": 214996,
"author": "dam",
"author_id": 87094,
"author_profile": "https://wordpress.stackexchange.com/users/87094",
"pm_score": -1,
"selected": false,
"text": "<pre><code>function mysite_woocommerce_order_status_processing( $order_id ) {\n\n $mobile=\"123456\";\n\n $url=\"****/api.php?username=******&password=1234&source=UPDATE&dmobile=\".$mobile.\"&message='.$msg.' \";\n\n $response = file_get_contents( $url );\n\n //print_r($response);\n\n }\n\n add_action( 'woocommerce_order_status_processing','mysite_woocommerce_order_status_processing' );\n</code></pre>\n\n<p>use <code>file_get_contents( $url )</code> instead of <code>wp_remote_get($url)</code> it will work fine</p>\n"
}
] |
2015/10/06
|
[
"https://wordpress.stackexchange.com/questions/204722",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/53934/"
] |
I want to redirect the url if it contains the string like `/blog/abcd.../` to blog listing page i.e. `/blog page`. I used a to code in htaccess file.
`Redirect 301 /blog/abcd http://www.example.com/blog`
But the browser says `Too many redirect` error. I think Wordpress also do a redirection for blog single post that is `/blog/abcd` to `/abcd`. Can we force htaccess to do redirect if url contains `/blog/` to blog listing page.
|
I think this is the error. The last variable `$msg` is incorrectly inserted. Here is the corrected code.
```
function mysite_woocommerce_order_status_processing( $order_id ) {
$mobile="123456";
$url="****/api.php?username=******&password=1234&source=UPDATE&dmobile=".$mobile."&message='".$msg."'";
$response = wp_remote_get( $url );
//print_r($response);
}
add_action( 'woocommerce_order_status_processing','mysite_woocommerce_order_status_processing' );
```
|
204,728 |
<p>I've tried to add my custom image size like:</p>
<p><code>add_image_size('224_226', 224, 226, false);</code></p>
<p>I need resize all images to same size what i define in style, when i've uploaded file - Wordpress resize it to '224x174' but i need size 224x226. </p>
<p>I don't need a crop image.</p>
<p>Guys tell me what to do?</p>
|
[
{
"answer_id": 204713,
"author": "Robert hue",
"author_id": 22461,
"author_profile": "https://wordpress.stackexchange.com/users/22461",
"pm_score": 1,
"selected": false,
"text": "<p>I think this is the error. The last variable <code>$msg</code> is incorrectly inserted. Here is the corrected code.</p>\n\n<pre><code>function mysite_woocommerce_order_status_processing( $order_id ) {\n\n $mobile=\"123456\";\n\n $url=\"****/api.php?username=******&password=1234&source=UPDATE&dmobile=\".$mobile.\"&message='\".$msg.\"'\";\n\n $response = wp_remote_get( $url );\n\n //print_r($response);\n\n}\n\nadd_action( 'woocommerce_order_status_processing','mysite_woocommerce_order_status_processing' );\n</code></pre>\n"
},
{
"answer_id": 214996,
"author": "dam",
"author_id": 87094,
"author_profile": "https://wordpress.stackexchange.com/users/87094",
"pm_score": -1,
"selected": false,
"text": "<pre><code>function mysite_woocommerce_order_status_processing( $order_id ) {\n\n $mobile=\"123456\";\n\n $url=\"****/api.php?username=******&password=1234&source=UPDATE&dmobile=\".$mobile.\"&message='.$msg.' \";\n\n $response = file_get_contents( $url );\n\n //print_r($response);\n\n }\n\n add_action( 'woocommerce_order_status_processing','mysite_woocommerce_order_status_processing' );\n</code></pre>\n\n<p>use <code>file_get_contents( $url )</code> instead of <code>wp_remote_get($url)</code> it will work fine</p>\n"
}
] |
2015/10/06
|
[
"https://wordpress.stackexchange.com/questions/204728",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81491/"
] |
I've tried to add my custom image size like:
`add_image_size('224_226', 224, 226, false);`
I need resize all images to same size what i define in style, when i've uploaded file - Wordpress resize it to '224x174' but i need size 224x226.
I don't need a crop image.
Guys tell me what to do?
|
I think this is the error. The last variable `$msg` is incorrectly inserted. Here is the corrected code.
```
function mysite_woocommerce_order_status_processing( $order_id ) {
$mobile="123456";
$url="****/api.php?username=******&password=1234&source=UPDATE&dmobile=".$mobile."&message='".$msg."'";
$response = wp_remote_get( $url );
//print_r($response);
}
add_action( 'woocommerce_order_status_processing','mysite_woocommerce_order_status_processing' );
```
|
204,738 |
<p>I have used the following function for breadcrumbs on every site to date, but todays site has 3 custom post types and the client would like the breadcrumbs working, e.g. instead of "home / wines / naire blanco" we just get "home / / naire blanco".</p>
<pre><code>function the_breadcrumb() {
echo '<ol class="breadcrumb" itemprop="breadcrumb">';
if (!is_home()) {
echo '<li><a href="';
echo get_option('home');
echo '">';
echo 'Home';
echo '</a></li>';
if (is_category() || is_single() || is_post_type()) {
echo '<li>';
the_category(' </li><li> ');
echo get_post_type(' </li><li> ');
if (is_single()) {
echo '</li><li>';
the_title();
echo '</li>';
}
} elseif (is_page()) {
if($post->post_parent){
$anc = get_post_ancestors( $post->ID );
foreach ( $anc as $ancestor ) {
$output = $output . '<li><a href="'.get_permalink($ancestor).'" title="'.get_the_title($ancestor).'">'.get_the_title($ancestor).'</a></li> ';
}
echo $output;
echo '<strong title="'.$title.'"> '.$title.'</strong>';
} else {
echo '<li><a class="active" href="';
echo the_permalink();
echo '">';
echo the_title();
echo '</a></li>';
}
}
}
elseif (is_tag()) {single_tag_title();}
elseif (is_day()) {echo"<li>Archive for "; the_time('F jS, Y'); echo'</li>';}
elseif (is_month()) {echo"<li>Archive for "; the_time('F, Y'); echo'</li>';}
elseif (is_year()) {echo"<li>Archive for "; the_time('Y'); echo'</li>';}
elseif (is_author()) {echo"<li>Author Archive"; echo'</li>';}
elseif (isset($_GET['paged']) && !empty($_GET['paged'])) {echo "<li>Blog Archives"; echo'</li>';}
elseif (is_search()) {echo"<li>Search Results"; echo'</li>';}
echo '</ol>';
}
</code></pre>
<p>As you can see in the code, I have tried to add <code>|| is_post_type()</code> after <code>is_category() || is_single()</code> with an <code>echo get_post_type()</code> but this didn't do anything.</p>
<p>Would appreciate some guidance please.</p>
<p>Thanks</p>
|
[
{
"answer_id": 221476,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 5,
"selected": true,
"text": "<p>The issue with most breadcrumb functions is that it relies on the <code>$post</code> object on all pages. Not only is the <code>$post</code> global totally unreliable (<em>see my post <a href=\"https://wordpress.stackexchange.com/q/167706/31545\">here</a></em>), it might not even contain the data that we need, even if the <code>$post</code> global is not compromised</p>\n\n<p>The <code>$post</code> global on archive pages (<em>which includes category, tag, date, taxonomy term, author and custom post type archive</em>) contains the first post in the loop before the loop. It is not always true that the first post is from the selected archive (<em>the archive page you are on</em>), which means that the info you are looking for might be incorrect, even though the <code>$post</code> global is not compromised. Conditions where the first post might not be from the selected archive is posts that are injected through custom stickies and the <code>the_posts</code> filter. </p>\n\n<p>I have recently rewritten one of my very old breadcrumb functions which makes use of the <code>$GLOBALS['wp_the_query']</code> object and the queried object saved in the <code>$GLOBALS['wp_the_query']</code> global. This way, we have a 99.999% reliable breadcrumb that does not rely on the <code>$post</code> global or any compromised data. </p>\n\n<p>Here is the function: (<em>Requires PHP 5.4+. Also, feel free to alter as necessary</em>)</p>\n\n<pre><code>function get_hansel_and_gretel_breadcrumbs()\n{\n // Set variables for later use\n $here_text = __( 'You are currently here!' );\n $home_link = home_url('/');\n $home_text = __( 'Home' );\n $link_before = '<span typeof=\"v:Breadcrumb\">';\n $link_after = '</span>';\n $link_attr = ' rel=\"v:url\" property=\"v:title\"';\n $link = $link_before . '<a' . $link_attr . ' href=\"%1$s\">%2$s</a>' . $link_after;\n $delimiter = ' &raquo; '; // Delimiter between crumbs\n $before = '<span class=\"current\">'; // Tag before the current crumb\n $after = '</span>'; // Tag after the current crumb\n $page_addon = ''; // Adds the page number if the query is paged\n $breadcrumb_trail = '';\n $category_links = '';\n\n /** \n * Set our own $wp_the_query variable. Do not use the global variable version due to \n * reliability\n */\n $wp_the_query = $GLOBALS['wp_the_query'];\n $queried_object = $wp_the_query->get_queried_object();\n\n // Handle single post requests which includes single pages, posts and attatchments\n if ( is_singular() ) \n {\n /** \n * Set our own $post variable. Do not use the global variable version due to \n * reliability. We will set $post_object variable to $GLOBALS['wp_the_query']\n */\n $post_object = sanitize_post( $queried_object );\n\n // Set variables \n $title = apply_filters( 'the_title', $post_object->post_title );\n $parent = $post_object->post_parent;\n $post_type = $post_object->post_type;\n $post_id = $post_object->ID;\n $post_link = $before . $title . $after;\n $parent_string = '';\n $post_type_link = '';\n\n if ( 'post' === $post_type ) \n {\n // Get the post categories\n $categories = get_the_category( $post_id );\n if ( $categories ) {\n // Lets grab the first category\n $category = $categories[0];\n\n $category_links = get_category_parents( $category, true, $delimiter );\n $category_links = str_replace( '<a', $link_before . '<a' . $link_attr, $category_links );\n $category_links = str_replace( '</a>', '</a>' . $link_after, $category_links );\n }\n }\n\n if ( !in_array( $post_type, ['post', 'page', 'attachment'] ) )\n {\n $post_type_object = get_post_type_object( $post_type );\n $archive_link = esc_url( get_post_type_archive_link( $post_type ) );\n\n $post_type_link = sprintf( $link, $archive_link, $post_type_object->labels->singular_name );\n }\n\n // Get post parents if $parent !== 0\n if ( 0 !== $parent ) \n {\n $parent_links = [];\n while ( $parent ) {\n $post_parent = get_post( $parent );\n\n $parent_links[] = sprintf( $link, esc_url( get_permalink( $post_parent->ID ) ), get_the_title( $post_parent->ID ) );\n\n $parent = $post_parent->post_parent;\n }\n\n $parent_links = array_reverse( $parent_links );\n\n $parent_string = implode( $delimiter, $parent_links );\n }\n\n // Lets build the breadcrumb trail\n if ( $parent_string ) {\n $breadcrumb_trail = $parent_string . $delimiter . $post_link;\n } else {\n $breadcrumb_trail = $post_link;\n }\n\n if ( $post_type_link )\n $breadcrumb_trail = $post_type_link . $delimiter . $breadcrumb_trail;\n\n if ( $category_links )\n $breadcrumb_trail = $category_links . $breadcrumb_trail;\n }\n\n // Handle archives which includes category-, tag-, taxonomy-, date-, custom post type archives and author archives\n if( is_archive() )\n {\n if ( is_category()\n || is_tag()\n || is_tax()\n ) {\n // Set the variables for this section\n $term_object = get_term( $queried_object );\n $taxonomy = $term_object->taxonomy;\n $term_id = $term_object->term_id;\n $term_name = $term_object->name;\n $term_parent = $term_object->parent;\n $taxonomy_object = get_taxonomy( $taxonomy );\n $current_term_link = $before . $taxonomy_object->labels->singular_name . ': ' . $term_name . $after;\n $parent_term_string = '';\n\n if ( 0 !== $term_parent )\n {\n // Get all the current term ancestors\n $parent_term_links = [];\n while ( $term_parent ) {\n $term = get_term( $term_parent, $taxonomy );\n\n $parent_term_links[] = sprintf( $link, esc_url( get_term_link( $term ) ), $term->name );\n\n $term_parent = $term->parent;\n }\n\n $parent_term_links = array_reverse( $parent_term_links );\n $parent_term_string = implode( $delimiter, $parent_term_links );\n }\n\n if ( $parent_term_string ) {\n $breadcrumb_trail = $parent_term_string . $delimiter . $current_term_link;\n } else {\n $breadcrumb_trail = $current_term_link;\n }\n\n } elseif ( is_author() ) {\n\n $breadcrumb_trail = __( 'Author archive for ') . $before . $queried_object->data->display_name . $after;\n\n } elseif ( is_date() ) {\n // Set default variables\n $year = $wp_the_query->query_vars['year'];\n $monthnum = $wp_the_query->query_vars['monthnum'];\n $day = $wp_the_query->query_vars['day'];\n\n // Get the month name if $monthnum has a value\n if ( $monthnum ) {\n $date_time = DateTime::createFromFormat( '!m', $monthnum );\n $month_name = $date_time->format( 'F' );\n }\n\n if ( is_year() ) {\n\n $breadcrumb_trail = $before . $year . $after;\n\n } elseif( is_month() ) {\n\n $year_link = sprintf( $link, esc_url( get_year_link( $year ) ), $year );\n\n $breadcrumb_trail = $year_link . $delimiter . $before . $month_name . $after;\n\n } elseif( is_day() ) {\n\n $year_link = sprintf( $link, esc_url( get_year_link( $year ) ), $year );\n $month_link = sprintf( $link, esc_url( get_month_link( $year, $monthnum ) ), $month_name );\n\n $breadcrumb_trail = $year_link . $delimiter . $month_link . $delimiter . $before . $day . $after;\n }\n\n } elseif ( is_post_type_archive() ) {\n\n $post_type = $wp_the_query->query_vars['post_type'];\n $post_type_object = get_post_type_object( $post_type );\n\n $breadcrumb_trail = $before . $post_type_object->labels->singular_name . $after;\n\n }\n } \n\n // Handle the search page\n if ( is_search() ) {\n $breadcrumb_trail = __( 'Search query for: ' ) . $before . get_search_query() . $after;\n }\n\n // Handle 404's\n if ( is_404() ) {\n $breadcrumb_trail = $before . __( 'Error 404' ) . $after;\n }\n\n // Handle paged pages\n if ( is_paged() ) {\n $current_page = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : get_query_var( 'page' );\n $page_addon = $before . sprintf( __( ' ( Page %s )' ), number_format_i18n( $current_page ) ) . $after;\n }\n\n $breadcrumb_output_link = '';\n $breadcrumb_output_link .= '<div class=\"breadcrumb\">';\n if ( is_home()\n || is_front_page()\n ) {\n // Do not show breadcrumbs on page one of home and frontpage\n if ( is_paged() ) {\n $breadcrumb_output_link .= $here_text . $delimiter;\n $breadcrumb_output_link .= '<a href=\"' . $home_link . '\">' . $home_text . '</a>';\n $breadcrumb_output_link .= $page_addon;\n }\n } else {\n $breadcrumb_output_link .= $here_text . $delimiter;\n $breadcrumb_output_link .= '<a href=\"' . $home_link . '\" rel=\"v:url\" property=\"v:title\">' . $home_text . '</a>';\n $breadcrumb_output_link .= $delimiter;\n $breadcrumb_output_link .= $breadcrumb_trail;\n $breadcrumb_output_link .= $page_addon;\n }\n $breadcrumb_output_link .= '</div><!-- .breadcrumbs -->';\n\n return $breadcrumb_output_link;\n}\n</code></pre>\n\n<p>You can simply call it as follow</p>\n\n<pre><code>echo get_hansel_and_gretel_breadcrumbs();\n</code></pre>\n\n<p>where needed</p>\n\n<p>This breadcrumb function takes care of custom post types as well</p>\n"
},
{
"answer_id": 266215,
"author": "perfectionist1",
"author_id": 119194,
"author_profile": "https://wordpress.stackexchange.com/users/119194",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Excellent!</strong>\nWorks the code of accepted answer (of Pieter Goosen).</p>\n\n<p><strong>Note:</strong> Just added a little task more. Make a <strong>validation check</strong> of that function <strong>before calling</strong> it, this way:</p>\n\n<pre><code><?php \n if(function_exists('get_hansel_and_gretel_breadcrumbs')): \n echo get_hansel_and_gretel_breadcrumbs();\n endif;\n?>\n</code></pre>\n\n<p><em>Additionally,</em> I saved that function into a file named <code>breadcrumbs.php</code> in project root folder and included it <strong>in functions.php</strong> file using <code>include_once('breadcrumbs.php');</code> to be more organized.</p>\n"
},
{
"answer_id": 318952,
"author": "user153920",
"author_id": 153920,
"author_profile": "https://wordpress.stackexchange.com/users/153920",
"pm_score": 0,
"selected": false,
"text": "<pre><code>function get_hansel_and_gretel_breadcrumbs()\n{\n // Set variables for later use\n $here_text = __( 'You are currently here!' );\n $home_link = home_url('/');\n $home_text = __( 'Home' );\n $link_before = '<span typeof=\"v:Breadcrumb\">';\n $link_after = '</span>';\n $link_attr = ' rel=\"v:url\" property=\"v:title\"';\n $link = $link_before . '<a' . $link_attr . ' href=\"%1$s\">%2$s</a>' . $link_after;\n $delimiter = ' &raquo; '; // Delimiter between crumbs\n $before = '<span class=\"current\">'; // Tag before the current crumb\n $after = '</span>'; // Tag after the current crumb\n $page_addon = ''; // Adds the page number if the query is paged\n $breadcrumb_trail = '';\n $category_links = '';\n\n /** \n * Set our own $wp_the_query variable. Do not use the global variable version due to \n * reliability\n */\n $wp_the_query = $GLOBALS['wp_the_query'];\n $queried_object = $wp_the_query->get_queried_object();\n\n // Handle single post requests which includes single pages, posts and attatchments\n if ( is_singular() ) \n {\n /** \n * Set our own $post variable. Do not use the global variable version due to \n * reliability. We will set $post_object variable to $GLOBALS['wp_the_query']\n */\n $post_object = sanitize_post( $queried_object );\n\n // Set variables \n $title = apply_filters( 'the_title', $post_object->post_title );\n $parent = $post_object->post_parent;\n $post_type = $post_object->post_type;\n $post_id = $post_object->ID;\n $post_link = $before . $title . $after;\n $parent_string = '';\n $post_type_link = '';\n\n if ( 'post' === $post_type ) \n {\n // Get the post categories\n $categories = get_the_category( $post_id );\n if ( $categories ) {\n // Lets grab the first category\n $category = $categories[0];\n\n $category_links = get_category_parents( $category, true, $delimiter );\n $category_links = str_replace( '<a', $link_before . '<a' . $link_attr, $category_links );\n $category_links = str_replace( '</a>', '</a>' . $link_after, $category_links );\n }\n }\n\n if ( !in_array( $post_type, ['post', 'page', 'attachment'] ) )\n {\n $post_type_object = get_post_type_object( $post_type );\n $archive_link = esc_url( get_post_type_archive_link( $post_type ) );\n\n $post_type_link = sprintf( $link, $archive_link, $post_type_object->labels->singular_name );\n }\n\n // Get post parents if $parent !== 0\n if ( 0 !== $parent ) \n {\n $parent_links = [];\n while ( $parent ) {\n $post_parent = get_post( $parent );\n\n $parent_links[] = sprintf( $link, esc_url( get_permalink( $post_parent->ID ) ), get_the_title( $post_parent->ID ) );\n\n $parent = $post_parent->post_parent;\n }\n\n $parent_links = array_reverse( $parent_links );\n\n $parent_string = implode( $delimiter, $parent_links );\n }\n\n // Lets build the breadcrumb trail\n if ( $parent_string ) {\n $breadcrumb_trail = $parent_string . $delimiter . $post_link;\n } else {\n $breadcrumb_trail = $post_link;\n }\n\n if ( $post_type_link )\n $breadcrumb_trail = $post_type_link . $delimiter . $breadcrumb_trail;\n\n if ( $category_links )\n $breadcrumb_trail = $category_links . $breadcrumb_trail;\n }\n\n // Handle archives which includes category-, tag-, taxonomy-, date-, custom post type archives and author archives\n if( is_archive() )\n {\n if ( is_category()\n || is_tag()\n || is_tax()\n ) {\n // Set the variables for this section\n $term_object = get_term( $queried_object );\n $taxonomy = $term_object->taxonomy;\n $term_id = $term_object->term_id;\n $term_name = $term_object->name;\n $term_parent = $term_object->parent;\n $taxonomy_object = get_taxonomy( $taxonomy );\n $current_term_link = $before . $taxonomy_object->labels->singular_name . ': ' . $term_name . $after;\n $parent_term_string = '';\n\n if ( 0 !== $term_parent )\n {\n // Get all the current term ancestors\n $parent_term_links = [];\n while ( $term_parent ) {\n $term = get_term( $term_parent, $taxonomy );\n\n $parent_term_links[] = sprintf( $link, esc_url( get_term_link( $term ) ), $term->name );\n\n $term_parent = $term->parent;\n }\n\n $parent_term_links = array_reverse( $parent_term_links );\n $parent_term_string = implode( $delimiter, $parent_term_links );\n }\n\n if ( $parent_term_string ) {\n $breadcrumb_trail = $parent_term_string . $delimiter . $current_term_link;\n } else {\n $breadcrumb_trail = $current_term_link;\n }\n\n } elseif ( is_author() ) {\n\n $breadcrumb_trail = __( 'Author archive for ') . $before . $queried_object->data->display_name . $after;\n\n } elseif ( is_date() ) {\n // Set default variables\n $year = $wp_the_query->query_vars['year'];\n $monthnum = $wp_the_query->query_vars['monthnum'];\n $day = $wp_the_query->query_vars['day'];\n\n // Get the month name if $monthnum has a value\n if ( $monthnum ) {\n $date_time = DateTime::createFromFormat( '!m', $monthnum );\n $month_name = $date_time->format( 'F' );\n }\n\n if ( is_year() ) {\n\n $breadcrumb_trail = $before . $year . $after;\n\n } elseif( is_month() ) {\n\n $year_link = sprintf( $link, esc_url( get_year_link( $year ) ), $year );\n\n $breadcrumb_trail = $year_link . $delimiter . $before . $month_name . $after;\n\n } elseif( is_day() ) {\n\n $year_link = sprintf( $link, esc_url( get_year_link( $year ) ), $year );\n $month_link = sprintf( $link, esc_url( get_month_link( $year, $monthnum ) ), $month_name );\n\n $breadcrumb_trail = $year_link . $delimiter . $month_link . $delimiter . $before . $day . $after;\n }\n\n } elseif ( is_post_type_archive() ) {\n\n $post_type = $wp_the_query->query_vars['post_type'];\n $post_type_object = get_post_type_object( $post_type );\n\n $breadcrumb_trail = $before . $post_type_object->labels->singular_name . $after;\n\n }\n } \n\n // Handle the search page\n if ( is_search() ) {\n $breadcrumb_trail = __( 'Search query for: ' ) . $before . get_search_query() . $after;\n }\n\n // Handle 404's\n if ( is_404() ) {\n $breadcrumb_trail = $before . __( 'Error 404' ) . $after;\n }\n\n // Handle paged pages\n if ( is_paged() ) {\n $current_page = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : get_query_var( 'page' );\n $page_addon = $before . sprintf( __( ' ( Page %s )' ), number_format_i18n( $current_page ) ) . $after;\n }\n\n $breadcrumb_output_link = '';\n $breadcrumb_output_link .= '<div class=\"breadcrumb\">';\n if ( is_home()\n || is_front_page()\n ) {\n // Do not show breadcrumbs on page one of home and frontpage\n if ( is_paged() ) {\n $breadcrumb_output_link .= $here_text . $delimiter;\n $breadcrumb_output_link .= '<a href=\"' . $home_link . '\">' . $home_text . '</a>';\n $breadcrumb_output_link .= $page_addon;\n }\n } else {\n $breadcrumb_output_link .= $here_text . $delimiter;\n $breadcrumb_output_link .= '<a href=\"' . $home_link . '\" rel=\"v:url\" property=\"v:title\">' . $home_text . '</a>';\n $breadcrumb_output_link .= $delimiter;\n $breadcrumb_output_link .= $breadcrumb_trail;\n $breadcrumb_output_link .= $page_addon;\n }\n $breadcrumb_output_link .= '</div><!-- .breadcrumbs -->';\n\n return $breadcrumb_output_link;\n}\n</code></pre>\n"
}
] |
2015/10/06
|
[
"https://wordpress.stackexchange.com/questions/204738",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/34820/"
] |
I have used the following function for breadcrumbs on every site to date, but todays site has 3 custom post types and the client would like the breadcrumbs working, e.g. instead of "home / wines / naire blanco" we just get "home / / naire blanco".
```
function the_breadcrumb() {
echo '<ol class="breadcrumb" itemprop="breadcrumb">';
if (!is_home()) {
echo '<li><a href="';
echo get_option('home');
echo '">';
echo 'Home';
echo '</a></li>';
if (is_category() || is_single() || is_post_type()) {
echo '<li>';
the_category(' </li><li> ');
echo get_post_type(' </li><li> ');
if (is_single()) {
echo '</li><li>';
the_title();
echo '</li>';
}
} elseif (is_page()) {
if($post->post_parent){
$anc = get_post_ancestors( $post->ID );
foreach ( $anc as $ancestor ) {
$output = $output . '<li><a href="'.get_permalink($ancestor).'" title="'.get_the_title($ancestor).'">'.get_the_title($ancestor).'</a></li> ';
}
echo $output;
echo '<strong title="'.$title.'"> '.$title.'</strong>';
} else {
echo '<li><a class="active" href="';
echo the_permalink();
echo '">';
echo the_title();
echo '</a></li>';
}
}
}
elseif (is_tag()) {single_tag_title();}
elseif (is_day()) {echo"<li>Archive for "; the_time('F jS, Y'); echo'</li>';}
elseif (is_month()) {echo"<li>Archive for "; the_time('F, Y'); echo'</li>';}
elseif (is_year()) {echo"<li>Archive for "; the_time('Y'); echo'</li>';}
elseif (is_author()) {echo"<li>Author Archive"; echo'</li>';}
elseif (isset($_GET['paged']) && !empty($_GET['paged'])) {echo "<li>Blog Archives"; echo'</li>';}
elseif (is_search()) {echo"<li>Search Results"; echo'</li>';}
echo '</ol>';
}
```
As you can see in the code, I have tried to add `|| is_post_type()` after `is_category() || is_single()` with an `echo get_post_type()` but this didn't do anything.
Would appreciate some guidance please.
Thanks
|
The issue with most breadcrumb functions is that it relies on the `$post` object on all pages. Not only is the `$post` global totally unreliable (*see my post [here](https://wordpress.stackexchange.com/q/167706/31545)*), it might not even contain the data that we need, even if the `$post` global is not compromised
The `$post` global on archive pages (*which includes category, tag, date, taxonomy term, author and custom post type archive*) contains the first post in the loop before the loop. It is not always true that the first post is from the selected archive (*the archive page you are on*), which means that the info you are looking for might be incorrect, even though the `$post` global is not compromised. Conditions where the first post might not be from the selected archive is posts that are injected through custom stickies and the `the_posts` filter.
I have recently rewritten one of my very old breadcrumb functions which makes use of the `$GLOBALS['wp_the_query']` object and the queried object saved in the `$GLOBALS['wp_the_query']` global. This way, we have a 99.999% reliable breadcrumb that does not rely on the `$post` global or any compromised data.
Here is the function: (*Requires PHP 5.4+. Also, feel free to alter as necessary*)
```
function get_hansel_and_gretel_breadcrumbs()
{
// Set variables for later use
$here_text = __( 'You are currently here!' );
$home_link = home_url('/');
$home_text = __( 'Home' );
$link_before = '<span typeof="v:Breadcrumb">';
$link_after = '</span>';
$link_attr = ' rel="v:url" property="v:title"';
$link = $link_before . '<a' . $link_attr . ' href="%1$s">%2$s</a>' . $link_after;
$delimiter = ' » '; // Delimiter between crumbs
$before = '<span class="current">'; // Tag before the current crumb
$after = '</span>'; // Tag after the current crumb
$page_addon = ''; // Adds the page number if the query is paged
$breadcrumb_trail = '';
$category_links = '';
/**
* Set our own $wp_the_query variable. Do not use the global variable version due to
* reliability
*/
$wp_the_query = $GLOBALS['wp_the_query'];
$queried_object = $wp_the_query->get_queried_object();
// Handle single post requests which includes single pages, posts and attatchments
if ( is_singular() )
{
/**
* Set our own $post variable. Do not use the global variable version due to
* reliability. We will set $post_object variable to $GLOBALS['wp_the_query']
*/
$post_object = sanitize_post( $queried_object );
// Set variables
$title = apply_filters( 'the_title', $post_object->post_title );
$parent = $post_object->post_parent;
$post_type = $post_object->post_type;
$post_id = $post_object->ID;
$post_link = $before . $title . $after;
$parent_string = '';
$post_type_link = '';
if ( 'post' === $post_type )
{
// Get the post categories
$categories = get_the_category( $post_id );
if ( $categories ) {
// Lets grab the first category
$category = $categories[0];
$category_links = get_category_parents( $category, true, $delimiter );
$category_links = str_replace( '<a', $link_before . '<a' . $link_attr, $category_links );
$category_links = str_replace( '</a>', '</a>' . $link_after, $category_links );
}
}
if ( !in_array( $post_type, ['post', 'page', 'attachment'] ) )
{
$post_type_object = get_post_type_object( $post_type );
$archive_link = esc_url( get_post_type_archive_link( $post_type ) );
$post_type_link = sprintf( $link, $archive_link, $post_type_object->labels->singular_name );
}
// Get post parents if $parent !== 0
if ( 0 !== $parent )
{
$parent_links = [];
while ( $parent ) {
$post_parent = get_post( $parent );
$parent_links[] = sprintf( $link, esc_url( get_permalink( $post_parent->ID ) ), get_the_title( $post_parent->ID ) );
$parent = $post_parent->post_parent;
}
$parent_links = array_reverse( $parent_links );
$parent_string = implode( $delimiter, $parent_links );
}
// Lets build the breadcrumb trail
if ( $parent_string ) {
$breadcrumb_trail = $parent_string . $delimiter . $post_link;
} else {
$breadcrumb_trail = $post_link;
}
if ( $post_type_link )
$breadcrumb_trail = $post_type_link . $delimiter . $breadcrumb_trail;
if ( $category_links )
$breadcrumb_trail = $category_links . $breadcrumb_trail;
}
// Handle archives which includes category-, tag-, taxonomy-, date-, custom post type archives and author archives
if( is_archive() )
{
if ( is_category()
|| is_tag()
|| is_tax()
) {
// Set the variables for this section
$term_object = get_term( $queried_object );
$taxonomy = $term_object->taxonomy;
$term_id = $term_object->term_id;
$term_name = $term_object->name;
$term_parent = $term_object->parent;
$taxonomy_object = get_taxonomy( $taxonomy );
$current_term_link = $before . $taxonomy_object->labels->singular_name . ': ' . $term_name . $after;
$parent_term_string = '';
if ( 0 !== $term_parent )
{
// Get all the current term ancestors
$parent_term_links = [];
while ( $term_parent ) {
$term = get_term( $term_parent, $taxonomy );
$parent_term_links[] = sprintf( $link, esc_url( get_term_link( $term ) ), $term->name );
$term_parent = $term->parent;
}
$parent_term_links = array_reverse( $parent_term_links );
$parent_term_string = implode( $delimiter, $parent_term_links );
}
if ( $parent_term_string ) {
$breadcrumb_trail = $parent_term_string . $delimiter . $current_term_link;
} else {
$breadcrumb_trail = $current_term_link;
}
} elseif ( is_author() ) {
$breadcrumb_trail = __( 'Author archive for ') . $before . $queried_object->data->display_name . $after;
} elseif ( is_date() ) {
// Set default variables
$year = $wp_the_query->query_vars['year'];
$monthnum = $wp_the_query->query_vars['monthnum'];
$day = $wp_the_query->query_vars['day'];
// Get the month name if $monthnum has a value
if ( $monthnum ) {
$date_time = DateTime::createFromFormat( '!m', $monthnum );
$month_name = $date_time->format( 'F' );
}
if ( is_year() ) {
$breadcrumb_trail = $before . $year . $after;
} elseif( is_month() ) {
$year_link = sprintf( $link, esc_url( get_year_link( $year ) ), $year );
$breadcrumb_trail = $year_link . $delimiter . $before . $month_name . $after;
} elseif( is_day() ) {
$year_link = sprintf( $link, esc_url( get_year_link( $year ) ), $year );
$month_link = sprintf( $link, esc_url( get_month_link( $year, $monthnum ) ), $month_name );
$breadcrumb_trail = $year_link . $delimiter . $month_link . $delimiter . $before . $day . $after;
}
} elseif ( is_post_type_archive() ) {
$post_type = $wp_the_query->query_vars['post_type'];
$post_type_object = get_post_type_object( $post_type );
$breadcrumb_trail = $before . $post_type_object->labels->singular_name . $after;
}
}
// Handle the search page
if ( is_search() ) {
$breadcrumb_trail = __( 'Search query for: ' ) . $before . get_search_query() . $after;
}
// Handle 404's
if ( is_404() ) {
$breadcrumb_trail = $before . __( 'Error 404' ) . $after;
}
// Handle paged pages
if ( is_paged() ) {
$current_page = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : get_query_var( 'page' );
$page_addon = $before . sprintf( __( ' ( Page %s )' ), number_format_i18n( $current_page ) ) . $after;
}
$breadcrumb_output_link = '';
$breadcrumb_output_link .= '<div class="breadcrumb">';
if ( is_home()
|| is_front_page()
) {
// Do not show breadcrumbs on page one of home and frontpage
if ( is_paged() ) {
$breadcrumb_output_link .= $here_text . $delimiter;
$breadcrumb_output_link .= '<a href="' . $home_link . '">' . $home_text . '</a>';
$breadcrumb_output_link .= $page_addon;
}
} else {
$breadcrumb_output_link .= $here_text . $delimiter;
$breadcrumb_output_link .= '<a href="' . $home_link . '" rel="v:url" property="v:title">' . $home_text . '</a>';
$breadcrumb_output_link .= $delimiter;
$breadcrumb_output_link .= $breadcrumb_trail;
$breadcrumb_output_link .= $page_addon;
}
$breadcrumb_output_link .= '</div><!-- .breadcrumbs -->';
return $breadcrumb_output_link;
}
```
You can simply call it as follow
```
echo get_hansel_and_gretel_breadcrumbs();
```
where needed
This breadcrumb function takes care of custom post types as well
|
204,744 |
<p>I want to fetch a list of posts with the most recent comments. However I don't wish to simply get the latest comments and have duplicate posts, but I want to group the posts (by their ID). I tried the following (ff it is important: the code is in the widget() methode of a widget class):</p>
<pre><code>function distinct() {
return "DISTINCT";
}
add_filter('posts_distinct', 'distinct');
$args = array(
'number' => 8
);
$query = new WP_Comment_Query;
$comments = $query->query($args);
</code></pre>
<p>The <em>posts_distinct</em> filter seemed like the correct way to achieve this, but it is not called and does not work. A different approach with <em>posts_groupby</em> doesn't work either:</p>
<pre><code>add_filter('posts_groupby', 'groupby' );
function groupby($groupby) {
global $wpdb;
$groupby = "{$wpdb->posts}.ID";
return $groupby;
}
</code></pre>
<p>How can I make WP_Comment_Query to return 8 distinguished posts?</p>
<p>I know that I could simply use a raw SQL query, but after a hour of fruitless googling I really wonder, how to solve this problem the WP way.</p>
|
[
{
"answer_id": 221476,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 5,
"selected": true,
"text": "<p>The issue with most breadcrumb functions is that it relies on the <code>$post</code> object on all pages. Not only is the <code>$post</code> global totally unreliable (<em>see my post <a href=\"https://wordpress.stackexchange.com/q/167706/31545\">here</a></em>), it might not even contain the data that we need, even if the <code>$post</code> global is not compromised</p>\n\n<p>The <code>$post</code> global on archive pages (<em>which includes category, tag, date, taxonomy term, author and custom post type archive</em>) contains the first post in the loop before the loop. It is not always true that the first post is from the selected archive (<em>the archive page you are on</em>), which means that the info you are looking for might be incorrect, even though the <code>$post</code> global is not compromised. Conditions where the first post might not be from the selected archive is posts that are injected through custom stickies and the <code>the_posts</code> filter. </p>\n\n<p>I have recently rewritten one of my very old breadcrumb functions which makes use of the <code>$GLOBALS['wp_the_query']</code> object and the queried object saved in the <code>$GLOBALS['wp_the_query']</code> global. This way, we have a 99.999% reliable breadcrumb that does not rely on the <code>$post</code> global or any compromised data. </p>\n\n<p>Here is the function: (<em>Requires PHP 5.4+. Also, feel free to alter as necessary</em>)</p>\n\n<pre><code>function get_hansel_and_gretel_breadcrumbs()\n{\n // Set variables for later use\n $here_text = __( 'You are currently here!' );\n $home_link = home_url('/');\n $home_text = __( 'Home' );\n $link_before = '<span typeof=\"v:Breadcrumb\">';\n $link_after = '</span>';\n $link_attr = ' rel=\"v:url\" property=\"v:title\"';\n $link = $link_before . '<a' . $link_attr . ' href=\"%1$s\">%2$s</a>' . $link_after;\n $delimiter = ' &raquo; '; // Delimiter between crumbs\n $before = '<span class=\"current\">'; // Tag before the current crumb\n $after = '</span>'; // Tag after the current crumb\n $page_addon = ''; // Adds the page number if the query is paged\n $breadcrumb_trail = '';\n $category_links = '';\n\n /** \n * Set our own $wp_the_query variable. Do not use the global variable version due to \n * reliability\n */\n $wp_the_query = $GLOBALS['wp_the_query'];\n $queried_object = $wp_the_query->get_queried_object();\n\n // Handle single post requests which includes single pages, posts and attatchments\n if ( is_singular() ) \n {\n /** \n * Set our own $post variable. Do not use the global variable version due to \n * reliability. We will set $post_object variable to $GLOBALS['wp_the_query']\n */\n $post_object = sanitize_post( $queried_object );\n\n // Set variables \n $title = apply_filters( 'the_title', $post_object->post_title );\n $parent = $post_object->post_parent;\n $post_type = $post_object->post_type;\n $post_id = $post_object->ID;\n $post_link = $before . $title . $after;\n $parent_string = '';\n $post_type_link = '';\n\n if ( 'post' === $post_type ) \n {\n // Get the post categories\n $categories = get_the_category( $post_id );\n if ( $categories ) {\n // Lets grab the first category\n $category = $categories[0];\n\n $category_links = get_category_parents( $category, true, $delimiter );\n $category_links = str_replace( '<a', $link_before . '<a' . $link_attr, $category_links );\n $category_links = str_replace( '</a>', '</a>' . $link_after, $category_links );\n }\n }\n\n if ( !in_array( $post_type, ['post', 'page', 'attachment'] ) )\n {\n $post_type_object = get_post_type_object( $post_type );\n $archive_link = esc_url( get_post_type_archive_link( $post_type ) );\n\n $post_type_link = sprintf( $link, $archive_link, $post_type_object->labels->singular_name );\n }\n\n // Get post parents if $parent !== 0\n if ( 0 !== $parent ) \n {\n $parent_links = [];\n while ( $parent ) {\n $post_parent = get_post( $parent );\n\n $parent_links[] = sprintf( $link, esc_url( get_permalink( $post_parent->ID ) ), get_the_title( $post_parent->ID ) );\n\n $parent = $post_parent->post_parent;\n }\n\n $parent_links = array_reverse( $parent_links );\n\n $parent_string = implode( $delimiter, $parent_links );\n }\n\n // Lets build the breadcrumb trail\n if ( $parent_string ) {\n $breadcrumb_trail = $parent_string . $delimiter . $post_link;\n } else {\n $breadcrumb_trail = $post_link;\n }\n\n if ( $post_type_link )\n $breadcrumb_trail = $post_type_link . $delimiter . $breadcrumb_trail;\n\n if ( $category_links )\n $breadcrumb_trail = $category_links . $breadcrumb_trail;\n }\n\n // Handle archives which includes category-, tag-, taxonomy-, date-, custom post type archives and author archives\n if( is_archive() )\n {\n if ( is_category()\n || is_tag()\n || is_tax()\n ) {\n // Set the variables for this section\n $term_object = get_term( $queried_object );\n $taxonomy = $term_object->taxonomy;\n $term_id = $term_object->term_id;\n $term_name = $term_object->name;\n $term_parent = $term_object->parent;\n $taxonomy_object = get_taxonomy( $taxonomy );\n $current_term_link = $before . $taxonomy_object->labels->singular_name . ': ' . $term_name . $after;\n $parent_term_string = '';\n\n if ( 0 !== $term_parent )\n {\n // Get all the current term ancestors\n $parent_term_links = [];\n while ( $term_parent ) {\n $term = get_term( $term_parent, $taxonomy );\n\n $parent_term_links[] = sprintf( $link, esc_url( get_term_link( $term ) ), $term->name );\n\n $term_parent = $term->parent;\n }\n\n $parent_term_links = array_reverse( $parent_term_links );\n $parent_term_string = implode( $delimiter, $parent_term_links );\n }\n\n if ( $parent_term_string ) {\n $breadcrumb_trail = $parent_term_string . $delimiter . $current_term_link;\n } else {\n $breadcrumb_trail = $current_term_link;\n }\n\n } elseif ( is_author() ) {\n\n $breadcrumb_trail = __( 'Author archive for ') . $before . $queried_object->data->display_name . $after;\n\n } elseif ( is_date() ) {\n // Set default variables\n $year = $wp_the_query->query_vars['year'];\n $monthnum = $wp_the_query->query_vars['monthnum'];\n $day = $wp_the_query->query_vars['day'];\n\n // Get the month name if $monthnum has a value\n if ( $monthnum ) {\n $date_time = DateTime::createFromFormat( '!m', $monthnum );\n $month_name = $date_time->format( 'F' );\n }\n\n if ( is_year() ) {\n\n $breadcrumb_trail = $before . $year . $after;\n\n } elseif( is_month() ) {\n\n $year_link = sprintf( $link, esc_url( get_year_link( $year ) ), $year );\n\n $breadcrumb_trail = $year_link . $delimiter . $before . $month_name . $after;\n\n } elseif( is_day() ) {\n\n $year_link = sprintf( $link, esc_url( get_year_link( $year ) ), $year );\n $month_link = sprintf( $link, esc_url( get_month_link( $year, $monthnum ) ), $month_name );\n\n $breadcrumb_trail = $year_link . $delimiter . $month_link . $delimiter . $before . $day . $after;\n }\n\n } elseif ( is_post_type_archive() ) {\n\n $post_type = $wp_the_query->query_vars['post_type'];\n $post_type_object = get_post_type_object( $post_type );\n\n $breadcrumb_trail = $before . $post_type_object->labels->singular_name . $after;\n\n }\n } \n\n // Handle the search page\n if ( is_search() ) {\n $breadcrumb_trail = __( 'Search query for: ' ) . $before . get_search_query() . $after;\n }\n\n // Handle 404's\n if ( is_404() ) {\n $breadcrumb_trail = $before . __( 'Error 404' ) . $after;\n }\n\n // Handle paged pages\n if ( is_paged() ) {\n $current_page = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : get_query_var( 'page' );\n $page_addon = $before . sprintf( __( ' ( Page %s )' ), number_format_i18n( $current_page ) ) . $after;\n }\n\n $breadcrumb_output_link = '';\n $breadcrumb_output_link .= '<div class=\"breadcrumb\">';\n if ( is_home()\n || is_front_page()\n ) {\n // Do not show breadcrumbs on page one of home and frontpage\n if ( is_paged() ) {\n $breadcrumb_output_link .= $here_text . $delimiter;\n $breadcrumb_output_link .= '<a href=\"' . $home_link . '\">' . $home_text . '</a>';\n $breadcrumb_output_link .= $page_addon;\n }\n } else {\n $breadcrumb_output_link .= $here_text . $delimiter;\n $breadcrumb_output_link .= '<a href=\"' . $home_link . '\" rel=\"v:url\" property=\"v:title\">' . $home_text . '</a>';\n $breadcrumb_output_link .= $delimiter;\n $breadcrumb_output_link .= $breadcrumb_trail;\n $breadcrumb_output_link .= $page_addon;\n }\n $breadcrumb_output_link .= '</div><!-- .breadcrumbs -->';\n\n return $breadcrumb_output_link;\n}\n</code></pre>\n\n<p>You can simply call it as follow</p>\n\n<pre><code>echo get_hansel_and_gretel_breadcrumbs();\n</code></pre>\n\n<p>where needed</p>\n\n<p>This breadcrumb function takes care of custom post types as well</p>\n"
},
{
"answer_id": 266215,
"author": "perfectionist1",
"author_id": 119194,
"author_profile": "https://wordpress.stackexchange.com/users/119194",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Excellent!</strong>\nWorks the code of accepted answer (of Pieter Goosen).</p>\n\n<p><strong>Note:</strong> Just added a little task more. Make a <strong>validation check</strong> of that function <strong>before calling</strong> it, this way:</p>\n\n<pre><code><?php \n if(function_exists('get_hansel_and_gretel_breadcrumbs')): \n echo get_hansel_and_gretel_breadcrumbs();\n endif;\n?>\n</code></pre>\n\n<p><em>Additionally,</em> I saved that function into a file named <code>breadcrumbs.php</code> in project root folder and included it <strong>in functions.php</strong> file using <code>include_once('breadcrumbs.php');</code> to be more organized.</p>\n"
},
{
"answer_id": 318952,
"author": "user153920",
"author_id": 153920,
"author_profile": "https://wordpress.stackexchange.com/users/153920",
"pm_score": 0,
"selected": false,
"text": "<pre><code>function get_hansel_and_gretel_breadcrumbs()\n{\n // Set variables for later use\n $here_text = __( 'You are currently here!' );\n $home_link = home_url('/');\n $home_text = __( 'Home' );\n $link_before = '<span typeof=\"v:Breadcrumb\">';\n $link_after = '</span>';\n $link_attr = ' rel=\"v:url\" property=\"v:title\"';\n $link = $link_before . '<a' . $link_attr . ' href=\"%1$s\">%2$s</a>' . $link_after;\n $delimiter = ' &raquo; '; // Delimiter between crumbs\n $before = '<span class=\"current\">'; // Tag before the current crumb\n $after = '</span>'; // Tag after the current crumb\n $page_addon = ''; // Adds the page number if the query is paged\n $breadcrumb_trail = '';\n $category_links = '';\n\n /** \n * Set our own $wp_the_query variable. Do not use the global variable version due to \n * reliability\n */\n $wp_the_query = $GLOBALS['wp_the_query'];\n $queried_object = $wp_the_query->get_queried_object();\n\n // Handle single post requests which includes single pages, posts and attatchments\n if ( is_singular() ) \n {\n /** \n * Set our own $post variable. Do not use the global variable version due to \n * reliability. We will set $post_object variable to $GLOBALS['wp_the_query']\n */\n $post_object = sanitize_post( $queried_object );\n\n // Set variables \n $title = apply_filters( 'the_title', $post_object->post_title );\n $parent = $post_object->post_parent;\n $post_type = $post_object->post_type;\n $post_id = $post_object->ID;\n $post_link = $before . $title . $after;\n $parent_string = '';\n $post_type_link = '';\n\n if ( 'post' === $post_type ) \n {\n // Get the post categories\n $categories = get_the_category( $post_id );\n if ( $categories ) {\n // Lets grab the first category\n $category = $categories[0];\n\n $category_links = get_category_parents( $category, true, $delimiter );\n $category_links = str_replace( '<a', $link_before . '<a' . $link_attr, $category_links );\n $category_links = str_replace( '</a>', '</a>' . $link_after, $category_links );\n }\n }\n\n if ( !in_array( $post_type, ['post', 'page', 'attachment'] ) )\n {\n $post_type_object = get_post_type_object( $post_type );\n $archive_link = esc_url( get_post_type_archive_link( $post_type ) );\n\n $post_type_link = sprintf( $link, $archive_link, $post_type_object->labels->singular_name );\n }\n\n // Get post parents if $parent !== 0\n if ( 0 !== $parent ) \n {\n $parent_links = [];\n while ( $parent ) {\n $post_parent = get_post( $parent );\n\n $parent_links[] = sprintf( $link, esc_url( get_permalink( $post_parent->ID ) ), get_the_title( $post_parent->ID ) );\n\n $parent = $post_parent->post_parent;\n }\n\n $parent_links = array_reverse( $parent_links );\n\n $parent_string = implode( $delimiter, $parent_links );\n }\n\n // Lets build the breadcrumb trail\n if ( $parent_string ) {\n $breadcrumb_trail = $parent_string . $delimiter . $post_link;\n } else {\n $breadcrumb_trail = $post_link;\n }\n\n if ( $post_type_link )\n $breadcrumb_trail = $post_type_link . $delimiter . $breadcrumb_trail;\n\n if ( $category_links )\n $breadcrumb_trail = $category_links . $breadcrumb_trail;\n }\n\n // Handle archives which includes category-, tag-, taxonomy-, date-, custom post type archives and author archives\n if( is_archive() )\n {\n if ( is_category()\n || is_tag()\n || is_tax()\n ) {\n // Set the variables for this section\n $term_object = get_term( $queried_object );\n $taxonomy = $term_object->taxonomy;\n $term_id = $term_object->term_id;\n $term_name = $term_object->name;\n $term_parent = $term_object->parent;\n $taxonomy_object = get_taxonomy( $taxonomy );\n $current_term_link = $before . $taxonomy_object->labels->singular_name . ': ' . $term_name . $after;\n $parent_term_string = '';\n\n if ( 0 !== $term_parent )\n {\n // Get all the current term ancestors\n $parent_term_links = [];\n while ( $term_parent ) {\n $term = get_term( $term_parent, $taxonomy );\n\n $parent_term_links[] = sprintf( $link, esc_url( get_term_link( $term ) ), $term->name );\n\n $term_parent = $term->parent;\n }\n\n $parent_term_links = array_reverse( $parent_term_links );\n $parent_term_string = implode( $delimiter, $parent_term_links );\n }\n\n if ( $parent_term_string ) {\n $breadcrumb_trail = $parent_term_string . $delimiter . $current_term_link;\n } else {\n $breadcrumb_trail = $current_term_link;\n }\n\n } elseif ( is_author() ) {\n\n $breadcrumb_trail = __( 'Author archive for ') . $before . $queried_object->data->display_name . $after;\n\n } elseif ( is_date() ) {\n // Set default variables\n $year = $wp_the_query->query_vars['year'];\n $monthnum = $wp_the_query->query_vars['monthnum'];\n $day = $wp_the_query->query_vars['day'];\n\n // Get the month name if $monthnum has a value\n if ( $monthnum ) {\n $date_time = DateTime::createFromFormat( '!m', $monthnum );\n $month_name = $date_time->format( 'F' );\n }\n\n if ( is_year() ) {\n\n $breadcrumb_trail = $before . $year . $after;\n\n } elseif( is_month() ) {\n\n $year_link = sprintf( $link, esc_url( get_year_link( $year ) ), $year );\n\n $breadcrumb_trail = $year_link . $delimiter . $before . $month_name . $after;\n\n } elseif( is_day() ) {\n\n $year_link = sprintf( $link, esc_url( get_year_link( $year ) ), $year );\n $month_link = sprintf( $link, esc_url( get_month_link( $year, $monthnum ) ), $month_name );\n\n $breadcrumb_trail = $year_link . $delimiter . $month_link . $delimiter . $before . $day . $after;\n }\n\n } elseif ( is_post_type_archive() ) {\n\n $post_type = $wp_the_query->query_vars['post_type'];\n $post_type_object = get_post_type_object( $post_type );\n\n $breadcrumb_trail = $before . $post_type_object->labels->singular_name . $after;\n\n }\n } \n\n // Handle the search page\n if ( is_search() ) {\n $breadcrumb_trail = __( 'Search query for: ' ) . $before . get_search_query() . $after;\n }\n\n // Handle 404's\n if ( is_404() ) {\n $breadcrumb_trail = $before . __( 'Error 404' ) . $after;\n }\n\n // Handle paged pages\n if ( is_paged() ) {\n $current_page = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : get_query_var( 'page' );\n $page_addon = $before . sprintf( __( ' ( Page %s )' ), number_format_i18n( $current_page ) ) . $after;\n }\n\n $breadcrumb_output_link = '';\n $breadcrumb_output_link .= '<div class=\"breadcrumb\">';\n if ( is_home()\n || is_front_page()\n ) {\n // Do not show breadcrumbs on page one of home and frontpage\n if ( is_paged() ) {\n $breadcrumb_output_link .= $here_text . $delimiter;\n $breadcrumb_output_link .= '<a href=\"' . $home_link . '\">' . $home_text . '</a>';\n $breadcrumb_output_link .= $page_addon;\n }\n } else {\n $breadcrumb_output_link .= $here_text . $delimiter;\n $breadcrumb_output_link .= '<a href=\"' . $home_link . '\" rel=\"v:url\" property=\"v:title\">' . $home_text . '</a>';\n $breadcrumb_output_link .= $delimiter;\n $breadcrumb_output_link .= $breadcrumb_trail;\n $breadcrumb_output_link .= $page_addon;\n }\n $breadcrumb_output_link .= '</div><!-- .breadcrumbs -->';\n\n return $breadcrumb_output_link;\n}\n</code></pre>\n"
}
] |
2015/10/06
|
[
"https://wordpress.stackexchange.com/questions/204744",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81196/"
] |
I want to fetch a list of posts with the most recent comments. However I don't wish to simply get the latest comments and have duplicate posts, but I want to group the posts (by their ID). I tried the following (ff it is important: the code is in the widget() methode of a widget class):
```
function distinct() {
return "DISTINCT";
}
add_filter('posts_distinct', 'distinct');
$args = array(
'number' => 8
);
$query = new WP_Comment_Query;
$comments = $query->query($args);
```
The *posts\_distinct* filter seemed like the correct way to achieve this, but it is not called and does not work. A different approach with *posts\_groupby* doesn't work either:
```
add_filter('posts_groupby', 'groupby' );
function groupby($groupby) {
global $wpdb;
$groupby = "{$wpdb->posts}.ID";
return $groupby;
}
```
How can I make WP\_Comment\_Query to return 8 distinguished posts?
I know that I could simply use a raw SQL query, but after a hour of fruitless googling I really wonder, how to solve this problem the WP way.
|
The issue with most breadcrumb functions is that it relies on the `$post` object on all pages. Not only is the `$post` global totally unreliable (*see my post [here](https://wordpress.stackexchange.com/q/167706/31545)*), it might not even contain the data that we need, even if the `$post` global is not compromised
The `$post` global on archive pages (*which includes category, tag, date, taxonomy term, author and custom post type archive*) contains the first post in the loop before the loop. It is not always true that the first post is from the selected archive (*the archive page you are on*), which means that the info you are looking for might be incorrect, even though the `$post` global is not compromised. Conditions where the first post might not be from the selected archive is posts that are injected through custom stickies and the `the_posts` filter.
I have recently rewritten one of my very old breadcrumb functions which makes use of the `$GLOBALS['wp_the_query']` object and the queried object saved in the `$GLOBALS['wp_the_query']` global. This way, we have a 99.999% reliable breadcrumb that does not rely on the `$post` global or any compromised data.
Here is the function: (*Requires PHP 5.4+. Also, feel free to alter as necessary*)
```
function get_hansel_and_gretel_breadcrumbs()
{
// Set variables for later use
$here_text = __( 'You are currently here!' );
$home_link = home_url('/');
$home_text = __( 'Home' );
$link_before = '<span typeof="v:Breadcrumb">';
$link_after = '</span>';
$link_attr = ' rel="v:url" property="v:title"';
$link = $link_before . '<a' . $link_attr . ' href="%1$s">%2$s</a>' . $link_after;
$delimiter = ' » '; // Delimiter between crumbs
$before = '<span class="current">'; // Tag before the current crumb
$after = '</span>'; // Tag after the current crumb
$page_addon = ''; // Adds the page number if the query is paged
$breadcrumb_trail = '';
$category_links = '';
/**
* Set our own $wp_the_query variable. Do not use the global variable version due to
* reliability
*/
$wp_the_query = $GLOBALS['wp_the_query'];
$queried_object = $wp_the_query->get_queried_object();
// Handle single post requests which includes single pages, posts and attatchments
if ( is_singular() )
{
/**
* Set our own $post variable. Do not use the global variable version due to
* reliability. We will set $post_object variable to $GLOBALS['wp_the_query']
*/
$post_object = sanitize_post( $queried_object );
// Set variables
$title = apply_filters( 'the_title', $post_object->post_title );
$parent = $post_object->post_parent;
$post_type = $post_object->post_type;
$post_id = $post_object->ID;
$post_link = $before . $title . $after;
$parent_string = '';
$post_type_link = '';
if ( 'post' === $post_type )
{
// Get the post categories
$categories = get_the_category( $post_id );
if ( $categories ) {
// Lets grab the first category
$category = $categories[0];
$category_links = get_category_parents( $category, true, $delimiter );
$category_links = str_replace( '<a', $link_before . '<a' . $link_attr, $category_links );
$category_links = str_replace( '</a>', '</a>' . $link_after, $category_links );
}
}
if ( !in_array( $post_type, ['post', 'page', 'attachment'] ) )
{
$post_type_object = get_post_type_object( $post_type );
$archive_link = esc_url( get_post_type_archive_link( $post_type ) );
$post_type_link = sprintf( $link, $archive_link, $post_type_object->labels->singular_name );
}
// Get post parents if $parent !== 0
if ( 0 !== $parent )
{
$parent_links = [];
while ( $parent ) {
$post_parent = get_post( $parent );
$parent_links[] = sprintf( $link, esc_url( get_permalink( $post_parent->ID ) ), get_the_title( $post_parent->ID ) );
$parent = $post_parent->post_parent;
}
$parent_links = array_reverse( $parent_links );
$parent_string = implode( $delimiter, $parent_links );
}
// Lets build the breadcrumb trail
if ( $parent_string ) {
$breadcrumb_trail = $parent_string . $delimiter . $post_link;
} else {
$breadcrumb_trail = $post_link;
}
if ( $post_type_link )
$breadcrumb_trail = $post_type_link . $delimiter . $breadcrumb_trail;
if ( $category_links )
$breadcrumb_trail = $category_links . $breadcrumb_trail;
}
// Handle archives which includes category-, tag-, taxonomy-, date-, custom post type archives and author archives
if( is_archive() )
{
if ( is_category()
|| is_tag()
|| is_tax()
) {
// Set the variables for this section
$term_object = get_term( $queried_object );
$taxonomy = $term_object->taxonomy;
$term_id = $term_object->term_id;
$term_name = $term_object->name;
$term_parent = $term_object->parent;
$taxonomy_object = get_taxonomy( $taxonomy );
$current_term_link = $before . $taxonomy_object->labels->singular_name . ': ' . $term_name . $after;
$parent_term_string = '';
if ( 0 !== $term_parent )
{
// Get all the current term ancestors
$parent_term_links = [];
while ( $term_parent ) {
$term = get_term( $term_parent, $taxonomy );
$parent_term_links[] = sprintf( $link, esc_url( get_term_link( $term ) ), $term->name );
$term_parent = $term->parent;
}
$parent_term_links = array_reverse( $parent_term_links );
$parent_term_string = implode( $delimiter, $parent_term_links );
}
if ( $parent_term_string ) {
$breadcrumb_trail = $parent_term_string . $delimiter . $current_term_link;
} else {
$breadcrumb_trail = $current_term_link;
}
} elseif ( is_author() ) {
$breadcrumb_trail = __( 'Author archive for ') . $before . $queried_object->data->display_name . $after;
} elseif ( is_date() ) {
// Set default variables
$year = $wp_the_query->query_vars['year'];
$monthnum = $wp_the_query->query_vars['monthnum'];
$day = $wp_the_query->query_vars['day'];
// Get the month name if $monthnum has a value
if ( $monthnum ) {
$date_time = DateTime::createFromFormat( '!m', $monthnum );
$month_name = $date_time->format( 'F' );
}
if ( is_year() ) {
$breadcrumb_trail = $before . $year . $after;
} elseif( is_month() ) {
$year_link = sprintf( $link, esc_url( get_year_link( $year ) ), $year );
$breadcrumb_trail = $year_link . $delimiter . $before . $month_name . $after;
} elseif( is_day() ) {
$year_link = sprintf( $link, esc_url( get_year_link( $year ) ), $year );
$month_link = sprintf( $link, esc_url( get_month_link( $year, $monthnum ) ), $month_name );
$breadcrumb_trail = $year_link . $delimiter . $month_link . $delimiter . $before . $day . $after;
}
} elseif ( is_post_type_archive() ) {
$post_type = $wp_the_query->query_vars['post_type'];
$post_type_object = get_post_type_object( $post_type );
$breadcrumb_trail = $before . $post_type_object->labels->singular_name . $after;
}
}
// Handle the search page
if ( is_search() ) {
$breadcrumb_trail = __( 'Search query for: ' ) . $before . get_search_query() . $after;
}
// Handle 404's
if ( is_404() ) {
$breadcrumb_trail = $before . __( 'Error 404' ) . $after;
}
// Handle paged pages
if ( is_paged() ) {
$current_page = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : get_query_var( 'page' );
$page_addon = $before . sprintf( __( ' ( Page %s )' ), number_format_i18n( $current_page ) ) . $after;
}
$breadcrumb_output_link = '';
$breadcrumb_output_link .= '<div class="breadcrumb">';
if ( is_home()
|| is_front_page()
) {
// Do not show breadcrumbs on page one of home and frontpage
if ( is_paged() ) {
$breadcrumb_output_link .= $here_text . $delimiter;
$breadcrumb_output_link .= '<a href="' . $home_link . '">' . $home_text . '</a>';
$breadcrumb_output_link .= $page_addon;
}
} else {
$breadcrumb_output_link .= $here_text . $delimiter;
$breadcrumb_output_link .= '<a href="' . $home_link . '" rel="v:url" property="v:title">' . $home_text . '</a>';
$breadcrumb_output_link .= $delimiter;
$breadcrumb_output_link .= $breadcrumb_trail;
$breadcrumb_output_link .= $page_addon;
}
$breadcrumb_output_link .= '</div><!-- .breadcrumbs -->';
return $breadcrumb_output_link;
}
```
You can simply call it as follow
```
echo get_hansel_and_gretel_breadcrumbs();
```
where needed
This breadcrumb function takes care of custom post types as well
|
204,768 |
<p>I can't get the Featured Image metabox and taxonomy to show up on the edit page for the default post and page post types.
it does work for the custom post type I've created using a plugin. It just doesn't work with the default ones.</p>
<p>Also been checking the screen options on the top right of the edit page and the checkbox for the Featured Image is not even there.</p>
<p>i have desactivated all my pluging + with basic theme and the featured image option doesn t show up</p>
<p>Problem since i upgraded 3 weeks ago on wp 4.3.1</p>
<p>My Html code is </p>
<pre><code><div style="" id="postimagediv" class="postbox hide-if-js">
</code></pre>
<p>if i put
<code><div style="display: block;" id="postimagediv" class="postbox hide-if-js"></code></p>
<p>My features image is display and i can post correctly, where can i set this value by defaut without adding the html code with firebug? </p>
<p>Thx</p>
|
[
{
"answer_id": 204804,
"author": "fatwombat",
"author_id": 81482,
"author_profile": "https://wordpress.stackexchange.com/users/81482",
"pm_score": 0,
"selected": false,
"text": "<p>Have you got the following in your functions.php file - it might solve the problem:</p>\n\n<pre><code>add_theme_support( 'post-thumbnails' );\n</code></pre>\n"
},
{
"answer_id": 205183,
"author": "Miroof",
"author_id": 81322,
"author_profile": "https://wordpress.stackexchange.com/users/81322",
"pm_score": -1,
"selected": false,
"text": "<p>No it not do anything, the only way i can get the featured images is by editing the code into firebug adding style=\"display: block;</p>\n\n<p>and i do not see the post content, with add media and field for the text =/</p>\n"
}
] |
2015/10/06
|
[
"https://wordpress.stackexchange.com/questions/204768",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81322/"
] |
I can't get the Featured Image metabox and taxonomy to show up on the edit page for the default post and page post types.
it does work for the custom post type I've created using a plugin. It just doesn't work with the default ones.
Also been checking the screen options on the top right of the edit page and the checkbox for the Featured Image is not even there.
i have desactivated all my pluging + with basic theme and the featured image option doesn t show up
Problem since i upgraded 3 weeks ago on wp 4.3.1
My Html code is
```
<div style="" id="postimagediv" class="postbox hide-if-js">
```
if i put
`<div style="display: block;" id="postimagediv" class="postbox hide-if-js">`
My features image is display and i can post correctly, where can i set this value by defaut without adding the html code with firebug?
Thx
|
Have you got the following in your functions.php file - it might solve the problem:
```
add_theme_support( 'post-thumbnails' );
```
|
204,773 |
<p>I basically want the output of <code>get_stylesheet_directory_uri()</code>, but without http(s) and the domain.</p>
|
[
{
"answer_id": 204777,
"author": "Chris Cox",
"author_id": 1718,
"author_profile": "https://wordpress.stackexchange.com/users/1718",
"pm_score": 2,
"selected": false,
"text": "<p>The easiest way to do this would be to regex it. Use preg_replace() or similar to trim the output of get_site_url() from the output of get_stylesheet_directory_uri().</p>\n\n<p>Edit: actually, str_replace would do the job without resorting to regex.</p>\n\n<pre><code>str_replace(get_site_url(), '', get_stylesheet_directory_uri());\n</code></pre>\n"
},
{
"answer_id": 204782,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 3,
"selected": true,
"text": "<p>Use <a href=\"http://php.net/manual/en/function.parse-url.php\" rel=\"nofollow\"><code>parse_url()</code></a>, because it exists exactly for that reason:</p>\n\n<pre><code>$path = parse_url( get_stylesheet_directory_uri(), PHP_URL_PATH );\n</code></pre>\n\n<p>Chris Cox’ solution will fail when the <code>wp-content</code> directory runs under a different domain than the rest of the site.</p>\n"
}
] |
2015/10/06
|
[
"https://wordpress.stackexchange.com/questions/204773",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40796/"
] |
I basically want the output of `get_stylesheet_directory_uri()`, but without http(s) and the domain.
|
Use [`parse_url()`](http://php.net/manual/en/function.parse-url.php), because it exists exactly for that reason:
```
$path = parse_url( get_stylesheet_directory_uri(), PHP_URL_PATH );
```
Chris Cox’ solution will fail when the `wp-content` directory runs under a different domain than the rest of the site.
|
204,779 |
<p>By default the WordPress Media Library allows you to filter results by their type or date. How can I add a third drop down to list and filter by author?</p>
<p>Currently we have this:</p>
<p><a href="https://i.stack.imgur.com/cHyP3.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/cHyP3.jpg" alt="enter image description here"></a></p>
<p>I'd like to have the following:</p>
<p><a href="https://i.stack.imgur.com/ej950.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/ej950.jpg" alt="enter image description here"></a></p>
<p>According to <a href="https://core.trac.wordpress.org/ticket/16044" rel="noreferrer">this ticket</a> (unless I'm reading it wrong) the code was added three years ago to <code>/wp-admin/includes/class-wp-media-list-table.php</code> to allow this, but I don't see how this actually works.</p>
<p><a href="https://codex.wordpress.org/Plugin_API/Filter_Reference/ajax_query_attachments_args" rel="noreferrer">The codex</a> also says that it's possible to modify the media library modal window you get when editing a page or post with:</p>
<pre><code>add_filter( 'ajax_query_attachments_args', 'show_current_user_attachments', 10, 1 );
function show_current_user_attachments( $query = array() ) {
$user_id = get_current_user_id();
if( $user_id ) {
$query['author'] = $user_id;
}
return $query;
}
</code></pre>
<p>So I'd think that it's possible to do something similar on the main Media Library page, but I can't see how.</p>
|
[
{
"answer_id": 204819,
"author": "sbounty",
"author_id": 81512,
"author_profile": "https://wordpress.stackexchange.com/users/81512",
"pm_score": 1,
"selected": false,
"text": "<p>If you need this for your own site then instead of code you can go to list view and click on author name under <strong>Author</strong> column. That would give you the list of media for that particular author. See below screenshot.</p>\n\n<p><a href=\"https://i.stack.imgur.com/TpQEl.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/TpQEl.png\" alt=\"enter image description here\"></a></p>\n\n<p>But if you are doing this for any client then you will need a code to provide user friendly way :) like the dropdown you shown in your screenshot :)</p>\n"
},
{
"answer_id": 204857,
"author": "Webloper",
"author_id": 29035,
"author_profile": "https://wordpress.stackexchange.com/users/29035",
"pm_score": 4,
"selected": true,
"text": "<p>In your question you showed the image which is grid-view and that codex belongs to list-view. So I am confused here for which section you are talking about.</p>\n\n<p><strong>Grid View :</strong> not possible unless you change the core as they don't provide any hook and the whole media section was created by jquery, backbone and unserscore. Please look into media-grid.min.js or media-grid.js for code.</p>\n\n<p><strong>List View :</strong> in this view you can easily add dropdown. here is the script to do this. If you want then add <code>parse_query</code> or <code>pre_get_posts</code> filter to change the query for the dropdown. As I am setting <code>author</code> to url, wordpress itself sets it for me so need for those filters.</p>\n\n<pre><code>function media_add_author_dropdown()\n{\n $scr = get_current_screen();\n if ( $scr->base !== 'upload' ) return;\n\n $author = filter_input(INPUT_GET, 'author', FILTER_SANITIZE_STRING );\n $selected = (int)$author > 0 ? $author : '-1';\n $args = array(\n 'show_option_none' => 'All Authors',\n 'name' => 'author',\n 'selected' => $selected\n );\n wp_dropdown_users( $args );\n}\nadd_action('restrict_manage_posts', 'media_add_author_dropdown');\n</code></pre>\n\n<p>Here are the references</p>\n\n<ol>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/restrict_manage_posts/\" rel=\"nofollow noreferrer\">restrict_manage_posts</a></li>\n<li><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow noreferrer\">pre_get_posts</a></li>\n<li><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/parse_query\" rel=\"nofollow noreferrer\">parse_query</a></li>\n</ol>\n\n<p><strong>Edit #1: Added author filter after this <a href=\"https://wordpress.stackexchange.com/questions/204779/how-can-i-add-an-author-filter-to-the-media-library/204857?noredirect=1#comment320285_204857\">comment</a></strong> </p>\n\n<pre><code>function author_filter($query) {\n if ( is_admin() && $query->is_main_query() ) {\n if (isset($_GET['author']) && $_GET['author'] == -1) {\n $query->set('author', '');\n }\n }\n}\nadd_action('pre_get_posts','author_filter');\n</code></pre>\n"
}
] |
2015/10/06
|
[
"https://wordpress.stackexchange.com/questions/204779",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/26666/"
] |
By default the WordPress Media Library allows you to filter results by their type or date. How can I add a third drop down to list and filter by author?
Currently we have this:
[](https://i.stack.imgur.com/cHyP3.jpg)
I'd like to have the following:
[](https://i.stack.imgur.com/ej950.jpg)
According to [this ticket](https://core.trac.wordpress.org/ticket/16044) (unless I'm reading it wrong) the code was added three years ago to `/wp-admin/includes/class-wp-media-list-table.php` to allow this, but I don't see how this actually works.
[The codex](https://codex.wordpress.org/Plugin_API/Filter_Reference/ajax_query_attachments_args) also says that it's possible to modify the media library modal window you get when editing a page or post with:
```
add_filter( 'ajax_query_attachments_args', 'show_current_user_attachments', 10, 1 );
function show_current_user_attachments( $query = array() ) {
$user_id = get_current_user_id();
if( $user_id ) {
$query['author'] = $user_id;
}
return $query;
}
```
So I'd think that it's possible to do something similar on the main Media Library page, but I can't see how.
|
In your question you showed the image which is grid-view and that codex belongs to list-view. So I am confused here for which section you are talking about.
**Grid View :** not possible unless you change the core as they don't provide any hook and the whole media section was created by jquery, backbone and unserscore. Please look into media-grid.min.js or media-grid.js for code.
**List View :** in this view you can easily add dropdown. here is the script to do this. If you want then add `parse_query` or `pre_get_posts` filter to change the query for the dropdown. As I am setting `author` to url, wordpress itself sets it for me so need for those filters.
```
function media_add_author_dropdown()
{
$scr = get_current_screen();
if ( $scr->base !== 'upload' ) return;
$author = filter_input(INPUT_GET, 'author', FILTER_SANITIZE_STRING );
$selected = (int)$author > 0 ? $author : '-1';
$args = array(
'show_option_none' => 'All Authors',
'name' => 'author',
'selected' => $selected
);
wp_dropdown_users( $args );
}
add_action('restrict_manage_posts', 'media_add_author_dropdown');
```
Here are the references
1. [restrict\_manage\_posts](https://developer.wordpress.org/reference/hooks/restrict_manage_posts/)
2. [pre\_get\_posts](https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts)
3. [parse\_query](https://codex.wordpress.org/Plugin_API/Action_Reference/parse_query)
**Edit #1: Added author filter after this [comment](https://wordpress.stackexchange.com/questions/204779/how-can-i-add-an-author-filter-to-the-media-library/204857?noredirect=1#comment320285_204857)**
```
function author_filter($query) {
if ( is_admin() && $query->is_main_query() ) {
if (isset($_GET['author']) && $_GET['author'] == -1) {
$query->set('author', '');
}
}
}
add_action('pre_get_posts','author_filter');
```
|
204,833 |
<p>I am learning how to work with Wordpress, and im trying to build my own website in it.</p>
<p>Since my website is a onepages, i would like to be able to load all my pages ( they then count as sections ) to get loaded on the frontpage, with there templates.</p>
<p>i now have a index.php that loops through the pages but doesnt load the page templates and i just cant get it to work, here is my index.php :</p>
<pre><code><?php get_header(); ?>
<!-- START CONTENT -->
<?php
$args = array(
'sort_order' => 'ASC',
'sort_column' => 'menu_order', //post_title
'hierarchical' => 1,
'exclude' => '',
'child_of' => 0,
'parent' => -1,
'exclude_tree' => '',
'number' => '',
'offset' => 0,
'post_type' => 'page',
'post_status' => 'publish'
);
$pages = get_pages($args);
//start loop
foreach ($pages as $page_data) {
$content = apply_filters('the_content', $page_data->post_content);
$title = $page_data->post_title;
$slug = $page_data->post_name;
?>
<div class='<?php echo "$slug" ?>'>
<?php
echo "$content";
?>
</div>
<?php } ?>
<!-- END CONTENT -->
<?php get_footer(); ?>
</code></pre>
<p>I really hope you guys can help me out!</p>
|
[
{
"answer_id": 204868,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 1,
"selected": false,
"text": "<p>Create a directory <code>page-templates</code> in your theme for <a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/page-templates/\" rel=\"nofollow\">page templates</a>. </p>\n\n<p>Then add your templates there, but omit the calls to <code>get_header()</code> and <code>get_footer()</code>.</p>\n\n<p>Create a template <code>default.php</code> and then all additional templates you might need.</p>\n\n<p>Now write the pages and assign the proper templates.</p>\n\n<p>In your loop do this:</p>\n\n<pre><code>foreach ($pages as $page_data)\n{\n setup_postdata( $page_data );\n\n $template = get_post_meta( $page_data->ID, '_wp_page_template', true );\n\n if ( ! $template )\n $template = 'default';\n\n locate_template( $template, true, false );\n}\n</code></pre>\n"
},
{
"answer_id": 204878,
"author": "Bryan Willis",
"author_id": 38123,
"author_profile": "https://wordpress.stackexchange.com/users/38123",
"pm_score": 1,
"selected": true,
"text": "<p>You could do this exchanging each page name for the page you want to use. I just tested and it seems to work. I'm sure there are downsides (speed for one).</p>\n\n<pre><code><?php\n/**\n * Template Name: OnePager\n */\n <?php get_header(); ?>\n <!-- Page One - How it Works -->\n <section id=\"section1\">\n <div class=\"container\">\n <div class=\"col-sm-12\">\n <?php\n $section1 = new WP_Query( 'pagename=how-it-works' );\n while ( $section1->have_posts() ) : $section1->the_post();?>\n <h1><?php the_title(); ?></h1>\n <?php the_content(); ?>\n <?php endwhile;\n wp_reset_postdata();\n ?>\n </div>\n </div>\n </div>\n </section>\n <!-- Page One - Who We Are -->\n <section id=\"section2\">\n <div class=\"container\">\n <div class=\"col-sm-12\">\n <?php\n $section2 = new WP_Query( 'pagename=who-we-are' );\n while ( $section2->have_posts() ) : $section2->the_post();?>\n <h1><?php the_title(); ?></h1>\n <?php the_content(); ?>\n <?php endwhile;\n wp_reset_postdata();\n ?>\n </div>\n </div>\n </div>\n </section>\n <!-- Additional Pages Below -->\n\n <?php get_footer(); ?>\n</code></pre>\n\n<p>Sometimes people (including myself) are so determined on using php with wordpress that they waste a lot of time trying to do things like this when they could have created what ever it was in a fraction of the time by just using html. Wordpress is mainly designed for dynamic content. Where for the most part one-pager sites are usually pretty static. </p>\n\n<p>I've done a few of these one page sites using wordpress and here's what I've tried.\n1) Static html in a wordpress template (fastest and easiest)\n2) Used a pagebuilder. There are a few out there, most notably Visual Composer that have support for doing this.\n3) Advanced Custom Fields</p>\n\n<p><strong>Personally I liked the advanced custom fields method the most and have used it a couple times to do this. This way you can easily add image fields and text fields without having to worry about what markup the post editor might alter on output.</strong> </p>\n\n<pre><code> <section>\n <h1><?php the_field('banner_h1_title_text'); ?></h1>\n <h2><?php the_field('banner_h2_description_text'); ?></h2>\n <a href=\"#\" class=\"btn btn-default\">\n <?php the_field('call_to_action_main_button'); ?>\n </a>\n </section>\n</code></pre>\n\n<p>Or if I'm feeling really lazy I'll use Advanced Custom Fields like above except use it with the <a href=\"https://wordpress.org/plugins/custom-content-shortcode/\" rel=\"nofollow\">Custom Content Shortcode</a> then you don't have to worry about php at all. It's sort of like mustache.js for wordpress, if you've ever used or heard of that. Here a couple pages I just made using that method (<a href=\"http://disputebills.com/\" rel=\"nofollow\">parallax</a> / <a href=\"http://mbistaffing.com/privacy/\" rel=\"nofollow\">sticky-sections</a>)</p>\n\n<p>Just do whatever is easiest for you. There's nothing wrong with using html for something that is hardly ever edited. Plus if you're doing it for a client, it would give them a reason to keep you around as they would still need your help if they wanted that page changed :)</p>\n"
}
] |
2015/10/07
|
[
"https://wordpress.stackexchange.com/questions/204833",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81545/"
] |
I am learning how to work with Wordpress, and im trying to build my own website in it.
Since my website is a onepages, i would like to be able to load all my pages ( they then count as sections ) to get loaded on the frontpage, with there templates.
i now have a index.php that loops through the pages but doesnt load the page templates and i just cant get it to work, here is my index.php :
```
<?php get_header(); ?>
<!-- START CONTENT -->
<?php
$args = array(
'sort_order' => 'ASC',
'sort_column' => 'menu_order', //post_title
'hierarchical' => 1,
'exclude' => '',
'child_of' => 0,
'parent' => -1,
'exclude_tree' => '',
'number' => '',
'offset' => 0,
'post_type' => 'page',
'post_status' => 'publish'
);
$pages = get_pages($args);
//start loop
foreach ($pages as $page_data) {
$content = apply_filters('the_content', $page_data->post_content);
$title = $page_data->post_title;
$slug = $page_data->post_name;
?>
<div class='<?php echo "$slug" ?>'>
<?php
echo "$content";
?>
</div>
<?php } ?>
<!-- END CONTENT -->
<?php get_footer(); ?>
```
I really hope you guys can help me out!
|
You could do this exchanging each page name for the page you want to use. I just tested and it seems to work. I'm sure there are downsides (speed for one).
```
<?php
/**
* Template Name: OnePager
*/
<?php get_header(); ?>
<!-- Page One - How it Works -->
<section id="section1">
<div class="container">
<div class="col-sm-12">
<?php
$section1 = new WP_Query( 'pagename=how-it-works' );
while ( $section1->have_posts() ) : $section1->the_post();?>
<h1><?php the_title(); ?></h1>
<?php the_content(); ?>
<?php endwhile;
wp_reset_postdata();
?>
</div>
</div>
</div>
</section>
<!-- Page One - Who We Are -->
<section id="section2">
<div class="container">
<div class="col-sm-12">
<?php
$section2 = new WP_Query( 'pagename=who-we-are' );
while ( $section2->have_posts() ) : $section2->the_post();?>
<h1><?php the_title(); ?></h1>
<?php the_content(); ?>
<?php endwhile;
wp_reset_postdata();
?>
</div>
</div>
</div>
</section>
<!-- Additional Pages Below -->
<?php get_footer(); ?>
```
Sometimes people (including myself) are so determined on using php with wordpress that they waste a lot of time trying to do things like this when they could have created what ever it was in a fraction of the time by just using html. Wordpress is mainly designed for dynamic content. Where for the most part one-pager sites are usually pretty static.
I've done a few of these one page sites using wordpress and here's what I've tried.
1) Static html in a wordpress template (fastest and easiest)
2) Used a pagebuilder. There are a few out there, most notably Visual Composer that have support for doing this.
3) Advanced Custom Fields
**Personally I liked the advanced custom fields method the most and have used it a couple times to do this. This way you can easily add image fields and text fields without having to worry about what markup the post editor might alter on output.**
```
<section>
<h1><?php the_field('banner_h1_title_text'); ?></h1>
<h2><?php the_field('banner_h2_description_text'); ?></h2>
<a href="#" class="btn btn-default">
<?php the_field('call_to_action_main_button'); ?>
</a>
</section>
```
Or if I'm feeling really lazy I'll use Advanced Custom Fields like above except use it with the [Custom Content Shortcode](https://wordpress.org/plugins/custom-content-shortcode/) then you don't have to worry about php at all. It's sort of like mustache.js for wordpress, if you've ever used or heard of that. Here a couple pages I just made using that method ([parallax](http://disputebills.com/) / [sticky-sections](http://mbistaffing.com/privacy/))
Just do whatever is easiest for you. There's nothing wrong with using html for something that is hardly ever edited. Plus if you're doing it for a client, it would give them a reason to keep you around as they would still need your help if they wanted that page changed :)
|
204,848 |
<p>Hi I have question about file names. If I have custom post type, and for template I can create for example <code>single-portfolio.php</code> and get content of portfolio posts into this file, but i need to get that post not in same file I want get it on individual files for example <code>single-portfolio-post1.php</code> something like this but second file that I create doesn't work how can i do that?</p>
<p>Thank you</p>
|
[
{
"answer_id": 204849,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 1,
"selected": false,
"text": "<p>You can use the dynamic filter <code>{type}_template</code> (where <code>{type}</code> is the current query type e.g. <code>single</code>, <code>index</code> etc.) found in <a href=\"https://developer.wordpress.org/reference/functions/get_query_template/\" rel=\"nofollow\"><code>get_query_template()</code></a>:</p>\n\n<pre><code>function wpse_204848_get_id_template( $template ) {\n if ( $post = get_queried_object() ) {\n if ( $_template = locate_template( \"single-{$post->post_type}-{$post->ID}.php\" ) )\n $template = $_template; \n }\n\n return $template;\n}\n\nadd_filter( 'single_template', 'wpse_204848_get_id_template' );\n</code></pre>\n\n<p>For a portfolio post of ID <code>5</code>, it will use the template <code>single-portfolio-5.php</code> if it exists.</p>\n"
},
{
"answer_id": 204850,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<h2>WordPress 4.3 and below</h2>\n\n<p>There's nothing in the template hierarchy for showing a template based on a post ID unless you're using the <code>page</code> post type.</p>\n\n<p>Instead you're going to have to place conditional logic at the top of your <code>single-portfolio.php</code>.</p>\n\n<p><strong>I would also recommend you use meta options, terms, or the post slug instead of the ID.If you use post IDs, a simple import and export of the content would break your theme.</strong></p>\n\n<p>Also consider implementing a metabox with a dropdown that allows you to choose a template. This way you're not restricting yourself and hardcoding content in your theme, and you can build reusable general templates for certain portfolio items</p>\n\n<h2>WordPress 4.4</h2>\n\n<p><a href=\"https://make.wordpress.org/core/2015/10/07/single-post_type-post_name-php-new-theme-template-in-wordpress-4-4/\" rel=\"nofollow\">4.4 adds a new template to the hierarchy</a> that takes the form:</p>\n\n<pre><code>single-{post_type}-{post_name}.php\n</code></pre>\n\n<blockquote>\n <p>A new theme template has been added to the theme hierarchy as of r34800: single-{post_type}-{post_name}.php. This template follows the rules of is_single() and is used for a single post or custom post type. It’s most useful for targeting a specific post in a custom post type, and brings consistency to the templates available for pages and taxonomies. It comes in the hierarchy before single.php and single-{post_type}.php.</p>\n \n <p>Don’t forget, too, that in WordPress 4.3 singular.php was introduced and the hierarchy of attachment templates was fixed.</p>\n</blockquote>\n"
},
{
"answer_id": 204870,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 1,
"selected": false,
"text": "<p>As of WordPress version 4.4, this kind of template structure:</p>\n\n<pre><code>single-{post_type}-{post_name}.php \n</code></pre>\n\n<p>will be supported. More <a href=\"https://make.wordpress.org/core/2015/10/07/single-post_type-post_name-php-new-theme-template-in-wordpress-4-4/\" rel=\"nofollow\">here on make.wordpress.org</a>.</p>\n"
},
{
"answer_id": 204873,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>A little different answer then the others</p>\n\n<p>If you have a different design for a specific post it is better to try to see what can you do with CSS only before resorting to writing a new template.</p>\n\n<p>Still the question no is how do you identify which content should go with design A and which with B, for which I think the best thing to do is to add a meta box in which a design can be seleceted and adopt your sing-{post type}.php code to take it into consideration. If it is very different then you can put the code in different file, but the important point here is giving the admin control over the template being used.</p>\n\n<p>The reason for giving control to the admin is that you might want to reuse the template, and things like IDs and slugs can change (especially slugs)</p>\n"
}
] |
2015/10/07
|
[
"https://wordpress.stackexchange.com/questions/204848",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/71310/"
] |
Hi I have question about file names. If I have custom post type, and for template I can create for example `single-portfolio.php` and get content of portfolio posts into this file, but i need to get that post not in same file I want get it on individual files for example `single-portfolio-post1.php` something like this but second file that I create doesn't work how can i do that?
Thank you
|
You can use the dynamic filter `{type}_template` (where `{type}` is the current query type e.g. `single`, `index` etc.) found in [`get_query_template()`](https://developer.wordpress.org/reference/functions/get_query_template/):
```
function wpse_204848_get_id_template( $template ) {
if ( $post = get_queried_object() ) {
if ( $_template = locate_template( "single-{$post->post_type}-{$post->ID}.php" ) )
$template = $_template;
}
return $template;
}
add_filter( 'single_template', 'wpse_204848_get_id_template' );
```
For a portfolio post of ID `5`, it will use the template `single-portfolio-5.php` if it exists.
|
204,851 |
<p>I have a blog that is located on a subdomain blog.example.com and I have a main website located on example.com. They both use the same wordpress template. </p>
<p>I'd like to transfer my blog from the subdomain to the directory of the example.com preserving 'recent posts', 'categories' and other blog-ish features. </p>
<p>I know that there is a plugin that allows for importing/exporting wordpress posts, but the main question is, how can I transfer those blog-ish features. </p>
<p>Thanks in advance. </p>
|
[
{
"answer_id": 204849,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 1,
"selected": false,
"text": "<p>You can use the dynamic filter <code>{type}_template</code> (where <code>{type}</code> is the current query type e.g. <code>single</code>, <code>index</code> etc.) found in <a href=\"https://developer.wordpress.org/reference/functions/get_query_template/\" rel=\"nofollow\"><code>get_query_template()</code></a>:</p>\n\n<pre><code>function wpse_204848_get_id_template( $template ) {\n if ( $post = get_queried_object() ) {\n if ( $_template = locate_template( \"single-{$post->post_type}-{$post->ID}.php\" ) )\n $template = $_template; \n }\n\n return $template;\n}\n\nadd_filter( 'single_template', 'wpse_204848_get_id_template' );\n</code></pre>\n\n<p>For a portfolio post of ID <code>5</code>, it will use the template <code>single-portfolio-5.php</code> if it exists.</p>\n"
},
{
"answer_id": 204850,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<h2>WordPress 4.3 and below</h2>\n\n<p>There's nothing in the template hierarchy for showing a template based on a post ID unless you're using the <code>page</code> post type.</p>\n\n<p>Instead you're going to have to place conditional logic at the top of your <code>single-portfolio.php</code>.</p>\n\n<p><strong>I would also recommend you use meta options, terms, or the post slug instead of the ID.If you use post IDs, a simple import and export of the content would break your theme.</strong></p>\n\n<p>Also consider implementing a metabox with a dropdown that allows you to choose a template. This way you're not restricting yourself and hardcoding content in your theme, and you can build reusable general templates for certain portfolio items</p>\n\n<h2>WordPress 4.4</h2>\n\n<p><a href=\"https://make.wordpress.org/core/2015/10/07/single-post_type-post_name-php-new-theme-template-in-wordpress-4-4/\" rel=\"nofollow\">4.4 adds a new template to the hierarchy</a> that takes the form:</p>\n\n<pre><code>single-{post_type}-{post_name}.php\n</code></pre>\n\n<blockquote>\n <p>A new theme template has been added to the theme hierarchy as of r34800: single-{post_type}-{post_name}.php. This template follows the rules of is_single() and is used for a single post or custom post type. It’s most useful for targeting a specific post in a custom post type, and brings consistency to the templates available for pages and taxonomies. It comes in the hierarchy before single.php and single-{post_type}.php.</p>\n \n <p>Don’t forget, too, that in WordPress 4.3 singular.php was introduced and the hierarchy of attachment templates was fixed.</p>\n</blockquote>\n"
},
{
"answer_id": 204870,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 1,
"selected": false,
"text": "<p>As of WordPress version 4.4, this kind of template structure:</p>\n\n<pre><code>single-{post_type}-{post_name}.php \n</code></pre>\n\n<p>will be supported. More <a href=\"https://make.wordpress.org/core/2015/10/07/single-post_type-post_name-php-new-theme-template-in-wordpress-4-4/\" rel=\"nofollow\">here on make.wordpress.org</a>.</p>\n"
},
{
"answer_id": 204873,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>A little different answer then the others</p>\n\n<p>If you have a different design for a specific post it is better to try to see what can you do with CSS only before resorting to writing a new template.</p>\n\n<p>Still the question no is how do you identify which content should go with design A and which with B, for which I think the best thing to do is to add a meta box in which a design can be seleceted and adopt your sing-{post type}.php code to take it into consideration. If it is very different then you can put the code in different file, but the important point here is giving the admin control over the template being used.</p>\n\n<p>The reason for giving control to the admin is that you might want to reuse the template, and things like IDs and slugs can change (especially slugs)</p>\n"
}
] |
2015/10/07
|
[
"https://wordpress.stackexchange.com/questions/204851",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81554/"
] |
I have a blog that is located on a subdomain blog.example.com and I have a main website located on example.com. They both use the same wordpress template.
I'd like to transfer my blog from the subdomain to the directory of the example.com preserving 'recent posts', 'categories' and other blog-ish features.
I know that there is a plugin that allows for importing/exporting wordpress posts, but the main question is, how can I transfer those blog-ish features.
Thanks in advance.
|
You can use the dynamic filter `{type}_template` (where `{type}` is the current query type e.g. `single`, `index` etc.) found in [`get_query_template()`](https://developer.wordpress.org/reference/functions/get_query_template/):
```
function wpse_204848_get_id_template( $template ) {
if ( $post = get_queried_object() ) {
if ( $_template = locate_template( "single-{$post->post_type}-{$post->ID}.php" ) )
$template = $_template;
}
return $template;
}
add_filter( 'single_template', 'wpse_204848_get_id_template' );
```
For a portfolio post of ID `5`, it will use the template `single-portfolio-5.php` if it exists.
|
204,861 |
<p>PHP:</p>
<pre><code><?php $posts_query = new WP_Query('post_type="posts&posts_per_page=-1"');
if ($posts_query->have_posts()) : while ($posts_query->have_posts()) : $posts_query->the_post(); ?>
<?php if( $posts_query->current_post%5 == 0 ) { echo "\n" . '<div class="column">'; }
elseif( $posts_query->current_post%5 == 2 ) { echo "\n" . '<div class="column">'; } ?>
<article>
<a class="post-link" href="<?php the_permalink(); ?>">
<?php the_post_thumbnail(); ?>
</a>
</article>
<?php if( $posts_query->current_post%5 == 1 || $posts_query->current_post%5 == 4 || $posts_query->current_post == $posts_query->post_count-1 ) { echo '</div>'; }
endwhile;
?>
<?php else: endif; ?>
</code></pre>
<p>The above code works great, however I've got a total of 8 posts and only 7 are being displayed. </p>
<p>Could someone steer me in the right direction?</p>
<p>Cheers</p>
|
[
{
"answer_id": 204910,
"author": "Jeff Mattson",
"author_id": 93714,
"author_profile": "https://wordpress.stackexchange.com/users/93714",
"pm_score": 0,
"selected": false,
"text": "<p>Make sure your posts are all published and that they are not in the trash can.</p>\n"
},
{
"answer_id": 204914,
"author": "bestprogrammerintheworld",
"author_id": 38848,
"author_profile": "https://wordpress.stackexchange.com/users/38848",
"pm_score": 1,
"selected": false,
"text": "<p>There seems to be a syntax in your Query:</p>\n\n<pre><code>post_type=\"posts&posts_per_page=-1\"\n</code></pre>\n\n<p>would mean that your post type is <strong><em>posts&posts_per_page=-1</em></strong></p>\n\n<p>I think you mean</p>\n\n<pre><code>$posts_query = new WP_Query('post_type=post&posts_per_page=-1');\n</code></pre>\n\n<p>(The post type is not posts, but <strong>post</strong>)</p>\n\n<p>In this case Wordpress would not apply anyhting at all (because it contain errors, but just fetches the default post type with setting (that is set in dashboard) \"nr of posts\".</p>\n\n<p>My opinion is that you always should array(s) as arguments to the WP_Query, because it's more readable and easier to debug.</p>\n\n<pre><code>$args = array(\n 'posts_per_page' => -1,\n 'post_type' => 'post',\n);\n\n$posts_query = new WP_Query($args);\n</code></pre>\n\n<p>In your case it would not matter, but when you want to extend functionality to include let's say a taxonomy it would be </p>\n\n<pre><code>$args = array(\n 'posts_per_page' => -1,\n 'post_type' => 'post',\n 'tax_query' => array(\n array(\n 'taxonomy' => 'people',\n 'field' => 'slug',\n 'terms' => 'bob',\n ),\n ),\n);\n$query = new WP_Query( $args );\n</code></pre>\n"
}
] |
2015/10/07
|
[
"https://wordpress.stackexchange.com/questions/204861",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70016/"
] |
PHP:
```
<?php $posts_query = new WP_Query('post_type="posts&posts_per_page=-1"');
if ($posts_query->have_posts()) : while ($posts_query->have_posts()) : $posts_query->the_post(); ?>
<?php if( $posts_query->current_post%5 == 0 ) { echo "\n" . '<div class="column">'; }
elseif( $posts_query->current_post%5 == 2 ) { echo "\n" . '<div class="column">'; } ?>
<article>
<a class="post-link" href="<?php the_permalink(); ?>">
<?php the_post_thumbnail(); ?>
</a>
</article>
<?php if( $posts_query->current_post%5 == 1 || $posts_query->current_post%5 == 4 || $posts_query->current_post == $posts_query->post_count-1 ) { echo '</div>'; }
endwhile;
?>
<?php else: endif; ?>
```
The above code works great, however I've got a total of 8 posts and only 7 are being displayed.
Could someone steer me in the right direction?
Cheers
|
There seems to be a syntax in your Query:
```
post_type="posts&posts_per_page=-1"
```
would mean that your post type is ***posts&posts\_per\_page=-1***
I think you mean
```
$posts_query = new WP_Query('post_type=post&posts_per_page=-1');
```
(The post type is not posts, but **post**)
In this case Wordpress would not apply anyhting at all (because it contain errors, but just fetches the default post type with setting (that is set in dashboard) "nr of posts".
My opinion is that you always should array(s) as arguments to the WP\_Query, because it's more readable and easier to debug.
```
$args = array(
'posts_per_page' => -1,
'post_type' => 'post',
);
$posts_query = new WP_Query($args);
```
In your case it would not matter, but when you want to extend functionality to include let's say a taxonomy it would be
```
$args = array(
'posts_per_page' => -1,
'post_type' => 'post',
'tax_query' => array(
array(
'taxonomy' => 'people',
'field' => 'slug',
'terms' => 'bob',
),
),
);
$query = new WP_Query( $args );
```
|
204,879 |
<p>Refer to the title, I'm trying to create a shortcode for Blog Post with Pagination. I'm able to show the blog post but the pagination is not working. I tried using the code below and the link to second page is www.mysite.com/postname/page/2 . But it goes back to www.mysite.com/postname/ when I click on the pagination link to second page. </p>
<pre><code><?php
$big = 999999999;
$pagination = paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $this->query->max_num_pages
) );
$html .= $pagination;
?>
</code></pre>
<p><a href="https://i.stack.imgur.com/nbv9g.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nbv9g.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/1ODJ8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1ODJ8.png" alt="enter image description here"></a></p>
|
[
{
"answer_id": 205072,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": false,
"text": "<p><code>paged</code> is the query var for archive pagination, and <code>/page/n/</code> is the format for archive pagination URLs. Single posts use <code>page</code> and the format is <code>/postname/n/</code>, where <code>n</code> is the page number. Your links are redirecting because they are an invalid format.</p>\n"
},
{
"answer_id": 205519,
"author": "Dejo Dekic",
"author_id": 20941,
"author_profile": "https://wordpress.stackexchange.com/users/20941",
"pm_score": 0,
"selected": false,
"text": "<p>Ok buddy add this code to your functions.php</p>\n\n<pre><code>//This function is responsible for splitting posts and pages using <!--nexpage-->\nfunction my_link_pages() {\n$paged_page_nav = wp_link_pages(\n array(\n 'before' => '<div class=\"page-navigation\"><ul><li class=\"pages\">' . esc_html__( 'Pages:', 'domain' ) . '</li>',\n 'after' => '</ul></div>',\n 'link_before' => '<span>',\n 'link_after' => '</span>',\n 'echo' => false\n )\n );\n\n//Add \"current\" and \"page_divide\" classes to our links\n//READ: http://wordpress.stackexchange.com/questions/17421/wp-link-page-wrap-current-page-element\n// Now let's wrap the nav inside <li>-elements\n$current_class = 'current';\n$classes = 'page_divide';\n$paged_page_nav = str_replace( '<a', '<li class=\"'. $classes .'\"><a' ,$paged_page_nav );\n$paged_page_nav = str_replace( '</span></a>', '</a></li>', $paged_page_nav );\n$paged_page_nav = str_replace( '\"><span>', '\">', $paged_page_nav );\n//Add \"current\" class\n$paged_page_nav = str_replace( '<span>', '<li class=\"'. $current_class .'\">', $paged_page_nav );\n$paged_page_nav = str_replace( '</span>', '</li>', $paged_page_nav );\necho $paged_page_nav ;\n}\n</code></pre>\n\n<p>Then call it in your single.php like so:</p>\n\n<pre><code><?php my_link_pages(); ?>\n</code></pre>\n\n<p>Make sure that you add <code><!--nexpage--></code> on your Post Edit screen (Select Text NOT Visual) </p>\n"
},
{
"answer_id": 205529,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>It is still somewhat a mystery what you need looking at all the comments and the question content. </p>\n\n<p>Here are two approaches that should work</p>\n\n<h2>FOR PAGES</h2>\n\n<p>I have written a complete function that will paginate any (<em>or almost any</em>) query except on single post pages. It also works out of the box for static front pages. I'm not going to go into details regarding the <code>get_paginated_numbers()</code> pagination function. Everything you need to know is discussed in <a href=\"https://wordpress.stackexchange.com/a/172818/31545\">my answer here</a>, so feel free to check it out. And don't forget to modify it to suit your exact needs.</p>\n\n<p>Here is a basic shortcode to showcase the usage</p>\n\n<pre><code>add_shortcode( 'paginate_shortcode', function ()\n{\n if ( get_query_var('paged') ) { \n $current_page = get_query_var('paged'); \n }elseif ( get_query_var('page') ) { \n $current_page = get_query_var('page'); \n }else{ \n $current_page = 1; \n }\n\n $q = new WP_Query( ['posts_per_page' => 1, 'paged' => $current_page] );\n return $q->posts[0]->post_title . '</br>' . get_paginated_numbers( ['query' => $q] );\n});\n</code></pre>\n\n<p>You can use <code>[paginate_shortcode]</code> on any page, it will display something like this</p>\n\n<p><a href=\"https://i.stack.imgur.com/90dCf.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/90dCf.png\" alt=\"enter image description here\"></a></p>\n\n<p>Note that the post title changes as the links changes</p>\n\n<h2>FOR SINGLE POSTS</h2>\n\n<p>Single posts with paginated sub queries are not really meant to be. If you are going to use your shortcode on a single post page (<em>which I discourage</em>) like for related posts, you can use the approach that I posted in <a href=\"https://wordpress.stackexchange.com/a/172900/31545\">this answer</a>. It is quite extensive, so I'm not going to repost it here. Feel free to check it out and modify as needed</p>\n"
}
] |
2015/10/07
|
[
"https://wordpress.stackexchange.com/questions/204879",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/26988/"
] |
Refer to the title, I'm trying to create a shortcode for Blog Post with Pagination. I'm able to show the blog post but the pagination is not working. I tried using the code below and the link to second page is www.mysite.com/postname/page/2 . But it goes back to www.mysite.com/postname/ when I click on the pagination link to second page.
```
<?php
$big = 999999999;
$pagination = paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $this->query->max_num_pages
) );
$html .= $pagination;
?>
```
[](https://i.stack.imgur.com/nbv9g.png)
[](https://i.stack.imgur.com/1ODJ8.png)
|
It is still somewhat a mystery what you need looking at all the comments and the question content.
Here are two approaches that should work
FOR PAGES
---------
I have written a complete function that will paginate any (*or almost any*) query except on single post pages. It also works out of the box for static front pages. I'm not going to go into details regarding the `get_paginated_numbers()` pagination function. Everything you need to know is discussed in [my answer here](https://wordpress.stackexchange.com/a/172818/31545), so feel free to check it out. And don't forget to modify it to suit your exact needs.
Here is a basic shortcode to showcase the usage
```
add_shortcode( 'paginate_shortcode', function ()
{
if ( get_query_var('paged') ) {
$current_page = get_query_var('paged');
}elseif ( get_query_var('page') ) {
$current_page = get_query_var('page');
}else{
$current_page = 1;
}
$q = new WP_Query( ['posts_per_page' => 1, 'paged' => $current_page] );
return $q->posts[0]->post_title . '</br>' . get_paginated_numbers( ['query' => $q] );
});
```
You can use `[paginate_shortcode]` on any page, it will display something like this
[](https://i.stack.imgur.com/90dCf.png)
Note that the post title changes as the links changes
FOR SINGLE POSTS
----------------
Single posts with paginated sub queries are not really meant to be. If you are going to use your shortcode on a single post page (*which I discourage*) like for related posts, you can use the approach that I posted in [this answer](https://wordpress.stackexchange.com/a/172900/31545). It is quite extensive, so I'm not going to repost it here. Feel free to check it out and modify as needed
|
204,888 |
<p>I’ve created .htaccess password in order to add a layer of security to a WordPress installation. The .htpasswd file is located one level above the installation. </p>
<p>Yet, I’ve seen brute force attack attempts that seem to bypass this login and directly try to login in WordPress wpadmin, using the correct username (which is not “admin” but a random string of character). </p>
<p>I know that the .htaccess solution is not perfect. I was wondering if there was a way to make it more secure? I wonder how the attack is able to bypass the .htaccess protection, but that may be too broad a question. </p>
<p>Any suggestion will be welcomed.</p>
<p>Thanks,</p>
<p>P.</p>
<p>P.S. I run my installation on a server that uses apache. My .htaccess file looks like this:</p>
<p><code><Files wp-login.php>
AuthUserFile /home/servername/.htpasswd
AuthType Basic
AuthName Restricted
Order Deny,Allow
Deny from all
Require valid-user
Satisfy any
</Files></code></p>
|
[
{
"answer_id": 204925,
"author": "Nikolay Nikolov",
"author_id": 81561,
"author_profile": "https://wordpress.stackexchange.com/users/81561",
"pm_score": 1,
"selected": false,
"text": "<p>What web server you use? If use nginx, you can try this to secure your wp-admin :</p>\n\n<pre><code>location ~ ^/(wp-login\\.php$) {\n root /var/www/wordpress/;\n allow 127.0.0.1;\n allow Your-ip-address;\n allow Your-second-ip-address;\n deny all;\n</code></pre>\n\n<p>Other way to secure your wp-admin from brute force attacks is to add this lines to your nginx.conf :</p>\n\n<h1>Limit Request</h1>\n\n<pre><code>limit_req_status 403;\nlimit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;\n</code></pre>\n\n<p>And those lines to your nginx virtual host conf:</p>\n\n<pre><code># Limit access to avoid brute force attack\nlocation = /wp-login.php {\n limit_req zone=one burst=1 nodelay;\n include fastcgi_params;\n fastcgi_pass php;\n}\n</code></pre>\n\n<p>With this setup, the hackers will got 403 forbidden when try to bruteforce.</p>\n\n<p>In your situation, I think the .htaccess setup may be wrong. If you don't have access to your web server and you use apache, your .htaccess file must be in your wordpress document root.</p>\n"
},
{
"answer_id": 265544,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>The only viable protection is to use strong passwords (actually with my experience even medium strength passwords will be enough to keep away any random script kiddy).</p>\n\n<p>The <code>wp-login.php</code> file is mainly UI and it is just one possible attack vector, with others will be the xml-rpc, rest api, and whatever plugins that let you do login via ajax. </p>\n\n<p>using htpasswd file, with passwords that is not stronger than the password that you use in wordpress is kinda pointless, and if your password there is stronger than the one in wordpress, why is it?</p>\n\n<p>To your other point.... wordpress do not do any real effort in hiding user names. Not always it is easy to get them, but there is no attempt to hide them. Therefor the fact that someone tried to login with the correct user name, it is just a fact of life when using wordpress and by itself it do not indicate any malicious attempt more complex than the \"normal\" script kiddies hacking attempts.</p>\n"
},
{
"answer_id": 285674,
"author": "scytale",
"author_id": 128374,
"author_profile": "https://wordpress.stackexchange.com/users/128374",
"pm_score": 1,
"selected": false,
"text": "<p>First, contrary to Mark Kaplun's answer htaccess <a href=\"https://wordpress.org/support/article/brute-force-attacks/\" rel=\"nofollow noreferrer\">protecting wp-login is <strong>recommended</strong> in the Wordpress Codex</a> and <strong>far from pointless</strong>. It will block many brute force/DDOS attacks BEFORE WP scripts are run and DB Connections and lookups are done i.e. drastically reduces server load; it enabled one of my sites to continue to be responsive instead of slow or falling over. Additionally many brute force tools are likely to halt immediately if presented with an authentication digest request.</p>\n<p>As you are required to enter credentials your htaccess is working. But you need to do more.</p>\n<p><strong>Protect your admin directory via its own htaccess file</strong>. The Codex above suggests (see caveats) "blocking" by IP. This may not be practical if you travel, so I password protect the directory instead, and this works fine.</p>\n<blockquote>\n<p>"(hackers) using the correct username (which is not “admin” but a\nrandom string of character)"</p>\n</blockquote>\n<p><strong>Prevent hackers identifying your (case insensitive) login names</strong>:</p>\n<p>WP uses your username to create an author URL slug i.e. broadcasting it to the world (even in Google searches). Advice in articles to change your admin user name (without additional warnings) give those taking the advice a false sense of security and demonstrate the article authors lack of knowledge (I haven't seen one hacker article saying try to login with "admin" - but I've seen many suggesting finding author slugs.).</p>\n<p>Try browsing <code>yoursite.com/?author=1</code> (or author=2 or author=3) chances are the resulting URL or content will identify your (case insensitive) login name. N.B. if you changed the initial admin you may have deleted author "1").</p>\n<p>Typically Hackers use security tools to list the first ten users (low numbers are more likely to be an admin). Use htaccess to foil most such tools and either 403 or redirect their requests e.g.</p>\n<pre><code>RewriteCond %{QUERY_STRING} author=\nRewriteRule (.*) https://www.fbi.gov/investigate/cyber/%1 [R=302,L]\n</code></pre>\n<p>However; on most sites it will still be possible to <em>manually</em> identify username from author link URLs which themes normally include in posts. Yours is already known. The solution is to create a new admin user and immediately change its URL slug (user_nicename) entry in the WP database. You do this using a plugin (possibly) <a href=\"https://wordpress.org/plugins/edit-author-slug/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/edit-author-slug/</a> (which you can then remove). Or if confident <a href=\"https://premium.wpmudev.org/blog/change-admin-username/\" rel=\"nofollow noreferrer\">by using phpMyadmin</a>. If you can login using you new admin user then you can delete your old admin.</p>\n<p>You can see the above suggestions in action on <a href=\"http://wptest.means.us.com/\" rel=\"nofollow noreferrer\">my site</a> (click on any author (AW) link to see change to nicename/url slug; and add "?author=1" to the original link to see redirection).</p>\n"
}
] |
2015/10/07
|
[
"https://wordpress.stackexchange.com/questions/204888",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/14075/"
] |
I’ve created .htaccess password in order to add a layer of security to a WordPress installation. The .htpasswd file is located one level above the installation.
Yet, I’ve seen brute force attack attempts that seem to bypass this login and directly try to login in WordPress wpadmin, using the correct username (which is not “admin” but a random string of character).
I know that the .htaccess solution is not perfect. I was wondering if there was a way to make it more secure? I wonder how the attack is able to bypass the .htaccess protection, but that may be too broad a question.
Any suggestion will be welcomed.
Thanks,
P.
P.S. I run my installation on a server that uses apache. My .htaccess file looks like this:
`<Files wp-login.php>
AuthUserFile /home/servername/.htpasswd
AuthType Basic
AuthName Restricted
Order Deny,Allow
Deny from all
Require valid-user
Satisfy any
</Files>`
|
What web server you use? If use nginx, you can try this to secure your wp-admin :
```
location ~ ^/(wp-login\.php$) {
root /var/www/wordpress/;
allow 127.0.0.1;
allow Your-ip-address;
allow Your-second-ip-address;
deny all;
```
Other way to secure your wp-admin from brute force attacks is to add this lines to your nginx.conf :
Limit Request
=============
```
limit_req_status 403;
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
```
And those lines to your nginx virtual host conf:
```
# Limit access to avoid brute force attack
location = /wp-login.php {
limit_req zone=one burst=1 nodelay;
include fastcgi_params;
fastcgi_pass php;
}
```
With this setup, the hackers will got 403 forbidden when try to bruteforce.
In your situation, I think the .htaccess setup may be wrong. If you don't have access to your web server and you use apache, your .htaccess file must be in your wordpress document root.
|
204,902 |
<p>I am confused as to how I'm supposed to switch parent themes in my child theme css. Right now my website protovest.com is using responsive theme but I want to change it to a theme called tesseract. Here is my code:</p>
<pre><code>/*
Theme Name: Responsive Child Proto-Vest
Description: Responsive Theme Used to Style Protovest
Author: Eva Berrios
Template: responsive
Version: 1.0.0
*/
@import url("../responsive/style.css");
</code></pre>
<p>I'm confused because I was told not to change the import url and other developers say that's how it's done. Can someone explain this switching theme process to me?</p>
<p>And how exactly do I create a backup in case it gets messed up when switching over? </p>
|
[
{
"answer_id": 204925,
"author": "Nikolay Nikolov",
"author_id": 81561,
"author_profile": "https://wordpress.stackexchange.com/users/81561",
"pm_score": 1,
"selected": false,
"text": "<p>What web server you use? If use nginx, you can try this to secure your wp-admin :</p>\n\n<pre><code>location ~ ^/(wp-login\\.php$) {\n root /var/www/wordpress/;\n allow 127.0.0.1;\n allow Your-ip-address;\n allow Your-second-ip-address;\n deny all;\n</code></pre>\n\n<p>Other way to secure your wp-admin from brute force attacks is to add this lines to your nginx.conf :</p>\n\n<h1>Limit Request</h1>\n\n<pre><code>limit_req_status 403;\nlimit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;\n</code></pre>\n\n<p>And those lines to your nginx virtual host conf:</p>\n\n<pre><code># Limit access to avoid brute force attack\nlocation = /wp-login.php {\n limit_req zone=one burst=1 nodelay;\n include fastcgi_params;\n fastcgi_pass php;\n}\n</code></pre>\n\n<p>With this setup, the hackers will got 403 forbidden when try to bruteforce.</p>\n\n<p>In your situation, I think the .htaccess setup may be wrong. If you don't have access to your web server and you use apache, your .htaccess file must be in your wordpress document root.</p>\n"
},
{
"answer_id": 265544,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>The only viable protection is to use strong passwords (actually with my experience even medium strength passwords will be enough to keep away any random script kiddy).</p>\n\n<p>The <code>wp-login.php</code> file is mainly UI and it is just one possible attack vector, with others will be the xml-rpc, rest api, and whatever plugins that let you do login via ajax. </p>\n\n<p>using htpasswd file, with passwords that is not stronger than the password that you use in wordpress is kinda pointless, and if your password there is stronger than the one in wordpress, why is it?</p>\n\n<p>To your other point.... wordpress do not do any real effort in hiding user names. Not always it is easy to get them, but there is no attempt to hide them. Therefor the fact that someone tried to login with the correct user name, it is just a fact of life when using wordpress and by itself it do not indicate any malicious attempt more complex than the \"normal\" script kiddies hacking attempts.</p>\n"
},
{
"answer_id": 285674,
"author": "scytale",
"author_id": 128374,
"author_profile": "https://wordpress.stackexchange.com/users/128374",
"pm_score": 1,
"selected": false,
"text": "<p>First, contrary to Mark Kaplun's answer htaccess <a href=\"https://wordpress.org/support/article/brute-force-attacks/\" rel=\"nofollow noreferrer\">protecting wp-login is <strong>recommended</strong> in the Wordpress Codex</a> and <strong>far from pointless</strong>. It will block many brute force/DDOS attacks BEFORE WP scripts are run and DB Connections and lookups are done i.e. drastically reduces server load; it enabled one of my sites to continue to be responsive instead of slow or falling over. Additionally many brute force tools are likely to halt immediately if presented with an authentication digest request.</p>\n<p>As you are required to enter credentials your htaccess is working. But you need to do more.</p>\n<p><strong>Protect your admin directory via its own htaccess file</strong>. The Codex above suggests (see caveats) "blocking" by IP. This may not be practical if you travel, so I password protect the directory instead, and this works fine.</p>\n<blockquote>\n<p>"(hackers) using the correct username (which is not “admin” but a\nrandom string of character)"</p>\n</blockquote>\n<p><strong>Prevent hackers identifying your (case insensitive) login names</strong>:</p>\n<p>WP uses your username to create an author URL slug i.e. broadcasting it to the world (even in Google searches). Advice in articles to change your admin user name (without additional warnings) give those taking the advice a false sense of security and demonstrate the article authors lack of knowledge (I haven't seen one hacker article saying try to login with "admin" - but I've seen many suggesting finding author slugs.).</p>\n<p>Try browsing <code>yoursite.com/?author=1</code> (or author=2 or author=3) chances are the resulting URL or content will identify your (case insensitive) login name. N.B. if you changed the initial admin you may have deleted author "1").</p>\n<p>Typically Hackers use security tools to list the first ten users (low numbers are more likely to be an admin). Use htaccess to foil most such tools and either 403 or redirect their requests e.g.</p>\n<pre><code>RewriteCond %{QUERY_STRING} author=\nRewriteRule (.*) https://www.fbi.gov/investigate/cyber/%1 [R=302,L]\n</code></pre>\n<p>However; on most sites it will still be possible to <em>manually</em> identify username from author link URLs which themes normally include in posts. Yours is already known. The solution is to create a new admin user and immediately change its URL slug (user_nicename) entry in the WP database. You do this using a plugin (possibly) <a href=\"https://wordpress.org/plugins/edit-author-slug/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/edit-author-slug/</a> (which you can then remove). Or if confident <a href=\"https://premium.wpmudev.org/blog/change-admin-username/\" rel=\"nofollow noreferrer\">by using phpMyadmin</a>. If you can login using you new admin user then you can delete your old admin.</p>\n<p>You can see the above suggestions in action on <a href=\"http://wptest.means.us.com/\" rel=\"nofollow noreferrer\">my site</a> (click on any author (AW) link to see change to nicename/url slug; and add "?author=1" to the original link to see redirection).</p>\n"
}
] |
2015/10/07
|
[
"https://wordpress.stackexchange.com/questions/204902",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81587/"
] |
I am confused as to how I'm supposed to switch parent themes in my child theme css. Right now my website protovest.com is using responsive theme but I want to change it to a theme called tesseract. Here is my code:
```
/*
Theme Name: Responsive Child Proto-Vest
Description: Responsive Theme Used to Style Protovest
Author: Eva Berrios
Template: responsive
Version: 1.0.0
*/
@import url("../responsive/style.css");
```
I'm confused because I was told not to change the import url and other developers say that's how it's done. Can someone explain this switching theme process to me?
And how exactly do I create a backup in case it gets messed up when switching over?
|
What web server you use? If use nginx, you can try this to secure your wp-admin :
```
location ~ ^/(wp-login\.php$) {
root /var/www/wordpress/;
allow 127.0.0.1;
allow Your-ip-address;
allow Your-second-ip-address;
deny all;
```
Other way to secure your wp-admin from brute force attacks is to add this lines to your nginx.conf :
Limit Request
=============
```
limit_req_status 403;
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
```
And those lines to your nginx virtual host conf:
```
# Limit access to avoid brute force attack
location = /wp-login.php {
limit_req zone=one burst=1 nodelay;
include fastcgi_params;
fastcgi_pass php;
}
```
With this setup, the hackers will got 403 forbidden when try to bruteforce.
In your situation, I think the .htaccess setup may be wrong. If you don't have access to your web server and you use apache, your .htaccess file must be in your wordpress document root.
|
204,911 |
<p>I've created a custom post type named "accommodation" and taxonomy for it named "categories" using the file "taxonomy-accommodation-categories.php" - this is working fine in my WordPress theme.</p>
<p>But I want to add this in a separate plugin instead, does anyone know how I can do this?</p>
<p>Appreciate any help, thanks.</p>
|
[
{
"answer_id": 204917,
"author": "Mitul",
"author_id": 74728,
"author_profile": "https://wordpress.stackexchange.com/users/74728",
"pm_score": 0,
"selected": false,
"text": "<p>You can create Page template in your plugin and add following filter which will called template from your plugin</p>\n\n<pre><code>add_filter( 'page_template', 'wpa3396_page_template' );\nfunction wpa3396_page_template( $page_template )\n{\n if ( is_page( 'my-custom-texonomy-slug' ) ) {\n $page_template = dirname( __FILE__ ) . '/template-neme.php';\n }\n return $page_template;\n}\n</code></pre>\n"
},
{
"answer_id": 204921,
"author": "The Bobster",
"author_id": 81594,
"author_profile": "https://wordpress.stackexchange.com/users/81594",
"pm_score": 1,
"selected": false,
"text": "<p>This works:</p>\n\n<pre><code>add_filter('template_include', 'taxonomy_template');\nfunction taxonomy_template( $template ){\n\nif( is_tax('accommodation-categories')){\n $template = BASE_DIR .'/templates/taxonomy-accommodation-categories.php';\n} \n\nreturn $template;\n\n}\n</code></pre>\n"
}
] |
2015/10/08
|
[
"https://wordpress.stackexchange.com/questions/204911",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81594/"
] |
I've created a custom post type named "accommodation" and taxonomy for it named "categories" using the file "taxonomy-accommodation-categories.php" - this is working fine in my WordPress theme.
But I want to add this in a separate plugin instead, does anyone know how I can do this?
Appreciate any help, thanks.
|
This works:
```
add_filter('template_include', 'taxonomy_template');
function taxonomy_template( $template ){
if( is_tax('accommodation-categories')){
$template = BASE_DIR .'/templates/taxonomy-accommodation-categories.php';
}
return $template;
}
```
|
205,025 |
<p>This is great for showing just the raw content...
<a href="https://wordpress.stackexchange.com/questions/51741/get-post-content-from-outside-the-loop">Get post content from outside the loop</a>
But i'd also like to apply shortcodes from various plugins to my content to affect the content.
What would I need to do to allow this?</p>
|
[
{
"answer_id": 205026,
"author": "Pete",
"author_id": 37346,
"author_profile": "https://wordpress.stackexchange.com/users/37346",
"pm_score": 0,
"selected": false,
"text": "<p>This works...</p>\n\n<pre><code><?php\n$post_id = 956; // <<<< change page id here\n$queried_post = get_post($post_id);\n$content = $queried_post->post_content;\n$content = apply_filters('the_content', $content);\n$content = str_replace(']]>', ']]&gt;', $content);\necho $content;\n?>\n</code></pre>\n"
},
{
"answer_id": 302143,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>Well, you can do this with much less code:</p>\n\n<pre><code>echo apply_filters( 'the_content', get_post_field('post_content', $post_id) );\n</code></pre>\n\n<p>You can also use <a href=\"https://codex.wordpress.org/Function_Reference/get_post_field\" rel=\"nofollow noreferrer\"><code>get_post_field</code></a> function to get other fields like <code>post_title</code>, and so on.</p>\n"
}
] |
2015/10/09
|
[
"https://wordpress.stackexchange.com/questions/205025",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37346/"
] |
This is great for showing just the raw content...
[Get post content from outside the loop](https://wordpress.stackexchange.com/questions/51741/get-post-content-from-outside-the-loop)
But i'd also like to apply shortcodes from various plugins to my content to affect the content.
What would I need to do to allow this?
|
Well, you can do this with much less code:
```
echo apply_filters( 'the_content', get_post_field('post_content', $post_id) );
```
You can also use [`get_post_field`](https://codex.wordpress.org/Function_Reference/get_post_field) function to get other fields like `post_title`, and so on.
|
205,080 |
<p>I am using latest version of <a href="https://wordpress.org/plugins/all-in-one-seo-pack/" rel="nofollow">All In One Seo Package</a>.</p>
<p>How can I remove metaboxes from posts for User Role: "Contributors"?</p>
|
[
{
"answer_id": 205026,
"author": "Pete",
"author_id": 37346,
"author_profile": "https://wordpress.stackexchange.com/users/37346",
"pm_score": 0,
"selected": false,
"text": "<p>This works...</p>\n\n<pre><code><?php\n$post_id = 956; // <<<< change page id here\n$queried_post = get_post($post_id);\n$content = $queried_post->post_content;\n$content = apply_filters('the_content', $content);\n$content = str_replace(']]>', ']]&gt;', $content);\necho $content;\n?>\n</code></pre>\n"
},
{
"answer_id": 302143,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>Well, you can do this with much less code:</p>\n\n<pre><code>echo apply_filters( 'the_content', get_post_field('post_content', $post_id) );\n</code></pre>\n\n<p>You can also use <a href=\"https://codex.wordpress.org/Function_Reference/get_post_field\" rel=\"nofollow noreferrer\"><code>get_post_field</code></a> function to get other fields like <code>post_title</code>, and so on.</p>\n"
}
] |
2015/10/09
|
[
"https://wordpress.stackexchange.com/questions/205080",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81706/"
] |
I am using latest version of [All In One Seo Package](https://wordpress.org/plugins/all-in-one-seo-pack/).
How can I remove metaboxes from posts for User Role: "Contributors"?
|
Well, you can do this with much less code:
```
echo apply_filters( 'the_content', get_post_field('post_content', $post_id) );
```
You can also use [`get_post_field`](https://codex.wordpress.org/Function_Reference/get_post_field) function to get other fields like `post_title`, and so on.
|
205,083 |
<p>This is code generated <a href="http://jeremyhixon.com/tool/wordpress-meta-box-generator/" rel="nofollow">here</a> and I made a few very small adjustments for customization. The problem I'm having is that I can't get the default value for the checkbox to be checked. If I manually add <code>checked="checked"</code>, it always loads checked even if it's saved as checked off. </p>
<p>I need help defining a default value of <code>checked="checked"</code> unless it has been checked off, then it should remain that way. </p>
<pre><code>/**
* Generated by the WordPress Meta Box generator
* at http://jeremyhixon.com/tool/wordpress-meta-box-generator/
*/
function display_sharing_buttons_get_meta( $value ) {
global $post;
$field = get_post_meta( $post->ID, $value, true );
if ( ! empty( $field ) ) {
return is_array( $field ) ? stripslashes_deep( $field ) :
stripslashes( wp_kses_decode_entities( $field ) );
} else {
return false;
}
}
function display_sharing_buttons_add_meta_box() {
add_meta_box(
'display_sharing_buttons-display-sharing-buttons',
__( 'Display UST Sharing Buttons', 'display_sharing_buttons' ),
'display_sharing_buttons_html',
'post',
'side',
'default'
);
add_meta_box(
'display_sharing_buttons-display-sharing-buttons',
__( 'Display UST Sharing Buttons', 'display_sharing_buttons' ),
'display_sharing_buttons_html',
'page',
'side',
'default'
);
}
add_action( 'add_meta_boxes', 'display_sharing_buttons_add_meta_box' );
function display_sharing_buttons_html( $post) {
wp_nonce_field( '_display_sharing_buttons_nonce', 'display_sharing_buttons_nonce' ); ?>
<p>
<input type="checkbox" name="display_sharing_buttons_display" id="display_sharing_buttons_display" value="display" <?php
echo ( display_sharing_buttons_get_meta( 'display_sharing_buttons_display' ) === 'display' ) ? 'checked' : ''; ?>>
<label for="display_sharing_buttons_display"><?php _e( 'Display', 'display_sharing_buttons' ); ?><img src="<?php
echo get_template_directory_uri() ?>/images/sharing-button-preview.png"></label>
</p>
<?php
}
function display_sharing_buttons_save( $post_id ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
if ( ! isset( $_POST['display_sharing_buttons_nonce'] ) ||
! wp_verify_nonce( $_POST['display_sharing_buttons_nonce'], '_display_sharing_buttons_nonce' ) ) return;
if ( ! current_user_can( 'edit_post', $post_id ) ) return;
if ( isset( $_POST['display_sharing_buttons_display'] ) )
update_post_meta( $post_id, 'display_sharing_buttons_display', esc_attr( $_POST['display_sharing_buttons_display'] ) );
else
update_post_meta( $post_id, 'display_sharing_buttons_display', null );
}
add_action( 'save_post', 'display_sharing_buttons_save' );
/*
Usage: display_sharing_buttons_get_meta( 'display_sharing_buttons_display' )
*/
</code></pre>
|
[
{
"answer_id": 205096,
"author": "Yatix",
"author_id": 8441,
"author_profile": "https://wordpress.stackexchange.com/users/8441",
"pm_score": 2,
"selected": false,
"text": "<p>Try </p>\n\n<pre><code>metadata_exists( 'post', $post->ID, 'display_sharing_buttons_save' )\n</code></pre>\n\n<p>This functions determine if meta-key exists and return true even with NULL value. \nSo in your case, if it returns FALSE you can show CHECKED by default. </p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/metadata_exists/\" rel=\"nofollow\">Source</a></p>\n"
},
{
"answer_id": 205101,
"author": "sMyles",
"author_id": 51201,
"author_profile": "https://wordpress.stackexchange.com/users/51201",
"pm_score": 2,
"selected": false,
"text": "<p>WordPress has a core function <code>checked()</code> you can use for handling the output.</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/checked\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/checked</a></p>\n\n<p>Basically it checks the first to arguments and if they match (second arg is true by default), it echos out the <code>checked=\"checked\"</code> HTML.</p>\n\n<pre><code>checked( $a_true_value );\n</code></pre>\n\n<p>That would output <code>checked=\"checked\"</code> as long as <code>$a_true_value</code> is <code>TRUE</code> ... if you specify the second argument it checks if it matches the first.</p>\n"
},
{
"answer_id": 211910,
"author": "Jeremy",
"author_id": 26817,
"author_profile": "https://wordpress.stackexchange.com/users/26817",
"pm_score": 1,
"selected": false,
"text": "<p>I regenerated the code based on what I saw in the code you shared and it's working on my local machine:</p>\n\n<pre><code>/**\n * Generated by the WordPress Meta Box generator\n * at http://jeremyhixon.com/tool/wordpress-meta-box-generator/\n */\n\nfunction display_ust_sharing_buttons_get_meta( $value ) {\n global $post;\n\n $field = get_post_meta( $post->ID, $value, true );\n if ( ! empty( $field ) ) {\n return is_array( $field ) ? stripslashes_deep( $field ) : stripslashes( wp_kses_decode_entities( $field ) );\n } else {\n return false;\n }\n}\n\nfunction display_ust_sharing_buttons_add_meta_box() {\n add_meta_box(\n 'display_ust_sharing_buttons-display-ust-sharing-buttons',\n __( 'Display UST Sharing Buttons', 'display_ust_sharing_buttons' ),\n 'display_ust_sharing_buttons_html',\n 'post',\n 'side',\n 'default'\n );\n add_meta_box(\n 'display_ust_sharing_buttons-display-ust-sharing-buttons',\n __( 'Display UST Sharing Buttons', 'display_ust_sharing_buttons' ),\n 'display_ust_sharing_buttons_html',\n 'page',\n 'side',\n 'default'\n );\n}\nadd_action( 'add_meta_boxes', 'display_ust_sharing_buttons_add_meta_box' );\n\nfunction display_ust_sharing_buttons_html( $post) {\n wp_nonce_field( '_display_ust_sharing_buttons_nonce', 'display_ust_sharing_buttons_nonce' ); ?>\n\n <p>\n\n <input type=\"checkbox\" name=\"display_ust_sharing_buttons_display\" id=\"display_ust_sharing_buttons_display\" value=\"display\" <?php echo ( display_ust_sharing_buttons_get_meta( 'display_ust_sharing_buttons_display' ) === 'display' ) ? 'checked' : ''; ?>>\n <label for=\"display_ust_sharing_buttons_display\"><?php _e( 'Display', 'display_ust_sharing_buttons' ); ?> <img src=\"<?php \n echo get_template_directory_uri() ?>/images/sharing-button-preview.png\"></label> </p><?php\n}\n\nfunction display_ust_sharing_buttons_save( $post_id ) {\n if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;\n if ( ! isset( $_POST['display_ust_sharing_buttons_nonce'] ) || ! wp_verify_nonce( $_POST['display_ust_sharing_buttons_nonce'], '_display_ust_sharing_buttons_nonce' ) ) return;\n if ( ! current_user_can( 'edit_post', $post_id ) ) return;\n\n if ( isset( $_POST['display_ust_sharing_buttons_display'] ) )\n update_post_meta( $post_id, 'display_ust_sharing_buttons_display', esc_attr( $_POST['display_ust_sharing_buttons_display'] ) );\n else\n update_post_meta( $post_id, 'display_ust_sharing_buttons_display', null );\n}\nadd_action( 'save_post', 'display_ust_sharing_buttons_save' );\n\n/*\n Usage: display_ust_sharing_buttons_get_meta( 'display_ust_sharing_buttons_display' )\n*/\n</code></pre>\n"
},
{
"answer_id": 232417,
"author": "CK MacLeod",
"author_id": 35923,
"author_profile": "https://wordpress.stackexchange.com/users/35923",
"pm_score": 0,
"selected": false,
"text": "<p>The generated code seems pointlessly complicated to me. (Maybe someone can explain why it's necessary or recommendable in this instance, or in other ones.) </p>\n\n<p>Not vouching for the rest of the code, of course, but you could try the following (getting rid of the <code>display_sharing_buttons_get_meta_()</code> function):</p>\n\n<pre><code>function display_sharing_buttons_html( $post) {\n\n wp_nonce_field( '_display_sharing_buttons_nonce', 'display_sharing_buttons_nonce' ); ?>\n\n //get meta value \n $display = get_post_meta( $post->ID , 'display_sharing_buttons_display', true );\n\n <p>\n\n /*use checked() function to test meta value\n breaking it up to make usage easier to see */\n <input type=\"checkbox\" name=\"display_sharing_buttons_display\" id=\"display_sharing_buttons_display\" value=\"display\" \n <?php checked( $display, 'display' ); ?> \n >\n\n <label for=\"display_sharing_buttons_display\">\n\n <?php _e( 'Display', 'display_sharing_buttons' ); ?><img src=\"<?php echo get_template_directory_uri() ?>/images/sharing-button-preview.png\">\n\n </label> \n\n </p>\n\n<?php \n\n}\n</code></pre>\n"
}
] |
2015/10/09
|
[
"https://wordpress.stackexchange.com/questions/205083",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/35926/"
] |
This is code generated [here](http://jeremyhixon.com/tool/wordpress-meta-box-generator/) and I made a few very small adjustments for customization. The problem I'm having is that I can't get the default value for the checkbox to be checked. If I manually add `checked="checked"`, it always loads checked even if it's saved as checked off.
I need help defining a default value of `checked="checked"` unless it has been checked off, then it should remain that way.
```
/**
* Generated by the WordPress Meta Box generator
* at http://jeremyhixon.com/tool/wordpress-meta-box-generator/
*/
function display_sharing_buttons_get_meta( $value ) {
global $post;
$field = get_post_meta( $post->ID, $value, true );
if ( ! empty( $field ) ) {
return is_array( $field ) ? stripslashes_deep( $field ) :
stripslashes( wp_kses_decode_entities( $field ) );
} else {
return false;
}
}
function display_sharing_buttons_add_meta_box() {
add_meta_box(
'display_sharing_buttons-display-sharing-buttons',
__( 'Display UST Sharing Buttons', 'display_sharing_buttons' ),
'display_sharing_buttons_html',
'post',
'side',
'default'
);
add_meta_box(
'display_sharing_buttons-display-sharing-buttons',
__( 'Display UST Sharing Buttons', 'display_sharing_buttons' ),
'display_sharing_buttons_html',
'page',
'side',
'default'
);
}
add_action( 'add_meta_boxes', 'display_sharing_buttons_add_meta_box' );
function display_sharing_buttons_html( $post) {
wp_nonce_field( '_display_sharing_buttons_nonce', 'display_sharing_buttons_nonce' ); ?>
<p>
<input type="checkbox" name="display_sharing_buttons_display" id="display_sharing_buttons_display" value="display" <?php
echo ( display_sharing_buttons_get_meta( 'display_sharing_buttons_display' ) === 'display' ) ? 'checked' : ''; ?>>
<label for="display_sharing_buttons_display"><?php _e( 'Display', 'display_sharing_buttons' ); ?><img src="<?php
echo get_template_directory_uri() ?>/images/sharing-button-preview.png"></label>
</p>
<?php
}
function display_sharing_buttons_save( $post_id ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
if ( ! isset( $_POST['display_sharing_buttons_nonce'] ) ||
! wp_verify_nonce( $_POST['display_sharing_buttons_nonce'], '_display_sharing_buttons_nonce' ) ) return;
if ( ! current_user_can( 'edit_post', $post_id ) ) return;
if ( isset( $_POST['display_sharing_buttons_display'] ) )
update_post_meta( $post_id, 'display_sharing_buttons_display', esc_attr( $_POST['display_sharing_buttons_display'] ) );
else
update_post_meta( $post_id, 'display_sharing_buttons_display', null );
}
add_action( 'save_post', 'display_sharing_buttons_save' );
/*
Usage: display_sharing_buttons_get_meta( 'display_sharing_buttons_display' )
*/
```
|
Try
```
metadata_exists( 'post', $post->ID, 'display_sharing_buttons_save' )
```
This functions determine if meta-key exists and return true even with NULL value.
So in your case, if it returns FALSE you can show CHECKED by default.
[Source](https://developer.wordpress.org/reference/functions/metadata_exists/)
|
205,094 |
<p>I have two forms (<code>form1</code> and <code>form2</code>). Once the admin is logged in anywhere, all visitors (not logged in) to my WordPress site should see <code>form1</code> on the page, otherwise they should see <code>form2</code>. I am using this code in a custom page template:</p>
<pre><code>if ( current_user_can( 'author' ) || current_user_can( 'administrator' ) ) {
// show form1
} else {
// show form2
}
</code></pre>
<p>This works fine, but only for the admin screen, not other users or visitors. How can I make this universal? </p>
|
[
{
"answer_id": 205089,
"author": "Subharanjan",
"author_id": 13615,
"author_profile": "https://wordpress.stackexchange.com/users/13615",
"pm_score": 4,
"selected": false,
"text": "<p>You can remove specific styles and java scripts for specific page template like below. Add the code into the <code>functions.php</code> file of your current theme. To see the list of all JS and CSS you may want to use a plugin like this: <a href=\"https://wordpress.org/plugins/debug-bar-list-dependencies/\">https://wordpress.org/plugins/debug-bar-list-dependencies/</a></p>\n\n<pre><code>/**\n * Remove specific java scripts.\n */\nfunction se_remove_script() {\n if ( is_page_template( 'blankPage.php' ) ) {\n wp_dequeue_script( 'some-js' );\n wp_dequeue_script( 'some-other-js' );\n }\n}\n\nadd_action( 'wp_print_scripts', 'se_remove_script', 99 );\n\n/**\n * Remove specific style sheets.\n */\nfunction se_remove_styles() {\n if ( is_page_template( 'blankPage.php' ) ) {\n wp_dequeue_style( 'some-style' );\n wp_dequeue_style( 'some-other-style' );\n }\n}\n\nadd_action( 'wp_print_styles', 'se_remove_styles', 99 );\n</code></pre>\n\n<p>You can remove all styles and java scripts in one go for specific page template like below. Add the code into the <code>functions.php</code> file of your current theme.</p>\n\n<pre><code>/**\n * Remove all java scripts.\n */\nfunction se_remove_all_scripts() {\n global $wp_scripts;\n if ( is_page_template( 'blankPage.php' ) ) {\n $wp_scripts->queue = array();\n }\n}\n\nadd_action( 'wp_print_scripts', 'se_remove_all_scripts', 99 );\n\n/**\n * Remove all style sheets.\n */\nfunction se_remove_all_styles() {\n global $wp_styles;\n if ( is_page_template( 'blankPage.php' ) ) {\n $wp_styles->queue = array();\n }\n}\n\nadd_action( 'wp_print_styles', 'se_remove_all_styles', 99 );\n</code></pre>\n"
},
{
"answer_id": 205215,
"author": "Ryan",
"author_id": 51462,
"author_profile": "https://wordpress.stackexchange.com/users/51462",
"pm_score": 1,
"selected": true,
"text": "<p>I seemed to solve the problem, and it was so simple that I'm shocked I've never seen this mentioned by anyone before.</p>\n\n<p>First, I deleted my entire child theme so that I could start over from a fresh place.</p>\n\n<p>Then, I used <a href=\"https://wordpress.org/plugins/one-click-child-theme/\" rel=\"nofollow\">https://wordpress.org/plugins/one-click-child-theme/</a> to create a brand new child theme of Salient.</p>\n\n<p>Then, in the <strong>Appearance > Editor</strong> menu, I viewed the <code>functions.php</code> file and noticed that it had pregenerated <code>add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );</code> and <code>function theme_enqueue_styles()</code> for me.</p>\n\n<p>So I simply wrapped the contents of the function within <code>if ( !is_page_template( 'rawHtmlPage.php' ) ) { ...}</code>.</p>\n"
}
] |
2015/10/10
|
[
"https://wordpress.stackexchange.com/questions/205094",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/50465/"
] |
I have two forms (`form1` and `form2`). Once the admin is logged in anywhere, all visitors (not logged in) to my WordPress site should see `form1` on the page, otherwise they should see `form2`. I am using this code in a custom page template:
```
if ( current_user_can( 'author' ) || current_user_can( 'administrator' ) ) {
// show form1
} else {
// show form2
}
```
This works fine, but only for the admin screen, not other users or visitors. How can I make this universal?
|
I seemed to solve the problem, and it was so simple that I'm shocked I've never seen this mentioned by anyone before.
First, I deleted my entire child theme so that I could start over from a fresh place.
Then, I used <https://wordpress.org/plugins/one-click-child-theme/> to create a brand new child theme of Salient.
Then, in the **Appearance > Editor** menu, I viewed the `functions.php` file and noticed that it had pregenerated `add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );` and `function theme_enqueue_styles()` for me.
So I simply wrapped the contents of the function within `if ( !is_page_template( 'rawHtmlPage.php' ) ) { ...}`.
|
205,120 |
<p>I have a bible page which is page_id of 135 and I am trying to create multiple WordPress rewrite rules. I am trying to obtain something like either of the following:</p>
<ul>
<li>website/bible/nasb</li>
<li>website/bible/nasb/Genesis</li>
<li>website/bible/nasb/Genesis/1</li>
</ul>
<p>I want to be able to access the query parameters via WordPress's get_query_var() function. However, all of the parameters seem to be kept in get_query_var('version'). They won't split into 3 different parameters. It puts "nasb/Genesis/1" into the version parameter.</p>
<p>I want to be able to access the parameters like this: </p>
<ul>
<li>get_query_var('version') </li>
<li>get_query_var('book') </li>
<li>get_query_var('chapter')</li>
</ul>
<p>Here is my code:</p>
<pre><code>add_action( 'init' , function() {
add_rewrite_tag('%version%','([^&]+)');
add_rewrite_tag('%book%','([^&]+)');
add_rewrite_tag('%chapter%','([^&]+)');
add_rewrite_rule(
'^bible/(.+)/?$',
'index.php?page_id=135&version=$matches[1]',
'top'
);
add_rewrite_rule(
'^bible/(.+)/(.+)/?$',
'index.php?page_id=135&version=$matches[1]&book=$matches[2]',
'top'
);
add_rewrite_rule(
'^bible/(.+)/(.+)/(.+)/?$',
'index.php?page_id=135&version=$matches[1]&book=$matches[2]&chapter=$matches[3]',
'top'
);
flush_rewrite_rules();
} );
</code></pre>
<p>Thank you.</p>
<p>P.S.</p>
<p>I currently have my permalinks set to post name which cleans up the url, so that is not an issue.</p>
|
[
{
"answer_id": 205129,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 0,
"selected": false,
"text": "<p>You don't want rewrite tags - these are only useful for defining permalink structures. Instead, keep your rules and <a href=\"http://codex.wordpress.org/Plugin_API/Filter_Reference/query_vars\" rel=\"nofollow\">add the parameters as query vars</a>:</p>\n\n<pre><code>function wpse_205120_query_vars( $qvars ) {\n $qvars[] = 'version';\n $qvars[] = 'chapter';\n $qvars[] = 'bible';\n return $qvars;\n}\n\nadd_filter( 'query_vars', 'wpse_205120_query_vars_query_vars' );\n</code></pre>\n\n<p>You'll also want <a href=\"http://codex.wordpress.org/Function_Reference/flush_rewrite_rules#Usage\" rel=\"nofollow\">to get rid of that <code>flush_rewrite_rules()</code></a> once it's all working.</p>\n"
},
{
"answer_id": 205130,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": true,
"text": "<p>The pattern <code>(.+)</code> matches any character, <em>including the slash</em>, so any combo of parameters will always match your first rule, with anything that follows being passed as the version query var. Change all instances of <code>(.+)</code> to <code>([^/]+)</code> to match all characters except the slash.</p>\n"
}
] |
2015/10/10
|
[
"https://wordpress.stackexchange.com/questions/205120",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81729/"
] |
I have a bible page which is page\_id of 135 and I am trying to create multiple WordPress rewrite rules. I am trying to obtain something like either of the following:
* website/bible/nasb
* website/bible/nasb/Genesis
* website/bible/nasb/Genesis/1
I want to be able to access the query parameters via WordPress's get\_query\_var() function. However, all of the parameters seem to be kept in get\_query\_var('version'). They won't split into 3 different parameters. It puts "nasb/Genesis/1" into the version parameter.
I want to be able to access the parameters like this:
* get\_query\_var('version')
* get\_query\_var('book')
* get\_query\_var('chapter')
Here is my code:
```
add_action( 'init' , function() {
add_rewrite_tag('%version%','([^&]+)');
add_rewrite_tag('%book%','([^&]+)');
add_rewrite_tag('%chapter%','([^&]+)');
add_rewrite_rule(
'^bible/(.+)/?$',
'index.php?page_id=135&version=$matches[1]',
'top'
);
add_rewrite_rule(
'^bible/(.+)/(.+)/?$',
'index.php?page_id=135&version=$matches[1]&book=$matches[2]',
'top'
);
add_rewrite_rule(
'^bible/(.+)/(.+)/(.+)/?$',
'index.php?page_id=135&version=$matches[1]&book=$matches[2]&chapter=$matches[3]',
'top'
);
flush_rewrite_rules();
} );
```
Thank you.
P.S.
I currently have my permalinks set to post name which cleans up the url, so that is not an issue.
|
The pattern `(.+)` matches any character, *including the slash*, so any combo of parameters will always match your first rule, with anything that follows being passed as the version query var. Change all instances of `(.+)` to `([^/]+)` to match all characters except the slash.
|
205,152 |
<p>I am trying to display a site vistors search query on the search page. The form has custom fields so is not showing if it's "Search" and it doesnt show none of my custom fields.</p>
<p>My search form -</p>
<pre><code><!-- Search Form -->
<section class="searchMain sm2">
<form method="get" id="searchform2" action="<?php echo home_url(); ?>/">
<input type="hidden" class="form-control" name="s" id="s" value="<?php _e('Search', 'framework'); ?>" />
<div class="search-con">
<!-- Search Row 1 -->
<div class="full-divsn">
<!-- City Taxonomy Search -->
<div class="search-field myFields-lg">
<label>City</label>
<select name="property_city" class="form-control">
<?php
$terms = get_terms( "city-type", array( 'hide_empty' => 0 ) );
$count = count($terms);
if ( $count > 0 ){
echo "<option class='button' value='City'>All</option>";
foreach ( $terms as $term ) {
echo "<option class='button' value='" . $term->slug . "'>" . $term->name . "</option>";
}
}
?>
</select>
</div>
<!-- End City Taxonomy Search -->
<!-- Search State Custom Field -->
<div class="search-field myFields-xxmd">
<label>State</label>
<select name="property_location" class="form-control">
<option value="Any">Any</option>
<?php
$metakey = 'imic_property_site_state';
$statez = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = %s ORDER BY meta_value ASC", $metakey) );
if ($statez) {
foreach ($statez as $states) {
echo "<option value=\"" . $states . "\">" . $states . "</option>";
}
}
?>
</select>
</div>
<!-- End Search State Custom Field -->
<!-- Search Price Custom Field -->
<div class="search-field myFields-md">
<label><?php _e('Price', 'framework'); ?></label>
<input type="text" name="min_price" class="form-control" placeholder="<?php _e('Any', 'framework'); ?>">
</div>
<div class="search-field myFields-txt">
<label>&nbsp;</label>
<div class="form-control">to</div>
</div>
<div class="search-field myFields-xmd-n">
<label>&nbsp;</label>
<input type="text" name="max_price" class="form-control" placeholder="<?php _e('Any', 'framework'); ?>">
</div>
<!-- End Search Price Custom Field -->
</div>
<!-- End Search Row 1 --> ....................
</code></pre>
<p>My search function in functions.php --</p>
<pre><code>/* Search Filter
================================= */
if(!function_exists('imic_search_filter')){
function imic_search_filter($query) {
if($query->is_search()) {
$property_contract_type=$property_type=$property_neighborhood=$property_location=$property_city=$beds=$baths=$min_price=$max_price=$min_area=$max_area=$ag_value=$ag_expertr='';
$property_contract_type = isset($_GET['property_contract_type'])?$_GET['property_contract_type']:"";
$property_contract_type= ($property_contract_type == __('Contract', 'framework')) ? '' :$property_contract_type;
$property_type = isset($_GET['property_type'])?$_GET['property_type']:'';
$property_type= ($property_type == __('Any', 'framework')) ? '' :$property_type;
$property_neighborhood = isset($_GET['neighborhood'])?$_GET['neighborhood']:'';
$property_neighborhood = ($property_neighborhood == __('Neighborhood', 'framework')) ? '' :$property_neighborhood;
$property_location = isset($_GET['property_location'])?$_GET['property_location']:'';
$property_location = ($property_location == __('Any', 'framework')) ? '' : $property_location;
$property_city = isset($_GET['property_city'])?$_GET['property_city']:'';
$property_city = ($property_city == __('City', 'framework')) ? '' :$property_city;
$beds = isset($_GET['beds'])?$_GET['beds']:'';
$beds = ($beds == __('Any', 'framework')) ? '' : $beds;
$baths = isset($_GET['baths'])?$_GET['baths']:'';
$baths = ($baths == __('Any', 'framework')) ? '' : $baths;
$min_price = isset($_GET['min_price'])?$_GET['min_price']:'';
$min_price = ($min_price == __('Any', 'framework')) ? '' :$min_price;
$max_price = isset($_GET['max_price'])?$_GET['max_price']:'';
$max_price = ($max_price == __('Any', 'framework')) ? '' :$max_price;
$min_area = isset($_GET['min_area'])?$_GET['min_area']:'';
$min_area = ($min_area == __('Any', 'framework')) ? '' :$min_area;
$max_area = isset($_GET['max_area'])?$_GET['max_area']:'';
$max_area = ($max_area == __('Any', 'framework')) ? '' :$max_area;
// Agent Property Value and Ratings
$apvr = isset($_GET['apvr'])?$_GET['apvr']:'';
$apvr = ($apvr == __('Any', 'framework')) ? '' :$apvr;
$apor = isset($_GET['apor'])?$_GET['apor']:'';
$apor = ($apor == __('Any', 'framework')) ? '' :$apor;
$id = isset($_GET['id'])?$_GET['id']:'';
$pincode = isset($_GET['pincode'])?$_GET['pincode']:'';
$address = isset($_GET['address'])?$_GET['address']:'';
// If the default text is in the box
if (!empty($property_contract_type)||!empty($property_type)|| !empty($property_location) || !empty($baths) ||!empty($beds)||(!empty($min_price)||!empty($max_price))||(!empty($min_area)||!empty($max_area))||!empty($apvr)||!empty($apor)||!empty($id)||!empty($pincode)||!empty($address)||!empty($property_city)||!empty($property_neighborhood)) {
$s = $_GET['s'];
$meta_query=array();
if ($s == __('Search', 'framework')) {
$query->set('s', '');
}
$query->set('post_type', 'property');
$query->set('post_status','publish');
if (!empty($property_type)) {
$query->set('property-type', $property_type);
}
if (!empty($property_city)) {
$query->set('city-type',$property_city);
}
if (!empty($property_neighborhood)) {
$query->set('neighborhood',$property_neighborhood);
}
if (!empty($property_contract_type)) {
$query->set('property-contract-type', $property_contract_type);
}
if (!empty($baths)) {
array_push($meta_query, array(
'key' => 'imic_property_baths',
'value' => $baths,
'type' => 'numeric',
'compare' => '>='
));
}
if (!empty($beds)) {
array_push($meta_query,array(
'key' => 'imic_property_beds',
'value' => $beds,
'type' => 'numeric',
'compare' => '>='
));
}
if(!empty($min_price)&&!empty($max_price)){
array_push($meta_query,array(
'key' =>'imic_property_price',
'value'=>array($min_price,$max_price),
'type' =>'numeric',
'compare'=> 'BETWEEN'
));
}
else{
if(!empty($min_price)){
array_push($meta_query,array(
'key' =>'imic_property_price',
'value'=>$min_price,
'type' =>'numeric',
'compare'=> '>='
));
}
if(!empty($max_price)){
array_push($meta_query,array(
'key' =>'imic_property_price',
'value'=>$max_price,
'type' =>'numeric',
'compare'=> '<='
));
}
}if(!empty($min_area)&&!empty($max_area)){
array_push($meta_query,array(
'key' => 'imic_property_area',
'value' => array($min_area,$max_area),
'type' => 'numeric',
'compare' => 'BETWEEN'
));
}
else{
if(!empty($min_area)){
array_push($meta_query,array(
'key' => 'imic_property_area',
'value' => $min_area,
'type' => 'numeric',
'compare' => '>='
));
}
if(!empty($max_area)){
array_push($meta_query,array(
'key' => 'imic_property_area',
'value' => $max_area,
'type' => 'numeric',
'compare' => '<='
));
}
}
if (!empty($property_location)) {
array_push($meta_query,array(
'key' => 'imic_property_site_state',
'value' => $property_location
));
}
if (!empty($apvr)) {
array_push($meta_query,array(
'key' => 'imic_property_apvr',
'value' => $apvr
));
}
if (!empty($apor)) {
array_push($meta_query,array(
'key' => 'imic_property_apor',
'value' => $apor
));
}
if (!empty($id)) {
array_push($meta_query,array(
'key' => 'imic_property_site_id',
'value' => $id,
'compare'=>'LIKE'
));
}
if (!empty($pincode)) {
array_push($meta_query,array(
'key' => 'imic_property_pincode',
'value' => $pincode
));
}
if (!empty($address)) {
array_push($meta_query,array(
'key' => 'imic_property_site_address',
'value' => $address,
'compare' => 'LIKE',
));
}
$query->set('meta_query',$meta_query);
}else {
$s = $_GET['s'];
if ($s == __('Search', 'framework')) {
$query->set('s', '');
$query->set('post_type', 'property');
}else{
$query->set('post_type', 'property');
} }
}
return $query;
}
# Add Filters
if(!is_admin()) {
add_filter('pre_get_posts', 'imic_search_filter'); }
}
</code></pre>
<p>On my search.php I have this displaying number of posts and the search query for ?s=Search -</p>
<pre><code><h4><?php $num = $wp_query->post_count; if (have_posts()) : ?>You have <?php echo $num; ?> search results in <?php echo get_search_query(); ?><?php endif;?></h4>
</code></pre>
<p>And on that same page, this is the loop I use --</p>
<pre><code><?php
if (have_posts()) : while (have_posts()):the_post();?>
<?php get_template_part('search','property'); ?>
<?php
endwhile; endif; wp_reset_query();
?>
</code></pre>
<p>And once again My query string looks something like this.... but obviously it changes depending on the users criteria --</p>
<pre><code>/?s=Search&property_city=las-vegas&property_location=Nevada&min_price=20000&max_price=500000&beds=2&baths=3&min_area=1000&max_area=1000000&property_type=apartment&s=Search&apor=Any&apvr=Any&post_type=property
</code></pre>
<p>So How can I get all of the search values to display as formatted text?</p>
|
[
{
"answer_id": 205129,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 0,
"selected": false,
"text": "<p>You don't want rewrite tags - these are only useful for defining permalink structures. Instead, keep your rules and <a href=\"http://codex.wordpress.org/Plugin_API/Filter_Reference/query_vars\" rel=\"nofollow\">add the parameters as query vars</a>:</p>\n\n<pre><code>function wpse_205120_query_vars( $qvars ) {\n $qvars[] = 'version';\n $qvars[] = 'chapter';\n $qvars[] = 'bible';\n return $qvars;\n}\n\nadd_filter( 'query_vars', 'wpse_205120_query_vars_query_vars' );\n</code></pre>\n\n<p>You'll also want <a href=\"http://codex.wordpress.org/Function_Reference/flush_rewrite_rules#Usage\" rel=\"nofollow\">to get rid of that <code>flush_rewrite_rules()</code></a> once it's all working.</p>\n"
},
{
"answer_id": 205130,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": true,
"text": "<p>The pattern <code>(.+)</code> matches any character, <em>including the slash</em>, so any combo of parameters will always match your first rule, with anything that follows being passed as the version query var. Change all instances of <code>(.+)</code> to <code>([^/]+)</code> to match all characters except the slash.</p>\n"
}
] |
2015/10/11
|
[
"https://wordpress.stackexchange.com/questions/205152",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/24067/"
] |
I am trying to display a site vistors search query on the search page. The form has custom fields so is not showing if it's "Search" and it doesnt show none of my custom fields.
My search form -
```
<!-- Search Form -->
<section class="searchMain sm2">
<form method="get" id="searchform2" action="<?php echo home_url(); ?>/">
<input type="hidden" class="form-control" name="s" id="s" value="<?php _e('Search', 'framework'); ?>" />
<div class="search-con">
<!-- Search Row 1 -->
<div class="full-divsn">
<!-- City Taxonomy Search -->
<div class="search-field myFields-lg">
<label>City</label>
<select name="property_city" class="form-control">
<?php
$terms = get_terms( "city-type", array( 'hide_empty' => 0 ) );
$count = count($terms);
if ( $count > 0 ){
echo "<option class='button' value='City'>All</option>";
foreach ( $terms as $term ) {
echo "<option class='button' value='" . $term->slug . "'>" . $term->name . "</option>";
}
}
?>
</select>
</div>
<!-- End City Taxonomy Search -->
<!-- Search State Custom Field -->
<div class="search-field myFields-xxmd">
<label>State</label>
<select name="property_location" class="form-control">
<option value="Any">Any</option>
<?php
$metakey = 'imic_property_site_state';
$statez = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = %s ORDER BY meta_value ASC", $metakey) );
if ($statez) {
foreach ($statez as $states) {
echo "<option value=\"" . $states . "\">" . $states . "</option>";
}
}
?>
</select>
</div>
<!-- End Search State Custom Field -->
<!-- Search Price Custom Field -->
<div class="search-field myFields-md">
<label><?php _e('Price', 'framework'); ?></label>
<input type="text" name="min_price" class="form-control" placeholder="<?php _e('Any', 'framework'); ?>">
</div>
<div class="search-field myFields-txt">
<label> </label>
<div class="form-control">to</div>
</div>
<div class="search-field myFields-xmd-n">
<label> </label>
<input type="text" name="max_price" class="form-control" placeholder="<?php _e('Any', 'framework'); ?>">
</div>
<!-- End Search Price Custom Field -->
</div>
<!-- End Search Row 1 --> ....................
```
My search function in functions.php --
```
/* Search Filter
================================= */
if(!function_exists('imic_search_filter')){
function imic_search_filter($query) {
if($query->is_search()) {
$property_contract_type=$property_type=$property_neighborhood=$property_location=$property_city=$beds=$baths=$min_price=$max_price=$min_area=$max_area=$ag_value=$ag_expertr='';
$property_contract_type = isset($_GET['property_contract_type'])?$_GET['property_contract_type']:"";
$property_contract_type= ($property_contract_type == __('Contract', 'framework')) ? '' :$property_contract_type;
$property_type = isset($_GET['property_type'])?$_GET['property_type']:'';
$property_type= ($property_type == __('Any', 'framework')) ? '' :$property_type;
$property_neighborhood = isset($_GET['neighborhood'])?$_GET['neighborhood']:'';
$property_neighborhood = ($property_neighborhood == __('Neighborhood', 'framework')) ? '' :$property_neighborhood;
$property_location = isset($_GET['property_location'])?$_GET['property_location']:'';
$property_location = ($property_location == __('Any', 'framework')) ? '' : $property_location;
$property_city = isset($_GET['property_city'])?$_GET['property_city']:'';
$property_city = ($property_city == __('City', 'framework')) ? '' :$property_city;
$beds = isset($_GET['beds'])?$_GET['beds']:'';
$beds = ($beds == __('Any', 'framework')) ? '' : $beds;
$baths = isset($_GET['baths'])?$_GET['baths']:'';
$baths = ($baths == __('Any', 'framework')) ? '' : $baths;
$min_price = isset($_GET['min_price'])?$_GET['min_price']:'';
$min_price = ($min_price == __('Any', 'framework')) ? '' :$min_price;
$max_price = isset($_GET['max_price'])?$_GET['max_price']:'';
$max_price = ($max_price == __('Any', 'framework')) ? '' :$max_price;
$min_area = isset($_GET['min_area'])?$_GET['min_area']:'';
$min_area = ($min_area == __('Any', 'framework')) ? '' :$min_area;
$max_area = isset($_GET['max_area'])?$_GET['max_area']:'';
$max_area = ($max_area == __('Any', 'framework')) ? '' :$max_area;
// Agent Property Value and Ratings
$apvr = isset($_GET['apvr'])?$_GET['apvr']:'';
$apvr = ($apvr == __('Any', 'framework')) ? '' :$apvr;
$apor = isset($_GET['apor'])?$_GET['apor']:'';
$apor = ($apor == __('Any', 'framework')) ? '' :$apor;
$id = isset($_GET['id'])?$_GET['id']:'';
$pincode = isset($_GET['pincode'])?$_GET['pincode']:'';
$address = isset($_GET['address'])?$_GET['address']:'';
// If the default text is in the box
if (!empty($property_contract_type)||!empty($property_type)|| !empty($property_location) || !empty($baths) ||!empty($beds)||(!empty($min_price)||!empty($max_price))||(!empty($min_area)||!empty($max_area))||!empty($apvr)||!empty($apor)||!empty($id)||!empty($pincode)||!empty($address)||!empty($property_city)||!empty($property_neighborhood)) {
$s = $_GET['s'];
$meta_query=array();
if ($s == __('Search', 'framework')) {
$query->set('s', '');
}
$query->set('post_type', 'property');
$query->set('post_status','publish');
if (!empty($property_type)) {
$query->set('property-type', $property_type);
}
if (!empty($property_city)) {
$query->set('city-type',$property_city);
}
if (!empty($property_neighborhood)) {
$query->set('neighborhood',$property_neighborhood);
}
if (!empty($property_contract_type)) {
$query->set('property-contract-type', $property_contract_type);
}
if (!empty($baths)) {
array_push($meta_query, array(
'key' => 'imic_property_baths',
'value' => $baths,
'type' => 'numeric',
'compare' => '>='
));
}
if (!empty($beds)) {
array_push($meta_query,array(
'key' => 'imic_property_beds',
'value' => $beds,
'type' => 'numeric',
'compare' => '>='
));
}
if(!empty($min_price)&&!empty($max_price)){
array_push($meta_query,array(
'key' =>'imic_property_price',
'value'=>array($min_price,$max_price),
'type' =>'numeric',
'compare'=> 'BETWEEN'
));
}
else{
if(!empty($min_price)){
array_push($meta_query,array(
'key' =>'imic_property_price',
'value'=>$min_price,
'type' =>'numeric',
'compare'=> '>='
));
}
if(!empty($max_price)){
array_push($meta_query,array(
'key' =>'imic_property_price',
'value'=>$max_price,
'type' =>'numeric',
'compare'=> '<='
));
}
}if(!empty($min_area)&&!empty($max_area)){
array_push($meta_query,array(
'key' => 'imic_property_area',
'value' => array($min_area,$max_area),
'type' => 'numeric',
'compare' => 'BETWEEN'
));
}
else{
if(!empty($min_area)){
array_push($meta_query,array(
'key' => 'imic_property_area',
'value' => $min_area,
'type' => 'numeric',
'compare' => '>='
));
}
if(!empty($max_area)){
array_push($meta_query,array(
'key' => 'imic_property_area',
'value' => $max_area,
'type' => 'numeric',
'compare' => '<='
));
}
}
if (!empty($property_location)) {
array_push($meta_query,array(
'key' => 'imic_property_site_state',
'value' => $property_location
));
}
if (!empty($apvr)) {
array_push($meta_query,array(
'key' => 'imic_property_apvr',
'value' => $apvr
));
}
if (!empty($apor)) {
array_push($meta_query,array(
'key' => 'imic_property_apor',
'value' => $apor
));
}
if (!empty($id)) {
array_push($meta_query,array(
'key' => 'imic_property_site_id',
'value' => $id,
'compare'=>'LIKE'
));
}
if (!empty($pincode)) {
array_push($meta_query,array(
'key' => 'imic_property_pincode',
'value' => $pincode
));
}
if (!empty($address)) {
array_push($meta_query,array(
'key' => 'imic_property_site_address',
'value' => $address,
'compare' => 'LIKE',
));
}
$query->set('meta_query',$meta_query);
}else {
$s = $_GET['s'];
if ($s == __('Search', 'framework')) {
$query->set('s', '');
$query->set('post_type', 'property');
}else{
$query->set('post_type', 'property');
} }
}
return $query;
}
# Add Filters
if(!is_admin()) {
add_filter('pre_get_posts', 'imic_search_filter'); }
}
```
On my search.php I have this displaying number of posts and the search query for ?s=Search -
```
<h4><?php $num = $wp_query->post_count; if (have_posts()) : ?>You have <?php echo $num; ?> search results in <?php echo get_search_query(); ?><?php endif;?></h4>
```
And on that same page, this is the loop I use --
```
<?php
if (have_posts()) : while (have_posts()):the_post();?>
<?php get_template_part('search','property'); ?>
<?php
endwhile; endif; wp_reset_query();
?>
```
And once again My query string looks something like this.... but obviously it changes depending on the users criteria --
```
/?s=Search&property_city=las-vegas&property_location=Nevada&min_price=20000&max_price=500000&beds=2&baths=3&min_area=1000&max_area=1000000&property_type=apartment&s=Search&apor=Any&apvr=Any&post_type=property
```
So How can I get all of the search values to display as formatted text?
|
The pattern `(.+)` matches any character, *including the slash*, so any combo of parameters will always match your first rule, with anything that follows being passed as the version query var. Change all instances of `(.+)` to `([^/]+)` to match all characters except the slash.
|
205,177 |
<p>I am trying to get the 'slug' used for each plugin installed. I have not found a good solution for this. I have created this function to get all the slugs and return them in an array. I am hoping there is a better way. Will this work for all plugins?</p>
<pre><code> function l7wau_get_slugs(){
$plugin_array = get_plugins();
$url_array = array_keys( $plugin_array );
foreach ( $url_array as $plugin_url ){
$temp_array = explode( '/', $plugin_url );
$slugs[] = str_replace( '.php', '', end( $temp_array ) );
}
return $slugs;
}
</code></pre>
<p>Thanks for your help in advance.</p>
|
[
{
"answer_id": 205189,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>I am hoping there is a better way</p>\n</blockquote>\n\n<p>You can write your code a bit better, like adding some protection should something fail in your function. One should never take code for granted that it will always work, even if looks like it. Always code with the mindset of that your code <strong>will</strong> fail.</p>\n\n<p>I will just simply do a <code>foreach</code> loop and then pass the keys through <a href=\"http://php.net/basename\" rel=\"nofollow\"><code>basename</code></a> will return everything after the last <code>/</code> if it exists and will also remove the <code>.php</code> extension.</p>\n\n<p>As for <a href=\"https://developer.wordpress.org/reference/functions/get_plugins/\" rel=\"nofollow\"><code>get_plugins()</code></a>, that is definitely a good option to go with as it utilizes the build-in cache system to cache it's results</p>\n\n<p>I would probably rewrite your code as follows; (<em>Requires PHP 5.4+</em>)</p>\n\n<pre><code>function l7wau_get_slugs()\n{\n $plugin_array = get_plugins();\n\n // First check if we have plugins, else return false\n if ( empty( $plugin_array ) )\n return false;\n\n // Define our variable as an empty array to avoid bugs if $plugin_array is empty\n $slugs = [];\n\n foreach ( $plugin_array as $plugin_slug=>$values ){\n $slugs[] = basename(\n $plugin_slug, // Get the key which holds the folder/file name\n '.php' // Strip away the .php part\n );\n }\n return $slugs;\n}\n</code></pre>\n\n<blockquote>\n <p>Will this work for all plugins?</p>\n</blockquote>\n\n<p>Yes, it will work for plugins in the plugin directory. <code>get_plugins()</code> uses <a href=\"https://developer.wordpress.org/reference/functions/get_plugin_data/\" rel=\"nofollow\"><code>get_plugin_data()</code></a> which parses the plugin header data to retrieve the meta data. Just look at the sources included in the links.</p>\n"
},
{
"answer_id": 216953,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 0,
"selected": false,
"text": "<p>Note if you are looking to get the plugin slug for use with the plugin update server (eg. for checking and displaying if your plugin has an update on a plugin screen) you should read this answer to a similar question: </p>\n\n<p><a href=\"https://wordpress.stackexchange.com/a/216940/76440\">https://wordpress.stackexchange.com/a/216940/76440</a></p>\n\n<p>So in that case this would work:</p>\n\n<pre><code> function get_plugin_update_slugs(){\n $plugin_array = get_plugins();\n if (empty($plugin_array)) {return array();}\n foreach ( $plugin_array as $pluginfile => $plugindata) {\n $slugs[] = sanitize_title($plugindata['Name']);\n }\n return $slugs;\n }\n</code></pre>\n"
},
{
"answer_id": 338811,
"author": "Jay",
"author_id": 168861,
"author_profile": "https://wordpress.stackexchange.com/users/168861",
"pm_score": 0,
"selected": false,
"text": "<p>Here's what I used to solve this:</p>\n\n<pre><code>function apc_get_plugin_slugs() {\n $all_plugins = get_plugins() ;\n if ( empty( $all_plugins ) ) { return []; } \n\n foreach ($all_plugins as $pluginFile => $pluginData ) {\n // Strip filename and slashes so we can get the slug\n if ( false !== strpos( $pluginFile, '/' ) ) {\n $slugs[] = substr( $pluginFile, 0, strpos( $pluginFile, '/'));\n }\n // If its just a php file then lets use the pluginData Name and sanitize it\n else {\n $slugs[] = sanitize_title( $pluginData[ 'Name' ] );\n }\n }\n return $slugs;\n}\n</code></pre>\n\n<p>Get the plugin folder name so we can query the .org api, if it's just a single php file we get the pluginData name (<code>hello.php</code> becomes hello-dolly). The first part of the function is for plugins that don't use the same structure for their name as they do on .org like Akismet, <code>/akismet/akismet.php</code> versus <code>akismet-anti-spam</code>. </p>\n"
}
] |
2015/10/11
|
[
"https://wordpress.stackexchange.com/questions/205177",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93714/"
] |
I am trying to get the 'slug' used for each plugin installed. I have not found a good solution for this. I have created this function to get all the slugs and return them in an array. I am hoping there is a better way. Will this work for all plugins?
```
function l7wau_get_slugs(){
$plugin_array = get_plugins();
$url_array = array_keys( $plugin_array );
foreach ( $url_array as $plugin_url ){
$temp_array = explode( '/', $plugin_url );
$slugs[] = str_replace( '.php', '', end( $temp_array ) );
}
return $slugs;
}
```
Thanks for your help in advance.
|
>
> I am hoping there is a better way
>
>
>
You can write your code a bit better, like adding some protection should something fail in your function. One should never take code for granted that it will always work, even if looks like it. Always code with the mindset of that your code **will** fail.
I will just simply do a `foreach` loop and then pass the keys through [`basename`](http://php.net/basename) will return everything after the last `/` if it exists and will also remove the `.php` extension.
As for [`get_plugins()`](https://developer.wordpress.org/reference/functions/get_plugins/), that is definitely a good option to go with as it utilizes the build-in cache system to cache it's results
I would probably rewrite your code as follows; (*Requires PHP 5.4+*)
```
function l7wau_get_slugs()
{
$plugin_array = get_plugins();
// First check if we have plugins, else return false
if ( empty( $plugin_array ) )
return false;
// Define our variable as an empty array to avoid bugs if $plugin_array is empty
$slugs = [];
foreach ( $plugin_array as $plugin_slug=>$values ){
$slugs[] = basename(
$plugin_slug, // Get the key which holds the folder/file name
'.php' // Strip away the .php part
);
}
return $slugs;
}
```
>
> Will this work for all plugins?
>
>
>
Yes, it will work for plugins in the plugin directory. `get_plugins()` uses [`get_plugin_data()`](https://developer.wordpress.org/reference/functions/get_plugin_data/) which parses the plugin header data to retrieve the meta data. Just look at the sources included in the links.
|
205,179 |
<p>I want to get all child comments ids from parent comment id. Do i have to write custom sql
or can i use get_comments() to achieve the following output.</p>
<p>eg 1</p>
<p>I want to get 2,3,4,5,6,7,8 ids from parent id 1.</p>
<pre><code>|- 1 (parent comment)
|-- 2 ( child of 1)
|--- 3 ( grand child )
|-- 4 ( child of 1)
|--- 5 ( grand child )
|---- 6 ( grand grand child )
|----- 7 ( grand grand grand child )
|------ 8 ( grand grand grand grand child )
</code></pre>
<p>eg 2</p>
<p>I want to get 5,6,7,8 comment ids from parent id 4.</p>
<pre><code>|- 1 (parent comment)
|-- 2 ( child of 1)
|--- 3 ( grand child )
|-- 4 ( child of 1)
|--- 5 ( grand child )
|---- 6 ( grand grand child )
|----- 7 ( grand grand grand child )
|------ 8 ( grand grand grand grand child )
</code></pre>
|
[
{
"answer_id": 223796,
"author": "Arun Basil Lal",
"author_id": 90061,
"author_profile": "https://wordpress.stackexchange.com/users/90061",
"pm_score": 2,
"selected": false,
"text": "<p>For anyone else trying to find this:</p>\n\n<p>This can be done using the $parent parameter of <a href=\"https://codex.wordpress.org/Function_Reference/get_comments\" rel=\"nofollow\">get_comments</a>. </p>\n\n<p>Here is the code assuming $parent_comment_id is the id of the parent comment. </p>\n\n<pre><code>$childcomments = get_comments(array(\n 'post_id' => get_the_ID(),\n 'status' => 'approve',\n 'order' => 'DESC',\n 'parent' => $question->comment_ID,\n));\n</code></pre>\n\n<p>Now $childcomments will have an object with comment_ID as the ID of the comment. Refer to the '<a href=\"https://codex.wordpress.org/Function_Reference/get_comments#Returns\" rel=\"nofollow\">Returns</a>' of get_comment for details. </p>\n\n<p>Hope this helps someone else searching for this.</p>\n"
},
{
"answer_id": 267056,
"author": "Des79",
"author_id": 119791,
"author_profile": "https://wordpress.stackexchange.com/users/119791",
"pm_score": 2,
"selected": false,
"text": "<p>I found this post because I was looking for a similar solution.</p>\n\n<p>As suggested by Captain47, get_comments with parent args, won't work because it's return only 1 level nested comments.</p>\n\n<p>To get unlimited nested you need to use hierarchical arg as:</p>\n\n<pre><code> $args = array(\n 'parent' => $comment_ID,\n 'hierarchical' => true,\n );\n $questions = get_comments($args);\n</code></pre>\n\n<p>Reference: <a href=\"https://codex.wordpress.org/Class_Reference/WP_Comment_Query\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Comment_Query</a></p>\n"
}
] |
2015/10/11
|
[
"https://wordpress.stackexchange.com/questions/205179",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/57992/"
] |
I want to get all child comments ids from parent comment id. Do i have to write custom sql
or can i use get\_comments() to achieve the following output.
eg 1
I want to get 2,3,4,5,6,7,8 ids from parent id 1.
```
|- 1 (parent comment)
|-- 2 ( child of 1)
|--- 3 ( grand child )
|-- 4 ( child of 1)
|--- 5 ( grand child )
|---- 6 ( grand grand child )
|----- 7 ( grand grand grand child )
|------ 8 ( grand grand grand grand child )
```
eg 2
I want to get 5,6,7,8 comment ids from parent id 4.
```
|- 1 (parent comment)
|-- 2 ( child of 1)
|--- 3 ( grand child )
|-- 4 ( child of 1)
|--- 5 ( grand child )
|---- 6 ( grand grand child )
|----- 7 ( grand grand grand child )
|------ 8 ( grand grand grand grand child )
```
|
For anyone else trying to find this:
This can be done using the $parent parameter of [get\_comments](https://codex.wordpress.org/Function_Reference/get_comments).
Here is the code assuming $parent\_comment\_id is the id of the parent comment.
```
$childcomments = get_comments(array(
'post_id' => get_the_ID(),
'status' => 'approve',
'order' => 'DESC',
'parent' => $question->comment_ID,
));
```
Now $childcomments will have an object with comment\_ID as the ID of the comment. Refer to the '[Returns](https://codex.wordpress.org/Function_Reference/get_comments#Returns)' of get\_comment for details.
Hope this helps someone else searching for this.
|
205,187 |
<p>I have a custom Taxonomy called 'owner' and it has multiple posts as owner names (Using as a category) so I can filter posts by 'owner' taxonomy.</p>
<p>I'm trying to make an index page of all owner names which starts with letter 'A'. I was able to list all the owners with following code.</p>
<pre><code>foreach ( get_terms( 'owner' ) as $o ){
$owner = $o -> name;
if($owner[0] === 'A'){
// Coding here...
}
}
</code></pre>
<p>The issue I face is I want to show a pagination at the bottom of the page because there are hundreds of authors stars with 'A'.</p>
|
[
{
"answer_id": 205758,
"author": "gloria",
"author_id": 28571,
"author_profile": "https://wordpress.stackexchange.com/users/28571",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to only visually limit the number of displayed names, you could use javascript or jQuery and CSS to paginate the results into smaller chunks that visitors could read through. But this will not create real, distinct pages.</p>\n\n<p>I will update this answer with a piece of code I used to limit a long list at X numbers of items, that you browse with a previous / next link, but also can easily add a numbered pagination to.</p>\n\n<p>Otherwise, a quick search produced that (WordPress) plugin, but I have not tested it, and am not sure about compatibility with current WP versions:\n<a href=\"http://wordpress.mfields.org/plugins/taxonomy-list-shortcode/\" rel=\"nofollow\">http://wordpress.mfields.org/plugins/taxonomy-list-shortcode/</a>\nIt seems it does precisely what you want (PHP) in the form of a shortcode.</p>\n\n<p>Update: I had scavenged most of this code from somewhere and modified it to suit my needs. In my application I used functions to disable and enable elements etc, which I reverted here into straight jQuery, so take into account there might be a piece or another of custom code that remains there that will need changing to work with your thing.</p>\n\n<p>This in jQuery:</p>\n\n<pre><code>var paginate_list = function(items) {\n var pageSize = items; // How many items per page\n var numberOfPages = Math.ceil(($('.lists li').length)/pageSize); // I used list items but you can use anything, this counts how many elements in total, and divides by the previous to know how many pages total\n var pageCounter = $(\"#current-page\"); // I store the current page number in a hidden input value for my particular situation but you can keep track of it anyway else\n var prev = $('#navigation .key-prev');\n var next = $('#navigation .key-next'); // the navigation buttons\n pageCounter.val(1); // initialize to page 1, also peculiar to my application\n prev.attr('disable', true); // disable prev button if page 1\n if ( numberOfPages <= 1 ) {\n next.attr('disable', true); // disable next if only 1 page\n }\n next.on('click', function () {\n // calculate the list offset\n $(\".lists li:nth-child(-n+\" + ((pageCounter.val() * pageSize) + pageSize) + \")\").show();\n $(\".lists li:nth-child(-n+\" + pageCounter.val() * pageSize + \")\").hide();\n pageCounter.val(Number(pageCounter.val()) + 1); // update page counter\n if (pageCounter.val() != 1) {\n prev.attr('disable', false); // enable previous button\n }\n if (pageCounter.val() == numberOfPages) {\n $(this).attr('disable', true); // disable the next button when you reach the end\n }\n });\n prev.on('click', function () {\n // the same in reverse\n pageCounter.val(Number(pageCounter.val()) - 1);\n $(\".lists li\").hide();\n $(\".lists li:nth-child(-n+\" + (pageCounter.val() * pageSize) + \")\").show();\n $(\".lists li:nth-child(-n+\" + ((pageCounter.val() * pageSize) - pageSize) + \")\").hide();\n if (pageCounter.val() == 1) {\n $(this).attr('disable', true);\n } \n if (pageCounter.val() < numberOfPages) {\n next.attr('disable', false);\n } \n });\n};\n</code></pre>\n\n<p>And it would work with lists like this:</p>\n\n<pre><code><ul class=\"lists\">\n <li><!-- your first item --></li>\n <li><!-- your second item --></li>\n <li><!-- your third item --></li>\n <li><!-- your fourth item etc... --></li>\n</ul>\n</code></pre>\n"
},
{
"answer_id": 205782,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 4,
"selected": true,
"text": "<p>Before we look at pagination, from what I have picked up in your question, you only need terms starting with <code>A</code>. If so, you can make use of the <code>name__like</code> parameter in <code>get_terms</code> to get terms only that starts with <code>A</code>. Just a note on that, the operation of the parameter was changed in Wordpress V3.7, so you will need to apply the following filter for this to work as expected (<em>Credit to @s_ha_dum, see his answer <a href=\"https://wordpress.stackexchange.com/a/123306/31545\">here</a>. NOTE: The code requires PHP 5.4+</em>)</p>\n\n<pre><code>add_filter( 'terms_clauses', function ($clauses) \n{\n remove_filter( 'term_clauses', __FUNCTION__ );\n\n $pattern = '|(name LIKE )\\'%(.+%)\\'|';\n $clauses['where'] = preg_replace($pattern,'$1 \\'$2\\'',$clauses['where']);\n return $clauses;\n});\n\n$terms = get_terms( 'ownwer' ['name__like' => 'A'] );\n</code></pre>\n\n<p>To paginate a list of terms, we need:</p>\n\n<ul>\n<li><p>The current page number</p></li>\n<li><p>The total amount of terms in the list</p></li>\n<li><p>Total amont of pages there will be</p></li>\n</ul>\n\n<p>To get the page number of the current page or any page is easy. This will work on all pages including static front pages and single post pages</p>\n\n<pre><code>if ( get_query_var( 'paged' ) ) {\n $current_page = get_query_var( 'paged' );\n} elseif ( get_query_var( 'page' ) ) {\n $current_page = get_query_var( 'page' );\n} else {\n $current_page = 1;\n}\n</code></pre>\n\n<p>We now need to know the total amount of terms from the taxonomy. Here we can use either <a href=\"https://developer.wordpress.org/reference/functions/wp_count_terms/\" rel=\"nofollow noreferrer\"><code>wp_count_terms()</code></a>, which uses <code>get_terms()</code> or use <code>get_terms()</code> itself. Remember, if we used the filter to get terms by a specific letter/name, the filter will be applied to this run of <code>get_terms()</code>/<code>wp_count_terms()</code> as well as we are making using of a closure</p>\n\n<pre><code>$terms_count = get_terms( 'owner', ['name__like' => 'A', 'fields' => 'count'] );\n</code></pre>\n\n<p>Now we have the total amount of terms matching our criteria. Just remember, if your are going to use <code>wp_count_terms()</code>, just remember to set <code>hide_empty</code> to true if you do not need to include empty terms. By default, <code>wp_count_terms()</code> sets this to <code>false</code></p>\n\n<p>Now we can calculate our maximum amount of pages</p>\n\n<pre><code>// Set the amount of terms we need to display per page\n$terms_per_page = 10;\n// Get the total amount of pages\n$max_num_pages = $terms_count / $terms_per_page;\n</code></pre>\n\n<p>To get pagination links to next and previous pages, it is really easy. The only thing a pagination function ever needs to know from any query is the maximum amount of pages, nothing else. It does not need to know what it should paginate. So we can simply use the <code>next_posts_link()</code> and <code>previous_posts_link()</code> functions. You can also make use <code>paginate_links()</code> or even write your own function to suite your needs. Just remember to pass <code>$max_num_pages</code> as the maximum amount of pages to the pagination function</p>\n\n<pre><code>next_posts_link( 'Next terms', $max_num_pages );\nprevious_posts_link( 'Previous terms' );\n</code></pre>\n\n<p>The only thing we still need to do is to paginate <code>get_terms()</code>, which is also really easy. We will make use of the <code>offset</code> parameter to offset the terms according to page and <code>number</code> to get the required amount of terms per page</p>\n\n<pre><code>// Calculate offset\n$offset = ( $current_page == 1) ? 0 : ( ($current_page - 1) * $terms_per_page );\n// Setup our arguments\n$args = [\n 'number' => $terms_per_page,\n 'offset' => $offset\n];\n</code></pre>\n\n<p>We can now put everything together</p>\n\n<h2>ALL TOGETHER NOW</h2>\n\n<p>Just before we do, a couple of important notes</p>\n\n<ul>\n<li><p>All of the code is untested</p></li>\n<li><p>The code needs at least PHP 5.4, which is the absolute minimum PHP version you should be running at time of this post</p></li>\n<li><p>Modify and tear apart as needed</p></li>\n</ul>\n\n<p>Here is the code, finally</p>\n\n<pre><code>add_filter( 'terms_clauses', function ($clauses) \n{\n remove_filter( 'term_clauses', __FUNCTION__ );\n\n $pattern = '|(name LIKE )\\'%(.+%)\\'|';\n $clauses['where'] = preg_replace($pattern,'$1 \\'$2\\'',$clauses['where']);\n return $clauses;\n});\n\n$taxonomy = 'owner';\n\n$terms_count = get_terms( $taxonomy, ['name__like' => 'A', 'fields' => 'count'] );\nif ( $terms_count && !is_wp_error( $terms ) ) {\n\n if ( get_query_var( 'paged' ) ) {\n $current_page = get_query_var( 'paged' );\n } elseif ( get_query_var( 'page' ) ) {\n $current_page = get_query_var( 'page' );\n } else {\n $current_page = 1;\n }\n\n\n // Set the amount of terms we need to display per page\n $terms_per_page = 10;\n // Get the total amount of pages\n $max_num_pages = $terms_count / $terms_per_page;\n\n // Calculate offset\n $offset = ( $current_page == 1) ? 0 : ( ($current_page - 1) * $terms_per_page );\n // Setup our arguments\n $args = [\n 'number' => $terms_per_page,\n 'offset' => $offset,\n 'name__like' => 'A'\n ];\n $terms = get_terms( $taxonomy, $args );\n\n // Do what you need to do with $terms\n\n next_posts_link( 'Next terms', $max_num_pages );\n previous_posts_link( 'Previous terms' );\n\n}\n</code></pre>\n"
}
] |
2015/10/11
|
[
"https://wordpress.stackexchange.com/questions/205187",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81765/"
] |
I have a custom Taxonomy called 'owner' and it has multiple posts as owner names (Using as a category) so I can filter posts by 'owner' taxonomy.
I'm trying to make an index page of all owner names which starts with letter 'A'. I was able to list all the owners with following code.
```
foreach ( get_terms( 'owner' ) as $o ){
$owner = $o -> name;
if($owner[0] === 'A'){
// Coding here...
}
}
```
The issue I face is I want to show a pagination at the bottom of the page because there are hundreds of authors stars with 'A'.
|
Before we look at pagination, from what I have picked up in your question, you only need terms starting with `A`. If so, you can make use of the `name__like` parameter in `get_terms` to get terms only that starts with `A`. Just a note on that, the operation of the parameter was changed in Wordpress V3.7, so you will need to apply the following filter for this to work as expected (*Credit to @s\_ha\_dum, see his answer [here](https://wordpress.stackexchange.com/a/123306/31545). NOTE: The code requires PHP 5.4+*)
```
add_filter( 'terms_clauses', function ($clauses)
{
remove_filter( 'term_clauses', __FUNCTION__ );
$pattern = '|(name LIKE )\'%(.+%)\'|';
$clauses['where'] = preg_replace($pattern,'$1 \'$2\'',$clauses['where']);
return $clauses;
});
$terms = get_terms( 'ownwer' ['name__like' => 'A'] );
```
To paginate a list of terms, we need:
* The current page number
* The total amount of terms in the list
* Total amont of pages there will be
To get the page number of the current page or any page is easy. This will work on all pages including static front pages and single post pages
```
if ( get_query_var( 'paged' ) ) {
$current_page = get_query_var( 'paged' );
} elseif ( get_query_var( 'page' ) ) {
$current_page = get_query_var( 'page' );
} else {
$current_page = 1;
}
```
We now need to know the total amount of terms from the taxonomy. Here we can use either [`wp_count_terms()`](https://developer.wordpress.org/reference/functions/wp_count_terms/), which uses `get_terms()` or use `get_terms()` itself. Remember, if we used the filter to get terms by a specific letter/name, the filter will be applied to this run of `get_terms()`/`wp_count_terms()` as well as we are making using of a closure
```
$terms_count = get_terms( 'owner', ['name__like' => 'A', 'fields' => 'count'] );
```
Now we have the total amount of terms matching our criteria. Just remember, if your are going to use `wp_count_terms()`, just remember to set `hide_empty` to true if you do not need to include empty terms. By default, `wp_count_terms()` sets this to `false`
Now we can calculate our maximum amount of pages
```
// Set the amount of terms we need to display per page
$terms_per_page = 10;
// Get the total amount of pages
$max_num_pages = $terms_count / $terms_per_page;
```
To get pagination links to next and previous pages, it is really easy. The only thing a pagination function ever needs to know from any query is the maximum amount of pages, nothing else. It does not need to know what it should paginate. So we can simply use the `next_posts_link()` and `previous_posts_link()` functions. You can also make use `paginate_links()` or even write your own function to suite your needs. Just remember to pass `$max_num_pages` as the maximum amount of pages to the pagination function
```
next_posts_link( 'Next terms', $max_num_pages );
previous_posts_link( 'Previous terms' );
```
The only thing we still need to do is to paginate `get_terms()`, which is also really easy. We will make use of the `offset` parameter to offset the terms according to page and `number` to get the required amount of terms per page
```
// Calculate offset
$offset = ( $current_page == 1) ? 0 : ( ($current_page - 1) * $terms_per_page );
// Setup our arguments
$args = [
'number' => $terms_per_page,
'offset' => $offset
];
```
We can now put everything together
ALL TOGETHER NOW
----------------
Just before we do, a couple of important notes
* All of the code is untested
* The code needs at least PHP 5.4, which is the absolute minimum PHP version you should be running at time of this post
* Modify and tear apart as needed
Here is the code, finally
```
add_filter( 'terms_clauses', function ($clauses)
{
remove_filter( 'term_clauses', __FUNCTION__ );
$pattern = '|(name LIKE )\'%(.+%)\'|';
$clauses['where'] = preg_replace($pattern,'$1 \'$2\'',$clauses['where']);
return $clauses;
});
$taxonomy = 'owner';
$terms_count = get_terms( $taxonomy, ['name__like' => 'A', 'fields' => 'count'] );
if ( $terms_count && !is_wp_error( $terms ) ) {
if ( get_query_var( 'paged' ) ) {
$current_page = get_query_var( 'paged' );
} elseif ( get_query_var( 'page' ) ) {
$current_page = get_query_var( 'page' );
} else {
$current_page = 1;
}
// Set the amount of terms we need to display per page
$terms_per_page = 10;
// Get the total amount of pages
$max_num_pages = $terms_count / $terms_per_page;
// Calculate offset
$offset = ( $current_page == 1) ? 0 : ( ($current_page - 1) * $terms_per_page );
// Setup our arguments
$args = [
'number' => $terms_per_page,
'offset' => $offset,
'name__like' => 'A'
];
$terms = get_terms( $taxonomy, $args );
// Do what you need to do with $terms
next_posts_link( 'Next terms', $max_num_pages );
previous_posts_link( 'Previous terms' );
}
```
|
205,193 |
<p>I search here and on Google and I can't find answer to my question, just hope you will find it relevant.</p>
<p>I'm doing a magazine website and I need to display names of contributors as a byline. I'm taking the information from the taxonomy 'Contributor' to display their names. </p>
<pre><code><?php echo get_the_term_list( $post->ID , 'contributors', 'By ',' and '); ?>
</code></pre>
<p>That gives me, By contributor1 and contributor2 and contributor3 and contributor4</p>
<p>But I would like to have something like that instead:</p>
<p><strong>By contributor1, contributor2, contributor3 and contributor4</strong></p>
<p>Maybe it's not possible, let me know.</p>
<p>Thanks in advance,</p>
<p>François</p>
|
[
{
"answer_id": 205758,
"author": "gloria",
"author_id": 28571,
"author_profile": "https://wordpress.stackexchange.com/users/28571",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to only visually limit the number of displayed names, you could use javascript or jQuery and CSS to paginate the results into smaller chunks that visitors could read through. But this will not create real, distinct pages.</p>\n\n<p>I will update this answer with a piece of code I used to limit a long list at X numbers of items, that you browse with a previous / next link, but also can easily add a numbered pagination to.</p>\n\n<p>Otherwise, a quick search produced that (WordPress) plugin, but I have not tested it, and am not sure about compatibility with current WP versions:\n<a href=\"http://wordpress.mfields.org/plugins/taxonomy-list-shortcode/\" rel=\"nofollow\">http://wordpress.mfields.org/plugins/taxonomy-list-shortcode/</a>\nIt seems it does precisely what you want (PHP) in the form of a shortcode.</p>\n\n<p>Update: I had scavenged most of this code from somewhere and modified it to suit my needs. In my application I used functions to disable and enable elements etc, which I reverted here into straight jQuery, so take into account there might be a piece or another of custom code that remains there that will need changing to work with your thing.</p>\n\n<p>This in jQuery:</p>\n\n<pre><code>var paginate_list = function(items) {\n var pageSize = items; // How many items per page\n var numberOfPages = Math.ceil(($('.lists li').length)/pageSize); // I used list items but you can use anything, this counts how many elements in total, and divides by the previous to know how many pages total\n var pageCounter = $(\"#current-page\"); // I store the current page number in a hidden input value for my particular situation but you can keep track of it anyway else\n var prev = $('#navigation .key-prev');\n var next = $('#navigation .key-next'); // the navigation buttons\n pageCounter.val(1); // initialize to page 1, also peculiar to my application\n prev.attr('disable', true); // disable prev button if page 1\n if ( numberOfPages <= 1 ) {\n next.attr('disable', true); // disable next if only 1 page\n }\n next.on('click', function () {\n // calculate the list offset\n $(\".lists li:nth-child(-n+\" + ((pageCounter.val() * pageSize) + pageSize) + \")\").show();\n $(\".lists li:nth-child(-n+\" + pageCounter.val() * pageSize + \")\").hide();\n pageCounter.val(Number(pageCounter.val()) + 1); // update page counter\n if (pageCounter.val() != 1) {\n prev.attr('disable', false); // enable previous button\n }\n if (pageCounter.val() == numberOfPages) {\n $(this).attr('disable', true); // disable the next button when you reach the end\n }\n });\n prev.on('click', function () {\n // the same in reverse\n pageCounter.val(Number(pageCounter.val()) - 1);\n $(\".lists li\").hide();\n $(\".lists li:nth-child(-n+\" + (pageCounter.val() * pageSize) + \")\").show();\n $(\".lists li:nth-child(-n+\" + ((pageCounter.val() * pageSize) - pageSize) + \")\").hide();\n if (pageCounter.val() == 1) {\n $(this).attr('disable', true);\n } \n if (pageCounter.val() < numberOfPages) {\n next.attr('disable', false);\n } \n });\n};\n</code></pre>\n\n<p>And it would work with lists like this:</p>\n\n<pre><code><ul class=\"lists\">\n <li><!-- your first item --></li>\n <li><!-- your second item --></li>\n <li><!-- your third item --></li>\n <li><!-- your fourth item etc... --></li>\n</ul>\n</code></pre>\n"
},
{
"answer_id": 205782,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 4,
"selected": true,
"text": "<p>Before we look at pagination, from what I have picked up in your question, you only need terms starting with <code>A</code>. If so, you can make use of the <code>name__like</code> parameter in <code>get_terms</code> to get terms only that starts with <code>A</code>. Just a note on that, the operation of the parameter was changed in Wordpress V3.7, so you will need to apply the following filter for this to work as expected (<em>Credit to @s_ha_dum, see his answer <a href=\"https://wordpress.stackexchange.com/a/123306/31545\">here</a>. NOTE: The code requires PHP 5.4+</em>)</p>\n\n<pre><code>add_filter( 'terms_clauses', function ($clauses) \n{\n remove_filter( 'term_clauses', __FUNCTION__ );\n\n $pattern = '|(name LIKE )\\'%(.+%)\\'|';\n $clauses['where'] = preg_replace($pattern,'$1 \\'$2\\'',$clauses['where']);\n return $clauses;\n});\n\n$terms = get_terms( 'ownwer' ['name__like' => 'A'] );\n</code></pre>\n\n<p>To paginate a list of terms, we need:</p>\n\n<ul>\n<li><p>The current page number</p></li>\n<li><p>The total amount of terms in the list</p></li>\n<li><p>Total amont of pages there will be</p></li>\n</ul>\n\n<p>To get the page number of the current page or any page is easy. This will work on all pages including static front pages and single post pages</p>\n\n<pre><code>if ( get_query_var( 'paged' ) ) {\n $current_page = get_query_var( 'paged' );\n} elseif ( get_query_var( 'page' ) ) {\n $current_page = get_query_var( 'page' );\n} else {\n $current_page = 1;\n}\n</code></pre>\n\n<p>We now need to know the total amount of terms from the taxonomy. Here we can use either <a href=\"https://developer.wordpress.org/reference/functions/wp_count_terms/\" rel=\"nofollow noreferrer\"><code>wp_count_terms()</code></a>, which uses <code>get_terms()</code> or use <code>get_terms()</code> itself. Remember, if we used the filter to get terms by a specific letter/name, the filter will be applied to this run of <code>get_terms()</code>/<code>wp_count_terms()</code> as well as we are making using of a closure</p>\n\n<pre><code>$terms_count = get_terms( 'owner', ['name__like' => 'A', 'fields' => 'count'] );\n</code></pre>\n\n<p>Now we have the total amount of terms matching our criteria. Just remember, if your are going to use <code>wp_count_terms()</code>, just remember to set <code>hide_empty</code> to true if you do not need to include empty terms. By default, <code>wp_count_terms()</code> sets this to <code>false</code></p>\n\n<p>Now we can calculate our maximum amount of pages</p>\n\n<pre><code>// Set the amount of terms we need to display per page\n$terms_per_page = 10;\n// Get the total amount of pages\n$max_num_pages = $terms_count / $terms_per_page;\n</code></pre>\n\n<p>To get pagination links to next and previous pages, it is really easy. The only thing a pagination function ever needs to know from any query is the maximum amount of pages, nothing else. It does not need to know what it should paginate. So we can simply use the <code>next_posts_link()</code> and <code>previous_posts_link()</code> functions. You can also make use <code>paginate_links()</code> or even write your own function to suite your needs. Just remember to pass <code>$max_num_pages</code> as the maximum amount of pages to the pagination function</p>\n\n<pre><code>next_posts_link( 'Next terms', $max_num_pages );\nprevious_posts_link( 'Previous terms' );\n</code></pre>\n\n<p>The only thing we still need to do is to paginate <code>get_terms()</code>, which is also really easy. We will make use of the <code>offset</code> parameter to offset the terms according to page and <code>number</code> to get the required amount of terms per page</p>\n\n<pre><code>// Calculate offset\n$offset = ( $current_page == 1) ? 0 : ( ($current_page - 1) * $terms_per_page );\n// Setup our arguments\n$args = [\n 'number' => $terms_per_page,\n 'offset' => $offset\n];\n</code></pre>\n\n<p>We can now put everything together</p>\n\n<h2>ALL TOGETHER NOW</h2>\n\n<p>Just before we do, a couple of important notes</p>\n\n<ul>\n<li><p>All of the code is untested</p></li>\n<li><p>The code needs at least PHP 5.4, which is the absolute minimum PHP version you should be running at time of this post</p></li>\n<li><p>Modify and tear apart as needed</p></li>\n</ul>\n\n<p>Here is the code, finally</p>\n\n<pre><code>add_filter( 'terms_clauses', function ($clauses) \n{\n remove_filter( 'term_clauses', __FUNCTION__ );\n\n $pattern = '|(name LIKE )\\'%(.+%)\\'|';\n $clauses['where'] = preg_replace($pattern,'$1 \\'$2\\'',$clauses['where']);\n return $clauses;\n});\n\n$taxonomy = 'owner';\n\n$terms_count = get_terms( $taxonomy, ['name__like' => 'A', 'fields' => 'count'] );\nif ( $terms_count && !is_wp_error( $terms ) ) {\n\n if ( get_query_var( 'paged' ) ) {\n $current_page = get_query_var( 'paged' );\n } elseif ( get_query_var( 'page' ) ) {\n $current_page = get_query_var( 'page' );\n } else {\n $current_page = 1;\n }\n\n\n // Set the amount of terms we need to display per page\n $terms_per_page = 10;\n // Get the total amount of pages\n $max_num_pages = $terms_count / $terms_per_page;\n\n // Calculate offset\n $offset = ( $current_page == 1) ? 0 : ( ($current_page - 1) * $terms_per_page );\n // Setup our arguments\n $args = [\n 'number' => $terms_per_page,\n 'offset' => $offset,\n 'name__like' => 'A'\n ];\n $terms = get_terms( $taxonomy, $args );\n\n // Do what you need to do with $terms\n\n next_posts_link( 'Next terms', $max_num_pages );\n previous_posts_link( 'Previous terms' );\n\n}\n</code></pre>\n"
}
] |
2015/10/11
|
[
"https://wordpress.stackexchange.com/questions/205193",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/6695/"
] |
I search here and on Google and I can't find answer to my question, just hope you will find it relevant.
I'm doing a magazine website and I need to display names of contributors as a byline. I'm taking the information from the taxonomy 'Contributor' to display their names.
```
<?php echo get_the_term_list( $post->ID , 'contributors', 'By ',' and '); ?>
```
That gives me, By contributor1 and contributor2 and contributor3 and contributor4
But I would like to have something like that instead:
**By contributor1, contributor2, contributor3 and contributor4**
Maybe it's not possible, let me know.
Thanks in advance,
François
|
Before we look at pagination, from what I have picked up in your question, you only need terms starting with `A`. If so, you can make use of the `name__like` parameter in `get_terms` to get terms only that starts with `A`. Just a note on that, the operation of the parameter was changed in Wordpress V3.7, so you will need to apply the following filter for this to work as expected (*Credit to @s\_ha\_dum, see his answer [here](https://wordpress.stackexchange.com/a/123306/31545). NOTE: The code requires PHP 5.4+*)
```
add_filter( 'terms_clauses', function ($clauses)
{
remove_filter( 'term_clauses', __FUNCTION__ );
$pattern = '|(name LIKE )\'%(.+%)\'|';
$clauses['where'] = preg_replace($pattern,'$1 \'$2\'',$clauses['where']);
return $clauses;
});
$terms = get_terms( 'ownwer' ['name__like' => 'A'] );
```
To paginate a list of terms, we need:
* The current page number
* The total amount of terms in the list
* Total amont of pages there will be
To get the page number of the current page or any page is easy. This will work on all pages including static front pages and single post pages
```
if ( get_query_var( 'paged' ) ) {
$current_page = get_query_var( 'paged' );
} elseif ( get_query_var( 'page' ) ) {
$current_page = get_query_var( 'page' );
} else {
$current_page = 1;
}
```
We now need to know the total amount of terms from the taxonomy. Here we can use either [`wp_count_terms()`](https://developer.wordpress.org/reference/functions/wp_count_terms/), which uses `get_terms()` or use `get_terms()` itself. Remember, if we used the filter to get terms by a specific letter/name, the filter will be applied to this run of `get_terms()`/`wp_count_terms()` as well as we are making using of a closure
```
$terms_count = get_terms( 'owner', ['name__like' => 'A', 'fields' => 'count'] );
```
Now we have the total amount of terms matching our criteria. Just remember, if your are going to use `wp_count_terms()`, just remember to set `hide_empty` to true if you do not need to include empty terms. By default, `wp_count_terms()` sets this to `false`
Now we can calculate our maximum amount of pages
```
// Set the amount of terms we need to display per page
$terms_per_page = 10;
// Get the total amount of pages
$max_num_pages = $terms_count / $terms_per_page;
```
To get pagination links to next and previous pages, it is really easy. The only thing a pagination function ever needs to know from any query is the maximum amount of pages, nothing else. It does not need to know what it should paginate. So we can simply use the `next_posts_link()` and `previous_posts_link()` functions. You can also make use `paginate_links()` or even write your own function to suite your needs. Just remember to pass `$max_num_pages` as the maximum amount of pages to the pagination function
```
next_posts_link( 'Next terms', $max_num_pages );
previous_posts_link( 'Previous terms' );
```
The only thing we still need to do is to paginate `get_terms()`, which is also really easy. We will make use of the `offset` parameter to offset the terms according to page and `number` to get the required amount of terms per page
```
// Calculate offset
$offset = ( $current_page == 1) ? 0 : ( ($current_page - 1) * $terms_per_page );
// Setup our arguments
$args = [
'number' => $terms_per_page,
'offset' => $offset
];
```
We can now put everything together
ALL TOGETHER NOW
----------------
Just before we do, a couple of important notes
* All of the code is untested
* The code needs at least PHP 5.4, which is the absolute minimum PHP version you should be running at time of this post
* Modify and tear apart as needed
Here is the code, finally
```
add_filter( 'terms_clauses', function ($clauses)
{
remove_filter( 'term_clauses', __FUNCTION__ );
$pattern = '|(name LIKE )\'%(.+%)\'|';
$clauses['where'] = preg_replace($pattern,'$1 \'$2\'',$clauses['where']);
return $clauses;
});
$taxonomy = 'owner';
$terms_count = get_terms( $taxonomy, ['name__like' => 'A', 'fields' => 'count'] );
if ( $terms_count && !is_wp_error( $terms ) ) {
if ( get_query_var( 'paged' ) ) {
$current_page = get_query_var( 'paged' );
} elseif ( get_query_var( 'page' ) ) {
$current_page = get_query_var( 'page' );
} else {
$current_page = 1;
}
// Set the amount of terms we need to display per page
$terms_per_page = 10;
// Get the total amount of pages
$max_num_pages = $terms_count / $terms_per_page;
// Calculate offset
$offset = ( $current_page == 1) ? 0 : ( ($current_page - 1) * $terms_per_page );
// Setup our arguments
$args = [
'number' => $terms_per_page,
'offset' => $offset,
'name__like' => 'A'
];
$terms = get_terms( $taxonomy, $args );
// Do what you need to do with $terms
next_posts_link( 'Next terms', $max_num_pages );
previous_posts_link( 'Previous terms' );
}
```
|
205,208 |
<p>My script cannot save the value of the dropdown box. I could not find any helpful documentation on this topic, so I have decided to ask the StackExchange community about it.</p>
<pre><code>function _cc_add_our_attachment_meta() {
add_meta_box( 'cc-license-attachment-meta-box', 'License of the Attachment', '_cc_our_attachment_meta_box_callback', 'attachment', 'normal', 'low');
}
add_action( 'admin_init', '_cc_add_our_attachment_meta' );
function _cc_our_attachment_meta_box_callback() {
global $post;
$value = get_post_meta($post->ID, '_license', false);
if($value == '')
{
$value = '0';
}
?>
<p>Choose a license for this file</p>
<select name="license_id">
<option value="0" <?php selected( '0', $value ); ?>>License 1</option>
<option value="1" <?php selected( '1', $value ); ?>>License 2</option>
<option value="2" <?php selected( '2', $value ); ?>>License 3</option>
<option value="3" <?php selected( '3', $value ); ?>>License 4</option>
<option value="4" <?php selected( '4', $value ); ?>>License 5</option>
<option value="5" <?php selected( '5', $value ); ?>>License 6</option>
</select>
<?php
}
function _cc_attachment_save_our_attachment_meta($post_ID) {
if( isset( $_POST['license_id'] ) ) {
$license = $_POST['license_id'];
switch($license)
{
case 0: $license = '0';
case 1: $license = '1';
case 2: $license = '2';
case 3: $license = '3';
case 4: $license = '4';
case 5: $license = '5';
default: $license = '0';
}
update_post_meta( $post_ID, '_license', $license );
}
}
add_action('edit_attachment', '_cc_attachment_save_our_attachment_meta', 10, 1);
</code></pre>
|
[
{
"answer_id": 205211,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": false,
"text": "<p><code>get_post_meta</code> returns an array when you set the 3rd parameter to <code>false</code>, so <code>$value</code> is an array in your metabox callback and you're treating it as string. I assume an attachment has a single value for license, so you want to set that to <code>true</code> instead.</p>\n"
},
{
"answer_id": 205214,
"author": "LZL0",
"author_id": 54201,
"author_profile": "https://wordpress.stackexchange.com/users/54201",
"pm_score": 0,
"selected": false,
"text": "<pre><code>function _cc_attachment_save_our_attachment_meta($post_ID) {\n if( isset( $_POST['license_id'] ) ) {\n $license = $_POST['license_id'];\n switch($license)\n {\n case 0: $license = '0'; break 1;\n case 1: $license = '1'; break 1;\n case 2: $license = '2'; break 1;\n case 3: $license = '3'; break 1;\n case 4: $license = '4'; break 1;\n case 5: $license = '5'; break 1;\n default: $license = '0'; break 1;\n }\n update_post_meta( $post_ID, '_license', $license );\n }\n}\n\nadd_action('edit_attachment', '_cc_attachment_save_our_attachment_meta', 10, 1);\n</code></pre>\n\n<p>Adding some breaks will solve the issue.</p>\n"
}
] |
2015/10/11
|
[
"https://wordpress.stackexchange.com/questions/205208",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/54201/"
] |
My script cannot save the value of the dropdown box. I could not find any helpful documentation on this topic, so I have decided to ask the StackExchange community about it.
```
function _cc_add_our_attachment_meta() {
add_meta_box( 'cc-license-attachment-meta-box', 'License of the Attachment', '_cc_our_attachment_meta_box_callback', 'attachment', 'normal', 'low');
}
add_action( 'admin_init', '_cc_add_our_attachment_meta' );
function _cc_our_attachment_meta_box_callback() {
global $post;
$value = get_post_meta($post->ID, '_license', false);
if($value == '')
{
$value = '0';
}
?>
<p>Choose a license for this file</p>
<select name="license_id">
<option value="0" <?php selected( '0', $value ); ?>>License 1</option>
<option value="1" <?php selected( '1', $value ); ?>>License 2</option>
<option value="2" <?php selected( '2', $value ); ?>>License 3</option>
<option value="3" <?php selected( '3', $value ); ?>>License 4</option>
<option value="4" <?php selected( '4', $value ); ?>>License 5</option>
<option value="5" <?php selected( '5', $value ); ?>>License 6</option>
</select>
<?php
}
function _cc_attachment_save_our_attachment_meta($post_ID) {
if( isset( $_POST['license_id'] ) ) {
$license = $_POST['license_id'];
switch($license)
{
case 0: $license = '0';
case 1: $license = '1';
case 2: $license = '2';
case 3: $license = '3';
case 4: $license = '4';
case 5: $license = '5';
default: $license = '0';
}
update_post_meta( $post_ID, '_license', $license );
}
}
add_action('edit_attachment', '_cc_attachment_save_our_attachment_meta', 10, 1);
```
|
`get_post_meta` returns an array when you set the 3rd parameter to `false`, so `$value` is an array in your metabox callback and you're treating it as string. I assume an attachment has a single value for license, so you want to set that to `true` instead.
|
205,260 |
<p>Is this possible to find out whether <code>add_filter( 'allow_major_auto_core_updates', '__return_true', 1 );</code> already added or not in some other plugin?</p>
<p>or </p>
<p>can i check this automatic updates set for particular WordPress site ?</p>
<p>if they defined automatic updates settings via constant then we can get it from via </p>
<pre><code>if(defined ('constant') ){
//code here
}
</code></pre>
<p>if they use filters, how to find it out? </p>
|
[
{
"answer_id": 205211,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": false,
"text": "<p><code>get_post_meta</code> returns an array when you set the 3rd parameter to <code>false</code>, so <code>$value</code> is an array in your metabox callback and you're treating it as string. I assume an attachment has a single value for license, so you want to set that to <code>true</code> instead.</p>\n"
},
{
"answer_id": 205214,
"author": "LZL0",
"author_id": 54201,
"author_profile": "https://wordpress.stackexchange.com/users/54201",
"pm_score": 0,
"selected": false,
"text": "<pre><code>function _cc_attachment_save_our_attachment_meta($post_ID) {\n if( isset( $_POST['license_id'] ) ) {\n $license = $_POST['license_id'];\n switch($license)\n {\n case 0: $license = '0'; break 1;\n case 1: $license = '1'; break 1;\n case 2: $license = '2'; break 1;\n case 3: $license = '3'; break 1;\n case 4: $license = '4'; break 1;\n case 5: $license = '5'; break 1;\n default: $license = '0'; break 1;\n }\n update_post_meta( $post_ID, '_license', $license );\n }\n}\n\nadd_action('edit_attachment', '_cc_attachment_save_our_attachment_meta', 10, 1);\n</code></pre>\n\n<p>Adding some breaks will solve the issue.</p>\n"
}
] |
2015/10/12
|
[
"https://wordpress.stackexchange.com/questions/205260",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67717/"
] |
Is this possible to find out whether `add_filter( 'allow_major_auto_core_updates', '__return_true', 1 );` already added or not in some other plugin?
or
can i check this automatic updates set for particular WordPress site ?
if they defined automatic updates settings via constant then we can get it from via
```
if(defined ('constant') ){
//code here
}
```
if they use filters, how to find it out?
|
`get_post_meta` returns an array when you set the 3rd parameter to `false`, so `$value` is an array in your metabox callback and you're treating it as string. I assume an attachment has a single value for license, so you want to set that to `true` instead.
|
205,277 |
<p>I am modifying a custom post type's post list screeen and I want to remove all of the stuffs on the tablenav head like what is marked in the following image.</p>
<p><a href="https://i.stack.imgur.com/iYfe8.png" rel="noreferrer"><img src="https://i.stack.imgur.com/iYfe8.png" alt="enter image description here"></a></p>
<p>Is wordpress have special hook for that, or will I need to use the dirty way?</p>
|
[
{
"answer_id": 205281,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 5,
"selected": true,
"text": "<p>I don't know what you mean by <em>dirty way</em>, hopefully <strong>not</strong> core editing!</p>\n\n<p>You can hide it with CSS.</p>\n\n<p>Or you can do it with PHP - see below:</p>\n\n<h2>Hide the views part</h2>\n\n<p>You can remove the <em>views</em> part with</p>\n\n<pre><code>add_filter( 'views_edit-post', '__return_null' );\n</code></pre>\n\n<p>for the <code>post</code> post type on the <code>edit.php</code> screen.</p>\n\n<p>The post table object is created from:</p>\n\n<pre><code>$wp_list_table = _get_list_table('WP_Posts_List_Table');\n</code></pre>\n\n<p>but there's no filter available in the <code>_get_list_table()</code> function.</p>\n\n<h2>Workaround - Extending the <code>WP_Posts_List_Table</code> class</h2>\n\n<p>So here's a workaround by extending the <code>WP_Posts_List_Table</code> class and override it's methods within the <code>views_edit-post</code> filter - <em>Don't try this at home!</em> ;-)</p>\n\n<pre><code>/**\n * Headless post table\n * \n * @link http://wordpress.stackexchange.com/a/205281/26350\n */\nadd_action( 'load-edit.php', function()\n{\n // Target the post edit screen\n if( 'edit-post' !== get_current_screen()->id )\n return;\n\n // Include the WP_Posts_List_Table class\n require_once ( ABSPATH . 'wp-admin/includes/class-wp-posts-list-table.php' );\n\n // Extend the WP_Posts_List_Table class and remove stuff\n class WPSE_Headless_Table extends WP_Posts_List_Table\n {\n public function search_box( $text, $input_id ){} // Remove search box\n protected function pagination( $which ){} // Remove pagination\n protected function display_tablenav( $which ){} // Remove navigation\n } // end class\n\n $mytable = new WPSE_Headless_Table; \n // Prepare our table, this method has already run with the global table object\n $mytable->prepare_items();\n\n // Override the global post table object\n add_filter( 'views_edit-post', function( $views ) use ( $mytable )\n {\n global $wp_list_table; \n // Let's clone it to the global object\n $wp_list_table = clone $mytable;\n // Let's remove the views part also\n return null;\n } ); \n} );\n</code></pre>\n\n<p>Here's a screenshot example:</p>\n\n<p><strong>Before:</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/WOAlh.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/WOAlh.jpg\" alt=\"before\"></a></p>\n\n<p><strong>After:</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/Kgf3y.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Kgf3y.jpg\" alt=\"after\"></a></p>\n"
},
{
"answer_id": 205283,
"author": "dswebsme",
"author_id": 62906,
"author_profile": "https://wordpress.stackexchange.com/users/62906",
"pm_score": 3,
"selected": false,
"text": "<p>The answer provided by @birgire is a solid programmatic way of handling the request but as he pointed out, his solutions gets a little tricky since WP core is missing an important filter.</p>\n\n<p>To simply suppress, my preferred method would be CSS. Lets assume your custom post type is called \"Event\" this CSS will reliably do the trick:</p>\n\n<pre><code>.post-type-event .subsubsub,\n.post-type-event .posts-filter .tablenav .actions,\n.post-type-event .posts-filter .tablenav .view-switch,\n.post-type-event .posts-filter .tablenav .tablenav-pages,\n.post-type-event .posts-filter .search-box {\n display: none;\n}\n</code></pre>\n\n<p>To ensure these styles are loaded on the WordPress dashboard be sure to enqueue it via the \"admin_enqueue_scripts\" hook using the wp_enqueue_style() helper.</p>\n\n<p>EDIT: Updated the styles to separate \"Actions\" \"View Icons\" and \"Pagination\" into separate styles. Since pagination is pretty important I thought you might want to keep it. Simply deleting this line from the code above will show pagination but hide everything else:</p>\n\n<pre><code>.post-type-event .posts-filter .tablenav .tablenav-pages,\n</code></pre>\n"
}
] |
2015/10/12
|
[
"https://wordpress.stackexchange.com/questions/205277",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/32989/"
] |
I am modifying a custom post type's post list screeen and I want to remove all of the stuffs on the tablenav head like what is marked in the following image.
[](https://i.stack.imgur.com/iYfe8.png)
Is wordpress have special hook for that, or will I need to use the dirty way?
|
I don't know what you mean by *dirty way*, hopefully **not** core editing!
You can hide it with CSS.
Or you can do it with PHP - see below:
Hide the views part
-------------------
You can remove the *views* part with
```
add_filter( 'views_edit-post', '__return_null' );
```
for the `post` post type on the `edit.php` screen.
The post table object is created from:
```
$wp_list_table = _get_list_table('WP_Posts_List_Table');
```
but there's no filter available in the `_get_list_table()` function.
Workaround - Extending the `WP_Posts_List_Table` class
------------------------------------------------------
So here's a workaround by extending the `WP_Posts_List_Table` class and override it's methods within the `views_edit-post` filter - *Don't try this at home!* ;-)
```
/**
* Headless post table
*
* @link http://wordpress.stackexchange.com/a/205281/26350
*/
add_action( 'load-edit.php', function()
{
// Target the post edit screen
if( 'edit-post' !== get_current_screen()->id )
return;
// Include the WP_Posts_List_Table class
require_once ( ABSPATH . 'wp-admin/includes/class-wp-posts-list-table.php' );
// Extend the WP_Posts_List_Table class and remove stuff
class WPSE_Headless_Table extends WP_Posts_List_Table
{
public function search_box( $text, $input_id ){} // Remove search box
protected function pagination( $which ){} // Remove pagination
protected function display_tablenav( $which ){} // Remove navigation
} // end class
$mytable = new WPSE_Headless_Table;
// Prepare our table, this method has already run with the global table object
$mytable->prepare_items();
// Override the global post table object
add_filter( 'views_edit-post', function( $views ) use ( $mytable )
{
global $wp_list_table;
// Let's clone it to the global object
$wp_list_table = clone $mytable;
// Let's remove the views part also
return null;
} );
} );
```
Here's a screenshot example:
**Before:**
[](https://i.stack.imgur.com/WOAlh.jpg)
**After:**
[](https://i.stack.imgur.com/Kgf3y.jpg)
|
205,287 |
<p>I have tried to to make a custom query, to some extend. it is working fine. But where i cannot make it work, is it to break after every 3 posts and do same thing (print div.row) and run same loop, For now, my code seem to output just 3 odd number posts, whereas i want it to break of after each 3 post. </p>
<pre><code>if ($news->have_posts() ) : while ($news->have_posts() ) : $news->the_post();
//$value = $news->current_post;
echo "<div class='col-lg-4'>";
if($value % 3 == 0){
?>
<div class="height <?php foreach(get_the_category() as $category) { echo $category->slug . ' ';} ?>">
<div class="text">
<h5><?php the_time('F jS, Y'); ?></h5>
<h4><a href=""><?php the_title(); ?></a></h4>
<?php the_excerpt(); ?>
</div>
</div>
<?php
//$i++;
//print($value);
}
echo "</div>";
endwhile; endif;
</code></pre>
<p>Edit : What is different about my layout, it should be in indivuial row, as shown in <a href="http://www.bootply.com/render/90113" rel="nofollow">bootly</a>, more like google cards layout.</p>
|
[
{
"answer_id": 205281,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 5,
"selected": true,
"text": "<p>I don't know what you mean by <em>dirty way</em>, hopefully <strong>not</strong> core editing!</p>\n\n<p>You can hide it with CSS.</p>\n\n<p>Or you can do it with PHP - see below:</p>\n\n<h2>Hide the views part</h2>\n\n<p>You can remove the <em>views</em> part with</p>\n\n<pre><code>add_filter( 'views_edit-post', '__return_null' );\n</code></pre>\n\n<p>for the <code>post</code> post type on the <code>edit.php</code> screen.</p>\n\n<p>The post table object is created from:</p>\n\n<pre><code>$wp_list_table = _get_list_table('WP_Posts_List_Table');\n</code></pre>\n\n<p>but there's no filter available in the <code>_get_list_table()</code> function.</p>\n\n<h2>Workaround - Extending the <code>WP_Posts_List_Table</code> class</h2>\n\n<p>So here's a workaround by extending the <code>WP_Posts_List_Table</code> class and override it's methods within the <code>views_edit-post</code> filter - <em>Don't try this at home!</em> ;-)</p>\n\n<pre><code>/**\n * Headless post table\n * \n * @link http://wordpress.stackexchange.com/a/205281/26350\n */\nadd_action( 'load-edit.php', function()\n{\n // Target the post edit screen\n if( 'edit-post' !== get_current_screen()->id )\n return;\n\n // Include the WP_Posts_List_Table class\n require_once ( ABSPATH . 'wp-admin/includes/class-wp-posts-list-table.php' );\n\n // Extend the WP_Posts_List_Table class and remove stuff\n class WPSE_Headless_Table extends WP_Posts_List_Table\n {\n public function search_box( $text, $input_id ){} // Remove search box\n protected function pagination( $which ){} // Remove pagination\n protected function display_tablenav( $which ){} // Remove navigation\n } // end class\n\n $mytable = new WPSE_Headless_Table; \n // Prepare our table, this method has already run with the global table object\n $mytable->prepare_items();\n\n // Override the global post table object\n add_filter( 'views_edit-post', function( $views ) use ( $mytable )\n {\n global $wp_list_table; \n // Let's clone it to the global object\n $wp_list_table = clone $mytable;\n // Let's remove the views part also\n return null;\n } ); \n} );\n</code></pre>\n\n<p>Here's a screenshot example:</p>\n\n<p><strong>Before:</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/WOAlh.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/WOAlh.jpg\" alt=\"before\"></a></p>\n\n<p><strong>After:</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/Kgf3y.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Kgf3y.jpg\" alt=\"after\"></a></p>\n"
},
{
"answer_id": 205283,
"author": "dswebsme",
"author_id": 62906,
"author_profile": "https://wordpress.stackexchange.com/users/62906",
"pm_score": 3,
"selected": false,
"text": "<p>The answer provided by @birgire is a solid programmatic way of handling the request but as he pointed out, his solutions gets a little tricky since WP core is missing an important filter.</p>\n\n<p>To simply suppress, my preferred method would be CSS. Lets assume your custom post type is called \"Event\" this CSS will reliably do the trick:</p>\n\n<pre><code>.post-type-event .subsubsub,\n.post-type-event .posts-filter .tablenav .actions,\n.post-type-event .posts-filter .tablenav .view-switch,\n.post-type-event .posts-filter .tablenav .tablenav-pages,\n.post-type-event .posts-filter .search-box {\n display: none;\n}\n</code></pre>\n\n<p>To ensure these styles are loaded on the WordPress dashboard be sure to enqueue it via the \"admin_enqueue_scripts\" hook using the wp_enqueue_style() helper.</p>\n\n<p>EDIT: Updated the styles to separate \"Actions\" \"View Icons\" and \"Pagination\" into separate styles. Since pagination is pretty important I thought you might want to keep it. Simply deleting this line from the code above will show pagination but hide everything else:</p>\n\n<pre><code>.post-type-event .posts-filter .tablenav .tablenav-pages,\n</code></pre>\n"
}
] |
2015/10/12
|
[
"https://wordpress.stackexchange.com/questions/205287",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/33028/"
] |
I have tried to to make a custom query, to some extend. it is working fine. But where i cannot make it work, is it to break after every 3 posts and do same thing (print div.row) and run same loop, For now, my code seem to output just 3 odd number posts, whereas i want it to break of after each 3 post.
```
if ($news->have_posts() ) : while ($news->have_posts() ) : $news->the_post();
//$value = $news->current_post;
echo "<div class='col-lg-4'>";
if($value % 3 == 0){
?>
<div class="height <?php foreach(get_the_category() as $category) { echo $category->slug . ' ';} ?>">
<div class="text">
<h5><?php the_time('F jS, Y'); ?></h5>
<h4><a href=""><?php the_title(); ?></a></h4>
<?php the_excerpt(); ?>
</div>
</div>
<?php
//$i++;
//print($value);
}
echo "</div>";
endwhile; endif;
```
Edit : What is different about my layout, it should be in indivuial row, as shown in [bootly](http://www.bootply.com/render/90113), more like google cards layout.
|
I don't know what you mean by *dirty way*, hopefully **not** core editing!
You can hide it with CSS.
Or you can do it with PHP - see below:
Hide the views part
-------------------
You can remove the *views* part with
```
add_filter( 'views_edit-post', '__return_null' );
```
for the `post` post type on the `edit.php` screen.
The post table object is created from:
```
$wp_list_table = _get_list_table('WP_Posts_List_Table');
```
but there's no filter available in the `_get_list_table()` function.
Workaround - Extending the `WP_Posts_List_Table` class
------------------------------------------------------
So here's a workaround by extending the `WP_Posts_List_Table` class and override it's methods within the `views_edit-post` filter - *Don't try this at home!* ;-)
```
/**
* Headless post table
*
* @link http://wordpress.stackexchange.com/a/205281/26350
*/
add_action( 'load-edit.php', function()
{
// Target the post edit screen
if( 'edit-post' !== get_current_screen()->id )
return;
// Include the WP_Posts_List_Table class
require_once ( ABSPATH . 'wp-admin/includes/class-wp-posts-list-table.php' );
// Extend the WP_Posts_List_Table class and remove stuff
class WPSE_Headless_Table extends WP_Posts_List_Table
{
public function search_box( $text, $input_id ){} // Remove search box
protected function pagination( $which ){} // Remove pagination
protected function display_tablenav( $which ){} // Remove navigation
} // end class
$mytable = new WPSE_Headless_Table;
// Prepare our table, this method has already run with the global table object
$mytable->prepare_items();
// Override the global post table object
add_filter( 'views_edit-post', function( $views ) use ( $mytable )
{
global $wp_list_table;
// Let's clone it to the global object
$wp_list_table = clone $mytable;
// Let's remove the views part also
return null;
} );
} );
```
Here's a screenshot example:
**Before:**
[](https://i.stack.imgur.com/WOAlh.jpg)
**After:**
[](https://i.stack.imgur.com/Kgf3y.jpg)
|
205,297 |
<p>Hi I want to display all the categories of products in a loop to display them in category menu along the numbers of products each category contains.
Some thing like that</p>
<p><a href="https://i.stack.imgur.com/bvNDW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bvNDW.png" alt="enter image description here"></a></p>
<p>so far I have done this to get all categories</p>
<pre><code> $args = array(
'number' => $number,
'orderby' => $orderby,
'order' => $order,
'hide_empty' => $hide_empty,
'include' => $ids
);
$product_categories = get_terms( 'product_cat', $args );
foreach( $product_categories as $cat ) { echo $cat->name; }
</code></pre>
<p>But I want to know how to display products numbers in each category.</p>
|
[
{
"answer_id": 209815,
"author": "asp111",
"author_id": 84247,
"author_profile": "https://wordpress.stackexchange.com/users/84247",
"pm_score": 4,
"selected": true,
"text": "<p>You just need to add <code>$cat->count</code> to get the count of all products in that category. Hope this helps you out. </p>\n\n<pre><code>$args = array(\n 'number' => $number,\n 'orderby' => $orderby,\n 'order' => $order,\n 'hide_empty' => $hide_empty,\n 'include' => $ids\n);\n\n$product_categories = get_terms( 'product_cat', $args );\n\nforeach( $product_categories as $cat ) { \n echo $cat->name.' ('.$cat->count.')'; \n}\n</code></pre>\n"
},
{
"answer_id": 301371,
"author": "Purnendu Sarkar",
"author_id": 137183,
"author_profile": "https://wordpress.stackexchange.com/users/137183",
"pm_score": -1,
"selected": false,
"text": "Category\n\n<pre><code> <ul class=\"Category-list\">\n\n <?php\n\n $wcatTerms = get_terms('product_cat', array('hide_empty' => 0, 'parent' =>0));\n $count = $category->category_count;\n\n foreach($wcatTerms as $wcatTerm) : ?>\n <?php\n $thumb_id = get_woocommerce_term_meta( $wcatTerm->term_id, 'thumbnail_id', true );\n $term_img = wp_get_attachment_url( $thumb_id );\n ?>\n <li><a href=\"<?php echo get_term_link( $wcatTerm->slug, $wcatTerm->taxonomy ); ?>\"><?php echo $wcatTerm->name; ?>(<?php echo $wcatTerm->count;?>)</a></li>\n <?php endforeach; ?>\n </ul>\n </div>\n</code></pre>\n"
},
{
"answer_id": 364048,
"author": "mohit saint",
"author_id": 185275,
"author_profile": "https://wordpress.stackexchange.com/users/185275",
"pm_score": 0,
"selected": false,
"text": "<pre><code>foreach( $product_categories as $cat ) { \n echo $cat->name.' ('.$cat->count.')'; \n}\n</code></pre>\n\n<p>WORKED FINE FOR ME,but How to show the number of product which are sale only?</p>\n"
},
{
"answer_id": 406073,
"author": "Dev",
"author_id": 104464,
"author_profile": "https://wordpress.stackexchange.com/users/104464",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$product_categories = get_terms( 'product_cat', $args );\n\nforeach( $product_categories as $cat ) { \n echo $cat->name.' ('.$cat->found_posts.')'; \n}\n</code></pre>\n<p>count only counts per page whereas found_posts is global.</p>\n"
}
] |
2015/10/12
|
[
"https://wordpress.stackexchange.com/questions/205297",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78548/"
] |
Hi I want to display all the categories of products in a loop to display them in category menu along the numbers of products each category contains.
Some thing like that
[](https://i.stack.imgur.com/bvNDW.png)
so far I have done this to get all categories
```
$args = array(
'number' => $number,
'orderby' => $orderby,
'order' => $order,
'hide_empty' => $hide_empty,
'include' => $ids
);
$product_categories = get_terms( 'product_cat', $args );
foreach( $product_categories as $cat ) { echo $cat->name; }
```
But I want to know how to display products numbers in each category.
|
You just need to add `$cat->count` to get the count of all products in that category. Hope this helps you out.
```
$args = array(
'number' => $number,
'orderby' => $orderby,
'order' => $order,
'hide_empty' => $hide_empty,
'include' => $ids
);
$product_categories = get_terms( 'product_cat', $args );
foreach( $product_categories as $cat ) {
echo $cat->name.' ('.$cat->count.')';
}
```
|
205,313 |
<p>Anybody knows if there's a hook before execution of a search query (not in main loop) in order to change the 's' parameter to avoid Wordpress' phrase splitting? Examples are welcome... thanks</p>
<p>P.S.:
I've also tried in this way as follow, but the first part of sql query seems to indicate that WP have already done the search and then re-run a query filtered by post_ids firstly found:</p>
<pre><code>function alter_the_query( $where = '' ) {
global $wpdb, $table_prefix, $wp_query;
$tmpQobj = $wp_query->queried_object;
$tmpTitle = $wp_query->queried_object->post_title;
$where .= $wpdb->prepare( " AND ({$table_prefix}posts.post_title like %s OR {$table_prefix}posts.post_content like %s )", "%{$tmpTitle}%", "%{$tmpTitle}%" );
debug($where);
return $where;
}
add_filter( 'posts_where', 'alter_the_query' );
</code></pre>
<p>And this is the content of request value (* stands for table prefix) returned by debug:</p>
<pre><code>[request] => SELECT SQL_CALC_FOUND_ROWS ***_posts.ID FROM ***__posts WHERE 1=1 AND ***__posts.ID IN (534,868,911,917) AND ***__posts.post_type IN ('multimedia', 'news', 'social_project', 'publication') AND ((***__posts.post_status = 'publish')) AND (***__posts.post_title like '%string to search%' OR ***__posts.post_content like '%string to searchs%' ) ORDER BY FIELD( ***__posts.ID, 534,868,911,917 ) LIMIT 0, 3
</code></pre>
<p>As You can see, the original search is already done and my changes affects only the second query... I don't know why WP Core developers have done it in this way, but it's quite a nightmare...</p>
<p>How can I hook the first query, the one releated to original search, I mean?</p>
|
[
{
"answer_id": 205328,
"author": "Welcher",
"author_id": 27210,
"author_profile": "https://wordpress.stackexchange.com/users/27210",
"pm_score": 1,
"selected": false,
"text": "<p>You are looking for the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow\"><code>pre_get_posts</code></a> hook.</p>\n"
},
{
"answer_id": 302027,
"author": "HU is Sebastian",
"author_id": 56587,
"author_profile": "https://wordpress.stackexchange.com/users/56587",
"pm_score": 3,
"selected": false,
"text": "<p>To avoid the splitting of searchphrases, use the <code>sentence</code> query variable in the pre_get_posts hook:</p>\n\n<pre><code>function only_search_for_full_phrase( $query ) {\n if ( $query->is_search() && $query->is_main_query() ) {\n $query->set( 'sentence', true );\n }\n}\nadd_action( 'pre_get_posts', 'only_search_for_full_phrase' );\n</code></pre>\n\n<p>Didn't test it, but should do the trick.</p>\n\n<p>Happy Coding!</p>\n"
}
] |
2015/10/12
|
[
"https://wordpress.stackexchange.com/questions/205313",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/59735/"
] |
Anybody knows if there's a hook before execution of a search query (not in main loop) in order to change the 's' parameter to avoid Wordpress' phrase splitting? Examples are welcome... thanks
P.S.:
I've also tried in this way as follow, but the first part of sql query seems to indicate that WP have already done the search and then re-run a query filtered by post\_ids firstly found:
```
function alter_the_query( $where = '' ) {
global $wpdb, $table_prefix, $wp_query;
$tmpQobj = $wp_query->queried_object;
$tmpTitle = $wp_query->queried_object->post_title;
$where .= $wpdb->prepare( " AND ({$table_prefix}posts.post_title like %s OR {$table_prefix}posts.post_content like %s )", "%{$tmpTitle}%", "%{$tmpTitle}%" );
debug($where);
return $where;
}
add_filter( 'posts_where', 'alter_the_query' );
```
And this is the content of request value (\* stands for table prefix) returned by debug:
```
[request] => SELECT SQL_CALC_FOUND_ROWS ***_posts.ID FROM ***__posts WHERE 1=1 AND ***__posts.ID IN (534,868,911,917) AND ***__posts.post_type IN ('multimedia', 'news', 'social_project', 'publication') AND ((***__posts.post_status = 'publish')) AND (***__posts.post_title like '%string to search%' OR ***__posts.post_content like '%string to searchs%' ) ORDER BY FIELD( ***__posts.ID, 534,868,911,917 ) LIMIT 0, 3
```
As You can see, the original search is already done and my changes affects only the second query... I don't know why WP Core developers have done it in this way, but it's quite a nightmare...
How can I hook the first query, the one releated to original search, I mean?
|
To avoid the splitting of searchphrases, use the `sentence` query variable in the pre\_get\_posts hook:
```
function only_search_for_full_phrase( $query ) {
if ( $query->is_search() && $query->is_main_query() ) {
$query->set( 'sentence', true );
}
}
add_action( 'pre_get_posts', 'only_search_for_full_phrase' );
```
Didn't test it, but should do the trick.
Happy Coding!
|
205,354 |
<p>Is there a WordPress REST API for Multisite?</p>
<p>I know this is fully functional for normal WordPress, but does the API also allow usage of Multisite?</p>
|
[
{
"answer_id": 205492,
"author": "Pat J",
"author_id": 16121,
"author_profile": "https://wordpress.stackexchange.com/users/16121",
"pm_score": 3,
"selected": false,
"text": "<p>I'm using the REST API to pull data about one multisite installation and feed it to sites in another multisite installation.</p>\n\n<p>Here's some of the code in use:</p>\n\n<pre><code>class WPSE205354_Demo {\n function __construct() {\n add_filter( 'json_endpoints', array( $this, 'register_routes' ) );\n }\n\n /**\n * Register the additional API routes\n * @param array $routes The routes from the WP REST API\n * @return array The filtered array of API routes\n */\n public function register_routes( array $routes ) {\n\n $routes['/sites'] = array(\n array( array( $this, 'get_sites' ), WP_JSON_Server::READABLE ),\n );\n\n return $routes;\n }\n\n /**\n * Get the list of public sites\n * @return array The list of public sites\n */\n function get_sites() {\n\n $args = array(\n 'public' => 1, // I only want the sites marked Public\n 'archived' => 0,\n 'mature' => 0,\n 'spam' => 0,\n 'deleted' => 0,\n );\n\n $sites = wp_get_sites( $args );\n\n return $sites;\n\n }\n\n}\n</code></pre>\n\n<p>I've network-activated the plugin, and also the WP JSON API plugin (I'm using v. 1.2.3).</p>\n\n<p>To see what that returns, you would go to <code>http://example.com/wp-json/sites</code> (spoiler alert: it's the list of public sites in your WordPress Multisite network).</p>\n\n<h2>References</h2>\n\n<p>I found pretty much everything I needed on the <a href=\"http://wp-api.org/\" rel=\"noreferrer\">WP API</a> site.</p>\n"
},
{
"answer_id": 390212,
"author": "golabs",
"author_id": 80269,
"author_profile": "https://wordpress.stackexchange.com/users/80269",
"pm_score": 1,
"selected": false,
"text": "<p>6 years later but this might still be handy for those with the same issue - like me till very very recent.</p>\n<p>Through this thread I landed on the right search in Google and found <strong><a href=\"https://github.com/WP-API/multisite\" rel=\"nofollow noreferrer\">https://github.com/WP-API/multisite</a></strong> which instantly made all the REST API functionality of the <strong>WooCommerce</strong> REST API work for me (so I assume the regular WordPress REST API will work then as well). Yeah!!!</p>\n<p>It's code from 2013 but it works and is by the hand of Ryan McCue who appears to be one of the co-leads of the original WordPress REST API back in 2012. That probably explains why it didn't need to be updated all those years.</p>\n<p>So hopefully this multisite api support will make it into the WordPress core one day so it's tested with every new release as well. #fingerscrossed</p>\n"
}
] |
2015/10/13
|
[
"https://wordpress.stackexchange.com/questions/205354",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3529/"
] |
Is there a WordPress REST API for Multisite?
I know this is fully functional for normal WordPress, but does the API also allow usage of Multisite?
|
I'm using the REST API to pull data about one multisite installation and feed it to sites in another multisite installation.
Here's some of the code in use:
```
class WPSE205354_Demo {
function __construct() {
add_filter( 'json_endpoints', array( $this, 'register_routes' ) );
}
/**
* Register the additional API routes
* @param array $routes The routes from the WP REST API
* @return array The filtered array of API routes
*/
public function register_routes( array $routes ) {
$routes['/sites'] = array(
array( array( $this, 'get_sites' ), WP_JSON_Server::READABLE ),
);
return $routes;
}
/**
* Get the list of public sites
* @return array The list of public sites
*/
function get_sites() {
$args = array(
'public' => 1, // I only want the sites marked Public
'archived' => 0,
'mature' => 0,
'spam' => 0,
'deleted' => 0,
);
$sites = wp_get_sites( $args );
return $sites;
}
}
```
I've network-activated the plugin, and also the WP JSON API plugin (I'm using v. 1.2.3).
To see what that returns, you would go to `http://example.com/wp-json/sites` (spoiler alert: it's the list of public sites in your WordPress Multisite network).
References
----------
I found pretty much everything I needed on the [WP API](http://wp-api.org/) site.
|
205,390 |
<p>I'm using Emberjs to build a front end to a WordPress site. It has two javascript files 1. vendor.js and 2. myapp.js. On Ember's dev server, the app works correctly but when I add the production builds to the WordPress app, I'm getting errors which suggest that the <code>vendor.js</code> file is not loaded prior to <code>myapp.js</code>. Note, vendor.js has jQuery inside it (along with other vendor code).</p>
<p>This is what I'm doing to add the js files to my WordPress app. In functions.php of my theme I do</p>
<pre><code>function add_my_js(){
wp_register_script('vendors', get_template_directory_uri() . '/vendor.js', array(), '20151006', true);
wp_register_script('myapp', get_template_directory_uri() . '/myapp.js', array(), '20151006', true);
wp_enqueue_script('vendors');
wp_enqueue_script('myapp');
}
add_action('wp_enqueue_scripts', 'add_my_js');
</code></pre>
<p>With that code, I can see (and click on) links to both js files on the front page of my WordPress app (in development server) so I know the files are both included. However, the error message I'm getting from the Ember app suggests that the vendor.js file might not be loaded at the correct time for the myapp.js file. </p>
<p>Question: is there another way to ensure that the first file is loaded prior to running the second file?</p>
|
[
{
"answer_id": 205492,
"author": "Pat J",
"author_id": 16121,
"author_profile": "https://wordpress.stackexchange.com/users/16121",
"pm_score": 3,
"selected": false,
"text": "<p>I'm using the REST API to pull data about one multisite installation and feed it to sites in another multisite installation.</p>\n\n<p>Here's some of the code in use:</p>\n\n<pre><code>class WPSE205354_Demo {\n function __construct() {\n add_filter( 'json_endpoints', array( $this, 'register_routes' ) );\n }\n\n /**\n * Register the additional API routes\n * @param array $routes The routes from the WP REST API\n * @return array The filtered array of API routes\n */\n public function register_routes( array $routes ) {\n\n $routes['/sites'] = array(\n array( array( $this, 'get_sites' ), WP_JSON_Server::READABLE ),\n );\n\n return $routes;\n }\n\n /**\n * Get the list of public sites\n * @return array The list of public sites\n */\n function get_sites() {\n\n $args = array(\n 'public' => 1, // I only want the sites marked Public\n 'archived' => 0,\n 'mature' => 0,\n 'spam' => 0,\n 'deleted' => 0,\n );\n\n $sites = wp_get_sites( $args );\n\n return $sites;\n\n }\n\n}\n</code></pre>\n\n<p>I've network-activated the plugin, and also the WP JSON API plugin (I'm using v. 1.2.3).</p>\n\n<p>To see what that returns, you would go to <code>http://example.com/wp-json/sites</code> (spoiler alert: it's the list of public sites in your WordPress Multisite network).</p>\n\n<h2>References</h2>\n\n<p>I found pretty much everything I needed on the <a href=\"http://wp-api.org/\" rel=\"noreferrer\">WP API</a> site.</p>\n"
},
{
"answer_id": 390212,
"author": "golabs",
"author_id": 80269,
"author_profile": "https://wordpress.stackexchange.com/users/80269",
"pm_score": 1,
"selected": false,
"text": "<p>6 years later but this might still be handy for those with the same issue - like me till very very recent.</p>\n<p>Through this thread I landed on the right search in Google and found <strong><a href=\"https://github.com/WP-API/multisite\" rel=\"nofollow noreferrer\">https://github.com/WP-API/multisite</a></strong> which instantly made all the REST API functionality of the <strong>WooCommerce</strong> REST API work for me (so I assume the regular WordPress REST API will work then as well). Yeah!!!</p>\n<p>It's code from 2013 but it works and is by the hand of Ryan McCue who appears to be one of the co-leads of the original WordPress REST API back in 2012. That probably explains why it didn't need to be updated all those years.</p>\n<p>So hopefully this multisite api support will make it into the WordPress core one day so it's tested with every new release as well. #fingerscrossed</p>\n"
}
] |
2015/10/13
|
[
"https://wordpress.stackexchange.com/questions/205390",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81301/"
] |
I'm using Emberjs to build a front end to a WordPress site. It has two javascript files 1. vendor.js and 2. myapp.js. On Ember's dev server, the app works correctly but when I add the production builds to the WordPress app, I'm getting errors which suggest that the `vendor.js` file is not loaded prior to `myapp.js`. Note, vendor.js has jQuery inside it (along with other vendor code).
This is what I'm doing to add the js files to my WordPress app. In functions.php of my theme I do
```
function add_my_js(){
wp_register_script('vendors', get_template_directory_uri() . '/vendor.js', array(), '20151006', true);
wp_register_script('myapp', get_template_directory_uri() . '/myapp.js', array(), '20151006', true);
wp_enqueue_script('vendors');
wp_enqueue_script('myapp');
}
add_action('wp_enqueue_scripts', 'add_my_js');
```
With that code, I can see (and click on) links to both js files on the front page of my WordPress app (in development server) so I know the files are both included. However, the error message I'm getting from the Ember app suggests that the vendor.js file might not be loaded at the correct time for the myapp.js file.
Question: is there another way to ensure that the first file is loaded prior to running the second file?
|
I'm using the REST API to pull data about one multisite installation and feed it to sites in another multisite installation.
Here's some of the code in use:
```
class WPSE205354_Demo {
function __construct() {
add_filter( 'json_endpoints', array( $this, 'register_routes' ) );
}
/**
* Register the additional API routes
* @param array $routes The routes from the WP REST API
* @return array The filtered array of API routes
*/
public function register_routes( array $routes ) {
$routes['/sites'] = array(
array( array( $this, 'get_sites' ), WP_JSON_Server::READABLE ),
);
return $routes;
}
/**
* Get the list of public sites
* @return array The list of public sites
*/
function get_sites() {
$args = array(
'public' => 1, // I only want the sites marked Public
'archived' => 0,
'mature' => 0,
'spam' => 0,
'deleted' => 0,
);
$sites = wp_get_sites( $args );
return $sites;
}
}
```
I've network-activated the plugin, and also the WP JSON API plugin (I'm using v. 1.2.3).
To see what that returns, you would go to `http://example.com/wp-json/sites` (spoiler alert: it's the list of public sites in your WordPress Multisite network).
References
----------
I found pretty much everything I needed on the [WP API](http://wp-api.org/) site.
|
205,393 |
<p>I am very new in wordpress theme development.
how can i make page template for my store page where my all categories listed with 6 to 10 latest post with that category and category name has a link to category page <code>category.php</code>
<strong>for example:</strong></p>
<p>in store page</p>
<p><strong>category 1</strong></p>
<ol>
<li>first item with this category</li>
<li>second item with this category</li>
<li>third item with this category</li>
<li>forth item with this category</li>
</ol>
<p><strong>category 2</strong></p>
<ol>
<li>first item with this category</li>
<li>second item with this category</li>
<li>third item with this category</li>
<li>forth item with this category</li>
</ol>
<p><strong>category 3</strong></p>
<ol>
<li>first item with this category</li>
<li>second item with this category</li>
<li>third item with this category</li>
<li>forth item with this category</li>
</ol>
<p><strong>and so on</strong></p>
<p>thanks in advance</p>
|
[
{
"answer_id": 205407,
"author": "RiaanZA",
"author_id": 81679,
"author_profile": "https://wordpress.stackexchange.com/users/81679",
"pm_score": 1,
"selected": false,
"text": "<p>You first need to grab a list of your categories, and they run a wordpress query for each category.</p>\n\n<pre><code>$cats = get_categories(); //Get all the categories\nforeach ($cats as $cat) : //Loop through all the categories\n $args = array(\n 'posts_per_page' => 5, //limit it to 5 posts per category\n 'cat' => $cat->term_id, //Get posts for this specific category in the loop\n );\n $query = new WP_Query($args);\n if ($query->have_posts()) : ?>\n <h2><?php echo $cat->name; ?></h2>\n <ul>\n <?php while $query->have_posts()) : the_post(); //loop through the posts in this category ?> \n <li><a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a></li>\n <?php endwhile; ?>\n </ul>\n <?php endif; wp_reset_query; //reset the query ?>\n<?php endforeach; ?>\n</code></pre>\n\n<p>If you want to restricted the categories you are looping through to a specific post type or something else, you can pass parameters to the get_categories method. See <a href=\"https://codex.wordpress.org/Function_Reference/get_categories\" rel=\"nofollow\">here</a> for more details on that</p>\n\n<p>This code would replace the loop in your categories.php template or where ever else you want to list them.</p>\n"
},
{
"answer_id": 205446,
"author": "Humaira Naz",
"author_id": 81619,
"author_profile": "https://wordpress.stackexchange.com/users/81619",
"pm_score": 1,
"selected": true,
"text": "<p>i think it is petty straightforward solution</p>\n\n<p>first get your all categories list by help of <code>get_categories()</code> function and loop though\nand find the post relative with that.</p>\n\n<pre><code><?php\n $categories = get_categories(); return all categories\n foreach( $categories as $cat ){\n $query = new WP_query(['cat'=>$cat->term_id, 'postes_per_page'=> 10]);\n if( $query->have_postes() ){\n echo $cate-name; // this this category name\n while( $query -> have_postes() ) {\n // show your all post relavent to this category..\n }\n }\n }\n?>\n</code></pre>\n"
}
] |
2015/10/13
|
[
"https://wordpress.stackexchange.com/questions/205393",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81875/"
] |
I am very new in wordpress theme development.
how can i make page template for my store page where my all categories listed with 6 to 10 latest post with that category and category name has a link to category page `category.php`
**for example:**
in store page
**category 1**
1. first item with this category
2. second item with this category
3. third item with this category
4. forth item with this category
**category 2**
1. first item with this category
2. second item with this category
3. third item with this category
4. forth item with this category
**category 3**
1. first item with this category
2. second item with this category
3. third item with this category
4. forth item with this category
**and so on**
thanks in advance
|
i think it is petty straightforward solution
first get your all categories list by help of `get_categories()` function and loop though
and find the post relative with that.
```
<?php
$categories = get_categories(); return all categories
foreach( $categories as $cat ){
$query = new WP_query(['cat'=>$cat->term_id, 'postes_per_page'=> 10]);
if( $query->have_postes() ){
echo $cate-name; // this this category name
while( $query -> have_postes() ) {
// show your all post relavent to this category..
}
}
}
?>
```
|
205,405 |
<p>I've a one-page template and I would like to get the pages according to the menu order, so I think to have a loop to get all pages from the "primary" menu. </p>
<p>But on "get_pages" I don't have the option to filter by menu, how can I do that?</p>
<pre><code>$mypages = get_pages( array( 'sort_column' => 'post_date', 'sort_order' => 'desc' ) );
foreach( $mypages as $page ) {
$content = $page->post_content;
if ( ! $content ) // Check for empty page
continue;
$content = apply_filters( 'the_content', $content );
?>
<h2><a href="<?php echo get_page_link( $page->ID ); ?>"><?php echo $page->post_title; ?></a></h2>
<div class="entry"><?php echo $content; ?></div>
<?php
}
</code></pre>
|
[
{
"answer_id": 205407,
"author": "RiaanZA",
"author_id": 81679,
"author_profile": "https://wordpress.stackexchange.com/users/81679",
"pm_score": 1,
"selected": false,
"text": "<p>You first need to grab a list of your categories, and they run a wordpress query for each category.</p>\n\n<pre><code>$cats = get_categories(); //Get all the categories\nforeach ($cats as $cat) : //Loop through all the categories\n $args = array(\n 'posts_per_page' => 5, //limit it to 5 posts per category\n 'cat' => $cat->term_id, //Get posts for this specific category in the loop\n );\n $query = new WP_Query($args);\n if ($query->have_posts()) : ?>\n <h2><?php echo $cat->name; ?></h2>\n <ul>\n <?php while $query->have_posts()) : the_post(); //loop through the posts in this category ?> \n <li><a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a></li>\n <?php endwhile; ?>\n </ul>\n <?php endif; wp_reset_query; //reset the query ?>\n<?php endforeach; ?>\n</code></pre>\n\n<p>If you want to restricted the categories you are looping through to a specific post type or something else, you can pass parameters to the get_categories method. See <a href=\"https://codex.wordpress.org/Function_Reference/get_categories\" rel=\"nofollow\">here</a> for more details on that</p>\n\n<p>This code would replace the loop in your categories.php template or where ever else you want to list them.</p>\n"
},
{
"answer_id": 205446,
"author": "Humaira Naz",
"author_id": 81619,
"author_profile": "https://wordpress.stackexchange.com/users/81619",
"pm_score": 1,
"selected": true,
"text": "<p>i think it is petty straightforward solution</p>\n\n<p>first get your all categories list by help of <code>get_categories()</code> function and loop though\nand find the post relative with that.</p>\n\n<pre><code><?php\n $categories = get_categories(); return all categories\n foreach( $categories as $cat ){\n $query = new WP_query(['cat'=>$cat->term_id, 'postes_per_page'=> 10]);\n if( $query->have_postes() ){\n echo $cate-name; // this this category name\n while( $query -> have_postes() ) {\n // show your all post relavent to this category..\n }\n }\n }\n?>\n</code></pre>\n"
}
] |
2015/10/13
|
[
"https://wordpress.stackexchange.com/questions/205405",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81884/"
] |
I've a one-page template and I would like to get the pages according to the menu order, so I think to have a loop to get all pages from the "primary" menu.
But on "get\_pages" I don't have the option to filter by menu, how can I do that?
```
$mypages = get_pages( array( 'sort_column' => 'post_date', 'sort_order' => 'desc' ) );
foreach( $mypages as $page ) {
$content = $page->post_content;
if ( ! $content ) // Check for empty page
continue;
$content = apply_filters( 'the_content', $content );
?>
<h2><a href="<?php echo get_page_link( $page->ID ); ?>"><?php echo $page->post_title; ?></a></h2>
<div class="entry"><?php echo $content; ?></div>
<?php
}
```
|
i think it is petty straightforward solution
first get your all categories list by help of `get_categories()` function and loop though
and find the post relative with that.
```
<?php
$categories = get_categories(); return all categories
foreach( $categories as $cat ){
$query = new WP_query(['cat'=>$cat->term_id, 'postes_per_page'=> 10]);
if( $query->have_postes() ){
echo $cate-name; // this this category name
while( $query -> have_postes() ) {
// show your all post relavent to this category..
}
}
}
?>
```
|
205,421 |
<p>over the last week I have been working on some cron jobs for a real-estate website that has hundreds of updates/deletes and new posts added each day. I am very near the end now and looking to schedule three WordPress events to take care of the process.</p>
<p>The code I have linked below runs and send a email to me with the output (with the second and third events commented out). The problem comes when I remove the comments from jobs 2 and 3. The plugin activates fine but when the jobs start running I get a lot of duplicate emails.</p>
<p>NOTE** This is a high traffic website that may get hit many times around the time the event is scheduled. Some of the reading I was doing mention that the wp-cron has had some known issues dealing with long scripts and can overlap.</p>
<p>That being said I am wondering if my cron jobs are too big for the wp-cron functionality to handle. Does that force me to DISABLE_WP_CRON in my wp-config.php and go with the cron scheduler provided by my host? Or is my problem in how I have created my plugin?</p>
<p>Thanks in advance!</p>
<pre><code>register_activation_hook(__FILE__,'cron_activation');
register_deactivation_hook(__FILE__,'cron_deactivation');
function cron_activation(){
wp_schedule_event(time()+60, 'daily', 'first_hook');
//wp_schedule_event(time()+420, 'hourly', 'second_hook');
//wp_schedule_event(time()+840, 'hourly', 'third_hook');
}
function cron_deactivation(){
wp_clear_scheduled_hook('first_hook');
//wp_clear_scheduled_hook('second_hook');
//wp_clear_scheduled_hook('third_hook');
}
add_action( 'first_hook', 'first_hook_function' );
//add_action( 'second_hook', 'second_hook_function' );
//add_action( 'third_hook', 'third_hook_function' );
function first_hook_function(){
//code to run takes 2 minutes.
//sends output as email to me for inspection
}
function second_hook_function(){
//code to run takes 3 minutes.
//sends output as email to me for inspection
}
function third_hook_function(){
//code to run takes 4 minutes.
//sends output as email to me for inspection
}
</code></pre>
<p>P.S. I hope I followed all the correct format, this is my first post!</p>
<p>Edit: To clarify my questions, is it possible to run these (2 to 4 minuet) functions all from the same plugin using the wp-cron method?</p>
|
[
{
"answer_id": 208095,
"author": "futuernorn",
"author_id": 83220,
"author_profile": "https://wordpress.stackexchange.com/users/83220",
"pm_score": 0,
"selected": false,
"text": "<p>In general using the <a href=\"https://wordpress.org/support/article/editing-wp-config-php/#alternative-cron\" rel=\"nofollow noreferrer\">Alternative Cron</a> <em>is</em> more reliable. I tried to make a demo using your example code as the basis in order to replicate what was being seen:</p>\n<pre><code><?php\n/*\n* Plugin Name: Overlapping Cron Test\n* Author: futuernorn\n*/\n\nregister_activation_hook(__FILE__,'cron_activation');\nregister_deactivation_hook(__FILE__,'cron_deactivation');\n\nfunction cron_activation(){\n wp_schedule_event(time()+30, 'daily', 'first_hook');\n wp_schedule_event(time()+60, 'hourly', 'second_hook');\n wp_schedule_event(time()+90, 'hourly', 'third_hook');\n}\n\nfunction cron_deactivation(){\n wp_clear_scheduled_hook('first_hook');\n wp_clear_scheduled_hook('second_hook');\n wp_clear_scheduled_hook('third_hook');\n}\n\n\nadd_action( 'first_hook', 'first_hook_function' );\nadd_action( 'second_hook', 'second_hook_function' );\nadd_action( 'third_hook', 'third_hook_function' );\n\nfunction first_hook_function(){\n //code to run takes 2 minutes.\n //sends output as email to me for inspection\n sleep(30);\n $crontest_data = get_option( '_crontest_data' );\n $crontest_data[] = 'first_hook_completed: '.date('Y-m-d H:i:s');\n update_option('_crontest_data', $crontest_data);\n}\n\nfunction second_hook_function(){\n //code to run takes 3 minutes.\n //sends output as email to me for inspection\\\n sleep(60);\n $crontest_data = get_option( '_crontest_data' );\n $crontest_data[] = 'second_hook_completed: '.date('Y-m-d H:i:s');\n update_option('_crontest_data', $crontest_data);\n}\n\nfunction third_hook_function(){\n //code to run takes 4 minutes.\n //sends output as email to me for inspection\n sleep(90);\n $crontest_data = get_option( '_crontest_data' );\n $crontest_data[] = 'third_hook_completed: '.date('Y-m-d H:i:s');\n update_option('_crontest_data', $crontest_data);\n}\n</code></pre>\n<p>With the normal wp-cron functionality in place, and a contrived set of concurrent traffic, we see just one entry per cron even however:</p>\n<pre><code>testsite$ wp plugin activate crontest\nSuccess: Plugin 'crontest' activated.\ntestsite$ for i in {1..10}; do curl -b -s $WEBSITE_URL 1>/dev/null; done\ntestsite$ for i in {1..10}; do curl -s $WEBSITE_URL 1>/dev/null; done\ntestsite$ wp option get _crontest_data\narray (\n 0 => 'first_hook_completed: 2015-11-09 19:49:25',\n 1 => 'second_hook_completed: 2015-11-09 19:50:25',\n 2 => 'third_hook_completed: 2015-11-09 19:51:55',\n)\n</code></pre>\n<p>Since I can not quite replicate what you're seeing, it may help to have a bit more information here.</p>\n"
},
{
"answer_id": 345332,
"author": "Kirill",
"author_id": 173660,
"author_profile": "https://wordpress.stackexchange.com/users/173660",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe the problem happens because you don't check if your hook is already scheduled.</p>\n\n<pre><code>if ( !wp_next_scheduled( 'first_hook' ) ) {\n wp_schedule_event(time()+60, 'daily', 'first_hook');\n}\n</code></pre>\n"
}
] |
2015/10/13
|
[
"https://wordpress.stackexchange.com/questions/205421",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81895/"
] |
over the last week I have been working on some cron jobs for a real-estate website that has hundreds of updates/deletes and new posts added each day. I am very near the end now and looking to schedule three WordPress events to take care of the process.
The code I have linked below runs and send a email to me with the output (with the second and third events commented out). The problem comes when I remove the comments from jobs 2 and 3. The plugin activates fine but when the jobs start running I get a lot of duplicate emails.
NOTE\*\* This is a high traffic website that may get hit many times around the time the event is scheduled. Some of the reading I was doing mention that the wp-cron has had some known issues dealing with long scripts and can overlap.
That being said I am wondering if my cron jobs are too big for the wp-cron functionality to handle. Does that force me to DISABLE\_WP\_CRON in my wp-config.php and go with the cron scheduler provided by my host? Or is my problem in how I have created my plugin?
Thanks in advance!
```
register_activation_hook(__FILE__,'cron_activation');
register_deactivation_hook(__FILE__,'cron_deactivation');
function cron_activation(){
wp_schedule_event(time()+60, 'daily', 'first_hook');
//wp_schedule_event(time()+420, 'hourly', 'second_hook');
//wp_schedule_event(time()+840, 'hourly', 'third_hook');
}
function cron_deactivation(){
wp_clear_scheduled_hook('first_hook');
//wp_clear_scheduled_hook('second_hook');
//wp_clear_scheduled_hook('third_hook');
}
add_action( 'first_hook', 'first_hook_function' );
//add_action( 'second_hook', 'second_hook_function' );
//add_action( 'third_hook', 'third_hook_function' );
function first_hook_function(){
//code to run takes 2 minutes.
//sends output as email to me for inspection
}
function second_hook_function(){
//code to run takes 3 minutes.
//sends output as email to me for inspection
}
function third_hook_function(){
//code to run takes 4 minutes.
//sends output as email to me for inspection
}
```
P.S. I hope I followed all the correct format, this is my first post!
Edit: To clarify my questions, is it possible to run these (2 to 4 minuet) functions all from the same plugin using the wp-cron method?
|
Maybe the problem happens because you don't check if your hook is already scheduled.
```
if ( !wp_next_scheduled( 'first_hook' ) ) {
wp_schedule_event(time()+60, 'daily', 'first_hook');
}
```
|
205,423 |
<p>I have a custom post type called "<strong>Releases</strong>" set up and paginated perfectly using the following code:</p>
<h1><strong>The Loop</strong></h1>
<pre><code> <?php
$paged = (get_query_var('page')) ? get_query_var('page') : 1;
$args = array( 'post_type' => 'releases', 'posts_per_page' => 3, 'paged' => $paged, 'page' => $paged );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
?>
<!-- Loop Content -->
<article>
<h3><?php the_title(); ?></h3>
<div><?php the_excerpt(); ?></div>
</article>
<!-- end Loop Content -->
<?php endwhile; ?>
<!-- Pagination -->
<?php
if (function_exists('single_view_pagination')) {
single_view_pagination($loop->max_num_pages,"", $paged);
}
?>
<!-- end Pagination -->
</code></pre>
<h1><strong>The Function</strong></h1>
<pre><code> function single_view_pagination($numpages = '', $pagerange = '', $paged='') {
if (empty($pagerange)) {
$pagerange = 2;
}
global $paged;
if (empty($paged)) {
$paged = 1;
}
if ($numpages == '') {
global $wp_query;
$numpages = $wp_query->max_num_pages;
if(!$numpages) {
$numpages = 1;
}
}
$pagination_args = array(
'base' => get_pagenum_link(1) . '%_%',
'format' => 'page/%#%',
'total' => $numpages,
'current' => $paged,
'show_all' => False,
'end_size' => 1,
'mid_size' => $pagerange,
'prev_next' => True,
'prev_text' => __('&laquo;'),
'next_text' => __('&raquo;'),
'type' => plain,
'add_args' => false,
'add_fragment' => ''
);
$paginate_links = paginate_links($pagination_args);
if ($paginate_links) {
echo "<nav>";
echo "<ul>";
echo "<li>" . $paginate_links . "</li> ";
echo "</ul>";
echo "</nav>";
}
}
</code></pre>
<h1><strong>The Problem</strong></h1>
<p>Now, when using the code above and viewing the <strong>Archive</strong> of the custom post type, everything works perfectly and the pagination URLs link as followed: </p>
<pre><code>http://localhost/releases/page/2
http://localhost/releases/page/3
</code></pre>
<p>However, when viewing the <strong>Single Post</strong> of the custom post type, the issue is that the pagination URLs change to: </p>
<pre><code>http://localhost/releases/post-name/page/2
http://localhost/releases/post-name/page/3
</code></pre>
<p>Is there any way I can update this code or set up an new function in order to get the <strong>pagination URLs on the Single Post view</strong> to link properly & without the post-name in the URLs like this?</p>
<pre><code>http://localhost/releases/page/1
http://localhost/releases/page/2
http://localhost/releases/page/3
</code></pre>
<p>All help is greatly appreciated. Thanks in advance!</p>
<p><strong><em>Edit:</em></strong>
Here's a screenshot diagram showing exactly the issue that I am trying to fix. I need the function to <strong>output the page number links for the post type</strong> "Releases", <strong>instead of outputting the page number links of the current post</strong> "Post Name." <a href="https://i.stack.imgur.com/rGeAn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rGeAn.png" alt="Help Screenshot"></a></p>
|
[
{
"answer_id": 208095,
"author": "futuernorn",
"author_id": 83220,
"author_profile": "https://wordpress.stackexchange.com/users/83220",
"pm_score": 0,
"selected": false,
"text": "<p>In general using the <a href=\"https://wordpress.org/support/article/editing-wp-config-php/#alternative-cron\" rel=\"nofollow noreferrer\">Alternative Cron</a> <em>is</em> more reliable. I tried to make a demo using your example code as the basis in order to replicate what was being seen:</p>\n<pre><code><?php\n/*\n* Plugin Name: Overlapping Cron Test\n* Author: futuernorn\n*/\n\nregister_activation_hook(__FILE__,'cron_activation');\nregister_deactivation_hook(__FILE__,'cron_deactivation');\n\nfunction cron_activation(){\n wp_schedule_event(time()+30, 'daily', 'first_hook');\n wp_schedule_event(time()+60, 'hourly', 'second_hook');\n wp_schedule_event(time()+90, 'hourly', 'third_hook');\n}\n\nfunction cron_deactivation(){\n wp_clear_scheduled_hook('first_hook');\n wp_clear_scheduled_hook('second_hook');\n wp_clear_scheduled_hook('third_hook');\n}\n\n\nadd_action( 'first_hook', 'first_hook_function' );\nadd_action( 'second_hook', 'second_hook_function' );\nadd_action( 'third_hook', 'third_hook_function' );\n\nfunction first_hook_function(){\n //code to run takes 2 minutes.\n //sends output as email to me for inspection\n sleep(30);\n $crontest_data = get_option( '_crontest_data' );\n $crontest_data[] = 'first_hook_completed: '.date('Y-m-d H:i:s');\n update_option('_crontest_data', $crontest_data);\n}\n\nfunction second_hook_function(){\n //code to run takes 3 minutes.\n //sends output as email to me for inspection\\\n sleep(60);\n $crontest_data = get_option( '_crontest_data' );\n $crontest_data[] = 'second_hook_completed: '.date('Y-m-d H:i:s');\n update_option('_crontest_data', $crontest_data);\n}\n\nfunction third_hook_function(){\n //code to run takes 4 minutes.\n //sends output as email to me for inspection\n sleep(90);\n $crontest_data = get_option( '_crontest_data' );\n $crontest_data[] = 'third_hook_completed: '.date('Y-m-d H:i:s');\n update_option('_crontest_data', $crontest_data);\n}\n</code></pre>\n<p>With the normal wp-cron functionality in place, and a contrived set of concurrent traffic, we see just one entry per cron even however:</p>\n<pre><code>testsite$ wp plugin activate crontest\nSuccess: Plugin 'crontest' activated.\ntestsite$ for i in {1..10}; do curl -b -s $WEBSITE_URL 1>/dev/null; done\ntestsite$ for i in {1..10}; do curl -s $WEBSITE_URL 1>/dev/null; done\ntestsite$ wp option get _crontest_data\narray (\n 0 => 'first_hook_completed: 2015-11-09 19:49:25',\n 1 => 'second_hook_completed: 2015-11-09 19:50:25',\n 2 => 'third_hook_completed: 2015-11-09 19:51:55',\n)\n</code></pre>\n<p>Since I can not quite replicate what you're seeing, it may help to have a bit more information here.</p>\n"
},
{
"answer_id": 345332,
"author": "Kirill",
"author_id": 173660,
"author_profile": "https://wordpress.stackexchange.com/users/173660",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe the problem happens because you don't check if your hook is already scheduled.</p>\n\n<pre><code>if ( !wp_next_scheduled( 'first_hook' ) ) {\n wp_schedule_event(time()+60, 'daily', 'first_hook');\n}\n</code></pre>\n"
}
] |
2015/10/13
|
[
"https://wordpress.stackexchange.com/questions/205423",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81886/"
] |
I have a custom post type called "**Releases**" set up and paginated perfectly using the following code:
**The Loop**
============
```
<?php
$paged = (get_query_var('page')) ? get_query_var('page') : 1;
$args = array( 'post_type' => 'releases', 'posts_per_page' => 3, 'paged' => $paged, 'page' => $paged );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
?>
<!-- Loop Content -->
<article>
<h3><?php the_title(); ?></h3>
<div><?php the_excerpt(); ?></div>
</article>
<!-- end Loop Content -->
<?php endwhile; ?>
<!-- Pagination -->
<?php
if (function_exists('single_view_pagination')) {
single_view_pagination($loop->max_num_pages,"", $paged);
}
?>
<!-- end Pagination -->
```
**The Function**
================
```
function single_view_pagination($numpages = '', $pagerange = '', $paged='') {
if (empty($pagerange)) {
$pagerange = 2;
}
global $paged;
if (empty($paged)) {
$paged = 1;
}
if ($numpages == '') {
global $wp_query;
$numpages = $wp_query->max_num_pages;
if(!$numpages) {
$numpages = 1;
}
}
$pagination_args = array(
'base' => get_pagenum_link(1) . '%_%',
'format' => 'page/%#%',
'total' => $numpages,
'current' => $paged,
'show_all' => False,
'end_size' => 1,
'mid_size' => $pagerange,
'prev_next' => True,
'prev_text' => __('«'),
'next_text' => __('»'),
'type' => plain,
'add_args' => false,
'add_fragment' => ''
);
$paginate_links = paginate_links($pagination_args);
if ($paginate_links) {
echo "<nav>";
echo "<ul>";
echo "<li>" . $paginate_links . "</li> ";
echo "</ul>";
echo "</nav>";
}
}
```
**The Problem**
===============
Now, when using the code above and viewing the **Archive** of the custom post type, everything works perfectly and the pagination URLs link as followed:
```
http://localhost/releases/page/2
http://localhost/releases/page/3
```
However, when viewing the **Single Post** of the custom post type, the issue is that the pagination URLs change to:
```
http://localhost/releases/post-name/page/2
http://localhost/releases/post-name/page/3
```
Is there any way I can update this code or set up an new function in order to get the **pagination URLs on the Single Post view** to link properly & without the post-name in the URLs like this?
```
http://localhost/releases/page/1
http://localhost/releases/page/2
http://localhost/releases/page/3
```
All help is greatly appreciated. Thanks in advance!
***Edit:***
Here's a screenshot diagram showing exactly the issue that I am trying to fix. I need the function to **output the page number links for the post type** "Releases", **instead of outputting the page number links of the current post** "Post Name." [](https://i.stack.imgur.com/rGeAn.png)
|
Maybe the problem happens because you don't check if your hook is already scheduled.
```
if ( !wp_next_scheduled( 'first_hook' ) ) {
wp_schedule_event(time()+60, 'daily', 'first_hook');
}
```
|
205,459 |
<p>So we are using a couple of custom things in our WP and one of them is a PW-Recovery form. Using this internally we're setting the password with</p>
<pre><code>wp_set_password($password, $userId)
</code></pre>
<p>Lately we realised a problem with passwords containing the apostrophe character <code>"</code></p>
<p>Setting a password with this will leave the user unable to log in using the same password that was just set. We have applied nothing to the login process and I can verify that the correct password is entered into the <code>wp_set_password()</code> function as well as the login form.</p>
<p>Any pointers as to where I can look for potential errors would be great. Thank you for your time.</p>
<p><strong>Update 1</strong></p>
<p>Using <code>wp_signon()</code> the user is able to login using the password <code>Test"123</code></p>
<p>Using <code>wp-login.php?page=login</code> and entering the password <code>Test"123</code> will not work</p>
<p>currently looking for all the filters that could potentionally interfere with this... </p>
<p><strong>Update 2</strong></p>
<p>Looks to me like an undocumented wordpress feature / bug?</p>
<p>All plugins have been deactivated. The unmodified theme <code>twentefifteen</code> has been used. Changing the password using <code>wp_set_password()</code> changes the PW in the database. However using a password with <code>"</code> or <code>'</code> will result you being <em>unable</em> to login using <code>wp-login.php</code>. It will give you invalid credentials error.</p>
<p>However using the same login data and <code>wp_signon()</code> it works. I'm just clueless, probably forwarding to wp bug forums.</p>
<p><strong>Update 3</strong></p>
<p>I am using this plugin snipped to reset and test the login.</p>
<pre><code>function resetLogin() {
// wp_set_password('Test"123', 1);
wp_update_user([
'ID' => 1,
'user_pass' => 'Test"123'
]);
}
//add_action('after_setup_theme', 'resetLogin');
function testLogin() {
var_dump(wp_signon([
'user_login' => 'admin',
'user_password' => 'Test"123',
'remember' => true
], false));
}
//add_action('after_setup_theme', 'testLogin');
</code></pre>
<p>To test I am commenting in the add_action - resetLogin once, and deactivate it immediately again before doing anything on the page. This then immediately breaks the login on wp-login.php</p>
|
[
{
"answer_id": 205469,
"author": "ThemesCreator",
"author_id": 54067,
"author_profile": "https://wordpress.stackexchange.com/users/54067",
"pm_score": 1,
"selected": false,
"text": "<p>I am not sure if this exactly what is happening to you, but this is what the codex says about wp_set_password():</p>\n\n<blockquote>\n <p>Please note: This function should be used sparingly and is really only\n meant for single-time application. Leveraging this improperly in a\n plugin or theme could result in an endless loop of password resets if\n precautions are not taken to ensure it does not execute on every page\n load.</p>\n</blockquote>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_set_password/\" rel=\"nofollow\">https://developer.wordpress.org/reference/functions/wp_set_password/</a></p>\n\n<p>I think you should only use it to reset the password and then delete it.</p>\n"
},
{
"answer_id": 205481,
"author": "Sam",
"author_id": 13711,
"author_profile": "https://wordpress.stackexchange.com/users/13711",
"pm_score": 4,
"selected": true,
"text": "<p>The resolution is pretty simply. Those functions require the passwords to be properly escaped. So</p>\n\n<p><strong>Instead of this:</strong></p>\n\n<pre><code>wp_set_password('Test\"123', $userId);\n</code></pre>\n\n<p><strong>You have to do this:</strong></p>\n\n<pre><code>wp_set_password(wp_slash('Test\"123'), $userId);\n</code></pre>\n\n<p>The same goes for <code>wp_update_user()</code> and <code>wp_signon()</code>. Further information and updates on the docs may be visible from this bug report:</p>\n\n<ul>\n<li><a href=\"https://core.trac.wordpress.org/ticket/34297#ticket\">https://core.trac.wordpress.org/ticket/34297#ticket</a></li>\n</ul>\n"
}
] |
2015/10/14
|
[
"https://wordpress.stackexchange.com/questions/205459",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/13711/"
] |
So we are using a couple of custom things in our WP and one of them is a PW-Recovery form. Using this internally we're setting the password with
```
wp_set_password($password, $userId)
```
Lately we realised a problem with passwords containing the apostrophe character `"`
Setting a password with this will leave the user unable to log in using the same password that was just set. We have applied nothing to the login process and I can verify that the correct password is entered into the `wp_set_password()` function as well as the login form.
Any pointers as to where I can look for potential errors would be great. Thank you for your time.
**Update 1**
Using `wp_signon()` the user is able to login using the password `Test"123`
Using `wp-login.php?page=login` and entering the password `Test"123` will not work
currently looking for all the filters that could potentionally interfere with this...
**Update 2**
Looks to me like an undocumented wordpress feature / bug?
All plugins have been deactivated. The unmodified theme `twentefifteen` has been used. Changing the password using `wp_set_password()` changes the PW in the database. However using a password with `"` or `'` will result you being *unable* to login using `wp-login.php`. It will give you invalid credentials error.
However using the same login data and `wp_signon()` it works. I'm just clueless, probably forwarding to wp bug forums.
**Update 3**
I am using this plugin snipped to reset and test the login.
```
function resetLogin() {
// wp_set_password('Test"123', 1);
wp_update_user([
'ID' => 1,
'user_pass' => 'Test"123'
]);
}
//add_action('after_setup_theme', 'resetLogin');
function testLogin() {
var_dump(wp_signon([
'user_login' => 'admin',
'user_password' => 'Test"123',
'remember' => true
], false));
}
//add_action('after_setup_theme', 'testLogin');
```
To test I am commenting in the add\_action - resetLogin once, and deactivate it immediately again before doing anything on the page. This then immediately breaks the login on wp-login.php
|
The resolution is pretty simply. Those functions require the passwords to be properly escaped. So
**Instead of this:**
```
wp_set_password('Test"123', $userId);
```
**You have to do this:**
```
wp_set_password(wp_slash('Test"123'), $userId);
```
The same goes for `wp_update_user()` and `wp_signon()`. Further information and updates on the docs may be visible from this bug report:
* <https://core.trac.wordpress.org/ticket/34297#ticket>
|
205,460 |
<p>I have a custom post type called projects, and its archive is at <code>/projects</code>, on the archive page I get notices <code>Notice: Trying to get property of non-object</code> every time I try to access the <code>$post</code> i.e. <code>$post->post_name</code>. Is this intended behaviour? Should I just accept that and always check the availability of <code>$post</code> before using it?</p>
<pre><code>if (!empty($post)) {
// Do something with $post
}
</code></pre>
|
[
{
"answer_id": 205469,
"author": "ThemesCreator",
"author_id": 54067,
"author_profile": "https://wordpress.stackexchange.com/users/54067",
"pm_score": 1,
"selected": false,
"text": "<p>I am not sure if this exactly what is happening to you, but this is what the codex says about wp_set_password():</p>\n\n<blockquote>\n <p>Please note: This function should be used sparingly and is really only\n meant for single-time application. Leveraging this improperly in a\n plugin or theme could result in an endless loop of password resets if\n precautions are not taken to ensure it does not execute on every page\n load.</p>\n</blockquote>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_set_password/\" rel=\"nofollow\">https://developer.wordpress.org/reference/functions/wp_set_password/</a></p>\n\n<p>I think you should only use it to reset the password and then delete it.</p>\n"
},
{
"answer_id": 205481,
"author": "Sam",
"author_id": 13711,
"author_profile": "https://wordpress.stackexchange.com/users/13711",
"pm_score": 4,
"selected": true,
"text": "<p>The resolution is pretty simply. Those functions require the passwords to be properly escaped. So</p>\n\n<p><strong>Instead of this:</strong></p>\n\n<pre><code>wp_set_password('Test\"123', $userId);\n</code></pre>\n\n<p><strong>You have to do this:</strong></p>\n\n<pre><code>wp_set_password(wp_slash('Test\"123'), $userId);\n</code></pre>\n\n<p>The same goes for <code>wp_update_user()</code> and <code>wp_signon()</code>. Further information and updates on the docs may be visible from this bug report:</p>\n\n<ul>\n<li><a href=\"https://core.trac.wordpress.org/ticket/34297#ticket\">https://core.trac.wordpress.org/ticket/34297#ticket</a></li>\n</ul>\n"
}
] |
2015/10/14
|
[
"https://wordpress.stackexchange.com/questions/205460",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/8698/"
] |
I have a custom post type called projects, and its archive is at `/projects`, on the archive page I get notices `Notice: Trying to get property of non-object` every time I try to access the `$post` i.e. `$post->post_name`. Is this intended behaviour? Should I just accept that and always check the availability of `$post` before using it?
```
if (!empty($post)) {
// Do something with $post
}
```
|
The resolution is pretty simply. Those functions require the passwords to be properly escaped. So
**Instead of this:**
```
wp_set_password('Test"123', $userId);
```
**You have to do this:**
```
wp_set_password(wp_slash('Test"123'), $userId);
```
The same goes for `wp_update_user()` and `wp_signon()`. Further information and updates on the docs may be visible from this bug report:
* <https://core.trac.wordpress.org/ticket/34297#ticket>
|
205,479 |
<p>Hi I am building a news website. I am trying to automate it. </p>
<ol>
<li>News url (metabox)</li>
<li>Title</li>
<li>Content area</li>
<li>Image (featured image option on wordpress)</li>
</ol>
<p>When paste the site url I would like the other metabox to pull the data from the source
<a href="http://www.bbc.co.uk/news/technology-34527439" rel="nofollow">http://www.bbc.co.uk/news/technology-34527439</a></p>
<p>I want title and description to pulled form bbc website</p>
<ol>
<li>News url: <a href="http://www.bbc.co.uk/news/technology-34527439" rel="nofollow">http://www.bbc.co.uk/news/technology-34527439</a></li>
<li>Title: Should be fetched from <code><title></code></li>
<li>Content area: should be from <code><meta name="description".></code></li>
<li>Image: Should be first image on the content</li>
</ol>
<p>I see you can use php cURL any more pointers to wordpress would be much appreciated
<a href="http://www.php.net/manual/en/curl.examples-basic.php" rel="nofollow">http://www.php.net/manual/en/curl.examples-basic.php</a></p>
<p>Thanks</p>
|
[
{
"answer_id": 205499,
"author": "Spongsta",
"author_id": 47571,
"author_profile": "https://wordpress.stackexchange.com/users/47571",
"pm_score": -1,
"selected": false,
"text": "<p>Try this one</p>\n\n<pre><code>$tags = get_meta_tags('http://www.bbc.com/news/technology-34527439');\n$title = $tags['twitter:title'];\n$content = $tags['description'];\n$image = $tags['twitter:image:src'];\n</code></pre>\n\n<p>If you're OK using the twitter:title and the twitter:image:src. You'll also have to vet every source you're trying to pull from to see if they have a consistent meta schema. If it alters from the bbc.com site just do a switch statement on some identifier for the site you're pulling tags from to build a data array.</p>\n\n<p>Output from URL provided.</p>\n\n<pre><code> Array\n(\n [description] => The UK's National Crime Agency says cyber-attackers have stolen more than £20m from British bank accounts.\n [x-country] => us\n [x-audience] => US\n [cps_audience] => US\n [cps_changequeueid] => 259204896\n [twitter:card] => summary_large_image\n [twitter:site] => @BBCWorld\n [twitter:title] => Online attackers steal £20m from UK bank accounts - BBC News\n [twitter:description] => The UK's National Crime Agency says cyber-attackers have stolen more than £20m from British bank accounts.\n [twitter:creator] => @BBCWorld\n [twitter:image:src] => http://ichef.bbci.co.uk/news/560/cpsprodpb/37A1/production/_86114241_thinkstock.jpg\n [twitter:domain] => www.bbc.com\n [apple-mobile-web-app-title] => BBC News\n [application-name] => BBC News\n [msapplication-tileimage] => http://static.bbci.co.uk/news/1.91.0426/windows-eight-icon-144x144.png\n [msapplication-tilecolor] => #bb1919\n [mobile-web-app-capable] => yes\n [robots] => NOODP,NOYDIR\n [theme-color] => #bb1919\n [viewport] => width=device-width, initial-scale=1, user-scalable=1\n)\n</code></pre>\n\n<p>FYI - wordpress has a wrapper for cURL that's helpful</p>\n\n<pre><code>wp_remote_get( $url, $args );\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_remote_get\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/wp_remote_get</a></p>\n"
},
{
"answer_id": 323238,
"author": "John Dee",
"author_id": 131224,
"author_profile": "https://wordpress.stackexchange.com/users/131224",
"pm_score": 0,
"selected": false,
"text": "<p>Here you go:</p>\n\n<pre><code>class UrlToTitleConverter{\n\n public function convert($Url){\n $response = wp_remote_get($Url);\n if ( is_array( $response ) ) {\n $body = $response['body'];\n $title = substr($body, strpos($body, '<title>')+7);\n $title = substr($title, 0, strpos($title, '</title>'));\n }\n return $title;\n }\n}\n</code></pre>\n"
}
] |
2015/10/14
|
[
"https://wordpress.stackexchange.com/questions/205479",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/19073/"
] |
Hi I am building a news website. I am trying to automate it.
1. News url (metabox)
2. Title
3. Content area
4. Image (featured image option on wordpress)
When paste the site url I would like the other metabox to pull the data from the source
<http://www.bbc.co.uk/news/technology-34527439>
I want title and description to pulled form bbc website
1. News url: <http://www.bbc.co.uk/news/technology-34527439>
2. Title: Should be fetched from `<title>`
3. Content area: should be from `<meta name="description".>`
4. Image: Should be first image on the content
I see you can use php cURL any more pointers to wordpress would be much appreciated
<http://www.php.net/manual/en/curl.examples-basic.php>
Thanks
|
Here you go:
```
class UrlToTitleConverter{
public function convert($Url){
$response = wp_remote_get($Url);
if ( is_array( $response ) ) {
$body = $response['body'];
$title = substr($body, strpos($body, '<title>')+7);
$title = substr($title, 0, strpos($title, '</title>'));
}
return $title;
}
}
```
|
205,487 |
<p>I have inmy opinion something simple that needs to be done but I can't get it to work.</p>
<p>I have a custom post type <code>adm_project</code> with <code>rewrite => array('slug' => 'projecten')</code></p>
<pre><code>add_action( 'init', 'adm_build_projecten_post_type', 0 );
function adm_build_projecten_post_type() {
register_taxonomy(
'project_werkgebied',
'adm_project',
array(
'label' => 'Werkgebieden',
'singular_label' => 'Werkgebied',
'hierarchical' => true,
'query_var' => true,
)
);
$labels = array(
'name' => 'Projecten',
'singular_name' => 'Project',
'menu_name' => 'Projecten',
'all_items' => 'Alle Projecten',
'add_new' => 'Project toevoegen',
'add_new_item' => 'Nieuwe Project',
'edit' => 'Bewerken',
'edit_item' => 'Project bewerken',
'new_item' => 'Nieuwe Project',
'view' => 'Bekijken',
'view_item' => 'Bekijk Projecten',
'search_items' => 'Zoek Project',
'not_found' => 'Geen Project(en) gevonden',
'not_found_in_trash' => 'Geen Project(en) in prullenbak gevonden',
'parent' => '',
);
$args = array(
'label' => 'Projecten',
'labels' => $labels,
'supports' => array( 'title', 'editor', 'thumbnail', 'excerpt' ),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'show_in_admin_bar' => true,
'menu_position' => 20,
'menu_icon' => 'dashicons-hammer',
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'page',
'rewrite' => array( 'slug' => 'projecten' )
);
register_post_type( 'adm_project', $args );
}
</code></pre>
<p>In the theme I have a file name <code>archive-adm_project.php</code> which shows all the projects including working pagination as wanted.</p>
<p>What I want is that when I go to </p>
<pre><code>/projecten/%project_werkgebied%
</code></pre>
<p>it does exactly the same but only show projects that have the taxonomy that is in the url.</p>
|
[
{
"answer_id": 205489,
"author": "Gareth Gillman",
"author_id": 33936,
"author_profile": "https://wordpress.stackexchange.com/users/33936",
"pm_score": -1,
"selected": false,
"text": "<p>1) Create a template called taxonomy-TAXONOMY_NAME.php)</p>\n\n<p>2) add the following WP Query to the template</p>\n\n<pre><code>global $post;\n$term = get_the_terms($post->id, 'TAXONOMY_NAME');\n$args = array(\n 'post_type' => 'POSTTYPE_NAME',\n 'tax_query' => array(\n array(\n 'taxonomy' => 'TAXONOMY_NAME',\n 'field' => 'slug',\n 'terms' => $term,\n ),\n ),\n);\n$query = new WP_Query( $args );\n</code></pre>\n\n<p>You will need to add the rest of the query stuff (like adding a title, excerpt etc) but that should (not tested) pull in all posts from the term which is defined for the page you are on.</p>\n"
},
{
"answer_id": 205490,
"author": "Spongsta",
"author_id": 47571,
"author_profile": "https://wordpress.stackexchange.com/users/47571",
"pm_score": 2,
"selected": true,
"text": "<p>I've not seen a \"clean\" way to do this - happy to learn it from someone else if they know. </p>\n\n<p>However, the way we've managed this in the past is to setup a page whose slug is 'projecten' with a custom page template that behaves and acts like an archive page. Then add child pages for each term (make sure to select the custom taxonomy for each term child page that relates - well this is only really important depending on how you want to find the term). </p>\n\n<p>This will get you the slug structure you want. You can then use the page template you created to also find the second url parameter (or find the taxonomy that relates to the post) and add a tax_query to the WP Query to limit by taxonomy term. Or try it another way, once you have that parent/child page relationship and your slug structure complete... </p>\n\n<p>I'm sure you can figure out the best way for you to code the required output.</p>\n"
}
] |
2015/10/14
|
[
"https://wordpress.stackexchange.com/questions/205487",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81939/"
] |
I have inmy opinion something simple that needs to be done but I can't get it to work.
I have a custom post type `adm_project` with `rewrite => array('slug' => 'projecten')`
```
add_action( 'init', 'adm_build_projecten_post_type', 0 );
function adm_build_projecten_post_type() {
register_taxonomy(
'project_werkgebied',
'adm_project',
array(
'label' => 'Werkgebieden',
'singular_label' => 'Werkgebied',
'hierarchical' => true,
'query_var' => true,
)
);
$labels = array(
'name' => 'Projecten',
'singular_name' => 'Project',
'menu_name' => 'Projecten',
'all_items' => 'Alle Projecten',
'add_new' => 'Project toevoegen',
'add_new_item' => 'Nieuwe Project',
'edit' => 'Bewerken',
'edit_item' => 'Project bewerken',
'new_item' => 'Nieuwe Project',
'view' => 'Bekijken',
'view_item' => 'Bekijk Projecten',
'search_items' => 'Zoek Project',
'not_found' => 'Geen Project(en) gevonden',
'not_found_in_trash' => 'Geen Project(en) in prullenbak gevonden',
'parent' => '',
);
$args = array(
'label' => 'Projecten',
'labels' => $labels,
'supports' => array( 'title', 'editor', 'thumbnail', 'excerpt' ),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'show_in_admin_bar' => true,
'menu_position' => 20,
'menu_icon' => 'dashicons-hammer',
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'page',
'rewrite' => array( 'slug' => 'projecten' )
);
register_post_type( 'adm_project', $args );
}
```
In the theme I have a file name `archive-adm_project.php` which shows all the projects including working pagination as wanted.
What I want is that when I go to
```
/projecten/%project_werkgebied%
```
it does exactly the same but only show projects that have the taxonomy that is in the url.
|
I've not seen a "clean" way to do this - happy to learn it from someone else if they know.
However, the way we've managed this in the past is to setup a page whose slug is 'projecten' with a custom page template that behaves and acts like an archive page. Then add child pages for each term (make sure to select the custom taxonomy for each term child page that relates - well this is only really important depending on how you want to find the term).
This will get you the slug structure you want. You can then use the page template you created to also find the second url parameter (or find the taxonomy that relates to the post) and add a tax\_query to the WP Query to limit by taxonomy term. Or try it another way, once you have that parent/child page relationship and your slug structure complete...
I'm sure you can figure out the best way for you to code the required output.
|
205,573 |
<p>I have a very simple shortcode to print some text using pre tags</p>
<pre><code>function term_shortcode( $atts, $content = null )
{
return "<pre>" . htmlentities($content) . "</pre>";
}
add_shortcode( 'term', 'term_shortcode' );
</code></pre>
<p>But while using the shortcode, if there is an arrow symbol in the content, the output gets terribly screwed up. The shortcode picks up content beyond the shortcode end.</p>
<p>Here is an example</p>
<pre><code>[term]
ABC < DEF
[/term]
MORE CONTENT. This is also taken up by the above shortcode.
</code></pre>
<p>If the left arrow character "<" is removed, it outputs fine.</p>
<p>How do I fix this ?</p>
<p>Visual editor is fully disabled. Using just text editor and typing pure html.</p>
|
[
{
"answer_id": 205584,
"author": "Benjamin Love",
"author_id": 81800,
"author_profile": "https://wordpress.stackexchange.com/users/81800",
"pm_score": 1,
"selected": false,
"text": "<p>I would try using <a href=\"http://php.net/manual/en/function.htmlspecialchars.php\" rel=\"nofollow\"><code>htmlspecialchars()</code></a> instead of <code>htmlentities()</code> and see if that solves the issue. </p>\n"
},
{
"answer_id": 205588,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>Short codes should not be used as a replacement to html tags. In this case if you want to use <code><pre></code> just use it, don't invent a shortcode for it.</p>\n\n<p>The usage of \"<\" breaks the validity of the html in the content which might break all kinds of parser and probably break the shortcodes parser (and will almost for sure break it even harder in versions 4.4+).</p>\n\n<p>In your case, the opposite of what you are trying to do is probably the better approach. Instead of encoding html elements, you should assume they are already encoded and you decode them to put them into a <code><pre></code>. This way you will also be able to use the visual editor for the shortcode.</p>\n"
},
{
"answer_id": 205643,
"author": "bonger",
"author_id": 57034,
"author_profile": "https://wordpress.stackexchange.com/users/57034",
"pm_score": 3,
"selected": true,
"text": "<p>This issue was introduced in WP 4.2.3 with the introduction of the <code>do_shortcodes_in_html_tags()</code> function, which does a HTML parse of content to protect against content containing shortcodes authored by untrustworthy contributors/authors who by specially crafting shortcode attributes can create XSS exploits.</p>\n\n<p>If that security situation doesn't apply to you and you only want this to work on your site then a simple workaround is to replace the default <code>do_shortcode</code> filter with your own version, with the call to <code>do_shortcodes_in_html_tags()</code> removed, eg</p>\n\n<pre><code>add_action( 'init', function () {\n remove_filter( 'the_content', 'do_shortcode', 11 );\n add_filter( 'the_content', function ( $content ) {\n global $shortcode_tags;\n\n if ( false === strpos( $content, '[' ) ) {\n return $content;\n }\n\n if (empty($shortcode_tags) || !is_array($shortcode_tags))\n return $content;\n\n $tagnames = array_keys($shortcode_tags);\n $tagregexp = join( '|', array_map('preg_quote', $tagnames) );\n $pattern = \"/\\\\[($tagregexp)/s\";\n\n if ( 1 !== preg_match( $pattern, $content ) ) {\n // Avoids parsing HTML when there are no shortcodes or embeds anyway.\n return $content;\n }\n\n // Avoid check for users without unfiltered html: $content = do_shortcodes_in_html_tags( $content, $ignore_html );\n\n $pattern = get_shortcode_regex();\n $content = preg_replace_callback( \"/$pattern/s\", 'do_shortcode_tag', $content );\n\n // Always restore square braces so we don't break things like <!--[if IE ]>\n // Not needed if do_shortcodes_in_html_tags not called: $content = unescape_invalid_shortcodes( $content );\n\n return $content;\n }, 11 );\n} );\n</code></pre>\n\n<p>On my testing you may also have to contend with <code>wpautop()</code> issues as well though...</p>\n"
}
] |
2015/10/15
|
[
"https://wordpress.stackexchange.com/questions/205573",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/32902/"
] |
I have a very simple shortcode to print some text using pre tags
```
function term_shortcode( $atts, $content = null )
{
return "<pre>" . htmlentities($content) . "</pre>";
}
add_shortcode( 'term', 'term_shortcode' );
```
But while using the shortcode, if there is an arrow symbol in the content, the output gets terribly screwed up. The shortcode picks up content beyond the shortcode end.
Here is an example
```
[term]
ABC < DEF
[/term]
MORE CONTENT. This is also taken up by the above shortcode.
```
If the left arrow character "<" is removed, it outputs fine.
How do I fix this ?
Visual editor is fully disabled. Using just text editor and typing pure html.
|
This issue was introduced in WP 4.2.3 with the introduction of the `do_shortcodes_in_html_tags()` function, which does a HTML parse of content to protect against content containing shortcodes authored by untrustworthy contributors/authors who by specially crafting shortcode attributes can create XSS exploits.
If that security situation doesn't apply to you and you only want this to work on your site then a simple workaround is to replace the default `do_shortcode` filter with your own version, with the call to `do_shortcodes_in_html_tags()` removed, eg
```
add_action( 'init', function () {
remove_filter( 'the_content', 'do_shortcode', 11 );
add_filter( 'the_content', function ( $content ) {
global $shortcode_tags;
if ( false === strpos( $content, '[' ) ) {
return $content;
}
if (empty($shortcode_tags) || !is_array($shortcode_tags))
return $content;
$tagnames = array_keys($shortcode_tags);
$tagregexp = join( '|', array_map('preg_quote', $tagnames) );
$pattern = "/\\[($tagregexp)/s";
if ( 1 !== preg_match( $pattern, $content ) ) {
// Avoids parsing HTML when there are no shortcodes or embeds anyway.
return $content;
}
// Avoid check for users without unfiltered html: $content = do_shortcodes_in_html_tags( $content, $ignore_html );
$pattern = get_shortcode_regex();
$content = preg_replace_callback( "/$pattern/s", 'do_shortcode_tag', $content );
// Always restore square braces so we don't break things like <!--[if IE ]>
// Not needed if do_shortcodes_in_html_tags not called: $content = unescape_invalid_shortcodes( $content );
return $content;
}, 11 );
} );
```
On my testing you may also have to contend with `wpautop()` issues as well though...
|
205,577 |
<p>I want to allow HTML into a plugin input field via a user, I am using the Settings API, but it strips everything HTML out. - Code below -any pointers?</p>
<pre><code>function plugin_settings(){
register_Setting(
'ng_settings_group',
'my_settings',
'plugin_prefix validate_input'
);
add_settings_section(
'my_section',
'My Settings',
'plugin_prefix my_section_callback',
'plugin'
);
add_settings_field(
'ng_menu_html',
'HTML Carat',
'plugin_prefix ng_html_callback',
'plugin',
'my_section'
);
}
add_action('admin_init', 'plugin_prefix plugin_settings');
function ng_html_callback() {
$options = get_option( 'my_settings' );
if( !isset( $options['ng_html'] ) ) $options['ng_html'] = '';
echo '<label for="ng_html">' . esc_attr_e( 'Insert additional HTML','plugin') . '</label>';
echo '<input type="text" id="ng_html" name="my_settings[ng_html]" value="' . $options['ng_html'] . '" placeholder="Add HTML">';
}
</code></pre>
|
[
{
"answer_id": 205584,
"author": "Benjamin Love",
"author_id": 81800,
"author_profile": "https://wordpress.stackexchange.com/users/81800",
"pm_score": 1,
"selected": false,
"text": "<p>I would try using <a href=\"http://php.net/manual/en/function.htmlspecialchars.php\" rel=\"nofollow\"><code>htmlspecialchars()</code></a> instead of <code>htmlentities()</code> and see if that solves the issue. </p>\n"
},
{
"answer_id": 205588,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>Short codes should not be used as a replacement to html tags. In this case if you want to use <code><pre></code> just use it, don't invent a shortcode for it.</p>\n\n<p>The usage of \"<\" breaks the validity of the html in the content which might break all kinds of parser and probably break the shortcodes parser (and will almost for sure break it even harder in versions 4.4+).</p>\n\n<p>In your case, the opposite of what you are trying to do is probably the better approach. Instead of encoding html elements, you should assume they are already encoded and you decode them to put them into a <code><pre></code>. This way you will also be able to use the visual editor for the shortcode.</p>\n"
},
{
"answer_id": 205643,
"author": "bonger",
"author_id": 57034,
"author_profile": "https://wordpress.stackexchange.com/users/57034",
"pm_score": 3,
"selected": true,
"text": "<p>This issue was introduced in WP 4.2.3 with the introduction of the <code>do_shortcodes_in_html_tags()</code> function, which does a HTML parse of content to protect against content containing shortcodes authored by untrustworthy contributors/authors who by specially crafting shortcode attributes can create XSS exploits.</p>\n\n<p>If that security situation doesn't apply to you and you only want this to work on your site then a simple workaround is to replace the default <code>do_shortcode</code> filter with your own version, with the call to <code>do_shortcodes_in_html_tags()</code> removed, eg</p>\n\n<pre><code>add_action( 'init', function () {\n remove_filter( 'the_content', 'do_shortcode', 11 );\n add_filter( 'the_content', function ( $content ) {\n global $shortcode_tags;\n\n if ( false === strpos( $content, '[' ) ) {\n return $content;\n }\n\n if (empty($shortcode_tags) || !is_array($shortcode_tags))\n return $content;\n\n $tagnames = array_keys($shortcode_tags);\n $tagregexp = join( '|', array_map('preg_quote', $tagnames) );\n $pattern = \"/\\\\[($tagregexp)/s\";\n\n if ( 1 !== preg_match( $pattern, $content ) ) {\n // Avoids parsing HTML when there are no shortcodes or embeds anyway.\n return $content;\n }\n\n // Avoid check for users without unfiltered html: $content = do_shortcodes_in_html_tags( $content, $ignore_html );\n\n $pattern = get_shortcode_regex();\n $content = preg_replace_callback( \"/$pattern/s\", 'do_shortcode_tag', $content );\n\n // Always restore square braces so we don't break things like <!--[if IE ]>\n // Not needed if do_shortcodes_in_html_tags not called: $content = unescape_invalid_shortcodes( $content );\n\n return $content;\n }, 11 );\n} );\n</code></pre>\n\n<p>On my testing you may also have to contend with <code>wpautop()</code> issues as well though...</p>\n"
}
] |
2015/10/15
|
[
"https://wordpress.stackexchange.com/questions/205577",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70831/"
] |
I want to allow HTML into a plugin input field via a user, I am using the Settings API, but it strips everything HTML out. - Code below -any pointers?
```
function plugin_settings(){
register_Setting(
'ng_settings_group',
'my_settings',
'plugin_prefix validate_input'
);
add_settings_section(
'my_section',
'My Settings',
'plugin_prefix my_section_callback',
'plugin'
);
add_settings_field(
'ng_menu_html',
'HTML Carat',
'plugin_prefix ng_html_callback',
'plugin',
'my_section'
);
}
add_action('admin_init', 'plugin_prefix plugin_settings');
function ng_html_callback() {
$options = get_option( 'my_settings' );
if( !isset( $options['ng_html'] ) ) $options['ng_html'] = '';
echo '<label for="ng_html">' . esc_attr_e( 'Insert additional HTML','plugin') . '</label>';
echo '<input type="text" id="ng_html" name="my_settings[ng_html]" value="' . $options['ng_html'] . '" placeholder="Add HTML">';
}
```
|
This issue was introduced in WP 4.2.3 with the introduction of the `do_shortcodes_in_html_tags()` function, which does a HTML parse of content to protect against content containing shortcodes authored by untrustworthy contributors/authors who by specially crafting shortcode attributes can create XSS exploits.
If that security situation doesn't apply to you and you only want this to work on your site then a simple workaround is to replace the default `do_shortcode` filter with your own version, with the call to `do_shortcodes_in_html_tags()` removed, eg
```
add_action( 'init', function () {
remove_filter( 'the_content', 'do_shortcode', 11 );
add_filter( 'the_content', function ( $content ) {
global $shortcode_tags;
if ( false === strpos( $content, '[' ) ) {
return $content;
}
if (empty($shortcode_tags) || !is_array($shortcode_tags))
return $content;
$tagnames = array_keys($shortcode_tags);
$tagregexp = join( '|', array_map('preg_quote', $tagnames) );
$pattern = "/\\[($tagregexp)/s";
if ( 1 !== preg_match( $pattern, $content ) ) {
// Avoids parsing HTML when there are no shortcodes or embeds anyway.
return $content;
}
// Avoid check for users without unfiltered html: $content = do_shortcodes_in_html_tags( $content, $ignore_html );
$pattern = get_shortcode_regex();
$content = preg_replace_callback( "/$pattern/s", 'do_shortcode_tag', $content );
// Always restore square braces so we don't break things like <!--[if IE ]>
// Not needed if do_shortcodes_in_html_tags not called: $content = unescape_invalid_shortcodes( $content );
return $content;
}, 11 );
} );
```
On my testing you may also have to contend with `wpautop()` issues as well though...
|
205,601 |
<p>I'm currently building a WordPress theme where my page consists of widgets. One widget is a part of the page. I'd like to be able to use anchor links with them, and to do this, I would like to output the widget's title as an ID of the widget. </p>
<p>I know the widget has and ID already but it results in ugly anchor links - the anchor link would be <code>url.com/#text-2</code>. I would like it to be <code>url.com/#about</code>.</p>
<p>In the source code, this is the default HTML output:</p>
<p><code><div id="text-2" class="widget-container widget_text"></code></p>
<p>This is the HTML output I aim for:</p>
<p><code><div id="text-2 about" class="widget-container widget_text"></code></p>
<p>How do I achieve this?</p>
<p>Thanks in advance!</p>
<hr>
<p>Update:</p>
<p>It seems an HTML element can't have two ID's.</p>
<p>Is it possible to instead add an <code><a></code> element within the widget's <code>widget-title</code> where the ID of the <code><a></code> is the widget's title? </p>
<p>So the HTML output looks like this:
<code><h2 class="widget-title"><a id="about">About</a></h2></code></p>
|
[
{
"answer_id": 205604,
"author": "Gareth Gillman",
"author_id": 33936,
"author_profile": "https://wordpress.stackexchange.com/users/33936",
"pm_score": 1,
"selected": true,
"text": "<p>Yes you can add an around the title of the widget, you do this in the register_sidebar code which you would put in your functions.php</p>\n\n<pre><code>add_action( 'widgets_init', 'theme_register_sidebars' );\nfunction theme_register_sidebars() {\n register_sidebar(\n array(\n 'id' => 'mysidebar-sidebar',\n 'name' => __( 'My Sidebar', 'themename' ),\n 'description' => __( 'Widgets for my sidebar', 'themename' ),\n 'before_widget' => '<div class=\"widget\">',\n 'after_widget' => '</div>',\n 'before_title' => '<h2 class=\"widget-title\"><a id=\"about\">',\n 'after_title' => '</a></h2>'\n )\n );\n}\n</code></pre>\n\n<p>You create the new \"widget area\" or sidebar which you then put in actual widget in.</p>\n\n<p>jQuery Version (not tested):</p>\n\n<pre><code>jQuery(document).ready(function($){\n $( '#id h2.widget-title').wrapInner( \"<a id=\"about\"></a>\" );\n});\n</code></pre>\n\n<p>You would then add the jQuery either to a JS file and <a href=\"https://codex.wordpress.org/Function_Reference/wp_enqueue_script\" rel=\"nofollow\">Enqueue</a> it or put it into wp_footer using the filter of the same name (<a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_footer\" rel=\"nofollow\">link</a>)</p>\n"
},
{
"answer_id": 254050,
"author": "Anselmo Coelho",
"author_id": 111811,
"author_profile": "https://wordpress.stackexchange.com/users/111811",
"pm_score": -1,
"selected": false,
"text": "<p>I was searching for a simplier way and I turned around by just adding a <code><span id=\"youranchornametag\">First words/text of the element</span></code>\nNow you call it from where ever you like <code>http://.../#youranchornametag</code>.</p>\n"
}
] |
2015/10/15
|
[
"https://wordpress.stackexchange.com/questions/205601",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82005/"
] |
I'm currently building a WordPress theme where my page consists of widgets. One widget is a part of the page. I'd like to be able to use anchor links with them, and to do this, I would like to output the widget's title as an ID of the widget.
I know the widget has and ID already but it results in ugly anchor links - the anchor link would be `url.com/#text-2`. I would like it to be `url.com/#about`.
In the source code, this is the default HTML output:
`<div id="text-2" class="widget-container widget_text">`
This is the HTML output I aim for:
`<div id="text-2 about" class="widget-container widget_text">`
How do I achieve this?
Thanks in advance!
---
Update:
It seems an HTML element can't have two ID's.
Is it possible to instead add an `<a>` element within the widget's `widget-title` where the ID of the `<a>` is the widget's title?
So the HTML output looks like this:
`<h2 class="widget-title"><a id="about">About</a></h2>`
|
Yes you can add an around the title of the widget, you do this in the register\_sidebar code which you would put in your functions.php
```
add_action( 'widgets_init', 'theme_register_sidebars' );
function theme_register_sidebars() {
register_sidebar(
array(
'id' => 'mysidebar-sidebar',
'name' => __( 'My Sidebar', 'themename' ),
'description' => __( 'Widgets for my sidebar', 'themename' ),
'before_widget' => '<div class="widget">',
'after_widget' => '</div>',
'before_title' => '<h2 class="widget-title"><a id="about">',
'after_title' => '</a></h2>'
)
);
}
```
You create the new "widget area" or sidebar which you then put in actual widget in.
jQuery Version (not tested):
```
jQuery(document).ready(function($){
$( '#id h2.widget-title').wrapInner( "<a id="about"></a>" );
});
```
You would then add the jQuery either to a JS file and [Enqueue](https://codex.wordpress.org/Function_Reference/wp_enqueue_script) it or put it into wp\_footer using the filter of the same name ([link](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_footer))
|
205,615 |
<p>I'm wanting to migrate a site from one WordPress multisite install (Dev) to another (Staging). I've read these posts </p>
<p><a href="https://wordpress.stackexchange.com/questions/10538/how-to-migrate-wordpress-blogs-into-multisite-without-using-the-gui-import-expor">How to migrate Wordpress Blogs into Multisite without using the GUI-Import/Export Feature</a>
which is about migrating a single site (rather than a site in an existing multisite) </p>
<p>and this one
<a href="https://wordpress.stackexchange.com/questions/165486/copy-site-from-one-multisite-to-another">Copy site from one multisite to another</a>
which doesn't do a complete job (i.e. you have to deal with menus, etc separately).</p>
<p>Any improvements on either of these answers for migrating a site from one WordPress multisite install to another.</p>
|
[
{
"answer_id": 205604,
"author": "Gareth Gillman",
"author_id": 33936,
"author_profile": "https://wordpress.stackexchange.com/users/33936",
"pm_score": 1,
"selected": true,
"text": "<p>Yes you can add an around the title of the widget, you do this in the register_sidebar code which you would put in your functions.php</p>\n\n<pre><code>add_action( 'widgets_init', 'theme_register_sidebars' );\nfunction theme_register_sidebars() {\n register_sidebar(\n array(\n 'id' => 'mysidebar-sidebar',\n 'name' => __( 'My Sidebar', 'themename' ),\n 'description' => __( 'Widgets for my sidebar', 'themename' ),\n 'before_widget' => '<div class=\"widget\">',\n 'after_widget' => '</div>',\n 'before_title' => '<h2 class=\"widget-title\"><a id=\"about\">',\n 'after_title' => '</a></h2>'\n )\n );\n}\n</code></pre>\n\n<p>You create the new \"widget area\" or sidebar which you then put in actual widget in.</p>\n\n<p>jQuery Version (not tested):</p>\n\n<pre><code>jQuery(document).ready(function($){\n $( '#id h2.widget-title').wrapInner( \"<a id=\"about\"></a>\" );\n});\n</code></pre>\n\n<p>You would then add the jQuery either to a JS file and <a href=\"https://codex.wordpress.org/Function_Reference/wp_enqueue_script\" rel=\"nofollow\">Enqueue</a> it or put it into wp_footer using the filter of the same name (<a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_footer\" rel=\"nofollow\">link</a>)</p>\n"
},
{
"answer_id": 254050,
"author": "Anselmo Coelho",
"author_id": 111811,
"author_profile": "https://wordpress.stackexchange.com/users/111811",
"pm_score": -1,
"selected": false,
"text": "<p>I was searching for a simplier way and I turned around by just adding a <code><span id=\"youranchornametag\">First words/text of the element</span></code>\nNow you call it from where ever you like <code>http://.../#youranchornametag</code>.</p>\n"
}
] |
2015/10/15
|
[
"https://wordpress.stackexchange.com/questions/205615",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48904/"
] |
I'm wanting to migrate a site from one WordPress multisite install (Dev) to another (Staging). I've read these posts
[How to migrate Wordpress Blogs into Multisite without using the GUI-Import/Export Feature](https://wordpress.stackexchange.com/questions/10538/how-to-migrate-wordpress-blogs-into-multisite-without-using-the-gui-import-expor)
which is about migrating a single site (rather than a site in an existing multisite)
and this one
[Copy site from one multisite to another](https://wordpress.stackexchange.com/questions/165486/copy-site-from-one-multisite-to-another)
which doesn't do a complete job (i.e. you have to deal with menus, etc separately).
Any improvements on either of these answers for migrating a site from one WordPress multisite install to another.
|
Yes you can add an around the title of the widget, you do this in the register\_sidebar code which you would put in your functions.php
```
add_action( 'widgets_init', 'theme_register_sidebars' );
function theme_register_sidebars() {
register_sidebar(
array(
'id' => 'mysidebar-sidebar',
'name' => __( 'My Sidebar', 'themename' ),
'description' => __( 'Widgets for my sidebar', 'themename' ),
'before_widget' => '<div class="widget">',
'after_widget' => '</div>',
'before_title' => '<h2 class="widget-title"><a id="about">',
'after_title' => '</a></h2>'
)
);
}
```
You create the new "widget area" or sidebar which you then put in actual widget in.
jQuery Version (not tested):
```
jQuery(document).ready(function($){
$( '#id h2.widget-title').wrapInner( "<a id="about"></a>" );
});
```
You would then add the jQuery either to a JS file and [Enqueue](https://codex.wordpress.org/Function_Reference/wp_enqueue_script) it or put it into wp\_footer using the filter of the same name ([link](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_footer))
|
205,617 |
<p>The content of the post is contained in a <code>div</code> which is centered in the page and thus any images in the post would be constrained to the width of that <code>div</code>. The image below illustrates what I would like to achieve. </p>
<p>A great example of this can be found in the following link but I can't figure out how the JavaScript does it. </p>
<p><a href="https://theintercept.com/drone-papers/manhunting-in-the-hindu-kush/" rel="nofollow noreferrer">https://theintercept.com/drone-papers/manhunting-in-the-hindu-kush/</a></p>
<p><a href="https://i.stack.imgur.com/lWD2P.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lWD2P.jpg" alt="enter image description here"></a></p>
|
[
{
"answer_id": 205604,
"author": "Gareth Gillman",
"author_id": 33936,
"author_profile": "https://wordpress.stackexchange.com/users/33936",
"pm_score": 1,
"selected": true,
"text": "<p>Yes you can add an around the title of the widget, you do this in the register_sidebar code which you would put in your functions.php</p>\n\n<pre><code>add_action( 'widgets_init', 'theme_register_sidebars' );\nfunction theme_register_sidebars() {\n register_sidebar(\n array(\n 'id' => 'mysidebar-sidebar',\n 'name' => __( 'My Sidebar', 'themename' ),\n 'description' => __( 'Widgets for my sidebar', 'themename' ),\n 'before_widget' => '<div class=\"widget\">',\n 'after_widget' => '</div>',\n 'before_title' => '<h2 class=\"widget-title\"><a id=\"about\">',\n 'after_title' => '</a></h2>'\n )\n );\n}\n</code></pre>\n\n<p>You create the new \"widget area\" or sidebar which you then put in actual widget in.</p>\n\n<p>jQuery Version (not tested):</p>\n\n<pre><code>jQuery(document).ready(function($){\n $( '#id h2.widget-title').wrapInner( \"<a id=\"about\"></a>\" );\n});\n</code></pre>\n\n<p>You would then add the jQuery either to a JS file and <a href=\"https://codex.wordpress.org/Function_Reference/wp_enqueue_script\" rel=\"nofollow\">Enqueue</a> it or put it into wp_footer using the filter of the same name (<a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_footer\" rel=\"nofollow\">link</a>)</p>\n"
},
{
"answer_id": 254050,
"author": "Anselmo Coelho",
"author_id": 111811,
"author_profile": "https://wordpress.stackexchange.com/users/111811",
"pm_score": -1,
"selected": false,
"text": "<p>I was searching for a simplier way and I turned around by just adding a <code><span id=\"youranchornametag\">First words/text of the element</span></code>\nNow you call it from where ever you like <code>http://.../#youranchornametag</code>.</p>\n"
}
] |
2015/10/15
|
[
"https://wordpress.stackexchange.com/questions/205617",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104703/"
] |
The content of the post is contained in a `div` which is centered in the page and thus any images in the post would be constrained to the width of that `div`. The image below illustrates what I would like to achieve.
A great example of this can be found in the following link but I can't figure out how the JavaScript does it.
<https://theintercept.com/drone-papers/manhunting-in-the-hindu-kush/>
[](https://i.stack.imgur.com/lWD2P.jpg)
|
Yes you can add an around the title of the widget, you do this in the register\_sidebar code which you would put in your functions.php
```
add_action( 'widgets_init', 'theme_register_sidebars' );
function theme_register_sidebars() {
register_sidebar(
array(
'id' => 'mysidebar-sidebar',
'name' => __( 'My Sidebar', 'themename' ),
'description' => __( 'Widgets for my sidebar', 'themename' ),
'before_widget' => '<div class="widget">',
'after_widget' => '</div>',
'before_title' => '<h2 class="widget-title"><a id="about">',
'after_title' => '</a></h2>'
)
);
}
```
You create the new "widget area" or sidebar which you then put in actual widget in.
jQuery Version (not tested):
```
jQuery(document).ready(function($){
$( '#id h2.widget-title').wrapInner( "<a id="about"></a>" );
});
```
You would then add the jQuery either to a JS file and [Enqueue](https://codex.wordpress.org/Function_Reference/wp_enqueue_script) it or put it into wp\_footer using the filter of the same name ([link](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_footer))
|
205,632 |
<p>When utilizing shortcode (plugin, etc.) near the top of the page, the plugin shortcode displays in the preview. Is there a way to hide text within brackets [text like this] from a preview on a recent posts type of page?</p>
<p>The following example shows the shortcode within a blog post preview:</p>
<p><a href="https://i.stack.imgur.com/C3kqh.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/C3kqh.jpg" alt="Example of Brackets within Preview"></a></p>
|
[
{
"answer_id": 205635,
"author": "beta208",
"author_id": 15360,
"author_profile": "https://wordpress.stackexchange.com/users/15360",
"pm_score": 0,
"selected": false,
"text": "<p>Excerpt was not showing but would do the trick. On the edit post page, accessing 'Screen Options' and selecting 'Excerpt' allows one to manually fill the excerpt.</p>\n"
},
{
"answer_id": 205638,
"author": "Ivijan Stefan Stipić",
"author_id": 82023,
"author_profile": "https://wordpress.stackexchange.com/users/82023",
"pm_score": 3,
"selected": true,
"text": "<p>You can do with PHP. Just remove part where is <code>get_content()</code> and add this:</p>\n\n<pre><code><?php \n $content=get_the_content();\n $content = preg_replace('#\\[[^\\]]+\\]#', '',$content);\n echo apply_filters('the_content', $content);\n ?>\n</code></pre>\n\n<p>That is regular expression added inside content. This regex will remove all tags inside content.</p>\n"
},
{
"answer_id": 210042,
"author": "Abhik",
"author_id": 26991,
"author_profile": "https://wordpress.stackexchange.com/users/26991",
"pm_score": 2,
"selected": false,
"text": "<p>Use this instead if you don't wanna manually write excerpts every time: </p>\n\n<pre><code>function wpse205632_filter_excerpt( $excerpt ) {\n\n $excerpt = strip_shortcodes( $excerpt );\n\n return $excerpt;\n}\nadd_filter( 'get_the_excerpt', 'wpse205632_filter_excerpt' ); \n</code></pre>\n\n<p>Just add this snippet in <code>functions.php</code> and you are good to go.</p>\n"
},
{
"answer_id": 327741,
"author": "Aleksandrs Krasnovskis",
"author_id": 136487,
"author_profile": "https://wordpress.stackexchange.com/users/136487",
"pm_score": 0,
"selected": false,
"text": "<p>This is what I used to get content as excerpt with limited amount of words, and exclude shortcodes from Visual Composer</p>\n\n<pre><code><?php $content=get_the_content(); $content = preg_replace('#\\[[^\\]]+\\]#', '',$trimmed_content = wp_trim_words($content, 20)); echo apply_filters('the_content', $content, $trimmed_content); ?\n</code></pre>\n"
}
] |
2015/10/15
|
[
"https://wordpress.stackexchange.com/questions/205632",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/15360/"
] |
When utilizing shortcode (plugin, etc.) near the top of the page, the plugin shortcode displays in the preview. Is there a way to hide text within brackets [text like this] from a preview on a recent posts type of page?
The following example shows the shortcode within a blog post preview:
[](https://i.stack.imgur.com/C3kqh.jpg)
|
You can do with PHP. Just remove part where is `get_content()` and add this:
```
<?php
$content=get_the_content();
$content = preg_replace('#\[[^\]]+\]#', '',$content);
echo apply_filters('the_content', $content);
?>
```
That is regular expression added inside content. This regex will remove all tags inside content.
|
205,684 |
<p>I'm using the comments_template() <a href="https://codex.wordpress.org/Function_Reference/comments_template" rel="nofollow">function</a> to echo out my comments template in the sidebar of each post. This is a requirement of the project.</p>
<p>It has been requested that I only echo out the three most recent comments in the sidebar for each post. </p>
<p>I've searched high and wide for a solution here and can't find anything. </p>
<p>Is there a function I can pop into my functions.php file to echo out only the most three recent comments for each post?</p>
<p>If it could include some jquery to add a "read more" link that opens up the rest of the comments that would be great, but it's not essential.</p>
|
[
{
"answer_id": 205635,
"author": "beta208",
"author_id": 15360,
"author_profile": "https://wordpress.stackexchange.com/users/15360",
"pm_score": 0,
"selected": false,
"text": "<p>Excerpt was not showing but would do the trick. On the edit post page, accessing 'Screen Options' and selecting 'Excerpt' allows one to manually fill the excerpt.</p>\n"
},
{
"answer_id": 205638,
"author": "Ivijan Stefan Stipić",
"author_id": 82023,
"author_profile": "https://wordpress.stackexchange.com/users/82023",
"pm_score": 3,
"selected": true,
"text": "<p>You can do with PHP. Just remove part where is <code>get_content()</code> and add this:</p>\n\n<pre><code><?php \n $content=get_the_content();\n $content = preg_replace('#\\[[^\\]]+\\]#', '',$content);\n echo apply_filters('the_content', $content);\n ?>\n</code></pre>\n\n<p>That is regular expression added inside content. This regex will remove all tags inside content.</p>\n"
},
{
"answer_id": 210042,
"author": "Abhik",
"author_id": 26991,
"author_profile": "https://wordpress.stackexchange.com/users/26991",
"pm_score": 2,
"selected": false,
"text": "<p>Use this instead if you don't wanna manually write excerpts every time: </p>\n\n<pre><code>function wpse205632_filter_excerpt( $excerpt ) {\n\n $excerpt = strip_shortcodes( $excerpt );\n\n return $excerpt;\n}\nadd_filter( 'get_the_excerpt', 'wpse205632_filter_excerpt' ); \n</code></pre>\n\n<p>Just add this snippet in <code>functions.php</code> and you are good to go.</p>\n"
},
{
"answer_id": 327741,
"author": "Aleksandrs Krasnovskis",
"author_id": 136487,
"author_profile": "https://wordpress.stackexchange.com/users/136487",
"pm_score": 0,
"selected": false,
"text": "<p>This is what I used to get content as excerpt with limited amount of words, and exclude shortcodes from Visual Composer</p>\n\n<pre><code><?php $content=get_the_content(); $content = preg_replace('#\\[[^\\]]+\\]#', '',$trimmed_content = wp_trim_words($content, 20)); echo apply_filters('the_content', $content, $trimmed_content); ?\n</code></pre>\n"
}
] |
2015/10/16
|
[
"https://wordpress.stackexchange.com/questions/205684",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78294/"
] |
I'm using the comments\_template() [function](https://codex.wordpress.org/Function_Reference/comments_template) to echo out my comments template in the sidebar of each post. This is a requirement of the project.
It has been requested that I only echo out the three most recent comments in the sidebar for each post.
I've searched high and wide for a solution here and can't find anything.
Is there a function I can pop into my functions.php file to echo out only the most three recent comments for each post?
If it could include some jquery to add a "read more" link that opens up the rest of the comments that would be great, but it's not essential.
|
You can do with PHP. Just remove part where is `get_content()` and add this:
```
<?php
$content=get_the_content();
$content = preg_replace('#\[[^\]]+\]#', '',$content);
echo apply_filters('the_content', $content);
?>
```
That is regular expression added inside content. This regex will remove all tags inside content.
|
205,696 |
<p>I need to delay AngularJS scripts from running so I can set up my application first. I need to initialize the application with ng-app="app". I want to add that attribute to the <strong>< body ></strong></p>
<p>< body ng-app="app" >< /body ></p>
<pre><code> wp_enqueue_script('plugin-setup', plugin_dir_url( __FILE__ ).'js/plugin-setup.js', array('jquery'), null, true);
</code></pre>
<p><strong>plugin-set.js</strong></p>
<pre><code>document.addEventListener("DOMContentLoaded", function(event) {
document.getElementsByTagName("body")[0].setAttribute("ng-app", "app");
});
</code></pre>
<p>After that is set up I can run my Angular Scripts:</p>
<pre><code>class pluginClass{
function pluginInit(){
add_action( 'wp_enqueue_scripts', array( $this, 'scriptThings' ) );
}
function scriptThings(){
wp_enqueue_script('angular-core', plugin_dir_url( __FILE__ ).'js/vendor/angular/angular.js', array('jquery'), null, true);
wp_enqueue_script('angular-resource', plugin_dir_url( __FILE__ ).'js/vendor/angular-resource/angular-resource.js', array('jquery'), null, true);
wp_enqueue_script('app', plugin_dir_url( __FILE__ ).'js/app.js', array(), null, true);
wp_enqueue_script('app-controller', plugin_dir_url( __FILE__ ).'js/controllers/app_controller.js', array(), null, true);
wp_enqueue_script('imagetile-factory', plugin_dir_url( __FILE__ ).'js/resource/imageTile_factory.js', array(), null, true);
}
}
$my_class = new pluginClass;
add_action('init', array($my_class, 'pluginInit'));
</code></pre>
<p>Is there a way to delay the Angular scripts from loading within my <strong>plugin.php*</strong>?</p>
|
[
{
"answer_id": 205699,
"author": "Gareth Gillman",
"author_id": 33936,
"author_profile": "https://wordpress.stackexchange.com/users/33936",
"pm_score": 1,
"selected": false,
"text": "<p>change the action to:</p>\n\n<pre><code>add_action('init', array($my_class, 'pluginInit','40'));\n</code></pre>\n\n<p>That tells the action to run much later in the queue, you could also check if the other script has been enqueued by using <code>wp_script_is</code> e.g.</p>\n\n<pre><code> $handle = 'plugin-setup.js';\n $list = 'enqueued';\n if (wp_script_is( $handle, $list )) {\n // enqueue scripts here\n }\n</code></pre>\n\n<p>Hope that points you in the right direction</p>\n"
},
{
"answer_id": 205701,
"author": "Robert hue",
"author_id": 22461,
"author_profile": "https://wordpress.stackexchange.com/users/22461",
"pm_score": 2,
"selected": false,
"text": "<p>I think you should use <code>setTimeout</code> to pause the execution of the script without blocking the UI.</p>\n\n<pre><code>setTimeout(function(){\n\n //your code to be executed after 2 seconds\n\n}, 2000);\n</code></pre>\n\n<p>So your code will become.</p>\n\n<pre><code>setTimeout(function(){\n\n document.addEventListener(\"DOMContentLoaded\", function(event) {\n document.getElementsByTagName(\"body\")[0].setAttribute(\"ng-app\", \"app\");\n }); \n\n}, 2000);\n</code></pre>\n\n<p>This will delay script execution for 2 seconds. You can change this value based on your requirements.</p>\n\n<h2>EDIT</h2>\n\n<p>On second thought, I think it would be better if you check for AngularJS is loaded in the current page before initializing your app.</p>\n\n<pre><code>function checkAngular() {\n if ( window.angular ) {\n\n // your code to be executed\n document.addEventListener(\"DOMContentLoaded\", function(event) {\n document.getElementsByTagName(\"body\")[0].setAttribute(\"ng-app\", \"app\");\n }); \n\n } else {\n window.setTimeout( checkAngular, 1000 );\n }\n}\ncheckAngular();\n</code></pre>\n\n<p>So what does this code do? It checks if AngularJS is already being loaded successfully. If AngularJS is initialized then it will execute the code otherwise it will delay for 1 sec and check again until AngularJS is loaded.</p>\n"
}
] |
2015/10/16
|
[
"https://wordpress.stackexchange.com/questions/205696",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82048/"
] |
I need to delay AngularJS scripts from running so I can set up my application first. I need to initialize the application with ng-app="app". I want to add that attribute to the **< body >**
< body ng-app="app" >< /body >
```
wp_enqueue_script('plugin-setup', plugin_dir_url( __FILE__ ).'js/plugin-setup.js', array('jquery'), null, true);
```
**plugin-set.js**
```
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementsByTagName("body")[0].setAttribute("ng-app", "app");
});
```
After that is set up I can run my Angular Scripts:
```
class pluginClass{
function pluginInit(){
add_action( 'wp_enqueue_scripts', array( $this, 'scriptThings' ) );
}
function scriptThings(){
wp_enqueue_script('angular-core', plugin_dir_url( __FILE__ ).'js/vendor/angular/angular.js', array('jquery'), null, true);
wp_enqueue_script('angular-resource', plugin_dir_url( __FILE__ ).'js/vendor/angular-resource/angular-resource.js', array('jquery'), null, true);
wp_enqueue_script('app', plugin_dir_url( __FILE__ ).'js/app.js', array(), null, true);
wp_enqueue_script('app-controller', plugin_dir_url( __FILE__ ).'js/controllers/app_controller.js', array(), null, true);
wp_enqueue_script('imagetile-factory', plugin_dir_url( __FILE__ ).'js/resource/imageTile_factory.js', array(), null, true);
}
}
$my_class = new pluginClass;
add_action('init', array($my_class, 'pluginInit'));
```
Is there a way to delay the Angular scripts from loading within my **plugin.php\***?
|
I think you should use `setTimeout` to pause the execution of the script without blocking the UI.
```
setTimeout(function(){
//your code to be executed after 2 seconds
}, 2000);
```
So your code will become.
```
setTimeout(function(){
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementsByTagName("body")[0].setAttribute("ng-app", "app");
});
}, 2000);
```
This will delay script execution for 2 seconds. You can change this value based on your requirements.
EDIT
----
On second thought, I think it would be better if you check for AngularJS is loaded in the current page before initializing your app.
```
function checkAngular() {
if ( window.angular ) {
// your code to be executed
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementsByTagName("body")[0].setAttribute("ng-app", "app");
});
} else {
window.setTimeout( checkAngular, 1000 );
}
}
checkAngular();
```
So what does this code do? It checks if AngularJS is already being loaded successfully. If AngularJS is initialized then it will execute the code otherwise it will delay for 1 sec and check again until AngularJS is loaded.
|
205,709 |
<p><a href="http://www.giuseppearcidiacono.it/apparecchio_invisibile_invisalign" rel="nofollow">On a page</a> I have embedded a video. On Ipad and also when you resize the browser window (look at the screenshot below), video goes over the sidebar.</p>
<p>It should regard some responsive issue.</p>
<p>Do you how to resolve it? Thanks</p>
|
[
{
"answer_id": 205710,
"author": "Gareth Gillman",
"author_id": 33936,
"author_profile": "https://wordpress.stackexchange.com/users/33936",
"pm_score": 0,
"selected": false,
"text": "<p>You just need to add the following to your css:</p>\n\n<pre><code>iframe {\n height:300px;\n max-width:100%;\n}\n</code></pre>\n\n<p>Change the height to your desired height.</p>\n"
},
{
"answer_id": 205711,
"author": "Robert hue",
"author_id": 22461,
"author_profile": "https://wordpress.stackexchange.com/users/22461",
"pm_score": 3,
"selected": true,
"text": "<p>Yes, there are issues with responsiveness.</p>\n\n<p>Add your video in a div with class <code>yt-video</code>. For example.</p>\n\n<pre><code><div class=\"yt-video\">\n <iframe width=\"560\" height=\"315\" frameborder=\"0\" allowfullscreen=\"allowfullscreen\" src=\"https://www.youtube.com/embed/602q_GYXOWA?rel=0\">\n</div>\n</code></pre>\n\n<p>And add this CSS in your <code>style.css</code> file.</p>\n\n<pre><code>div.yt-video {\n position: relative;\n padding-bottom: 56.25%;\n height: 0;\n overflow: hidden;\n max-width: 100%;\n height: auto;\n}\n\ndiv.yt-video iframe, div.yt-video object, div.yt-video embed{\n position: absolute;\n top: 0;\n left: 0;\n width: 100% !important;\n height: 100% !important;\n}\n</code></pre>\n\n<p>It will make your video responsive. But make sure you always add video inside a div element with class <code>yt-video</code>.</p>\n\n<h2>EDIT</h2>\n\n<p>This will be your style.css</p>\n\n<pre><code>@charset \"utf-8\";\n/* CSS Document */\n\n@font-face {\nfont-family: 'ProximaNova-Regular';\nsrc: url('../font/proximanovaregular.eot');\nsrc: url('../font/proximanovaregular.eot?#iefix') format('embedded-opentype'),\nurl('../font/proximanovaregular.woff') format('woff'),\nurl('../font/proximanovaregular.ttf') format('truetype'),\nurl('../font/proximanovaregular.svg#proximanovaregular') format('svg');\nfont-weight: normal;\nfont-style: normal;\n}\n\n@font-face {\nfont-family: 'ProximaNova-Bold';\nsrc: url('../font/proximanovabold.eot');\nsrc: url('../font/proximanovabold.eot?#iefix') format('embedded-opentype'),\nurl('../font/proximanovabold.woff') format('woff'),\nurl('../font/proximanovabold.ttf') format('truetype'),\nurl('../font/proximanovabold.svg#proximanovabold') format('svg');\nfont-weight: normal;\nfont-style: normal;\n}\n\n@font-face {\nfont-family: 'ProximaNova-Semibold';\nsrc: url('../font/proximanovasemibold.eot');\nsrc: url('../font/proximanovasemibold.eot?#iefix') format('embedded-opentype'),\nurl('../font/proximanovasemibold.woff') format('woff'),\nurl('../font/proximanovasemibold.ttf') format('truetype'),\nurl('../font/proximanovasemibold.svg#proximanovasemibold') format('svg');\nfont-weight: normal;\nfont-style: normal;\n}\n\n@font-face {\nfont-family: 'MyriadPro-Regular';\nsrc: url('../font/myriadproregular.eot');\nsrc: url('../font/myriadproregular.eot?#iefix') format('embedded-opentype'),\nurl('../font/myriadproregular.woff') format('woff'),\nurl('../font/myriadproregular.ttf') format('truetype'),\nurl('../font/myriadproregular.svg#myriadproregular') format('svg');\nfont-weight: normal;\nfont-style: normal;\n}\n\n.header{\nmargin:0 -20px;\npadding:15px 20px 0;\nborder-top:5px solid #a2dbd8;\nbackground-color: #355f7d;\n*background-color: #355f7d;\nbackground-image: -moz-linear-gradient(top, #428999, #355f7d);\nbackground-image: -webkit-gradient(linear, 0 0, 0 100%, from(#428999), to(#355f7d));\nbackground-image: -webkit-linear-gradient(top, #ffffff, #355f7d);\nbackground-image: -o-linear-gradient(top, #428999, #355f7d);\nbackground-image: linear-gradient(to bottom, #428999, #355f7d);\nbackground-repeat: repeat-x;\n}\n\n.logo{ color:#fff;}\n.logo h2{font-family:'ProximaNova-Bold'; font-size:26px; font-weight:normal; margin:0; padding:10px 0 0 0; line-height:28px;}\n.logo h5{font-family:'ProximaNova-Regular'; font-size:16px; font-weight:normal; margin:0; padding:0; line-height:16px;}\n.logo a{ color:#fff; text-decoration:none;}\n.logo a:hover{ color:#fff; text-decoration:none;}\n\n.phn{ color:#fff; font-size:16px; padding:23px 0 0 0;}\n.phn i{ margin:0 4px;}\n.phn span{font-family:'ProximaNova-Bold'; font-size:21px;}\n\n.navigation{ margin:0; padding:0;\nbackground-color: #d3e1f1;\n*background-color: #d3e1f1;\nbackground-image: -moz-linear-gradient(top, #ffffff, #d3e1f1);\nbackground-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#d3e1f1));\nbackground-image: -webkit-linear-gradient(top, #ffffff, #d3e1f1);\nbackground-image: -o-linear-gradient(top, #ffffff, #d3e1f1);\nbackground-image: linear-gradient(to bottom, #ffffff, #d3e1f1);\nbackground-repeat: repeat-x;\nborder:1px solid #fff;\nmargin:15px 0 0 0;\n -webkit-border-radius: 6px 6px 0 0;\n -moz-border-radius:6px 6px 0 0;\nborder-radius:6px 6px 0 0;\n}\n\n.body-container{ margin:0 -20px; padding:0 20px; background:url(../img/background.jpg) no-repeat top center;}\n.banner{ margin:0; padding:0; border-bottom:5px solid #ccc; background:#38617f;}\n.banner .carousel-caption{ padding-bottom:30px; padding-right:15px; padding-left:0}\n.banner .carousel-caption h4{ color:#80dbe0; font-size:24px; font-weight:normal; font-family:'ProximaNova-Bold';}\n.banner .carousel-caption h2{ color:#fff; font-size:40px; font-weight:normal; font-family:'ProximaNova-Bold';}\n\n.body-wrap{ margin:0; padding:15px;\nbackground-color: #f4f4f4;\n *background-color: #f4f4f4;\n background-image: -moz-linear-gradient(top, #ffffff, #f4f4f4);\n background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#f4f4f4));\n background-image: -webkit-linear-gradient(top, #ffffff, #f4f4f4);\n background-image: -o-linear-gradient(top, #ffffff, #f4f4f4);\n background-image: linear-gradient(to bottom, #ffffff, #f4f4f4);\n background-repeat: repeat-x;\n}\n.block{}\n.block h5{ color:#355f7d; font-size:16px; font-weight:normal; font-family:'ProximaNova-Bold';}\n.block h4{ color:#355f7d; font-size:21px; font-weight:normal; font-family:'ProximaNova-Bold';}\n.block ul{ margin:0; padding:0 0 0 15px;}\n.block ul li{ margin:0; padding:0; list-style:disc;}\n\n.right-col{ margin-top:40px;}\n.right-col-inner{}\n.right-col-inner h4.maptitle{ color:#0270c4; font-size:16px; font-weight:normal; font-family:'ProximaNova-Bold'; margin-top:20px;}\n\n.contentmanage h2{ margin:0; padding:0; font-weight:normal; font-family:'ProximaNova-Bold'; color:#38617f; font-size:23px;}\n.contentmanage h4{ margin:0; padding:0; font-weight:normal; font-family:'ProximaNova-Bold'; color:#38617f; font-size:19px;}\n.contentmanage p span{ font-family:'ProximaNova-Bold'; color:#38617f;}\n.contentmanage p{ margin:0; padding:15px 0 0 0;}\n.contentmanage ul.list-text{ margin:0; padding:15px 0 0 20px; font-family:'ProximaNova-Bold'; color:#38617f; font-size:16px;}\n.contentmanage ul{ margin:0; padding:15px 0 0 20px;}\n\n.Flexible-container {\n position: relative;\n padding-bottom: 56.25%;\n padding-top: 30px;\n height: 0;\n overflow: hidden;\n margin:10px 0 0 0;\n}\n\n.Flexible-container iframe,\n.Flexible-container object,\n.Flexible-container embed {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n}\n\n.innertop-box{ margin:0 0 20px 0; padding:0;}\n.innertop-box .img{ -webkit-border-radius:10px 10px 0 0;\n -moz-border-radius:10px 10px 0 0;\nborder-radius:10px 10px 0 0;}\n\n.innertop-box .info{ margin:0; padding:15px; color:#fff;\nbackground-color: #71bcbf;\n *background-color: #71bcbf;\n background-image: -moz-linear-gradient(top, #90d2d2, #71bcbf);\n background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#71bcbf));\n background-image: -webkit-linear-gradient(top, #90d2d2, #71bcbf);\n background-image: -o-linear-gradient(top, #90d2d2, #71bcbf);\n background-image: linear-gradient(to bottom, #90d2d2, #71bcbf);\n background-repeat: repeat-x;\n\n -webkit-border-radius:0 0 10px 10px;\n -moz-border-radius:0 0 10px 10px;\nborder-radius:0 0 10px 10px;}\n.innertop-box .info h3{ margin:0; padding:0; font-size:21px; line-height:30px; font-family:'ProximaNova-Bold'; font-weight:normal;}\n\n.timetable{ margin:0; padding:0; background:url(../img/pattern.jpg); -webkit-border-radius:6px;\n -moz-border-radius:6px;\nborder-radius:6px;}\n.timeblock{ margin:0; padding:15px; background:url(../img/watchbg.png) no-repeat right top; font-family:'ProximaNova-Bold'; text-transform:uppercase; text-shadow:1px 1px 1px #000; color:#fff; font-size:19px; -webkit-border-radius:6px;\n -moz-border-radius:6px;\nborder-radius:6px;}\n\n.quoteform{ margin:20px 0; padding:15px; background:#a5e5ef; -webkit-border-radius:10px; -moz-border-radius:10px; border-radius:10px;}\n.quoteform h3{ margin:0; padding:0 0 5px 0; font-weight:normal; font-family:'ProximaNova-Regular'; line-height:26px; font-size:21px; color:#3d5b65;}\n.quoteform input[type=text]{ color:#43636d;}\n.quoteform input[type=submit]{ margin:5px 0 0 0;}\n.quoteform form{ margin:0; padding:0;}\n.quoteform label.checkbox{ font-size:11px; co#43636d; line-height:15px;}\n\ndiv.fb-like-box,\ndiv.fb-like-box > span,\ndiv.fb-like-box > span > iframe[style],\ndiv.fb-comments,\ndiv.fb-comments > span,\ndiv.fb-comments > span > iframe[style] {width: 100% !important;}\n\n@media only screen and (min-width: 992px) and (max-width: 1199px) {\n.sub-con {\n background: #ececec none repeat scroll 0 0 !important;\n height: 250px !important;\n margin: 0 12px 0 0 !important;\n padding-top: 10px !important;\n}\n}\n\n\n@media (min-width: 768px) and (max-width: 979px) {\n\n.span3 {\n margin: 0 8px 0 0 !important;\n}\n\n}\n\ndiv.yt-video {\n position: relative;\n padding-bottom: 56.25%;\n height: 0;\n overflow: hidden;\n max-width: 100%;\n height: auto;\n}\n\ndiv.yt-video iframe, div.yt-video object, div.yt-video embed{\n position: absolute;\n top: 0;\n left: 0;\n width: 100% !important;\n height: 100% !important;\n}\n</code></pre>\n"
}
] |
2015/10/16
|
[
"https://wordpress.stackexchange.com/questions/205709",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81951/"
] |
[On a page](http://www.giuseppearcidiacono.it/apparecchio_invisibile_invisalign) I have embedded a video. On Ipad and also when you resize the browser window (look at the screenshot below), video goes over the sidebar.
It should regard some responsive issue.
Do you how to resolve it? Thanks
|
Yes, there are issues with responsiveness.
Add your video in a div with class `yt-video`. For example.
```
<div class="yt-video">
<iframe width="560" height="315" frameborder="0" allowfullscreen="allowfullscreen" src="https://www.youtube.com/embed/602q_GYXOWA?rel=0">
</div>
```
And add this CSS in your `style.css` file.
```
div.yt-video {
position: relative;
padding-bottom: 56.25%;
height: 0;
overflow: hidden;
max-width: 100%;
height: auto;
}
div.yt-video iframe, div.yt-video object, div.yt-video embed{
position: absolute;
top: 0;
left: 0;
width: 100% !important;
height: 100% !important;
}
```
It will make your video responsive. But make sure you always add video inside a div element with class `yt-video`.
EDIT
----
This will be your style.css
```
@charset "utf-8";
/* CSS Document */
@font-face {
font-family: 'ProximaNova-Regular';
src: url('../font/proximanovaregular.eot');
src: url('../font/proximanovaregular.eot?#iefix') format('embedded-opentype'),
url('../font/proximanovaregular.woff') format('woff'),
url('../font/proximanovaregular.ttf') format('truetype'),
url('../font/proximanovaregular.svg#proximanovaregular') format('svg');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'ProximaNova-Bold';
src: url('../font/proximanovabold.eot');
src: url('../font/proximanovabold.eot?#iefix') format('embedded-opentype'),
url('../font/proximanovabold.woff') format('woff'),
url('../font/proximanovabold.ttf') format('truetype'),
url('../font/proximanovabold.svg#proximanovabold') format('svg');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'ProximaNova-Semibold';
src: url('../font/proximanovasemibold.eot');
src: url('../font/proximanovasemibold.eot?#iefix') format('embedded-opentype'),
url('../font/proximanovasemibold.woff') format('woff'),
url('../font/proximanovasemibold.ttf') format('truetype'),
url('../font/proximanovasemibold.svg#proximanovasemibold') format('svg');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'MyriadPro-Regular';
src: url('../font/myriadproregular.eot');
src: url('../font/myriadproregular.eot?#iefix') format('embedded-opentype'),
url('../font/myriadproregular.woff') format('woff'),
url('../font/myriadproregular.ttf') format('truetype'),
url('../font/myriadproregular.svg#myriadproregular') format('svg');
font-weight: normal;
font-style: normal;
}
.header{
margin:0 -20px;
padding:15px 20px 0;
border-top:5px solid #a2dbd8;
background-color: #355f7d;
*background-color: #355f7d;
background-image: -moz-linear-gradient(top, #428999, #355f7d);
background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#428999), to(#355f7d));
background-image: -webkit-linear-gradient(top, #ffffff, #355f7d);
background-image: -o-linear-gradient(top, #428999, #355f7d);
background-image: linear-gradient(to bottom, #428999, #355f7d);
background-repeat: repeat-x;
}
.logo{ color:#fff;}
.logo h2{font-family:'ProximaNova-Bold'; font-size:26px; font-weight:normal; margin:0; padding:10px 0 0 0; line-height:28px;}
.logo h5{font-family:'ProximaNova-Regular'; font-size:16px; font-weight:normal; margin:0; padding:0; line-height:16px;}
.logo a{ color:#fff; text-decoration:none;}
.logo a:hover{ color:#fff; text-decoration:none;}
.phn{ color:#fff; font-size:16px; padding:23px 0 0 0;}
.phn i{ margin:0 4px;}
.phn span{font-family:'ProximaNova-Bold'; font-size:21px;}
.navigation{ margin:0; padding:0;
background-color: #d3e1f1;
*background-color: #d3e1f1;
background-image: -moz-linear-gradient(top, #ffffff, #d3e1f1);
background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#d3e1f1));
background-image: -webkit-linear-gradient(top, #ffffff, #d3e1f1);
background-image: -o-linear-gradient(top, #ffffff, #d3e1f1);
background-image: linear-gradient(to bottom, #ffffff, #d3e1f1);
background-repeat: repeat-x;
border:1px solid #fff;
margin:15px 0 0 0;
-webkit-border-radius: 6px 6px 0 0;
-moz-border-radius:6px 6px 0 0;
border-radius:6px 6px 0 0;
}
.body-container{ margin:0 -20px; padding:0 20px; background:url(../img/background.jpg) no-repeat top center;}
.banner{ margin:0; padding:0; border-bottom:5px solid #ccc; background:#38617f;}
.banner .carousel-caption{ padding-bottom:30px; padding-right:15px; padding-left:0}
.banner .carousel-caption h4{ color:#80dbe0; font-size:24px; font-weight:normal; font-family:'ProximaNova-Bold';}
.banner .carousel-caption h2{ color:#fff; font-size:40px; font-weight:normal; font-family:'ProximaNova-Bold';}
.body-wrap{ margin:0; padding:15px;
background-color: #f4f4f4;
*background-color: #f4f4f4;
background-image: -moz-linear-gradient(top, #ffffff, #f4f4f4);
background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#f4f4f4));
background-image: -webkit-linear-gradient(top, #ffffff, #f4f4f4);
background-image: -o-linear-gradient(top, #ffffff, #f4f4f4);
background-image: linear-gradient(to bottom, #ffffff, #f4f4f4);
background-repeat: repeat-x;
}
.block{}
.block h5{ color:#355f7d; font-size:16px; font-weight:normal; font-family:'ProximaNova-Bold';}
.block h4{ color:#355f7d; font-size:21px; font-weight:normal; font-family:'ProximaNova-Bold';}
.block ul{ margin:0; padding:0 0 0 15px;}
.block ul li{ margin:0; padding:0; list-style:disc;}
.right-col{ margin-top:40px;}
.right-col-inner{}
.right-col-inner h4.maptitle{ color:#0270c4; font-size:16px; font-weight:normal; font-family:'ProximaNova-Bold'; margin-top:20px;}
.contentmanage h2{ margin:0; padding:0; font-weight:normal; font-family:'ProximaNova-Bold'; color:#38617f; font-size:23px;}
.contentmanage h4{ margin:0; padding:0; font-weight:normal; font-family:'ProximaNova-Bold'; color:#38617f; font-size:19px;}
.contentmanage p span{ font-family:'ProximaNova-Bold'; color:#38617f;}
.contentmanage p{ margin:0; padding:15px 0 0 0;}
.contentmanage ul.list-text{ margin:0; padding:15px 0 0 20px; font-family:'ProximaNova-Bold'; color:#38617f; font-size:16px;}
.contentmanage ul{ margin:0; padding:15px 0 0 20px;}
.Flexible-container {
position: relative;
padding-bottom: 56.25%;
padding-top: 30px;
height: 0;
overflow: hidden;
margin:10px 0 0 0;
}
.Flexible-container iframe,
.Flexible-container object,
.Flexible-container embed {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.innertop-box{ margin:0 0 20px 0; padding:0;}
.innertop-box .img{ -webkit-border-radius:10px 10px 0 0;
-moz-border-radius:10px 10px 0 0;
border-radius:10px 10px 0 0;}
.innertop-box .info{ margin:0; padding:15px; color:#fff;
background-color: #71bcbf;
*background-color: #71bcbf;
background-image: -moz-linear-gradient(top, #90d2d2, #71bcbf);
background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#71bcbf));
background-image: -webkit-linear-gradient(top, #90d2d2, #71bcbf);
background-image: -o-linear-gradient(top, #90d2d2, #71bcbf);
background-image: linear-gradient(to bottom, #90d2d2, #71bcbf);
background-repeat: repeat-x;
-webkit-border-radius:0 0 10px 10px;
-moz-border-radius:0 0 10px 10px;
border-radius:0 0 10px 10px;}
.innertop-box .info h3{ margin:0; padding:0; font-size:21px; line-height:30px; font-family:'ProximaNova-Bold'; font-weight:normal;}
.timetable{ margin:0; padding:0; background:url(../img/pattern.jpg); -webkit-border-radius:6px;
-moz-border-radius:6px;
border-radius:6px;}
.timeblock{ margin:0; padding:15px; background:url(../img/watchbg.png) no-repeat right top; font-family:'ProximaNova-Bold'; text-transform:uppercase; text-shadow:1px 1px 1px #000; color:#fff; font-size:19px; -webkit-border-radius:6px;
-moz-border-radius:6px;
border-radius:6px;}
.quoteform{ margin:20px 0; padding:15px; background:#a5e5ef; -webkit-border-radius:10px; -moz-border-radius:10px; border-radius:10px;}
.quoteform h3{ margin:0; padding:0 0 5px 0; font-weight:normal; font-family:'ProximaNova-Regular'; line-height:26px; font-size:21px; color:#3d5b65;}
.quoteform input[type=text]{ color:#43636d;}
.quoteform input[type=submit]{ margin:5px 0 0 0;}
.quoteform form{ margin:0; padding:0;}
.quoteform label.checkbox{ font-size:11px; co#43636d; line-height:15px;}
div.fb-like-box,
div.fb-like-box > span,
div.fb-like-box > span > iframe[style],
div.fb-comments,
div.fb-comments > span,
div.fb-comments > span > iframe[style] {width: 100% !important;}
@media only screen and (min-width: 992px) and (max-width: 1199px) {
.sub-con {
background: #ececec none repeat scroll 0 0 !important;
height: 250px !important;
margin: 0 12px 0 0 !important;
padding-top: 10px !important;
}
}
@media (min-width: 768px) and (max-width: 979px) {
.span3 {
margin: 0 8px 0 0 !important;
}
}
div.yt-video {
position: relative;
padding-bottom: 56.25%;
height: 0;
overflow: hidden;
max-width: 100%;
height: auto;
}
div.yt-video iframe, div.yt-video object, div.yt-video embed{
position: absolute;
top: 0;
left: 0;
width: 100% !important;
height: 100% !important;
}
```
|
205,730 |
<p>I am looking to display all tags in select form that are from posts that have been assigned to a specific category.</p>
<p>I am using the following code to generate every tag in a select form</p>
<pre><code><div>
<?php
echo "<select onChange=\"document.location.href=this.options[this.selectedIndex].value;\">";
echo "<option>By product</option>\n";
foreach (get_tags() as $tag)
{
echo "<option value=\"";
echo get_tag_link($tag->term_id);
echo "\">".$tag->name."</option>\n";
}
echo "</select>"; ?>
</div>
</code></pre>
<p>Can someone point me in the direction on how I can just display the tags that are from all posts assigned to the videos category?</p>
<p>Any help much appreciated </p>
|
[
{
"answer_id": 205731,
"author": "Domain",
"author_id": 26523,
"author_profile": "https://wordpress.stackexchange.com/users/26523",
"pm_score": -1,
"selected": false,
"text": "<pre><code><div>\n<?php\necho \"<select onChange=\\\"document.location.href=this.options[this.selectedIndex].value;\\\">\";\necho \"<option>By product</option>\\n\";\nforeach (get_tags() as $tag)\n{\nif($tag['taxonomy']==\"your_category\"){\n echo \"<option value=\\\"\";\n echo get_tag_link($tag->term_id);\n echo \"\\\">\".$tag->name.\"</option>\\n\";\n }\n}\n echo \"</select>\"; ?>\n</div>\n</code></pre>\n\n<p>use this and put your category</p>\n"
},
{
"answer_id": 205733,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 3,
"selected": true,
"text": "<p>From my understanding of the question and your comment: </p>\n\n<blockquote>\n <p>I want to display all tags that are from posts that have been assigned to the specific category</p>\n</blockquote>\n\n<p>You would first need to get all the posts that have that tag assigned, loop through said posts and save the unique tags to an array. Finally, loop through the array and display them in the select list. The only thing you would need to do on your end is replace <code>$reltaed_term_id = 7</code> with whatever the ID is of the tag you're looking to target.</p>\n\n<pre><code><?php\n $reltaed_term_id = 7;\n $unique_related_tags = array();\n\n $related = new WP_Query( array(\n 'post_type' => 'post',\n 'posts_per_page'=> -1,\n 'fields' => 'ids',\n 'cat ' => $reltaed_term_id,\n ) );\n\n if( $related->have_posts() ) {\n foreach( $related->posts as $post_id ) {\n $tags = wp_get_post_tags( $post_id );\n if( ! empty( $tags ) ) {\n foreach( $tags as $tag ) {\n if( empty( $unique_related_tags ) || ! array_key_exists( $tag->term_id, $unique_related_tags ) ) {\n $unique_related_tags[ $tag->term_id ] = $tag->name;\n }\n }\n }\n }\n\n wp_reset_postdata();\n }\n\n if( ! empty( $unique_related_tags ) ) :\n?>\n\n <div>\n <select onChange=\"document.location.href=this.options[this.selectedIndex].value;\">\n <option>By product</option>\n\n <?php foreach( $unique_related_tags as $tag_id => $tag_name ) : ?>\n\n <option value=\"<?php echo get_tag_link( $tag_id ); ?>\"><?php echo $tag_name; ?></option>\n\n <?php endforeach; ?>\n\n </select>\n </div>\n\n<?php endif; ?>\n</code></pre>\n\n<p>I haven't tested the above code so let me know if you run into issues.</p>\n"
}
] |
2015/10/16
|
[
"https://wordpress.stackexchange.com/questions/205730",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37243/"
] |
I am looking to display all tags in select form that are from posts that have been assigned to a specific category.
I am using the following code to generate every tag in a select form
```
<div>
<?php
echo "<select onChange=\"document.location.href=this.options[this.selectedIndex].value;\">";
echo "<option>By product</option>\n";
foreach (get_tags() as $tag)
{
echo "<option value=\"";
echo get_tag_link($tag->term_id);
echo "\">".$tag->name."</option>\n";
}
echo "</select>"; ?>
</div>
```
Can someone point me in the direction on how I can just display the tags that are from all posts assigned to the videos category?
Any help much appreciated
|
From my understanding of the question and your comment:
>
> I want to display all tags that are from posts that have been assigned to the specific category
>
>
>
You would first need to get all the posts that have that tag assigned, loop through said posts and save the unique tags to an array. Finally, loop through the array and display them in the select list. The only thing you would need to do on your end is replace `$reltaed_term_id = 7` with whatever the ID is of the tag you're looking to target.
```
<?php
$reltaed_term_id = 7;
$unique_related_tags = array();
$related = new WP_Query( array(
'post_type' => 'post',
'posts_per_page'=> -1,
'fields' => 'ids',
'cat ' => $reltaed_term_id,
) );
if( $related->have_posts() ) {
foreach( $related->posts as $post_id ) {
$tags = wp_get_post_tags( $post_id );
if( ! empty( $tags ) ) {
foreach( $tags as $tag ) {
if( empty( $unique_related_tags ) || ! array_key_exists( $tag->term_id, $unique_related_tags ) ) {
$unique_related_tags[ $tag->term_id ] = $tag->name;
}
}
}
}
wp_reset_postdata();
}
if( ! empty( $unique_related_tags ) ) :
?>
<div>
<select onChange="document.location.href=this.options[this.selectedIndex].value;">
<option>By product</option>
<?php foreach( $unique_related_tags as $tag_id => $tag_name ) : ?>
<option value="<?php echo get_tag_link( $tag_id ); ?>"><?php echo $tag_name; ?></option>
<?php endforeach; ?>
</select>
</div>
<?php endif; ?>
```
I haven't tested the above code so let me know if you run into issues.
|
205,777 |
<p>Hello WordPress Developers,</p>
<p>I got this erros messages when I check my site like below</p>
<p>mysite.com/wp-content/themes/mythemes</p>
<p>When I visite that url, it give me this message </p>
<blockquote>
<p>Fatal error: Call to undefined function get_header() in
/users/my-username/www/mysite-folder/wp-content/themes/twentyfifteen/index.php
on line 17</p>
</blockquote>
<p>You know, the errors messages shouldn't give us like that, Am I right? And I googled for this and found no better solutions. Here are some steps that I have tried</p>
<ul>
<li>define( 'WP_MEMORY_LIMIT', '228M' ); (it doesn't work)</li>
<li><code><?php @get_header(); ?></code> (it can make errors message disappear, but it is not the best solution.)</li>
<li><code><?php ini_set('display_errors', 0); ?></code> (it can also make errors disappear, but it is also not the right solutions.)</li>
<li>So, I make new wordpress installation, it still give me that errors message</li>
</ul>
<p>Please note: I don't install any plugins</p>
<p>What I understand on this errors, wordpress can't load</p>
<p>So, do you have better solution for this kind of errors? Please advice me, I have spent 3 hours for this.</p>
|
[
{
"answer_id": 205788,
"author": "Ashok Dhaduk",
"author_id": 81215,
"author_profile": "https://wordpress.stackexchange.com/users/81215",
"pm_score": 0,
"selected": false,
"text": "<p>As per described by you I thought you had issue with the theme. Can you switch the theme ?</p>\n\n<p>If its not possible with backend then Try with FTP just rename that theme folder to another name & then Look whats happen. If it still exist then you need to try it with disabling all plugin at once & then activate one by one to check which plugin will cause this issue.</p>\n\n<p>I hope this will help you out in fixing this issue.</p>\n"
},
{
"answer_id": 253241,
"author": "Umer Shoukat",
"author_id": 94940,
"author_profile": "https://wordpress.stackexchange.com/users/94940",
"pm_score": 2,
"selected": false,
"text": "<p>I got your point What you are trying to do. The solution to your problem is these lines of code to place above all the code of your index file or you may place it on all files of your theme.</p>\n\n<pre><code><?php\n\n// Do not allow directly accessing this file.\nif ( ! defined( 'ABSPATH' ) ) {\n exit( 'Direct script access denied.' );\n}\n?>\n</code></pre>\n"
}
] |
2015/10/17
|
[
"https://wordpress.stackexchange.com/questions/205777",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/31832/"
] |
Hello WordPress Developers,
I got this erros messages when I check my site like below
mysite.com/wp-content/themes/mythemes
When I visite that url, it give me this message
>
> Fatal error: Call to undefined function get\_header() in
> /users/my-username/www/mysite-folder/wp-content/themes/twentyfifteen/index.php
> on line 17
>
>
>
You know, the errors messages shouldn't give us like that, Am I right? And I googled for this and found no better solutions. Here are some steps that I have tried
* define( 'WP\_MEMORY\_LIMIT', '228M' ); (it doesn't work)
* `<?php @get_header(); ?>` (it can make errors message disappear, but it is not the best solution.)
* `<?php ini_set('display_errors', 0); ?>` (it can also make errors disappear, but it is also not the right solutions.)
* So, I make new wordpress installation, it still give me that errors message
Please note: I don't install any plugins
What I understand on this errors, wordpress can't load
So, do you have better solution for this kind of errors? Please advice me, I have spent 3 hours for this.
|
I got your point What you are trying to do. The solution to your problem is these lines of code to place above all the code of your index file or you may place it on all files of your theme.
```
<?php
// Do not allow directly accessing this file.
if ( ! defined( 'ABSPATH' ) ) {
exit( 'Direct script access denied.' );
}
?>
```
|
205,778 |
<p>The snippet below links a user's Easy Digital Download (EDD) download payment to allocating a secondary user role to that user.</p>
<p>As per the example below...</p>
<ul>
<li>If a user buys a EDD download with a download ID of 340 then that
user will be allocated a secondary user role of "buyer"... or,</li>
<li>If a user buys a EDD download with a download ID of 240 then that
user will be allocated a secondary user role of "other_role".</li>
</ul>
<p>I'd like each secondary user role to be unallocated from each user X days after the successful EDD payment.</p>
<pre><code>function pw_edd_run_when_purchase_complete( $payment_id, $new_status, $old_status ) {
if ( $old_status == 'publish' || $old_status == 'complete' ) {
return;
} // Make sure that payments are only completed once
// Make sure the payment completion is only processed when new status is complete
if ( $new_status != 'publish' && $new_status != 'complete' ) {
return;
}
$downloads = edd_get_payment_meta_downloads( $payment_id );
$user_id = edd_get_payment_user_id( $payment_id );
if ( is_array( $downloads ) ) {
// Increase purchase count and earnings
foreach ( $downloads as $download ) {
$user = new WP_User( $user_id );
if(!$user )
continue;
if( $download['id'] == 340 ) {
// Add custom role
// Change 340 to the download id of the product that a certain role corresponds
$user->add_role( 'buyer' );
//also change buyer depending on your role that you created in User Role Editor
} elseif( $download['id'] == 240 ) {
// Add custom role
// Change 340 to the download id of the product that a certain role corresponds
$user->add_role( 'other_role' );
//also change other_role depending on your role that you created in User Role Editor
}
}
}
}
add_action( 'edd_update_payment_status', 'pw_edd_run_when_purchase_complete', 100, 3 );
</code></pre>
|
[
{
"answer_id": 205788,
"author": "Ashok Dhaduk",
"author_id": 81215,
"author_profile": "https://wordpress.stackexchange.com/users/81215",
"pm_score": 0,
"selected": false,
"text": "<p>As per described by you I thought you had issue with the theme. Can you switch the theme ?</p>\n\n<p>If its not possible with backend then Try with FTP just rename that theme folder to another name & then Look whats happen. If it still exist then you need to try it with disabling all plugin at once & then activate one by one to check which plugin will cause this issue.</p>\n\n<p>I hope this will help you out in fixing this issue.</p>\n"
},
{
"answer_id": 253241,
"author": "Umer Shoukat",
"author_id": 94940,
"author_profile": "https://wordpress.stackexchange.com/users/94940",
"pm_score": 2,
"selected": false,
"text": "<p>I got your point What you are trying to do. The solution to your problem is these lines of code to place above all the code of your index file or you may place it on all files of your theme.</p>\n\n<pre><code><?php\n\n// Do not allow directly accessing this file.\nif ( ! defined( 'ABSPATH' ) ) {\n exit( 'Direct script access denied.' );\n}\n?>\n</code></pre>\n"
}
] |
2015/10/17
|
[
"https://wordpress.stackexchange.com/questions/205778",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37346/"
] |
The snippet below links a user's Easy Digital Download (EDD) download payment to allocating a secondary user role to that user.
As per the example below...
* If a user buys a EDD download with a download ID of 340 then that
user will be allocated a secondary user role of "buyer"... or,
* If a user buys a EDD download with a download ID of 240 then that
user will be allocated a secondary user role of "other\_role".
I'd like each secondary user role to be unallocated from each user X days after the successful EDD payment.
```
function pw_edd_run_when_purchase_complete( $payment_id, $new_status, $old_status ) {
if ( $old_status == 'publish' || $old_status == 'complete' ) {
return;
} // Make sure that payments are only completed once
// Make sure the payment completion is only processed when new status is complete
if ( $new_status != 'publish' && $new_status != 'complete' ) {
return;
}
$downloads = edd_get_payment_meta_downloads( $payment_id );
$user_id = edd_get_payment_user_id( $payment_id );
if ( is_array( $downloads ) ) {
// Increase purchase count and earnings
foreach ( $downloads as $download ) {
$user = new WP_User( $user_id );
if(!$user )
continue;
if( $download['id'] == 340 ) {
// Add custom role
// Change 340 to the download id of the product that a certain role corresponds
$user->add_role( 'buyer' );
//also change buyer depending on your role that you created in User Role Editor
} elseif( $download['id'] == 240 ) {
// Add custom role
// Change 340 to the download id of the product that a certain role corresponds
$user->add_role( 'other_role' );
//also change other_role depending on your role that you created in User Role Editor
}
}
}
}
add_action( 'edd_update_payment_status', 'pw_edd_run_when_purchase_complete', 100, 3 );
```
|
I got your point What you are trying to do. The solution to your problem is these lines of code to place above all the code of your index file or you may place it on all files of your theme.
```
<?php
// Do not allow directly accessing this file.
if ( ! defined( 'ABSPATH' ) ) {
exit( 'Direct script access denied.' );
}
?>
```
|
205,804 |
<p>I am adding Favicons and Icons to my site manually in a more proper way than what WordPress adds by default. My WordPress is generating the below 4 lines of code automatically. </p>
<pre><code><link rel="icon" href="http://example.com/wp-content/uploads/sites/3/2015/09/cropped-group_logo-32x32.png" sizes="32x32">
<link rel="icon" href="http://example.com/wp-content/uploads/sites/3/2015/09/cropped-group_logo-192x192.png" sizes="192x192">
<link rel="apple-touch-icon-precomposed" href="http://example.com/wp-content/uploads/sites/3/2015/09/cropped-group_logo-180x180.png">
<meta name="msapplication-TileImage" content="http://example.com/wp-content/uploads/sites/3/2015/09/cropped-group_logo-270x270.png">
</code></pre>
<p>I tried a lot but could not figure out how to stop WordPress from generating this.</p>
<p>Kindly help</p>
<p>Update:
After using the function provided by @Gareth, I am getting the following error:</p>
<pre><code>Warning: array_filter() expects parameter 1 to be array, null given in C:\xampp\htdocs\example\wp-includes\general-template.php on line 2466
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\example\wp-includes\general-template.php on line 2468
</code></pre>
|
[
{
"answer_id": 205806,
"author": "Gareth Gillman",
"author_id": 33936,
"author_profile": "https://wordpress.stackexchange.com/users/33936",
"pm_score": 0,
"selected": false,
"text": "<p>from looking at line 2446 of general-template.php where the meta tags are defined, they are defined in an array of $meta_tags, the only way I could think of to remove the 2 options you want is:</p>\n\n<pre><code>function theme_metatags($meta_tags) {\n array_splice($meta_tags, 2);\n}\nadd_filter('site_icon_meta_tags', 'theme_metatags');\n</code></pre>\n\n<p>That should remove the last 2 icons from the array which is the 2 lines in your post.</p>\n\n<p>I haven't tested this and it's probably not the ideal solution (hopefully someone else will be able to work out a better way).</p>\n"
},
{
"answer_id": 205830,
"author": "Vikram",
"author_id": 2122,
"author_profile": "https://wordpress.stackexchange.com/users/2122",
"pm_score": 4,
"selected": true,
"text": "<p>Finally I found the answer outside of this place, hence I am posting it here as it may be useful to someone like me.</p>\n\n<p>Simply add this to your functions.php file</p>\n\n<pre><code>remove_action ('wp_head', 'wp_site_icon', 99);\n</code></pre>\n"
},
{
"answer_id": 310362,
"author": "KZeni",
"author_id": 60913,
"author_profile": "https://wordpress.stackexchange.com/users/60913",
"pm_score": 2,
"selected": false,
"text": "<p>I was able to use the following in my functions.php to remove the apple-touch-icon:</p>\n\n<pre><code>// Don't use the Site Icon as Apple Touch Icon (instead, use those for favicon & others while the touch icon is provided elsewhere)\nfunction removeAppleTouchIconFilter($string) {\n return strpos($string, 'apple-touch-icon') === false;\n}\nfunction prevent_apple_touch_icon_metatag($meta_tags){\n return array_filter($meta_tags, 'removeAppleTouchIconFilter');\n}\nadd_filter('site_icon_meta_tags','prevent_apple_touch_icon_metatag');\n</code></pre>\n\n<p>This way, it finds the icon within the array of meta tags rather than using a hard-set index value. This should prevent issues if the position of this item in the array ever changes.</p>\n"
}
] |
2015/10/17
|
[
"https://wordpress.stackexchange.com/questions/205804",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/2122/"
] |
I am adding Favicons and Icons to my site manually in a more proper way than what WordPress adds by default. My WordPress is generating the below 4 lines of code automatically.
```
<link rel="icon" href="http://example.com/wp-content/uploads/sites/3/2015/09/cropped-group_logo-32x32.png" sizes="32x32">
<link rel="icon" href="http://example.com/wp-content/uploads/sites/3/2015/09/cropped-group_logo-192x192.png" sizes="192x192">
<link rel="apple-touch-icon-precomposed" href="http://example.com/wp-content/uploads/sites/3/2015/09/cropped-group_logo-180x180.png">
<meta name="msapplication-TileImage" content="http://example.com/wp-content/uploads/sites/3/2015/09/cropped-group_logo-270x270.png">
```
I tried a lot but could not figure out how to stop WordPress from generating this.
Kindly help
Update:
After using the function provided by @Gareth, I am getting the following error:
```
Warning: array_filter() expects parameter 1 to be array, null given in C:\xampp\htdocs\example\wp-includes\general-template.php on line 2466
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\example\wp-includes\general-template.php on line 2468
```
|
Finally I found the answer outside of this place, hence I am posting it here as it may be useful to someone like me.
Simply add this to your functions.php file
```
remove_action ('wp_head', 'wp_site_icon', 99);
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.